From 20530f435558f925b6b749d8193ee2eb3aa73b42 Mon Sep 17 00:00:00 2001 From: hackerwins Date: Thu, 7 Nov 2024 02:59:39 +0000 Subject: [PATCH] deploy: 924ba4c80c6fa83ab9bb1511ba6b8387e2e34c61 --- api-reference/assets/search.js | 2 +- api-reference/classes/Change.html | 28 ++-- api-reference/classes/Client.html | 42 +++--- api-reference/classes/Counter.html | 16 +- api-reference/classes/Document.html | 140 +++++++++--------- api-reference/classes/Primitive.html | 48 +++--- api-reference/classes/Text.html | 38 ++--- api-reference/classes/TimeTicket.html | 30 ++-- api-reference/classes/Tree.html | 52 +++---- api-reference/classes/VersionVector.html | 20 +-- api-reference/enums/ClientCondition.html | 6 +- api-reference/enums/ClientStatus.html | 6 +- api-reference/enums/DocEventType.html | 26 ++-- api-reference/enums/DocumentStatus.html | 8 +- api-reference/enums/DocumentSyncStatus.html | 6 +- api-reference/enums/LogLevel.html | 4 +- api-reference/enums/OpSource.html | 4 +- .../enums/StreamConnectionStatus.html | 6 +- api-reference/enums/SyncMode.html | 10 +- api-reference/enums/TreeChangeType.html | 4 +- api-reference/interfaces/ChangeInfo.html | 4 +- api-reference/interfaces/ClientOptions.html | 14 +- .../interfaces/ConnectionChangedEvent.html | 4 +- .../interfaces/InitializedEvent.html | 4 +- .../interfaces/LocalChangeEvent.html | 6 +- api-reference/interfaces/Observable.html | 4 +- api-reference/interfaces/Observer.html | 4 +- .../interfaces/PresenceChangedEvent.html | 4 +- .../interfaces/RemoteChangeEvent.html | 6 +- api-reference/interfaces/SnapshotEvent.html | 6 +- .../interfaces/SyncStatusChangedEvent.html | 4 +- api-reference/interfaces/UnwatchedEvent.html | 4 +- api-reference/interfaces/WatchedEvent.html | 4 +- api-reference/modules/Devtools.html | 2 +- api-reference/types/ActorID.html | 2 +- api-reference/types/AddOpInfo.html | 2 +- api-reference/types/ArrayOperationInfo.html | 2 +- api-reference/types/CRDTTreeNodeIDStruct.html | 2 +- api-reference/types/CompleteFn.html | 2 +- api-reference/types/CounterOperationInfo.html | 2 +- api-reference/types/CounterValue.html | 2 +- api-reference/types/Devtools.Client.html | 2 +- .../types/Devtools.ContainerValue.html | 2 +- api-reference/types/Devtools.JSONElement.html | 2 +- .../types/Devtools.TreeNodeInfo.html | 2 +- api-reference/types/DocEvent.html | 2 +- api-reference/types/EditOpInfo.html | 2 +- api-reference/types/ElementNode.html | 2 +- api-reference/types/ErrorFn.html | 2 +- .../types/FullPanelToSDKMessage.html | 2 +- .../types/FullSDKToPanelMessage.html | 2 +- api-reference/types/IncreaseOpInfo.html | 2 +- api-reference/types/Indexable.html | 2 +- api-reference/types/JSONArray.html | 26 ++-- api-reference/types/JSONElement.html | 2 +- api-reference/types/JSONObject.html | 8 +- api-reference/types/MoveOpInfo.html | 2 +- api-reference/types/NextFn.html | 2 +- api-reference/types/ObjectOperationInfo.html | 2 +- api-reference/types/OperationInfo.html | 2 +- api-reference/types/PanelToSDKMessage.html | 2 +- api-reference/types/PrimitiveValue.html | 2 +- api-reference/types/RemoveOpInfo.html | 2 +- api-reference/types/SDKToPanelMessage.html | 2 +- api-reference/types/SetOpInfo.html | 2 +- api-reference/types/StyleOpInfo.html | 2 +- api-reference/types/TextNode.html | 2 +- api-reference/types/TextOperationInfo.html | 2 +- api-reference/types/TextPosStruct.html | 2 +- api-reference/types/TextPosStructRange.html | 2 +- api-reference/types/TimeTicketStruct.html | 2 +- api-reference/types/TransactionEvent.html | 2 +- api-reference/types/TreeChange.html | 2 +- api-reference/types/TreeEditOpInfo.html | 2 +- api-reference/types/TreeNode.html | 2 +- api-reference/types/TreeOperationInfo.html | 2 +- api-reference/types/TreePosStructRange.html | 2 +- api-reference/types/TreeStyleOpInfo.html | 2 +- api-reference/types/Unsubscribe.html | 2 +- api-reference/types/WrappedElement.html | 2 +- .../variables/EventSourceDevPanel.html | 2 +- api-reference/variables/EventSourceSDK.html | 2 +- api-reference/variables/converter.html | 2 +- api-reference/variables/default.html | 2 +- examples/nextjs-scheduler/404.html | 2 +- ...d0264d2385.js => page-ae882aa4f8b3039b.js} | 2 +- .../_buildManifest.js | 0 .../_ssgManifest.js | 0 examples/nextjs-scheduler/index.html | 2 +- examples/nextjs-scheduler/index.txt | 4 +- .../{index-DCwEJGaT.js => index-D7a58tRm.js} | 2 +- examples/profile-stack/index.html | 2 +- .../{index-Bx94zqRc.js => index-DiI1EHxC.js} | 2 +- examples/react-tldraw/index.html | 2 +- .../{index-q-5ISMOx.js => index-B-Ld1ayL.js} | 2 +- examples/react-todomvc/index.html | 2 +- .../{index-BSvZl1Rn.js => index-CxBZH87P.js} | 2 +- examples/simultaneous-cursors/index.html | 2 +- .../{index-BKhO_6dR.js => index-BPneh9Tw.js} | 32 ++-- examples/vanilla-codemirror6/index.html | 2 +- .../{index-CXKQfVgS.js => index-VO1uos3h.js} | 2 +- examples/vanilla-quill/index.html | 2 +- .../{index-aMQmcurO.js => index-zFTIUwA1.js} | 2 +- examples/vuejs-kanban/index.html | 2 +- 104 files changed, 384 insertions(+), 380 deletions(-) rename examples/nextjs-scheduler/_next/static/chunks/app/{page-a4871ed0264d2385.js => page-ae882aa4f8b3039b.js} (85%) rename examples/nextjs-scheduler/_next/static/{6_IyhgbJWQCmw1jrIomT- => iUxV02k8f3BmWC_fcwSG3}/_buildManifest.js (100%) rename examples/nextjs-scheduler/_next/static/{6_IyhgbJWQCmw1jrIomT- => iUxV02k8f3BmWC_fcwSG3}/_ssgManifest.js (100%) rename examples/profile-stack/assets/{index-DCwEJGaT.js => index-D7a58tRm.js} (98%) rename examples/react-tldraw/assets/{index-Bx94zqRc.js => index-DiI1EHxC.js} (99%) rename examples/react-todomvc/assets/{index-q-5ISMOx.js => index-B-Ld1ayL.js} (99%) rename examples/simultaneous-cursors/assets/{index-BSvZl1Rn.js => index-CxBZH87P.js} (99%) rename examples/vanilla-codemirror6/assets/{index-BKhO_6dR.js => index-BPneh9Tw.js} (97%) rename examples/vanilla-quill/assets/{index-CXKQfVgS.js => index-VO1uos3h.js} (99%) rename examples/vuejs-kanban/assets/{index-aMQmcurO.js => index-zFTIUwA1.js} (99%) diff --git a/api-reference/assets/search.js b/api-reference/assets/search.js index 9a62e205b..bc000edb3 100644 --- a/api-reference/assets/search.js +++ b/api-reference/assets/search.js @@ -1 +1 @@ -window.searchData = "data:application/octet-stream;base64,H4sIAAAAAAAAA8V9XZPcttHuf1ndbjaDr/nwnWM5Jz6xLb2WkvdUbblS1Ay1O9HscExyNlJS+e+nABCcRrMbBDlr+0qjZQPdRDcajacb4H9u6upfzc1X9/+5+bQ/7m6+UvL25lg8lTdf3ezKj8X50N7c3pzrw81XN89FvS8+HMrmj92Tu8f26XBze7M9FE1TNjdf3dz89zZ0tDRGLfu+/vGP9supHOnqVU8Fery9ORV1eWyBQBcmYiF1z+Obw97SZfG464mTrO46iRiOr6vt+SmfJyC/huvbev+0b/fPmcN5B+mv4fu+/Jz7ph3pNdy+qc7Htqxz1dlTX/WGdZk7qB3pNdy+rx6+L5/LQyZHQH4N16ZsJzKOW0zkPd8NQL5dv38QmQJEMjMD8d2xfZ8vzIX6OpUfHyYwBeRTuco15xe7nv7o/5z04UZcVoNtdWza+rxtqzrV1auYjha7k4gZpP0uycA9vvTbNrs/7Js/nOr9c9GW+Vw+lV+SbPzz6/k0bdGemySrnuR6bkXbFttHu8j8UJySTDHlC/A+7f86Mqg9yfXcttVxt2/31TE9thHZC2jzy3H7fVWdXp/rwvaa1uuQ+HoJ6nJbHY/ltn3X1mXx9Lo8FOkxZxq8hCRt/eVdeMcMOQjyF5DitB13cK8g1fU826L59D/n8lwmeUKq63me6mpbNs3++JBkGpHN4ioX+rJ2FNs2tEjM6gtRpr+PeOzKLC4R2Rw+3uNlOMXZ7zHaf08yp//tY3F8KO0M+qHapcdqQDqHn3Vfo/5tZt91+VQ9p9+hJ5nT/0PZfvc62X2gmNn72ErXk8zpf998vY02eGQcdCGa+Q7vxkMTSDWTyzdhBR5jBAnn8PpQV8VuWzTplQBSzbLc8zEsYmnzjeiu98T1+fi/Rbt9zGEMCa/n/Fgcd4fS9RkQjOansjlVxyZtoSMNr5fssiR8Z3f/x+KQuYIA8peQwjr1TAkQ6fXcrRPO4o0IX8ouvvHB5bd1PbIxJMmvl6I8/mJjrPdF8ynJPqa7nm8XaP0IQbFEQPYjRsQm8MVbeeS3y+P5KfD0j5KbenGBY173E2I31turmDblOTvxSI5fZ/P7ei43PFrD9Qey7J/mjtnA+fO9vSIXgOErXCQkOQ7dfoIl7frzeK6jl4yCTM8x/Dl3rH4ojmfglYhOXvUktLC9IGT/P5XFod0/JcV8BYiu4fH23Dy+OR6+ZPECxNfwtFRvPn7MYnmhzeYozRLNlTenGFHZ2/XiY7HtfVpHkDYADmZL9jYA3IY2G6TLw5/S3AgkajLDtvpUHjP5Bdor2LHYU5pzEoWaLEQC9EmLMQL/zBAkgYONiTKCiOUIc3GWr6vtt88lyib4qQofZS8wbkH7xu3g8TI56O8VpqZfIhKR5NrFZfvqmMuZajGXu7WLie9NtJjN/VicmseqHWd6IZzL6/tqWxy8yKPsYtq5HH8qn6q2zGSJiOfy/O64b/fFYf/vDE3GtHM5urgng9uFbi6nvx3/lckLUs7l9rYum/K4LXPnxZB+Luc/DeAUjuefRiGVzHmRz3JAPokvDHzCnHZ01AISEeQHPlGiO9ndq2TRSywfFxpU53qby64nvoLhc3E45/ILtNPYJQsHMhjejRQTxe28jNzo4vUhn/1dM7ZkEHKMVnDUz2X9rvxlljyg8YsJ1LX4exlVB8wYpb6HK0SDkxusoOz8xjTXT3Gyx/QsHwg6eaLTTEfmei5bdrrTXNMzPpdpXfwLRS2jjGGTycyh4cA4iLWcAdH1pkN3mbadoayTjYdhO2I92YxZ82H4pu0nm23SgBjW4xaUYh8hKnh/xNoRTXm9MSX6TVsUI/pU7ab4p1U8KkAUweGtIB/KkZQvENPx/Y4Ed7Tok4OuBP+R6GtMADjQ3d6JHV74/PpBHfSWHspIuMkOcMhsxPflsGP1NeSW1hLDLDdEZtiNRchRs2SAvHUYGSi4yGZ+B5rmSjESjZ66HfAMYUDT+cLAGdMjAOyciSmunzVEf+l5g0ScPHMohiNzJ48lO3sojun5wzLMnUEsy7E5hBrOnkVjAozPI0qSK2bSqECjcylPIDibELbFzimK7vqZxfaanl+k0JNnGc98ZK5NYc/OOJ57et6NMM+dfSPsx+Yg2Xz2TMwTZnw+8lJdMSszhRudm1OEgzMUYPns7MQ0189Mssf0rBwIOnlG0kxHZmMuW3Ym0lzTszDBFFR8uFToZd9F1hjRRLmJza7dIImR6PUVbMPsYGjB6XqnfbOdIQRqNlOOKGHsiiEvm69hvgMRTKlOorJEVHevemI2eYLFZHn+udgfJvHtG8zgTYxkchQn1sTZEk3+XaKSuJ505C1SFXFtNj9AOp/fT66sPofdhXIiN7nYrISRYFXYlZ/tKceeqfXN1pl1f0/qBvcWcnqos/DnSX29r4tjU7j5SvWJH6dtSA7tclAZGh4ke8o9dhl1lnXwspdrwqHImEv+scgxXszByJjdpKORYxyrUzvGryN5CW7+DA5xCgWp7UL2MlzL7adTtR+zvVcR4UtwPlwyK2OjjEhfgntdVWNvbEnQCfIrxvlQHYenH9AQdzQz+SW3RwmOY/uhvomXb/6AQm53HX0Oy8wNzpgVRexhoxeQoXx2C5sN6UakiClfwrRAj28++Hx9vgygxYu4zONhfyx9DeSo70S0L8E/1xZ6uheb4I/7pq3qseXwQpW94M6Y1h2X8VswLs06uTjvVRz/dtxVE9neXZrlsZ94Hcg0KcIf9FRx+tfgB+enctbgdM1+58GxUoQ/yDmD416DGZzzDLM5//42cwYGs548JueEtdQzTKX+/e2kBkaynDwgdcJC9t0Zw79kOdAh9bydy77522lXtNT1CIghJJy5UEQHAc+2u7Hx74my3y4+5Hn+0Gzr/YcxNpBuHqfT+cNh3wxvMUDLbU81j8u+eVc8ld8eSkv0pv7mcX/Yvfk4qjmm0UtosTidDl/8luRtsR0eJY1FGVLPGwd76j13w4Zpr+CYtTGNKedxeyya7/O3hUPqeVzLY3Ouy28ydmgx5Txu27osQj1YhukQ5DN9Qtl+nQELAbK5c/XbowXpXpfPbVUdxpRIkM+2VOqSjYGRpo7xZfBgLsEYsBm5BiNn3lkz+2l8W41IZ/PLY3Udl6L+UDyU31SHQ7kdZYaJr3qzNx/+mcES0c7m+H+87N+Xw1tMBhwj2hfg+Oe6espxZmyjeTK01f999+bHEZ490Vwe76q6LXdZnCLSq+Z75nSfP9vtsPy5qt+XxGU0wwG8UM7j5qKRwSHGROSSc44xN1oaG0tEejW/fHbXcXOlflkIIEF+jR5z1qOY8gpug2Ragh+gvYIjm3JLcCbazJ7/f7e1En/68rZoxzY5A+LZcdqbCSgqQT6Pr0VEJ3EmG8zU9G4HOxrT8YB67hvbhPUExmSD2Tudt7gwi93lvB2rv8qw4x++ZPLDtLM55vN7SW55yyjZ4GreGXHC2+y8UyomKQ8fs98zJv410w4xs7v4v38QPZi4GMcPk11ll2FeKeZ4UWaevFMLNK8Ve7Rcc67Y2A7ftI9l3WRbIiafiZ9k5aI6qmvSexHXj/tDW9Z/L+tmXx3RwWVaArrFS8iSl3DqqF5sBDIyOeeXHPGMREn9ku/3ULbWYt61xfZTtkkTLeajFOVU7kSLedz5q1BjnuOXoeZE1BMmEUGezxcervXI9PHjxaTgwdP+aX5x+VPZNAV9VBh19+pCSssOhGMr0Up/GRd91RriF1HPZVlwdzNgbkX60w2jjPwiy1xPgZlB4rkMk/dhYIbj91+QDKHtDYpyALvwLN/ujvACUa6nV8fUB3V6gbiCouhuVpZHObiTdQqTbfV0OpQtOYFiPoAym9Vw/KN64gGv0ari2IIG6VW+w4wcKxCQYeg2DtVn8sI6zA/QTmCXe7aK4zZWRAja9QLyddb29ts/X6BzX13t/5jUUvItBr2MfT+sk4IX091KPJCz++u1gsJuxiQNgvCiftNNooG0lwfXCox6GpMZSMSL/bfjcK55buDJtYLjrsYkh0LR9fzv90/l+/32UzkMqC6PRk4egKCpGpY6oG5eVfxNrkAYbnNTV0/v3FmAUT4R6QR+uWcUML+cUwokw7jWvHg6VfX4213ocnYU43x35cF+S48oyMWcIeXL8HZxGQGGYM4Xutl8US7ru9fv2pqqrMKsI9K5xttWmaYLCOfzstus7LeLiOfyZOs2ML/Ryo1xXg9l+72fAl83mW9JNrme/wS+1/F7nT1FEfEVPL/OnJoR6Vx+xceclwtUc7mUv5wLotYHs+nJ5vKxm4GiHmKlw3Uj0E3ihI779UTIxXTH/dDja+MQsr+xYGQgY+YSOM7yjloNU6xHcO7hYpghA70uXiEFXhYzZKBWyGkSYMPCDsAL0f01vQ8FUWYaSIueJvvMjc2GPWaFZ7GYjFqec1/i1fMUKJ3jjVfYHMaebNo7Ys+fw+fhWj5PxWduFSXYRdTXcc1kdx0ft1K9qb/95Ux8wIhgiOiv4Lwry9O2Og1rTAmugPYKjj6HlMOvp7yCW7P/93BhpSaCp7uC07316EVb1T/n8PtHoP7HDK6x430ToPEoFeDdb/RsZHOO4oTyc5vqefB8Uu/dt8pTDCiSSTy+ruviS4rDkGBS/76iNjn6Q4ppOqjLMqkD/Hza+Ox2b07UsIS/Xxv7xR2NBX0XcZjlNJfDXR6bsQoGWByX4nZKFcblctvba0Cy2AXKyfyGN5LYYxhNSdpA/PBaQyB6G7MGJF2+SfC80naB2k02jgTfpIVM4hvfiTXKeOxOrDRnbDD+LhzSXOCja41l0NeYqURy5RsKxydtJlGryUbC8kyayASe8PKaEZapb41N4Eh5LpZn2nmluWJzfFe2pC32f7/WEOOOxqzwIk6+CZIc0vZ3aTLZ+GhuScvL5TY0O5pZyuYSvLDqf+D80A8v5oV+mOaDfpjjgWgeaf3/cIX3YfglLSCfX10+76tz8x3hDzjGqMmVElCeiOGc9kMpjoN0+W5Pu6HLg6uT5nFPo3nzi0T5pkjzSJsiaDPZFBl+SVPM5mfzuXn8Osor+bUjuu9Hk7/wIpsXFQEy7NLRX4rjbKOM7sdN3NEzYJ6+i7ho23r/4dyCwwgTpLiLmk8SaEQZ2+rYloMbE/OEurS9UqJBXNR+OdCrI3hydWyEuhqNjoBQE+IjmstIhAQaTY+RGI7pKCmbI+GZOI5J15TPceCb2DHlnVM+N8o7cQxHPsqS4jnfQHMd1JD9TA+VJ0eOi+JEGvcIFiZk45T44dXp3mFvo8neWLp878DzSjsI1G6yj0jwTbqJSXwJT5Hgm3QWk/gO/EVqlHmXMYkn5TUSbNOOYxLn5nTYt9+Xz+Uhn33U5oU0/XaSlYEWL6Lxadx7+nm8KefEhyzo6Uu4p6mhCxZwmoOaFcLghrNc1KxQZhpnxknNCmmmcSbd1IzQZvr7MpMl9c6j82XKe0/knzFbrwvvUszHPfW1Yd4o9/FQjxZjZriXL09OyJcSbawkrO/9feVx9ZeQFPT1EhJfiifenN7FX5nxn2QIf06Xj6FvHaf6eBUoaPF7Mcje/VdPk933JHP6twdvo0PQFAdAlM8DFNi9rW3t4R7YQ6hS6Z9cdYgj7iV1huMiCdO7sxp7idefvrTEPRSI04B6Jld3lKujeU9dEIH4EvQzOe+bd+cTWeKGWELC2by+O7blA1GINeB1IcznlVt+iZjllF5S7IarVI7mIGFO4WUe5yyuV3DMuaAOsRy5oS6DS+KKugGvjDvqst6LuzKAeLmxuwJG+bFlkIjZaAlkjnvJ9CrXOpMfz09lvd/mcMPE89/t7zlTANDNto+sNeFCNv+NvnGX1e6+HjVERDuY3/vjY1nv/ffTJklAnKoZsqZPu83maXOgee98oXw57t1nt7L4Q9qXk+Bt1extVWWmEIj8heRosvXQ/Ap6aCbooflV9FDHGxeGdz3cklzFdd/g78OxXpP6PNx03jEg1tP8ndhtxw8nlfv+b12cTuWuuzse9Rs/nNSvXejpTsGTyT2iq40vHfoHk/tztd5Ed+7v2aeTupr0gWF0f3+RE0mwr6yAOAg1ORyOOE0NhnO4ZnB8GW4umf556KXwWLb4CpkrOI5bwqsL0TyOsVvqP2GbZhrR5VpMRsgRMRkGHNP6p8NEzCIdJGZyGTd9RDmL274rph7TTU81i0tqWxQxytkUUbzIUzrUQgQfZbvP99QctX98EcfZd5R3wYaVZaI7iThM8CUpXiOM5nPJdR4XXhmeI8WDdhuX7tM+I9Vzudunxqh7PL3fXRnd1jXsuSeYIfPTqR3CCUDo7vn0nht7JvvLISU3IJnevyuO/cleAPe+els1P5E3zkOrIcmn8z11jd9X3/VdJvgy5NP5pi9AuczErKtPEnxcvENcJ9Fz6Any+l5KocFdCOXxgbjO/dJ7TzBrZtvEzp++xMXd5BSPCa/hNeJLANUcnWfo+wpdM7gs7D0JkI71zQUBMYOxCCDFxX+jyc2qcWYkcSbP4bHjt1VD300Cn11dCjLobLQQJBKNO4Swy+Vzt+c/Kx83mpUYT7DNyIkT/K28XLw0gEgnCHG3JUHTDHFGUuDVx4/wFowpIvVNX1KeujwUFrp5M02uQbNZJpOcZ/FSSwjkCPLD/LokFu66TPeQHeaHjvLCfCsLe2DIxbvkN8IuXGKqrEA8wZPdWsC3mhL0J3i1ST286h7P4JK9tcCDmNxaJHgwW4u++5GtRaLnD+f9YTdiAZBmluzv0oNzoZjV+4/VrhznAKjmjb+N6NIz+xUim86nsZsW5sNEFzYx1UwuY/3P6tmnIpjdWd9/TDWdi93vftd9MzjBBpFdO89td6OqiYjmvdmfzodPeXwg4TxeIxyueocM6Wf131b/74fvU269ez6nZ3rTArpOb1pG+mb3ERGD0Q3ECBdbd5jHKaac5RXtqmBJrHdNO0ZEOZ2bw1neVyMTI6aazsVWh3eISoJLTDWPyyjCFHHLBpjGRjCf7TRgK/W2WcDW5XUnAVtZfN+GEcxiC6kzuQ7PdEQz4lJybP88KXnbJZCJ7sCTa8EA3NXoGXsgVP55EIbLyCl70Ci35DuTb8656GzuW/sp+rocfDiA4Q3IZ3CmdrOUwXV/fgmsKNs2elkmHBQi+h85IRRazDiwQTEbOanBcqNmPvpG7WXu+wdJZayJnqIEri+Jjx/mng74Bh3XZ/t69c3I4XwkHMkt3gXwvMb3AWOcfiJ2HTy/nzJ3HyTXQYb4p9fvg1t3994PUVuK5NoJyfY5+oEOSt6JqOYY8wxAk+xiBpo5KsoIkJknBzXJ09jhgCC/wor+wHWG6yCyF6luXvUkzNB4QZj+E18XgTwyviwy4JNdJwbfJadMDDPi8hYUgz1Z40gVMSW5EN98o7gxH3ubyzV8O3Tctl4NSK/njj+qR7GlvqY3gV9O9RbgNlK8Ndb7DxkvFJHN4fNYNG/yjAVTznyrTG6Ycg439usnkNHol09Gx+9tvtlT1DPHcQJXinoO1/JzuT2PePsLTSaHrG9FExzuun/7rxePsLxD7XjXaeGqtHFyItxdGk8RZTSf+VzW9vrYmUJF7a+TK7+eB0qWVdGTNj32Q00xn6kxgIpCgOeyhqXGz0W9tx8dbP7YP5sfT3OdjQXSF7EY63AXH+CvgI9wu0ONRlhPLIyYwrwvBVhmixELz23+K6/rt8X2U7ZgqNFvOyqQeRgVuc4flUj4hK3MGJdBs9/eXoZjI+Q0i5kyOs0M2Xjn+uuPS9MPip4zKA0/i8KmNX9E4ja/9RzqeYcRURNGBIqesJHpY4Jb/fZ2MhgXMcG1xOJzcZM7L/YenRcekw23+m1HJuLeO90JFhOLz4zMhy/uRhd00m5MNtzqtx2ZiHsYGZM/MLH06YF5dyxOzWM1eWhAu99lcAL/MDybycPTv8GvLFg/6Rf9L74mdUzY8OeRTUs1X6FJue/qVIHYNOHHr1p3QWa+O5v0IrD73+BturZ/AQUHma/zl0T1wa88x/5Sfu5X8snDZOVmBuPRFm9MW6qiJr/tYFxY94vUIn80gOBsnPeX8jPayI/HWrDNbx3n9bx765gwIFB0dkT+tj+26/g0+7hYUaPfekwuzPtBmbCrjoRnR6XHZCfIBdv81mPS8+6HZMK2EYo+gjOATEDuRj+RGvi1MYbvXvd+ZJKF9IIzo/H2w+TRiJpMHg1qgZsswrDd77LUYdVMj9DG1BOC8slzmGj4+2xH8GxeTd+RjM3oZ/g10GnhEtn0tx2ooQi945uw4SdeJBVH0d+SzgpqcNPfIa6KPxob/OKEZYJ4EarQ6vvqIb4B3ZcOhT/nFle9r/fP+8Hlq1Evry409Cv0opAcXpcfzg/J/gPFnN6jy8epzjuCOX3/b1Efk313BHP6/raugXFTnQeKOb3/uWhHdBoosnvXYqPVAtzBX7YDE3yqdudD2fSZcEBA2iHIl337XB5bfwPu6/L5bXEE3V7mHUGVNHSawbvXf033/e71XycVOztB3lfvXv8VF1m0/vov/HxS7+9e/9UWdx/LA9374Pmk3v98PhzG5CdpJnMZew+SJslFAyfz3FbVocGm+MfwYJK03xz25eBatL4n/5ToEEygXp5J9ZEUi7GMLmrDVkW6pyCMHeV4B5pksc6EvyZIcBrLKY9KkH/rXd9V+vq7l9Mx5pOtaPgO+cXqY3zThetk67S+hx8XHRUh9Z3RGRJQZfSjMqRL6mdIwdUjj0oyXo+cJ83werBjW+yP9AVhlxkVUf263m7IKt/rxS8zfriJ+FpN3xmk+VXfeMAo+32j1xgvCs7km7rUhG6ctvk5757pgCZI0TWeKkff7OUkaeA5/1w5mtSx/zlSJP0hK0amQ5wgRz24njhXlpq8rPhaeYY3B2dPG/Iq4avlOdqy3ufp0vTtXlSWH+HFJxNk+RFfh3KtLMxZxXFhRk8tzpGGPbc5Lk/GCc45Eu3K0+AjU+PChFYvaTPDL3rnWEzqWPo8/z9jOJLfWZslRTXdQE6Jou+0DD/fdsP/1X8C9nzz1Y28U3e2nuTjvjzsmpuv7r1wtzfb6sntI37unnnA0VJ4kj8ubm7vF7dmc7dW4uefb+9DC/fA/cGRiZvbe3Er5Z1ROiITEZm8ub2Xt0bcKbOOyGREpm5u79Wt0XcrqSIyFZHpm9t7TZHpiMzc3N4biqmJyJY3t/dLimwZka1ubu9XFNkqIlvf3N6vKdnWEdnm5vZ+Q5Ft4uFdsOOL9OAUQSpMxKqwBa/3QpCUsTaE4rQmYn3YctF7IW+1uFOr+HVErBJhh16oW72+W2sTU8ZasZXc90LfanMnloh7rBhhFSAMNZgi1o0tVrwXS/LVY/UIqwaxIvuMNSSdhtZUnzJWkXQqIpUu0Wxx02VBUsYqkk5FgqSMdWTLEe+lJOWMdSStIqQiKWMd2azvvdQkZawjaRUhDUkZ68jWqt9LUkcy1pG0ipArkjLWkS3quJekjlSsI2UVITckZawjWwBwr8gJp5BTc16N1JGKdWSLjO+VpGxexTpSVhGKdpWxjmztxr0idaRiHSmrCEXOIxXryOYA7xWpIxXrSFlFKNJtqlhH2ipCkTrSsY60VYQidaRjHWmrCE3qSMc60lYRmnSKGq09bvEh55GOdaStIjQ5j3SsI20VoUkd6VhH2ipCk/NIxzrSVhGa1JGOdaStIjQ5j3SsI2MVoUkdmVhHxipCkzoysY6MVYQhdWRiHRmrCEPqyMQ6MlYRhtSRQSGCixFIHZlYR8YqwpA6MrGOjFWEIXVkYh0ZqwhD6sjEOjJWEYbUkYl1tLSKMKSOlrGOloJdYZexjpaSXQ2XsY6WTkek3pexjpaaXQ2XsY6Whl3jliiSW7Lr5jLW0dIqYkla3TLW0dIqYkla3TLW0dIqYkla3TLW0coqYkla3SrW0coqYknGuqtYRyuriCVpdatYRyuriCVpdatYRyuriCVpdatYRyuriCVpdatYRysXbpMWskIBt4u4SR2tYh2t1uwqs4p1tLKKWJHaXMU6WltFrEhtrmMdra0iVupWybtVHNKuYxWtrR5W+laru5VaxZSxitZWDytzq/SdWCPmsYrWmtsgrGMNrQ1rSetYQ2urhtWSpIw1tHYaIu1jjXZFVg0r0j7WsYbWG3Y0YwVtFuxobmIFbQQ7mptYQxunIXpfFmtoY9WwJo1zE2too7kX2sQa2hj+hWINbZb8C8Ua2qz4F4o1tHEbV3JmbNDWldXQBm9eF6yc/hmktZpYk/PNP4O0kpPAP4Kk/EzyzyCt1ceadMv+GaQ1vAhoI7tYsnr1zyDtKiEu2swu1jw2gHazC6uYtb7Vy7u1QpvpBVKaAxbWhqQdgA5OafSGGsMOglcaxh0cvMCMGIYeHMDAjBgGHzz6QI4YRh8cxsCMGMYfHMrAjRhSmsMZ1qTLFBiDEOxEEwiEEJJ3hgLBEELy7lBIjBVJdsQQEiEc3sCMGMIihEMcmBFDaIRwmMOaXDoEwiOEQx3oEUOAhHCwAzdiSGkOeOBGDCnNQQ9rMr4RCJYQDnzY0KAdAiaEgx82NGyHoAnhAIgN7UsVxvisaja000PwhHAgxIbcAwkEUAgHQ2zIeFQgiEI4IGJDuxEEUggHRWzoCYRgCuHAiA1tOgioEA6O2NB6Q1CFcICEWNCKQ2iF0B6ZpTWHAAvhYAkS1hEIsRAOl+BAV4zPah5MRaiFcNgEA6ci3EI4dEIsaEtD0IVwAIVY0KaG0AvhMAqxoG0NARjCwRRiQRsbwjCE8cojEX+BYAxhvPJoc0NIhjC8s0RQhnCABSsE0p7DLMRiTRNjgN2pb0EbMsI0hEMuBJM2QLCGcOCFYDIHCNkQZp2SGenPQRhC0GaE8A2x5FMiCOAQHuEQ9HxCGIdY8tpDIIdwUIYQ5GZKIJxDLNkdmkBAh3BwhmDm3hLnR5Z8v0hzS685cksnEN4hlnxYiQAPsfR6o2cHwjyEQzYEnSkRCPYQK6852ooR8iEcviFo3Ecg8EOsvNukrRjhH2LlE1u0YSIIRDigQ9CJE4FQEOGwDkHnTsQKJ7ic/uj0iUBYiHCIh6AzKALBIcKBHoJOogiEiAiHewg6jyIQKCIc9iFsKoVwAAgYEQ7+EHQ2RSBsRDgEhM59CISOCAeC0DkNgQASsfa5SdoyEEYiHBIiFG0ZCCYRDgwRirYMhJQIh4cIOmMjEFgiHCYiFG0ZCDARDhYRdN5GIMxEOGREqBWZqkWwidh4/ZF5b4GQE+HwEUEncAQCT8TGRy4LcquAABThYBJBp3EEwlDExieYaQ0iGEU4sETQyRyBkBTh8BJB53MEAlOEw0wEndIRCFCRDjQRdFZHIkRFLjy+TydIEaQiHW4i6NyORKCKdMCJoNM7EqEq0iEngs7wSASryIUPPkkNSgSsSAeeCDrPIxGyIhe+SoBOayNoRXpohc72SASuSAegCDrhIxG6In1BB53zkQhekb6og077SISvSF/XQWd+JEJYpENRyEVeIoBFOhCF3tdLBLBIh6LQ+3qJEBbpCzzoXJFEEIv0NR50JCcRxiK7Mg/a4hDIIn2lBx3LSVzr4Ys96ABN4nIPX+9BR11yUPHhtEfnmSQu+nBwiqBTTRLXfTg8hU6OSFz54fAUQWemJC7+cIiKWNKTBNd/OEhFLJmRQwqUXoHMyCEFOlBF0FkqiRAX6VAVQSeqJIJcpINV6ESIRJCLVF5/tDUjzEU6XEXQqS2JQBfpgBWxYmp8kAIdsiLotJVEsIt00IpY0dpGuItUKz7Ilgh4kQ5cESvaNBDyIh26QvsiBLxID7ysaFeLgBep2dpEiWAXqX2Cm/bKCHiRmvedCHeRHnehM2QSAS9Ss+i0RLiL9LgLnU+TCHeRHneh+0V686jLirZihLpIj7qsaYtAqIv0qMuatmKEukiPupDQlkSgi/Sgi00cUR0j1XnYZU0vIwh2kR52WWvScyLYRXrYZU1bJoJdpIdd1rRnQbCL9LDLmnbgCHaRHnahd10SwS7Swy40tC4R7CI97EID2xIBL9IDLzSyLRHwIj3wQkPbEkEv0kMvNLYtEfQiuxoT2sEh8EV68IVGtyUCX6QHX2h4WyL4RS75CYjAF+nBF8aaEfwiPfzCWDOCX6SHXxhrRvCL9PALR4z05+EXGr6XCH6RKx61lgh9kR59obF+idAX6dEXGuyXCH2RHn2h0X6J0BfpABZJo/0SoS/SASySRvslQl+kA1gkDZ9LhL5IB7DIBa1thL5IB7BIGj6XCH2Ra19uTMdmCH2RDmGRC6ZAF2nQQSyShs8lwl+kg1jkgtYgwl/k2pd60RpE+It0EIukYW6J8BfpIBZJw9wS4S/SQSySRq4lwl+kg1ikoN0Rwl/kho9eEPoiN2xmXSLsRW58vbi+1Ys7tZKIGGnPwStSGAoCkgh7kRtfpUfbBcJe5IbFriVCXqSvYKFfDmlus069HC4e37A5XYlgF7XwiiPNWCHYRS1YxSkEuii+jkUhyEUtEopTCHJRCz7dpxDiohaGV7JCiItyoIqkMXyFEBe1YJc9hfAW5SAVZiBQQflikxoIpDiPttADgcAW5fAUSaccFAJblGCTRQpBLcoXs5DvhqAWJXTi3RDWohyeIiV9AgGBLUosE1pGYItyeIqkUyQKgS1KsOkihaAWxdezKAS0KLlIjAQCWpTDUqSU5MshoEX5szWSPIKkENCiJF89phDOoiSb51MIZlH+hI0kMTWFYBblD9lI+lwGglmUP2dDJ38UglmU5FWHQBYledXhszYqpTp83EalVIdP3KiU6gaHbhKqw8duFK86fO5GpVSHj94orzp63cCnbxTvLvHxG8W7S3z+RqXcJYJXlENQOG0geEVpkdAGAliUw1AYbSB8RTkQRTLHtRDCorQ/1kZWuCqEsCjtT7aRiIVCGItyMIqk04EKYSyKx1gUwliU5pWHEBalU8pDCIsyKeUhhEWZlPIQxKKMTIwxgliUQ1G4MUYQizJ88aZCCIsyLDymEL6izDIxSRG+ohyEIulMrkL4inIQiqQzuQrhK8pBKJI5e4fwFeUgFElnchXCV5SDUCRzAg/hK8pBKGR+QyF0RXl0hYb0FEJXlANQpKK9G0JXlD/EQ5/vUwhdUf4cD50hVghdUQ5CkfQpP4XwFeXxFRJ+UAheUQ5BkZo+uIngFbXiS90VQlfUKpFaVwhdUatEal0hdEV5dIXOlisEr6iV5gEFheAV5RAUSWfLFYJX1MqfC6ZnCYJXlIdXNG2gCF5RHl6hs+UKwSvKwyt0tlwheEU5BIU5e4vQFeXRFTqzrhC6ojy6QmfWFUJXlEdX6My6QuiK8ugKnVlXCF1RHl2hM+sKoSvKASjMkWUErigPrhgSslQIXFEeXKGz8AqBK8qDK3QWXiFwRXlwxdBhMgJXlENQJJ2FVwheUQ5DkXQWXiGARTkMhSzrVAheURv+1gSF0BXl0RXGFyF0RSWOBykEr6iN1x5Zp6kQwKIchsK8HD737XVHJiIUwlf0gp97GsEreiF4d6ERwKIdiiLpSgCNIBbtIRY6Ba8RxKIXibokjTAW7TEWOl+vEcaiHYxCXluiEcKiPcJCWpBGEIterHlFawSyaIejMDIg3YkFr2iNMBbtYBRG0Qhi0cLrjlyeNAJZtL+qhK5F0Ahm0R5moc/KagSzaA+z0MdlNYJZtIdZluRJaY1gFu1hliW5smsEs2gPs9BZQI2AFu3QFEkXI2gEtWgPtdDFCBpBLdpDLfQBWo2gFu2hFroYQSOoRfubTOhiBI2wFu2xFjqC0ght0b6ohZmqCG3RHm2hKxc0Qlu0R1vocgSN0BbNoy0aoS3al7SQmzON4Bat2HJ4jcAW7cGWFenANQJbtAdbVrQpI7BFK688+vYOhLZoB6lIushAI7xFO0iFtnqEtmhfzkJ7QwS2aIeoSPr8rkZwi1Yp14kAF+0wFUZgpDqdcp340hOdcJ342hOHqEj6MK/GN594uIU+easHl5843dFnZDW+/8TDLWt6LuErUDzcQhdQaHwLivbqIwsoNL4IxaEqck1bMr4LxUMudE2ERpCL9pALXROhEeSiPeRC10RoBLlok1r8EOSiPeRCF1BoBLloB6tIuoBCI8xFe8yF8bMIddG+qoXxswh10R51oUszNEJdtEdd6NIMjVAX7VEXujRDI9RFe9SFrl3QCHXRHnWh6xE0Ql30UiZCAYS76KVKhAIId9Eed6ErHTTCXbTHXehKB41wF+2gFUVXOmiEu2i+qkUj1EUvWchTI9BFe9CFhu40Al20A1bUgtwVaYS6aAesKLrYQiPURa/Y/J5GmItesfk9jRAXveLhTo0AF+0wFUWfltQIcNErrzh6giDARXvAhU4oaQS4aA+4MJ4WAS7aAy6Mp0WAi/aAC31oUyPERa/ZpLpGeIv2eAsT5SC8RXu8hYlyEN6i/WEiuvRFI7xFr73+aGeB8Bbt8Ra69EUjwEX700R0KaVGgIte84CnRniLXifCTgS3aH+WiC7R1ghu0Rs/9WgnhOAW7c8S0ZXiGsEt2mEqTFSE8BbtMBVFVwFpBLhoh6kougpII8BFbzxcRrsWhLhof5SILtHUCHHRDlZRdMmQRpiLdrCKErQXQJiL8ZiLoK8pQ6CL4WtaDIJcjENVFF0HZBDkYhb+akT6XjMEuRgPudBbYIMgF+MPEtF+yyDIxSy8/piL7dDtbnxZi0GYi1l47dHX4CHMxSzYMniDMBcjPF5GX5qHMBcjeN0hyMU4VEXRhR8GQS6GP0JkEOBihL/Xkr6QDwEuhr+kxSC4xThERdEnbg2CW4zg9YbAFuPwFEUfzjUIbDGC1xuCWoz0eqPnHIJajOT1hoAWI73e6DmHgBYjeb0hmMX4o0N0/YJBMIuRvN4QyGIkW/5nEMRi/Lkh+qIEgyAWIxOXDhgEshgHpCi6zMAglMXwKItBKItRfqNOT3qEshjFxpkGYSzGXyNLn5E2CGMxfEWLQQiL6a6SZe7VRJpTvOYQxGL8dbJ0Xt0giMUoFhwzCGAx/kpZOgVvEMRiNK83BLAYD7DQ2XqDEBbj72mhs/UGISyGPzBkEL5iHISi6MS+QfiK4Q8MGYSuGAegKDpXbxC6YvhiFoOwFePgE0Wn9Q3CVozmPSW+aNaBJ+R22OCbZo3XGz3f8GWzDjpRdLGAwffNOuhE0cfJDb5y1kEnik6Qm8Gts4Y/02fwxbPG3+DMXFKLdOegE7JSx+DLZx1wouhj6gbfP+uAE0Un3g1CVYwDThSdeDcIVTEOOFF0Mt0gVMUsvf5oe0Ooill6/dGWgVAVs/Q3RdCWgVAV41EVcplBmIrhr2kxCFExDjahT1obBKkYh5vQJ60NwlSMx1To1LhBmIpZ8R4TISpmxV58ahCeYjyeQhZiGwSomBVfuWkQomJ8DQu92TcIUjEeUmFukEaQilnxekOAiln5i9PpqY8AFbPiVzoEp5gVvx83CE0x/rpaUhcISzEOMFHMpdcITTGps0EGoSkmcW2tQWCK6W5mob0PAlNMV7xC1pgYBKYYD6YwF3AjMMWsve6YO7jxdd1rHm80CE0x6wSSaRCcYhxiorgLvpECffUKXcxvEJxifPUKXUNqEJxiPJxC3yFhOjzFfWjGfbl6953/4Mz9ff/Vu//c/KP7Co0I38H5z424+eo//729EQv/71qH/6+7H8J0P6TsfpjwY7kIP/q/hObLZfjR9WOvrvA/1Kb7oUX4ER5pE36suh/L8GMTiDddz/bATvejo7GnO7ofHVNb3N/9CH9R4S8qtAq8bKWq+6EDsU3S+h9BDAsw+x/rjrtZ9D9W4Uf3gnYL3/1Q4YcJPwKxCMQyEMtALAOx7F7ZBHns/qP7ocOPnqYT3sbQ3Y/QYRheE17Zhnb+R9CXXUe6H/1fXIf/vXyWyP7PGl+xbffPRRtZljQX05KrkYY72FJvLi2N4Fvaz28DS16uAEO5SbXbR/zsCdpLS9ONowzvb0/SMn3tdtXxsD+W2+6DxKBPA2aWvRKH7+G0d5+8BCMnFGi7WXBtP7ZlPAIbCdotVapdVZe/nO0XxgHbBWy+YgfwtHffgQV8wcAHI/Z+gGx+OnzZPhbHh9gPaQU7Ye3l0vpUbD9FPUjYw4od8UsPTSyAhAIsU8131bZ8xgrXS6hwVmm2fXMsTs1jhdpDV7xJit+0RXtG0hvYmtfd6fClrYtjYydedSTeAk6iBWv4tp9/Fe32sWnrsniKu9BQFNZl1HXxpTqVdWEFGU6BBZBjzZpD2xbbx6ghlJ8dBtcsdjobaMQqzdD+6ak4xd4HNGffGXxXEIgswYCp4OrtKaVuMVqGpSe46HXixToGbeW/xRkxUsDE7ZkJupMPdVXstkUTGYYCwxOW7VVY0P3aSnV1th92rGJLtxUvfV+2zoVp+8W9hp+qscO2iM5lhRjr4dF+thA0lmvQmLWRrnH14Z/lNh4JuYTtR5j3Fh7LD7vQ7Oj5LihvoaCdG3b8t8WxLnfRzLJ3aF0sdRniLcGNw7Y4no+4C+hplyEcE5xBDb29TbheTGDNOTtK9/Zm4gtzneaJ3Yq9BgvECJyT75aHL8ftU7WLpxAITRTnHbeP5fbTqdoj17qAA685H3H5FiocLjhj+rhszfYxCEfgyu5b94Hokh1918u2Ou722IDNAlpfsn2sPRhpiRAd25v6u41Fb44hmF2yCna9VycrWuRODZjeS24Z9q2b8pfYOkBTqUbaDtZguHRqdjodqmMc+MCpINhwd1s92S+MxuEeNGZejdXT6VDGsbm9egy86VjTj8e4MVxjWe/VG04cqMAhZke4Oh7LLdoVbBZwgR5puq+OfhJHXSzBWy9ZDeEeBkESXL/Y+GZbHZu2Pg92KTDKDFvkftdrgi9ddX9RYdNsj5r4KCBsLnXY52neD1THttgfy/rZfyMceBS4PTFssGw7wJ4E7utU2I/agqREF5/jLuAUVZvwPot+r514H4doRCOqoEnZMgCu7fmIWoJFOCAJmzDuCb26fvjIdQGWCHvFTbKbgWIktFHN7hu39a5t67I8Vrtyv/OGFq8YBi6w7GypS7Rrt9VNoCErvmvIbcRAF2KE966ITWMFlKKVCBYeQI4V621cb7WV52NV27gp7ha4Ss2u+7uSBDLgxo4zi0vTGMqIbHO07d7axDHelsN9oeb29Lvyw/kh0qOGSzS7Ru/K8rStTl9iC4bww7qLNhQ79LvyY3E+ROMNePMvjRclCYMzLfhXPeyf9hj6WEOZTfCnrJPvPqoOHSIMqFnMZVcONpzQl6WbofUM7hgVb5K2JWkX0FHwuvEfI49fFZrGkm26b+h1GOIUbAxMQiQLuIRrdrC6phiqXoLWbFi4q7bnJ8QXmIYKKy47Ibr2w/BuAxEWNmTq2385bok+4OqvOBnK3T72XksFJ0bAndlJbdt/OB8ipyyh2rThJldo+uHLqYgniITxl2bjVNfBsPF6AxtzmreNKVO3Bz2ArXOT2jYn0FQJ3lyxm9TyUNr/H9GGT0Gb1UtumpZPpzZ2oku4AAtukpXHX87luWyLJtIWRPPYLW55bM51OdxQQGhAsDCug3/j0HwDfSjrF8q6RiHtCkLdfRrCcFPEdYC3FHCNZSencwtNda63Nio/FcfyEK95Gq553FINeml2n+IOIK5k2KFzHQyBTxj5Cf71L62rD01ZP6OVDCKfwrAG97ncnlHoJqD0LAL9sWgLNGwKvjXH8eP+gBZdCRENueZcgm/4XNbN3sbvw7wNhHpZ7PRjXT3F0xqCmSFlpkLIqELOS7HexvZIR7AKugwjOHO8dBCvr1Ayw05923rgJyN8SYcEJevpXR912ZTHLTIFmEJbpMZ0uHcQcH8rTUh8siC87SXsRdBAwPnIa/Z8OLi53FbN7tNT2TQFQgujKJrNLNl+mt2ntnKdkf3AUWHzYw9F/aF4KLfV4YCgX/ttGLCz4QbkoYxbbeCOcMXNrwcb6Q1zk3Ddluy7P5QtCZbCzbpg9+iuNYlZQg2KlOhuGcJIv/1KDxgvziPa5hTKCFFyFhOwjcmdJMzHKXYZfChbekMBwx255HzbQ9l25nKIIVsBUxSCTdhE7Z0/GSzncBQEuzF5KBHSGuV6giMJmzm9CD9CYYIOJRh6w86LsnV927keR2dw36YTWkZ5YzibQrbLfhqKbX8onk5VjZwVnFws3ntpXDRNW++PD3EnEJVk1/2HsqW8Clyw9YZz97Zx9Ty0UphXY5dQ2/gL5ejtx28AnpqYJM477/+NNAc3Fuwm8qFse7grdvAQzdRszty2bx/LuiGQGftlGbD6J7o4VY3zEMMhhGtmynzoAYRlKouE6kNrIpsFU2qaTb6DPsiBgCGwSBhy6CQO3iF+IUXCkE619Xb75xLvr+21b5eBZPMJrovqM6oAgWaY8tU2Hdm0xfYTNQQQ+5QyoUmf2x4YApR/nVgqh+sU3JezoGfXcpgStp+BA+1Tr19VPW4b766hCbFbl4eybcrDR9J8oAtjQ1bbwcAJREBSYtQtnhEbnYI7ntTCMYRC4PoYCvDEOuGC7LB9+BIvchLmsTSbi7+0ds2iDiAsIhPTZjBbIP6m2AzKQ9na9Dlv8jC8S73AMFMAd7tq1WdREu/g+hiiM0JHSbkxIQYjATdwOtmc3wNC6EFyg/lYHHeHMqCSGIeA46G5Oey7cKVLPVRXl82pOjbRS0H4nMUjHovmUG2LA1VOBrMGgi2cfCwabmmFhsmWgz0WDb2qwfFccHE/aE2tajA4YPNhj+XntnKVKnH0CbdaLErsGrNWoeCCZNiKice9rXaK16MozcoGdGizBDd3fQHwJmx/Q/EVu5XYH+1GpEFzA6pxwXnI0JSqBYVhAWsHQ8cGwSAZksdqEYrKQsmF2XC6cR0VHw7R+8CtrFD8SOzKzy4X11anqqmxaUlYqqtFX9/GzTO/7aiGkDSESXktoyFVMKNmWCh8f9y3++KAV0sYr6pNsI5QNK/ZrMalu7gkAYwEm2EDbYfFCDDZynrOrodhKR50c2zV4/7YHFEOX8Fw1bBQyP5oPcxz3BLClGywFfIA5OyGCDeb49sPU0gRtsoaviuOfUbQEQyN2Ybl0U4YKulmv5oMQkTW0hv73g8IZ4WLkWJTX/vmeH4q6/12GKrAjTaL4uybLqyO7R2GOetwWoDFcvZNUzyVXTKlql01W/UxXhmhb+ZtvmnOJ7zblzDgVGw2Zt+cT7uixbt8WCgiVuxEtWUEaCWyH1ICSDfnMv7ZVEdX1xyPYFQ6y2netu2GLW4N4+RNKP1jjd52M9ygSDhbFevycV1/VCnqOYdqT9GD04vwI/hAs+LekcRv4J4vnCeSS26xP5THB7QKrKJQjVOrC9RiW4Jzml09XDuyJBpuHdigAMSHkdsHWuWH69J24PZXwJbZDScbnMLqIMHmUw/Vw6F8jnNskG2nbjbBcqiODwMPDBFh7sWfiiM6mwJhLjZD9VTEIRCsmpVsCP5UfCbsUsK8r2SRcwIPFFC3UoZ9GTvxrcul4r6o0pibsXhZFnAy2G/U8s1wBhZKzUYx3rUkjm3AIWft0vdCbhtgbMDOZZ83xbGp/UQueHfOSsik6xKikGxhBlrIYPAkw/k5xeaVqo8fmzgzJGElrQ4n+TS7vsDDZvGEjqYVe7IjUbQI0UMWhaG3qvZ6MWDwoYqTTVV4Y0e7XRhNshBCdfJp+9iNR1kE1uROaMQWUSEuZywjeUkoNZt7sHXbqCAJbs8Ni/oP9jtwQZahVFVuQonwIhSvhsJ6JfpDryEbrvofgaY/+Ml6KCtHajcHj05pNlVme2mr4UYV1sFpfhA/0AeB4LqgWdbI2iBWaljYMrxrJzSxi4VVSeEYr2bn/6W/fkDjgYDdseU3FNyzhst5CMNEkEiEo8+yP3PMhlcJOAhWt2g2hIw7iJQFlyZ2QUXth9tduPVjSwroFAksbRbhmK8wIY5ha3vtDnZfnZuh7Uq4MRPcnqjPuEQAIxjNsHKwEzB0MASBoSdR7IJ7qqtt2TRoQySj8yPppjjQgK6PReZO5w+HfRNjzbC0Rqy4uVIX/xqa4ApY4KZbLNmTwnVZHNr9U9RBhDyMNTydm8fqeIh2RDHoMdKBLQGtPkYhQ1xkzLbvEG5fJLYrD2hDCcOObhjYrfDw+B/Epfs7FdjMR10eCmt5VPAC/RUbalpMAdV5R6kf1uP7hsTWCbwAbz+g8dCHgAFkvf/w+CwsZlFhqWXxKwJLgQ5esElSMrepog0QG6D5tvydBHCvzZ6U6TohtiQQyGDrC33zpv1yQGlGGCXoECWyG2frwVs+4IU17HLBj0dbf7Hz8FBVp+FEiupWu4nEOfG6tHmKsjqhwBXOaBbfHyScIZ4kQomdCOcWDHtfRn3aEoc7oVrZoTgfw0BELwAnMavS89FlzAaNYUjAeZCRkjw4fmzs6Hds6LgmrBled/CUZFNNDS7KgzlPNn3bdEV58RIGkyDh9hdp+o0Pp7ymbClIBa5qnf7Zxamhq4jgbFCsd0hOKFhFI1lDtl0QjiE6A8P5lYar24BnERWLLDe2igA7FbgYaDYAG5Q8QPxL9ofLWFSeOoEPDyutOhvgZe86GMJ4YOqyJ+VC62GGFOIHbA5muGeG1Trh7QO0vAmFeItwKDucFBdhEylY99ScDvt2YOAyOiPFVpgQt5pE1asdc7bA0Lenjv0C+2J3Pj7Yuhz+HUoDKw0Fe28EsfBBGw33LWkWj3QdUEdoYLKTBSxca+oQDEwA8Po7f2i29f4DOlACU1fh2ivJZgvtMhPvHCHrRCMULcF0PBte2nYfi/0BtYWZC8X6wy/HLXmyDhY+sNZGLKbRoeqUxC4cOQ8vBhFRMWQXkaTEx/dTRMBSSnR+soAe2BzZoIdhjA3hNbYmyZ57cgeg4v0BzAhxLdF+FO7suhkWHJhmqzptJ8MDX7CkjL36q3UFCSycCoMLdlWwfZyqZngCQ0IwXrOzNWo/xJPgdlmzk8DuVNv99hMKj2BjyW7wL42JYySwOkOyG9QW+SmIZ4TdrQrQuApV6oo9gEhkFaSOag3Zl2HuGoJTii15CY2HR4ngYVu2rNfdUjQsTFfQdxrWCbaVuwNgUNUOFcB6g7b6J1mYDYsORF9AFC6m0CHtq8OFVZrNy1kOdopQB/M3ka9lLb2yee1IPBVdOhfMIkRiOmCeOvHen+IjG7CyhwVx2Rud4Jkvdmkkapii1TFcy6jY1aOtGjuKu+F4QHAhoGOKzS231dBgJEygabb+2jUdnBmDOaBwY5lh769oK2sJlM3CRJQJwVK4xdOwO/22Yo6gwdnLHi9oq/P+2K4HtRtKRSs6/zafn+KIFx701oYVOnUTH8xeC3Z3jQ/jwHKybvDC0RrNO6+6JBF/aA7sFvnSGOf6FTwfqtm6I9sBd3QbIk5sRpcuqIerH4vq9Heo4BpBCJUZNlthmyeS4RCXYY+A2T74VVwtIqCdt6Sy5EL/CLdkNw5tvX/eo4PBEN8x/IqL1A69SEBHQvVsWEdC4aRYhOvIQmWqCPcbiHCVqAiXDMng1mS4M0iF5ipcHqTCblWF5iqU8KpwH67q0cdlD0MG5C0sIIbdjQ9vw4O71GW4t5gtXrDtMSovo6OOLAx2PtIbNIjES1bDHYiHwn2gYnaG9i2HYT7EMdkqFVeNh8qA4GaajbIH+S4YGK87nYXFP1wHLcLhRhES4iLcmSX6K7fC7kqEegW56e0lWFAP8utgZaYPg0IaPTDVq3DvQW9KbBmHeyt72HMYqUbXbLI7P9dB3HAZQbGcr3kmz2/AemgVLhlVbK05cXwDVgBItqSTP/4BawAkG7NE7Yf3esKxM+ws+FdRx5EbPMdj2KWamjpg1rGrIztxILrBRjUk6h4tTWzLujidyh1ZUQrrHull6efbm9P+VFqs+Oar+5//+9//D1OTW6zNzQEA"; \ No newline at end of file +window.searchData = "data:application/octet-stream;base64,H4sIAAAAAAAAA8W9bZPcNs4u/F/GX2dnm2/9km/ZOHs2Z5PYJ/bu/VRNpbbkbnmm1z2tjqSete/U/venSIpqEAIoSj1JPrk9AgmIAEHwAkj9elNX/2luvrr/9ebT/ri7+UrJ25tj8VTefHWzKz8W50N7c3tzrg83X908F/W++HAomz93T+4e26fDze3N9lA0TdncfHVz89/b0NHSGLXs+/rXv9ovp3Kkq1c9Fejx9uZU1OWxBQJdmIiF1D2Pbw57S5fF464nTrK66yRiOL6utuenfJ6A/Bqub+v9077dP2cO5x2kv4bv+/Jz7pt2pNdw+6Y6H9uyzlVnT33VG9Zl7qB2pNdw+756+L58Lg+ZHAH5NVybsp3IOG4xkfd8NwD5dv3+SWQKEMnMDMR3x/Z9vjAX6utUfnyYwBSQT+Uq15xf7Hr6s/9z0ocbcVkNttWxaevztq3qVFevYjpa7E4iZpD2uyQD9/jSb9vs/rRv/nSq989FW+Zz+VR+SbLxz6/n07RFe26SrHqS67kVbVtsH+0i80NxSjLFlC/A+7T/+8ig9iTXc9tWx92+3VfH9NhGZC+gzS/H7fdVdXp9rgvba1qvQ+LrJajLbXU8ltv2XVuXxdPr8lCkx5xp8BKStPWXd+EdM+QgyF9AitN23MG9glTX82yL5tP/O5fnMskTUl3P81RX27Jp9seHJNOIbBZXudCXtaPYtqFFYlZfiDL9fcRjV2Zxicjm8PEeL8Mpzn6P0f57kjn9bx+L40NpZ9AP1S49VgPSOfys+xr1bzP7rsun6jn9Dj3JnP4fyva718nuA8XM3sdWup5kTv/75utttMEj46AL0cx3eDcemkCqmVy+CSvwGCNIOIfXh7oqdtuiSa8EkGqW5Z6PYRFLm29Ed70nrs/H/yna7WMOY0h4PefH4rg7lK7PgGA0P5XNqTo2aQsdaXi9ZJcl4Tu7+z8Wh8wVBJC/hBTWqWdKgEiv526dcBZvRPhSdvGNDy6/reuRjSFJfr0U5fEXG2O9L5pPSfYx3fV8u0DrRwiKJQKyHzEiNoEv3sojv10ez0+Bp3+U3NSLCxzzup8Qu7HeXsW0Kc/ZiUdy/Dqb39dzueHRGq4/kGX/NHfMBs6f7+0VuQAMX+EiIclx6PYTLGnXn8dzHb1kFGR6juHPuWP1Q3E8A69EdPKqJ6GF7QUh+/+pLA7t/ikp5itAdA2Pt+fm8c3x8CWLFyC+hqelevPxYxbLC202R2mWaK68OcWIyt6uFx+Lbe/TOoK0AXAwW7K3AeA2tNkgXR7+lOZGIFGTGbbVp/KYyS/QXsGOxZ7SnJMo1GQhEqBPWowR+GeGIAkcbEyUEUQsR5iLs3xdbb99LlE2wU9V+Ch7gXEL2jduB4+XyUF/rzA1/RKRiCTXLi7bV8dczlSLudytXUx8b6LFbO7H4tQ8Vu040wvhXF7fV9vi4EUeZRfTzuX4U/lUtWUmS0Q8l+d3x327Lw77/83QZEw7l6OLezK4XejmcvrH8T+ZvCDlXG5v67Ipj9syd14M6edy/ssATuF4/mUUUsmcF/ksB+ST+MLAJ8xpR0ctIBFBfuATJbqT3b1KFr3E8nGhQXWut7nseuIrGD4Xh3Muv0A7jV2ycCCD4d1IMVHczsvIjS5eH/LZ3zVjSwYhx2gFR/1c1u/KX2bJAxq/mEBdi3+WUXXAjFHqe7hCNDi5wQrKzm9Mc/0UJ3tMz/KBoJMnOs10ZK7nsmWnO801PeNzmdbFf1DUMsoYNpnMHBoOjINYyxkQXW86dJdp2xnKOtl4GLYj1pPNmDUfhm/afrLZJg2IYT1uQSn2EaKC90esHdGU1xtTot+0RTGiT9Vuin9axaMCRBEc3gryoRxJ+QIxHd/vSHBHiz456ErwH4m+xgSAA93tndjhhc+vH9RBb+mhjISb7ACHzEZ8Xw47Vl9DbmktMcxyQ2SG3ViEHDVLBshbh5GBgots5negaa4UI9HoqdsBzxAGNJ0vDJwxPQLAzpmY4vpZQ/SXnjdIxMkzh2I4MnfyWLKzh+KYnj8sw9wZxLIcm0Oo4exZNCbA+DyiJLliJo0KNDqX8gSCswlhW+ycouiun1lsr+n5RQo9eZbxzEfm2hT27Izjuafn3Qjz3Nk3wn5sDpLNZ8/EPGHG5yMv1RWzMlO40bk5RTg4QwGWz85OTHP9zCR7TM/KgaCTZyTNdGQ25rJlZyLNNT0LE0xBxYdLhV72XWSNEU2Um9js2g2SGIleX8E2zA6GFpyud9o32xlCoGYz5YgSxq4Y8rL5GuY7EMGU6iQqS0R196onZpMnWEyW51+L/WES377BDN7ESCZHcWJNnC3R5N8lKonrSUfeIlUR12bzA6Tz+f3kyupz2F0oJ3KTi81KGAlWhV352Z5y7Jla32ydWff3pG5wbyGnhzoLf57U1/u6ODaFm69Un/hx2obk0C4HlaHhQbKn3GOXUWdZBy97uSYcioy55B+LHOPFHIyM2U06GjnGsTq1Y/w6kpfg5s/gEKdQkNouZC/Dtdx+OlX7Mdt7FRG+BOfDJbMyNsqI9CW411U19saWBJ0gv2KcD9VxePoBDXFHM5NfcnuU4Di2H+qbePnmDyjkdtfR57DM3OCMWVHEHjZ6ARnKZ7ew2ZBuRIqY8iVMC/T45oPP1+fLAFq8iMs8HvbH0tdAjvpORPsS/HNtoad7sQn+uG/aqh5bDi9U2QvujGndcRm/BePSrJOL817F8R/HXTWR7d2lWR77ideBTJMi/EFPFad/DX5wfipnDU7X7A8eHCtF+IOcMzjuNZjBOc8wm/MfbzNnYDDryWNyTlhLPcNU6j/eTmpgJMvJA1InLGTfnTH8W5YDHVLP27nsm3+cdkVLXY+AGELCmQtFdBDwbLsbG/+eKPvt4kOe5w/Ntt5/GGMD6eZxOp0/HPbN8BYDtNz2VPO47Jt3xVP57aG0RG/qbx73h92bj6OaYxq9hBb9bQP23Fa5+z5/J5No9hJSFafT4Yvv8m2xHR5wjYUZUs/Tjj2Ln7uNxLRXcMzaLseU87g9Fs0EFQ+p53Etj825Lr/J2DfGlPO4beuyCFVqGaZDkM/0VGX7dQZYBcjmepBvjxY6fF0+t1V1GFMiQT7bUqmrPwZGmjpcmMGDuZpjwGbkco6ceWfN7KfxzT4inc0vj9V1XIr6Q/FQflMdDuV2lBkmvurN3nz4dwZLRDub4//xsn9fDu9WGXCMaF+A41/r6inHmbGN5snQVv/33ZsfR3j2RHN5vKvqttxlcYpIr5rvmdN9/my3w/LXqn5fElfkDAfwQjmPm4tGBkcrE5FLzunK3GhpbCwR6dX88tldx80VIGbhkgT5NXrMWY9iyiu4DVJ8CX6A9gqObCIwwZloM3v+/9NWcPzly9uiHdt6DYhnx2lvJmC7BPk8vhanncSZbDBT07sd7GhMxwPquW9st4gTGJMNZu903uJyMXaX83asKizDjn/4kskP087mmM/vJbnlLaNkg6t5Z8QJb7OzYamYpDx8zH7PmPi3TIbEzO7i//5J9BDnYhzVTHaVXRx6pZjjpaJ58k4tG71W7NEi0rliYzt80z6WdZNtiZh8Jn6SlSHrqK5JOkZcP+4PbVn/s6ybfXVEx6lpCegWLyFLXhqso3qxEcjIL51fcsQz0jf1S77fQ9lai3nXFttP2SZNtJiPUpRTuRMt5nHnL2iNeY5f0ZoTUU+YRAR5Pl945Ncj08ePF5OCx2H7p/kl709l0xT0AWbU3asLKS07EI6tjyv9FWH0BXCIX0Q9l2XB3RiBuRXpD0qMMvKLLHNpBmYGiecyTN7SgRmO38pBMoS2NygVAuzCs3y7O8JrTbmeXh1Tn/npBeLKnKIbY1ke5eCm2ClMttXT6VC25ASK+QDKbFbD8Y+qnAe8RmudYwsaJH35DjMyv0BAhqHbOFSfyWv0MD9AO4Fd7okvjttYaSNo1wvIV3/bO3n/eoHOfc23/2NSS8m3GPQy9lWzTgpeTHdX8kDO7q/XCgq7GZM0CMKL+k03iQbSXh5cKzDqaUxmIBEv9j+Ow7nmuYEn1wqOuxqTHApFnzJ4v38q3++3n8phQHV5NHIeAgRN1bAAA3XzquLvlwXCcJubunp6504ojPKJSCfwyz05gfnlnJ0gGcYV8MXTqarH3+5Cl7OjGOe7Kw/2C39EmTDmDClfhreLywgwBHO+0M3mi3JZ371+19ZUvRdmHZHONd62yjRdQDifl91mZb9dRDyXJ1u3gfmNVm6M83oo2+/9FPi6yXxLssn1/CfwvY7f6+wpioiv4Pl15tSMSOfyKz7mvFygmsul/OVcELU+mE1PNpeP3QwU9RArHa4bgW4SJ3QIsSdCLqY7hIgeXxuHkP2NBSMDGTOXwHGWd9RqmGI9gnMPF8MMGeh18Qop8LKYIQO1Qk6TABsWdgBeiO6v6X0oiDLTQFr0NNlnbmw27DErPIvFZNTynPsSr56nQOkcb7zC5jD2ZNPeEXv+HD4P1/J5Kj5zqyjBLqK+jmsmu+v4uJXqTf3tL2fis0oEQ0R/BeddWZ621WlYY0pwBbRXcPQ5pBx+PeUV3Jr9/w4XVmoieLorON1bj160Vf1zDr9/Bep/zeAaO943ARqPUgHe/UbPRjbnKE4oP7epngfPJ/XefUE9xYAimcTj67ouvqQ4DAkm9e8rapOjP6SYpoO6LJM6wM+njc9u9+ZEDUv4+7WxX9zRWNB3EYdZTnM53OWxGatggMVxKW6nVGFcLre9vZwki12gnMxveE+KPYbRlKQNxA+vNQSitzFrQNLlmwTPK20XqN1k40jwTVrIJL7xTV2jjMdu6kpzxgbjb+ghzQU+utZYBn2NmUokV76hcHzSZhK1mmwkLM+kiUzgCa/UGWGZ+gLaBI6U52J5pp1Xmis2x3dlS9pi//drDTHuaMwKL+LkmyDJIW1/lyaTjY/mlrS8XG5Ds6OZpWwuwQur/gfOD/3wYl7oh2k+6Ic5Hojmkdb/D1d4H4Zf0gLy+dXl8746N98R/oBjjJpcKQHliRjOaT+U4jhIl+/2tBu6PLg6aR73NJo3v0iUb4o0j7QpgjaTTZHhlzTFbH42n5vHr6O8kl87ovt+NPlrOLJ5UREgwy4d/aU4zjbK6NbexM1BA+bpG5KLtq33H84tOIwwQYq7qPkkgUaUsa2ObTm4xzFPqEvbKyUaxEXtlwO9OoInV8dGqKvR6AgINSE+ormMREig0fQYieGYjpKyORKeieOYdE35HAe+iR1T3jnlc6O8E8dw5FMxKZ7zDTTXQQ3Zz/RQeXLkuChOpHGPYGFCNk6JH16d7h32NprsjaXL9w48r7SDQO0m+4gE36SbmMSX8BQJvklnMYnvwF+kRpl3GZN4Ul4jwTbtOCZxbk6Hfft9+Vwe8tlHbV5I028nWRlo8SIan8a9p5/Hm3JOfMiCnr6Ee5oaumABpzmoWSEMbjjLRc0KZaZxZpzUrJBmGmfSTc0Ibaa/LzNZUu88Ol+mvPdE/hmz9brwLsV83FNfG+aNch8P9WgxZoZ7+fLkhHwp0cZKwvre31ceV38JSUFfLyHxpXjizeld/O0b/6GI8Od0+Rj6AnOqj1eBgha/F4Ps3X+LNdl9TzKnf3vwNjoETXEARPk8QIHd29rWHu6BPYQqlf7JVYc44l5SZzgukjC9O6uxl3j95UtL3EOBOA2oZ3J1R7k6mvfUBRGIL0E/k/O+eXc+kSVuiCUknM3ru2NbPhCFWANeF8J8Xrnll4hZTuklxW64SuVoDhLmFF7mcc7iegXHnAvqEMuRG+oyuCSuqBvwyrijLuu9uCsDiJcbuytglB9bBomYjZZA5riXTK9yrTP58fxU1vttDjdMPP/d/pkzBQDdbPvIWhMuZPPf6Bt3We3u61FDRLSD+b0/Ppb13n/VbZIExKmaIWv6tNtsnjYHmvfOF8qX4959DCyLP6R9OQneVs3eVlVmCoHIX0iOJlsPzW+gh2aCHprfRA91vHFheNfDLclVXPcN/mod6zWpj9ZN5x0DYj3NP4nddvxwUrnv/9TF6VTuuhvtUb/xw0n92oWe7hQ8mdwjutr40qF/MLk/V+tNdOf+nn06qatJHxhG9/cXOZEE+8oKiINQk8PhiNPUYDiHawbHl+Hmkumfh14Kj2WLr5C5guO4Jby6EM3jGLul/sO6aaYRXa7FZIQcEZNhwDGtfzpMxCzSQWIml3HTR5SzuO27Yuox3fRUs7iktkURo5xNEcWLPKVDLUTwUbb7fE/NUfvHF3GcfUd5F2xYWSa6k4jDBF+S4jXCaD6XXOdx4ZXhOVI8aLdx6T7tM1I9l7t9aoy6x9P73ZXRbV3DnnuCGTI/ndohnACE7p5P77mxZ7K/HFJyA5Lp/bvi2J/sBXDvq7dV8xN54zy0GpJ8Ot9T1/h99V3fZYIvQz6db/oClMtMzLr6JMHHxTvEdRI9h54gr++lFBrchVAeH4jr3C+99wSzZrZN7PzlS1zcTU7xmPAaXiO+BFDN0XmGvq/QNYPLwt6TAOlY31wQEDMYiwBSXPw3mtysGmdGEmfyHB47fls19N0k8NnVpSCDzkYLQSLRuEMIu1w+d3v+Y/dxo1mJ8QTbjJw4wd/Ky8VLA4h0ghB3WxI0zRBnJAVeffwIb8GYIlLf9CXlqctDYaGbN9PkGjSbZTLJeRYvtYRAjiA/zK9LYuGuy3QP2WF+6CgvzLeysAeGXLxLfiPswiWmygrEEzzZrQV8qylBf4JXm9TDq+7xDC7ZWws8iMmtRYIHs7Xoux/ZWiR6/nDeH3YjFgBpZsn+Lj04F4pZvf9Y7cpxDoBq3vjbiC49s18hsul8GrtpYT5MdGETU83kMtb/rJ59KoLZnfX9x1TTudj97nfdl4wTbBDZtfPcdjeqmoho3pv95Xz4lMcHEs7jNcLhqnfIkH5W/231//3wfcqtd8/n9ExvWkDX6U3LSN/sPiJiMLqBGOFi6w7zOMWUs7yiXRUsifWuaceIKKdzczjL+2pkYsRU07nY6vAOUUlwianmcRlFmCJu2QDT2Ajms50GbKXeNgvYurzuJGAri+/bMIJZbCF1JtfhmY5oRlxKju2fJyVvuwQy0R14ci0YgLsaPWMPhMo/D8JwGTllDxrllnxn8s05F53Nffu4P+zqcvDhAIY3IJ/BmdrNUgbX/fklsKJs2+hlmXBQiOh/5IRQaDHjwAbFbOSkBsuNmvnoG7WXue8fJJWxJnqKEri+JD5+mHs64Bt0XJ/t69U3I4fzkXAkt3gXwPMa3weMcfqJ2HXw/H7K3H2QXAcZ4p9evw9u3d17P0RtKZJrJyTb5+gHOih5J6KaY8wzAE2yixlo5qgoI0BmnhzUJE9jhwOC/Aor+gPXGa6DyF6kunnVkzBD4wVh+k98XQTyyPiyyIBPdp0YfJecMjHMiMtbUAz2ZI0jVcSU5EJ8843ixnzsbS7X8O3Qcdt6NSC9njv+qB7Flvqa3gR+OdVbgNtI8dZY7z9kvFBENofPY9G8yTMWTDnzrTK5Yco53Nivn0BGo18+GR2/t/lmT1HPHMcJXCnqOVzLz+X2POLtLzSZHLK+FU1wuOv+7b9ePMLyDrXjXaeFq9LGyYlwd2k8RZTRfOZzWdvrY2cKFbW/Tq78eh4oWVZFT9r02A81xXymxgAqCgGeyxqWGj8X9d5+dLD5c/9sfjzNdTYWSF/EYqzDXXyAvwI+wu0ONRphPbEwYgrzvhRgmS1GLDy3+a+8rt8W20/ZgqFGv++oQOZhVOQ6f1Qi4RO2MmNcBs1+f3sZjo2Q0yxmyug0M2TjnetvPy5NPyh6zqA0/CwKm9b8EYnb/N5zqOcdRkRNGBEoesJGpo8JbvX728lgXMQE1xKLz8VN7rzYe3ReeEw23Or3HZmIe+90J1hMLD4zMh++uBtd0Em7Mdlwq993ZCLuYWRM/sDE0qcH5t2xODWP1eShAe3+kMEJ/MPwbCYPT/8Gv7Fg/aRf9L/4mtQxYcOfRzYt1XyFJuW+q1MFYtOEH79q3QWZ+e5s0ovA7n+Ht+na/g0UHGS+zt8S1Qe/8Rz7W/m5X8knD5OVmxmMR1u8MW2pipr8voNxYd0vUov80QCCs3He38rPaCM/HmvBNr93nNfz7q1jwoBA0dkR+cf+2K7j0+zjYkWNfu8xuTDvB2XCrjoSnh2VHpOdIBds83uPSc+7H5IJ20Yo+gjOADIBuRv9RGrgt8YYvnvd+5FJFtILzozG2w+TRyNqMnk0qAVusgjDdn/IUodVMz1CG1NPCMonz2Gi4R+zHcGzeTV9RzI2o5/h10CnhUtk0993oIYi9I5vwoafeJFUHEV/SzorqMFN/4C4Kv5obPCLE5YJ4kWoQqvvq4f4BnRfOhT+nFtc9b7eP+8Hl69Gvby60NCv0ItCcnhdfjg/JPsPFHN6jy4fpzrvCOb0/T9FfUz23RHM6fvbugbGTXUeKOb0/teiHdFpoMjuXYuNVgtwB3/ZDkzwqdqdD2XTZ8IBAWmHIF/27XN5bP0NuK/L57fFEXR7mXcEVdLQaQbvXv893fe713+fVOzsBHlfvXv9d1xk0frrv/DzSb2/e/13W9x9LA9074Pnk3r/6/lwGJOfpJnMZew9SJokFw2czHNbVYcGm+Kfw4NJ0n5z2JeDa9H6nvxTokMwgXp5JtVHUizGMrqoDVsV6Z6CMHaU4x1oksU6E/6aIMFpLKc8KkH+rXd9V+nr715Ox5hPtqLhO+QXq4/xTReuk63T+h5+XHRUhNR3RmdIQJXRj8qQLqmfIQVXjzwqyXg9cp40w+vBjm2xP9IXhF1mVET123q7Iat8rxe/zPjhJuJrNX1nkOY3feMBo+z3jV5jvCg4k2/qUhO6cdrm57x7pgOaIEXXeKocfbOXk6SB5/xz5WhSx/7nSJH0h6wYmQ5xghz14HriXFlq8rLia+UZ3hycPW3Iq4Svludoy3qfp0vTt3tRWX6EF59MkOVHfB3KtbIwZxXHhRk9tThHGvbc5rg8GSc450i0K0+Dj0yNCxNavaTNDL/onWMxqWPp8/z/jOFIfmdtlhTVdAM5JYq+0zL8fNsN/1e/Buz55qsbeafubD3Jx3152DU3X9174W5vttWT20f83D3zgKOl8CR/Xtzc3i9uzeZurdc//3x7H1q4B+4Pjkzc3N6LWynvjBERmYjI5M3tvbw14k6tTEQmIzJ1c3uvbo2+W6lNRKYiMn1ze68pMh2RmZvbe0MxNRHZ8ub2fkmRLSOy1c3t/YoiW0Vk65vb+zUl2zoi29zc3m8osk08vAt2fJEenCJIhYlYFbbg9V4IkjLWhlCc1kSsD1suei/krRZ3ah2/johVIuzQC3Wr13frpYwpY63YSu57oW+1uRNrHVPGihFWAcJQgyli3dhixXuxJF89Vo+wahArss9YQ9JpaE31KWMVSaciUukSzRY3XRYkZawi6VQkSMpYR7Yc8V5KUs5YR9IqQiqSMtaRzfreS01SxjqSVhHSkJSxjmyt+r0kdSRjHUmrCLkiKWMd2aKOe0nqSMU6UlYRckNSxjqyBQD3ipxwCjk159VIHalYR7bI+F5JyuZVrCNlFaFoVxnryNZu3CtSRyrWkbKKUOQ8UrGObA7wXpE6UrGOlFWEIt2minWkrSIUqSMd60hbRShSRzrWkbaK0KSOdKwjbRWhSaeo0drjFh9yHulYR9oqQpPzSMc60lYRmtSRjnWkrSI0OY90rCNtFaFJHelYR9oqQpPzSMc6MlYRmtSRiXVkrCI0qSMT68hYRRhSRybWkbGKMKSOTKwjYxVhSB0ZFCK4GIHUkYl1ZKwiDKkjE+vIWEUYUkcm1pGxijCkjkysI2MVYUgdmVhHS6sIQ+poGetoKdgVdhnraCnZ1XAZ62jpdETqfRnraKnZ1XAZ62hp2DVuiSK5JbtuLmMdLa0ilqTVLWMdLa0ilqTVLWMdLa0ilqTVLWMdrawilqTVrWIdrawilmSsu4p1tLKKWJJWt4p1tLKKWJJWt4p1tLKKWJJWt4p1tLKKWJJWt4p1tHLhNmkhKxRwu4ib1NEq1tFqza4yq1hHK6uIFanNVayjtVXEitTmOtbR2ipipW6VvFstVzFlrKO1VcRK32p1tzIqpox1tLaKWJlbpe/EBnGPdbTW3A5hHatobVhTWscqWls9rJYkZayitVMRaSBrtC2yeliRBrKOVbTe8MMZq2izYIdzE6toI9jh3MQq2jgV0TuzWEUbq4c1aZ6bWEUbzb7RJtbRxvBvFOtos+TfKNbRZsW/Uayjjdu7kpNjg3avvI42eAO7YAX1zyCt1cWanHP+GaSVrAj+GaTlZ5N/BmmtRtakb/bPIK1JyIC2s4slq1r/DNKuEvKiLe1izSMEaE+7sKpZ61u9vFsbtKFfILU5eGFtSNoB9ODURm+rMfggEmrD8INDGZghwwiEwxmYIcMYhAchyCHDIISDGpghwzCEAxu4IUNac3DDmnScAkMRgp9sAoERQvIuUSA4QkjeKQqJMSPJDhlCJITDHZghQ5iEcMgDM2QIlRAOe1iTK4hAuIRw6AMzZAiZEA5/4IYMqc0hENyQIbU5DGJNBjoC4RPCoRAbGr1DCIVwOMSGxu8QRiEcErGhHarCYJ/VzYZ2fAinEA6N2JCbIYGQCuHwiA0ZmAqEVQiHSGxoT4LQCuEwiQ09hRBeIRwqsaFtByEWwuESG1pvCLMQDpkQC1pxCLYQ2kO0tOYQciEcPkHiOwJBF8IBFBz6ioFazaOqCL4QDqRgcFUEYAgHU4gFbWkIwxAOqRAL2tQQjCEcWCEWtK0hJEM4vEIsaGNDYIYwXnkk9C8QniGMVx5tbgjSEIb3lgjTEA65YIVA2nPghVisaWKMtDv1LWhDRuCGcBCGYPIHCN8QDsUQTAoBQRzCrFMyI/05LEMI2owQ0CGWfG4EIR3CQx2Cnk8I7BBLXnsI7RAO0xCC3FQJBHiIJbtTEwjxEA7XEMzcW+JEyZLvF2lu6TVHbu0EAj7Eko8sEfIhll5v9OxA4IdwEIegUyYC4R9i5TVHWzGCQIQDOgQNAAmEgoiVd5u0FSMgRKx8hos2TISFCId4CDqDIhAcIhzoIegkiljhTJfTH51HEQgUEQ76EHQqRSBcRDj0Q9DZFIGgEeEAEEEnVARCR4TDQASdUxEIIBEOBhE2rUJ4C4SRCIeECEVrEMEkwqEhdMZEIKREODyEzoQIhJUIh4gIRVsGgkuEA0WEoi0DISbC4SKCTt0IBJoIB40IRVsGwk2EQ0cEncARCDoRDiARirYMhJ6IjdffmkzwIgBFbLz+SGhCIAxFbHzkQq9QCEYRDiwRWpAbC4SkiI3PNNMaRGCKcJCJoLM6AuEpwqEmgk7sCASpCAecCDq3IxCqIh1yIuj0jkSwilx4oJ/OlCJcRTrsRNBJHomAFenAE0HneSRCVqRDTwSd6pEIWpELH3ySc1sibEU6/ETQCR+JwBW58OUCdH4boSvSoyt02kcifEU6DEXQmR+JABbpKzvo5I9ECIv01R10/kciiEX6Ag86BSQRxiIdjiLojI1EIIsUbAQjEcYiHZBCowASgSzSgywkCiARyCJ9sQeduZEIZZG+3oMO+ySCWaQv+aAzPRIXffiqDzrwk7juwxd+0NGcHJR+SD5Ek7j6w+Epgs45SVwA4gAVQaedJK4BcYgKnVKRuArEISpiSU8SXAgivQLpSYJrQaQv2GEGAylQegWSaUqJEBfpUBVBZ6wkglykg1UEnbSSCHORDlehsycSYS7S4SqCznFJBLpIB6wIOnklEeoiHbIibP6KEgMp0EErYkVbBsJdpMNWxIrWNgJepFrzEblEyItUvuiKNg0EvUjN7v4kAl6kB15WtKtFwIvU7O5PIuBFeuCFTn9JhLxIzftOBLxID7zQyTKJkBep2d2fRLiL9LjLijZjhLtIze7+JEJdpEdd6FSYRKiL9KjLmi5ZQ6iL9KjLmrZihLpIj7qQOJhEsIv0sMuaXhkQ7CI97LKmnT2CXaSHXdZk3alEsIv0sAudOpEIdpEedlnT/g3BLtLDLmsSdpEIdpEedqF3XRLBLtLDLjSwLRHwIj3wQiPbEgEv0gMvNLQtEfQiPfRCY9sSQS+yKzahHRwCX6QHX2h0WyLwRXrwhYa3JYJfpIdfaHxbIvhF8vCLRPCL9PALY80IfpEefmGsGcEv0sMvjDUj+EV6+IUjRvrz8AuN30sEv8gVX2AsEfoiPfpCg/0SoS/Soy802i8R+iIdwCJptF8i9EU6gEXSaL9E6It0AIuk4XOJ0BfpABZJw+cSoS/SASxyQWsboS9y7euOaWNG6It0AItc0IEOQl+kQ1gkDZ9LBL9IB7HIBa1BhL/Ita/5ojWI8BfpIBZJw9wS4S/SQSyShrklwl+kg1gkjVxLhL9IB7FIQWsQ4S/SQSxS0O4I4S9yw0cvCH2RDmChc6QSgS/S4StSmFu9GE5ABL7Ija/XW1IYkETgi3T4iqSRY4nAF+nBF/rtkPIcusK9Ha4j36TeDpeS8/UsCgEvauFVxxSeo3ryBas6hWAXteBVpxDqohYJ1SmEuiiPupDpQYVAF7VY8mpWCHRRCz/x6MJ6BLoovqRFIchFLfjaCIUQFyUWiZFAiIsSfHGsQoCLcpiKlPRZAAS4KA+4kC+H4BYl+LoxhfAWJUzq5ZDqHKgi6dSHQoiLEquEnhHiohyoIuk8iUKIi/KICz0USHe+roUeCgS3KCkSQ4HgFuWP2kjyRJJCcIvyp22kpomR9iRfkaQQ2qIkW5GkENii/JkbSaJlCoEtyh+7keQarRDYovzJGzoFpBDYoiSvO3z4RiV0h4/fqJTu8AkcldLd4BBOSnf4HI5K6A6fxFG87vBRHJXSHT6No7zu6MUDH8hRvMvEJ3JUwmUikEXplMtEMItySAqnDgSzKC0T6kBAi9J8/aZCOIvS/pwbvdIgpEVpf9SNhKcUQlqUg1Mkc5ALYS3KwSmSTgsqhLUoHmtRCGtROqE9BLUok9IeglqUSWkPQS3KpLSHsBbl4BRukBHWohycwg0ywlqUg1MYu0BQizIsTqYQ0KLMKjFNEdCiHJYi6ZSuQkCLcliKZE7jIaBFOSxF0ildhYAW5bAUyZzJQ0CLcliKpFO6CgEtymEp5P5RIZhFeZiFxvYUglmUP9ZDn/hTCGZR/mQPfehPIZhFOSRF0qlihWAW5bAUSR/9UwhoUR5oIXEIhXAW5aAUqUnsUiGcRa34WlyFYBa1SuTYFYJZ1CqRY1cIZlEeZqHT5grhLGpleGRBIZxFrfxJYXqWIJxFeZyFTpsrhLMoj7No5tgq0p/HWei0uUI4i/I4C502VwhnUQ5KYY7uIphFeZiFTrErBLMoD7PQKXaFYBblYRY6xa4QzKI8zEKn2BWCWZSHWegUu0Iwi3JICuPDEcqiPMpi6KPMCGVRHmWh0/EKoSzKoyx0Ol4hlEV5lMXQkTJCWZSDUiSdjlcIZ1EOS5F0Ol4hoEU5LIUsBlUIZlG+xoX2RQhlUR5lYXwRQlnUhj99ohDMojZeextaYnwWfMO/HD4M7nS3JDMSGsEsesHPPY1QFr2QvLvQCGfRDkuRdEmARkCL9kALnYvXCGjRi0SBkkZIi/ZIC5241whp0Q5MISF4jXAW7XEW0oI0Alr0YsMrWiOkRTswhZYB4SzaYSmcohHQoh2Wwiga4SzaX15Cn3fUCGnRwuuOPlePoBbtoRb6AK1GUIv2UAt9hlYjqEV7qGVJXh+jEdSiPdSyJFd2jaAW7aEWOh2oEdiiHaAi6aoEjdAW7dEWuipBI7RFe7SFPlWrEdqiPdpCVyVohLZof70JXZWgEdyiPdxCR1AaAS7aV7cwUxUBLtoDLnQJg0aAi/aAC12XoBHgonnARSPARfvaFnInpxHgohV7gZNGcIv2cMuKrAnSCG7RHm5Z0aaM4BatvPLoKz0Q3qIdqCLpagONEBftQBVGYqQ6X9dCe0MEt2iHqUj6qKxGgItWKdeJb0FxoAotML4GRadcJ74JRSdcJ74LxUEqkj6HqwfXoTjd0QdmNb4RxeMta3qW4ktRPN6ypucSvhfF4y10JYXGV6Norz6ykkLj21EcqiLXtCUjyEV7yIUujtAIctEecqGLIzSCXLSHXOjiCI0gF21Six+CXLSHXOhKCo0gF+1gFUlXUmiEuWiPuTB+FqEu2pe3MH4WoS7aoy50jYZGqIv2qAtdo6ER6qI96kLXaGiEumiPutBFDBqhLtqjLnRhgkaoi16qRCiAcBe91IlQAOEu2uMudMmDRriLdtCKokseNMJdtINWFF3yoBHuovnyFo1QF73kMU+NUBftURcau9MIddEOWVELclukEeyiV/7CL9ryEeyiV2yWTyPQRa/4LJ9GmIte8YCnRpCLXnnV0VMEQS565VXHXCyFVOchFzqrpBHkoj3kwvhaBLloD7kwvhZBLtpDLgvmiiukvTWbXdcIcdEecWHiHIS4aI+4MHEOQly0P1dEV8FohLjotdcf7S4Q4qI94kJXwWgEuWh/sIiuqtQIctFrHvLUCHHRm0TgiQAX7Y8V0dXaGgEu2mEqiq7b0Qhw0f5YEV00rhHgojf8lXsaIS7aoSqKLgjSCHLRDlVRdEGQRpCL3njAjPYtCHPR/lQRXa2pEeaiHbCi6OohjVAX44AVJeiryxDqYjzqQt+maRDsYvjiFoNAF7Pw1yXSd50h0MU4XEXRFTYGgS7Ggy70Jtgg0MX4M0W03zIIdDELrz/6vjsEuxi+vMUg1MU4YEXRlSUGoS6GvyvWINTFCI+Y0XfpIdTFCF53CHQxDldRdPmHQaCL4U8TGQS5GIeqKPpErUGQixFsps8gwMU4TEXRh28NAlyM4PWG4BYjvN7oiYTgFiN5vSGwxUivN3rOIbDF8He2GAS1GOn1Rs85BLUYyesNAS3GnyKiaxgMAlqM5PWGYBYj2UJAg0AW448Q0RcsGASyGA+y0JcVGASzGAelKLrSwCCcxfA4i0E4i/E3y9JXyxqEsxjFBpoGoSzG3y5LH5c2CGUxfFWLQRiL8TfM0qUOBqEsRvGaQyCL8bfM0pl1g0AWo1h4zCCIxfibZukkvEEgi9G83hDEYjzEQufrDcJYjINRFJ2vNwhjMfzZIYMQFqP9xcD0TEYIi+HPDhmErxgHoSg6W28QvmL4ehaD0BXjABRFJ/YNvn7W8J4S3z/r4BMyKjf4AloHnii6XMDgO2gdeKLocgGDr6F14ImiT5abwU20TnN0itzgy2g9skIf7zP4PloHnig6n27wlbQOPCGRBIPvpHXQiaJPrBuEqxgHnSg69W4QrmIcdKLo1LtBuIpZev3RpolwFbP0+qPtDeEqxkEnirmcGOEqZukvjaAtA+EqxtezkMsMQlXMkveYCFMxDjihD10bBKoYB5zQh64NAlWMB1Xo5LhBoIpZ8R4TQSpmxV8GaBCiYjyiQhZkGwSpmBVfvmkQpGJ8GQu92zcIUzEeU2FulkaYilnxikOIivEX2DL3UCNExaz4pQ7hKWbNb8gNglNM4hpbg9AU4yATxdyGjfAUkzooZBCeYtYJ1SE4xXTXtND+B8EppitgIetMDIJTjIdTuJu58SXeXnm0s0JwinGQCQM5GoSnmE0CzDQIUDEOM1F0nYlBgIrxFSx0Ub9BgIrxFSx0HalBgIrxgAp9oYTpEBX3rRr38evdd/6bNff3/Yfzfr35V/chGxE+pfPrjbj56tf/3t6Ihf93rcP/190PYbofUnY/TPixXIQf/V9C8+Uy/Oj6sfdY+B96EX7I8KN/tAw/Qqu++SYQb1b+hz270/3oaOwxj+7HpvshTfgR/qLCX1RoFXjZalX3Qwdim6j1P4IYFmP2P9Ydd7Pof3Q0Joyl3cR3P3T4sQw/ArEMxGF47Vav+xGIZffKJshjdyDdDxN+9DSd8DaK7n6EDsPwmvDKNrjzP5ah+Sq0WvV/cR3+9/JlI/s/a3zFtt0/F21kWdJcTMuLnWi4gy315tLSCL6l/YI3sOTlGjBUi1S7fcTPHqe9tDTdOMrw/vZYLdPXblcdD/tjue2+aQz6vHwd89cbez8O38Np776aCUZOaNB2w47Ax7aMR2CjQDs/Abl2VV3+crYfKQdsF7D5mh3A0959ShbwXQEn0tnckh2z0+nwZftYHB9iP6Q17GQ93vpUbD9FPUjYw4od8UsPTSyAggKwBmub76pt+YwVrldQ4azSbPvmWJyaxwq1l5B/UvymLdozkn4JufO6Ox2+tHVxbOzEq47EW8BJtEgq8T9Fu31s2rosnuIuDHwR1mXUdfGlOpV1YQUZTgEBbZE1h7Ytto9RQ6gFlrdrFjudDTRixarftbR/eipOsfcBzRPi9p8mBCJDT6mCq7dnlbrFaBVWnOCiN6x+ewZt5T/nGTFSwMTtuQm6kw91Vey2RRMZhgLDE9aVVViR/dpKdXW234asYku3VS99X7bWhWn7xb2Gn6qxw1YKjLYZ6+HRfvkQNJZweWHXia5x9eHf5TYeCWhiFrhNtw8WHssPu9Ds6PkuKG9h8V4gBNfDtjjW5S6aWQIuLvb+1E6F3Dhsi+P5iLuArnIZlknW7Ife3qZcLyaw5pwdpXsBVyl7k3GyKXIr9k6si3tgo5Juefhy3D5Vu3gKAdtRnI/fPpbbT6dqj1zrAg685gcrfE4VDhecMX1ctub82zAcgcGIbx0iZLNkR9/1sq2Ouz02YLOA1pdsH2tvDcdg0fkREWJhIYM5hq2GWbLj5HqvTla0yJ0aYFpL1qpd66b8JbYOoF3Jq9e3HazBMADQvGqqYxz4LODCw4a72+rJfqQ0DvegMfNqrJ5OhzKOze09ZOBNx5p+PMaNYYzAeq/ecOJAJYov+KbHcot2BZsFXKBHmu6ro5/EURdLMA2WrIZwD4MgaQ1iEzZS3VbHpq3Pg10KjPLCFlkHsw/7aXvhjl/8l2G3uulmhA6bSx32eZr3A9WxLfbHsn72nxkHHgVuTwwbLNsOsCeRYO1Vso9NEuPQum9Vw50h9KKb8D6Lfq+deB+HaEQjaksCLq+yYH16dT6iluBFQqy1CePOxq1dP4nIFdipve8m2c1AMfYIysWLsPvGbb1r27osj9Wu3O+8ocUrxhIusKxXqUu0a7f1TaAhK75ryG3EQBdihPeuiE1jBZ2oksHCw2K1Yr2N66228nysahs3xd0CV6nZdX9XkkAG3FpxZn5pGkMZMEzjfNal7d7axDHelmsBR4Tt4sP5IdIjbGaTZly78rStTtF2XsJARa67aEOxQ78rPxbnQzTeYArwL40XJQmDMy04+GJXHvZPewx9wMDC3hfYuVGeu/suO3SIUFMs5rIrBxtO0I5dlXwztJ7BHSO7BPuWpF1Euyi2uf+eefyq0DSWrFr3Db0OQ8iYDZJIiGQBl3DNDlbXFEPVS9B6yU7hant+QnzhrjesuFzQGtoPwzsYbQnFjlpo/+W4JfqAq7/iZCh3+9h7LTWcGAF3Zie1bf/hfIicsoSsteHsJTT98OVUxBNEQr1rNuh3HRCNF7AxZzS2MWXq9rAHaM4Zjm1OoKkSvLliN6nlobT/P6INny21v7Bmza58OrWxE13CBVhw5lIefzmX57ItmkhbEEJjt7jlsTnX5XBDAT2SYGFcB//GofkG+lDWL5R1jULaFdxd9mkIw7k01wHeUkDYjl3lnFtoqnO9tVH5qTiWh3jNM3DN4yI40Euz+xR3AHEldvPoOxgCnzB0EoYdv0vr6kNT1s9oJYPxo+AH8XO5PaPQDWKQhkWgPxZtgYZNw2HjzO3j/oAWXXuLJQgUOJfgGz6XdbO38fswbwOhXsFp7WNdPcXTGrr1kDJTIWRUIeelWG9je6QjWAVdhhGcOV46iNdXKJlhp75tPfCTCihf6ZCgZD2966Mum/K4jU1BQoBmkRrT4d5BQHxWmpD4ZEF420vYi6CBgPOR1+z5cHBzua2a3aensmkKhBZGCcElOxjnw6HZfWor1xnVTwRbsfmxh6L+UDyU2+pwQNCv/VAMcK3cgDyU8fINwx654ubXg430hrlJuG5L9t0fypYES+HeRbB7dNeaxCyhBkVKdLcMYaTffrIHjBfny2xzCmWEKL9KyU7uJCEcp9hl8KFs6Q0FDHckm818KNvOXA4xZCug8IJN2ETtnT8ZLOcqyq5yzuyhREgrHHoVUI2wmdOL8CMUJuhQgqE37LwoW9e3netxdAajFZ3QMsobx+moLjJfJ9gfiqdTVccmBiNLuUwMT9e4aJq23h8fYo8HgV923X8oW8qrwFSl3nDu3jaunodWCreP7BJqG3+hHL39Eg7AUzkX+1C6wLbZ/y/SHNxYsEjuQ9n2cFfs4GEiSLM5c9u+fSzrhkBmBNzV2Y/LsF2cqsZ5iMEQQq+uUuZDDyBEd0RC9aE1kc0ScJ1jk++gD2ogDAyBRcKQQydx8A7xCykShnSqrbfbP5d4f22vfrsMJJtPcF1Un1EFCDRDFr99KFubjmzaYvuJtAWYlZAJTfrc9mAuQfnXiaVyuE7BnCILenYthylh+0040D71+lXV47bxBhn6UHbr8lC2TXn4SJoPdGFsyGo7GDgBOIlZJMm2bIsWVZ3AvUpq4RhCIXDIQibDfviP7cIO24cv8SInYR5Ls7n4S2vXLOoAwiIyMW0GswXWCyk2g/JQtjZ9zps8DO9SLzDMFOhoBPssSuIdXB9DdEbAiWM/KZfuYDAScAOnk835PSCEHiQ3mI/FcXcoAyqJcQi4jWWjEN+FK13qobq6bE7VsYleClo2CxY+Fs2h2hYHqpwMVokItnDysWi4pRUaJlsO9lg09KoGx3PBxc6gNbWqwfFk82GP5ee2cpUqcWgHt1os0ukas1ah4IJk2JT6495WO8XrUZRmZd0p2izBRSBkW9UihMWh+IrdSuyPdiPSoLkB1bjgPGRoStWCRgVtnB0MHRsEg2RIHqtFSHSKUNO74XTjOio+HKL32UCIi13nHbHLxbXVqWpqbFoSlurqIIpmd7d+21ENUWWIsbJhOx5SBTMnhoXC98d9uy8OeLWE8apeBOsQYT+lucDt0l1ckgDUuxoXhShGgGgvWwjW9TAsxYuSi5yf2B+bI8rhKxiuGhYK2R+th3mOW0KYkg22Qh6AnN3Qt7KFHPthCinCVllNueLYZwRBwdCYbVge7YShkm72E8ogRGQtvbHv/YBwVpjLVWxF1L45np/Ker8dhipQehbF2TddWB3vrmCYsw6nBVgsZ980xVPZJVOq2lWzVR/jlRH6Zt7mm+Z8wrt9CZdlxWZj9s35tCtavMuHtUeCTQ1bJKhAK5GERVqS3WP+u6mOrq45HkG4xd9wmrdtu2GLW0MQbNMfyeCkt90MNyjSROW7nMvHdf1RpajnHKo9RThKYr9Z0y0pvXDcO1L4Ddx9SBMKodhJfSiPD2gVWEEfJrlZ7QK1eLsL42d29XDtyJJoyJcN8EB8GLl9wJs9XgLaDtw+rMFjvS8bnMLEjWADq0P1cCif4xwbZNupm02wHKrjw8ADQzfIvfhTcURnU2A8y+bEnoo4BIJVs5LV0FPxmbBLCfO+kkXOCTxQwMyvlGFfxk5863KprDX0dOxI4WVZQKOUinNUthnOwEKp2SjGu5ZE8RscchYI8b1Q2waYrzDsXPZ5Uxyb2u/lgnfnFgcy6bqCKKTiVIUWMhg8yXB+TrF5perjxwZlhuAs1uEkn2bXF3jYLJ7Q0bRiU7i83mA9vmRRGHqrKmAMK/sTk2yqwhs72u3CaJKFEKqTT9vHbhwGN+xWrzqhEVtEhbicSxnJS0Kp2dyDrdtGBUmRO2NR/8F+B+LMMpSqyk0oEV6EJTkcO1WiP/QasuHh3KgKZ29Vf/CT9VBWjtRubgOtmE2V2V7aarhRhQevND+IH+iDQBB5Z3GaE7I2iJUaFrYM79oJTexiYVVSOMar2fl/6a8f0HggYHds+Q0F98AEnAjKF2FfLcIxYtmfOWbDqxQcBDe+bAgZdxApC/pYdhOC2g+3u3DrxxZz0SkS6OREqBEVpj9/nRiU5311boa2K+HGTLBOJGRcIoARjGZYOdgJGDoYgsDQkyh2wT3V1bZsGrQhklG9V7opDjR0VF/OtT1/OOybGGuGQybYnUJd/GdogiswQcIlAGzSsS6LQ7t/ijqAyVJ2kQwNT+fmsToeoh1RDF2MdGBLQKuPUcgQgSacsuqAcPsisV15QBtKGKt0w8Bm64bH/2BdQjjrL9nMR10eCmt5VPAC/RUbalpMAdV5R3UdrMf3DYmtE2jN2w9oPPQhYADZRW94fBYiOCFWUyx+RWApcJ0ULNhG5jZVZLpsgObb8ncSwL02e1Km64SAoqNS95Tent3sKXd8dgRi7ezJAt9V0345oIwlDDh0CDhZYN4uBi0fO8NyeLngZWnrL3ZKH6rqNJyT0barm5N8VzblUVYnFANHZ0XY+YRz1/CkjwjBnAhIimFPrNSnLXFOFO7fWBHOxzAQ0QtArbC6OB9d8m3QOIqlmMbp6r7orA0bhvrNHzr5CTe/63DzDJu1Qo5QwMBNspngpqvvi1FhCEiHi2Sk6fdQnPKasqXQGbhAdvpnl6mGLkiCs0GxjiY9oeACxRqy7YLwMbCGg3VRDVcCAo81KhakbmxBAnYqcBer2VhuUD2xiE6HhVnHAvzUYX6Y/A6Hu/mR7zoYIoLg1VlXGFoPk62wAp9d1Ibbb4i5BPsNqdKQdRQh6yjC2RUR7joS7Fm85nTYtwMDl9EBfLZYhbggJSpk7ZizFW++PXWCGMwONhHj47bLOeKhNLDeULD7DmLhgzYarm7SLLTpOiBO46xh8M6eL3GtKWQS5hLY5aU5f2i29f4DOpsC/d0q+Ds2FrLLTOTjISjKuucvxy0KvGC0waJ7tt3HYn9AbWEShI1ybVvykB6sT2KtjVhMozN6KYldOHIe3jEionqwLiJJiY+vuoDBInuY5XLMjZosoAc2YTXoYRiuQ6SODTvtESp3lireakCElmuJtrYw0u5m2CKUKLAForaT4dkxqH02zdO62gYWmYV6ZFc028epaoaHOSQMbTQ7W6P2Q2gK7pg0e/bRbnrb/fYTCo9gY8kmmy6NiRMpsNBDsmnfFvkpCI2EoFz1O7dQ8K7Ys4xEgkJC3EOxjpe7tgjCvmyIHBoPTyVBn8CWL7gLj4Y17kpFHoXzBG3lrhMYFMhDBbAJuLb6N1njDesXRF+LFO640CGDrMPdV5oFZywHO0WoM/7QU2s27LU9IE8JNy4iAEsqrE463BypE+/9KT79AQFmFtVjL4eCjpddGolyqAigCDc8KrbAqa0aO4q74XjA6GQT5guLtbTV0GAkjAs1u5N0TQfHz2A6KVx+ZtirMNrKWgJlszCnFVBeHS4oNOxOv62Y02xw9rInFdrqvD+260EZiIIHcgxbQ9RWn5/iiHcThRCs0KlL/WAuW7C7a3yuB1amdYMX7qTTvPOqSyp5AK+U0OwW+dIYlw2oRXQimh38uiy5U+AQvGKTw1RtvoLn9zSLtPbXseBywyiQYisJbPNEXh0GMuxpMtsHv4orWMSk2Q2m7YQL/eNDZfwg7p/3+IwxrAfmV1ykdljeH86urbsJHPKfIf0pwvW7IqwnIhxuE2HSi7DCyODWZLh+SC2Cowv3EKlwP5MKu1Wl+h+Bpkcfw0VNOixrJiwghr0CZ3ixHtylLsNFtGwdhG2PAX4Z3dTIwmDnI71Bg6C+ZDXcgXgo3AdN2SnetxyG+RDHZKMbV9iHKorgcrXiGg5SZ/DIUsBtQn3dJgAWocBXBOsQYSsg+tu7wu5KyN6UgpmEzKvqT2CGq76U6cOgkJEP11nrVbhCoTcltiLEvZU9NzqMVGFUo1gs2nUQN1xFRx84X/NMHgWBpdUq3Feq2LJ14iQITJJINjPAnySB5QSSjVmi9sMrQuHYGXYW/Keo48hNR1tmTnZq6gB+7DuzEweiGyzcSqLu0S1wbMu6OJ3KHVmcCkso6WXp59ub0/5UWqz45qv7n//73/8fBENL5fHOAQA="; \ No newline at end of file diff --git a/api-reference/classes/Change.html b/api-reference/classes/Change.html index c8577ac74..917fb5110 100644 --- a/api-reference/classes/Change.html +++ b/api-reference/classes/Change.html @@ -1,5 +1,5 @@ Change | yorkie-js-sdk

Class Change<P>

Change represents a unit of modification in the document.

-

Type Parameters

Constructors

Type Parameters

Constructors

Properties

Constructors

  • Type Parameters

    Parameters

    • __namedParameters: {
          id: ChangeID;
          message?: string;
          operations?: Operation[];
          presenceChange?: PresenceChange<P>;
      }
      • id: ChangeID
      • Optional message?: string
      • Optional operations?: Operation[]
      • Optional presenceChange?: PresenceChange<P>

    Returns Change<P>

Properties

id: ChangeID
message?: string
operations: Operation[]
presenceChange?: PresenceChange<P>

Methods

  • execute executes the operations of this change to the given root.

    -

    Parameters

    • root: CRDTRoot
    • presences: Map<string, P>
    • source: OpSource

    Returns {
        opInfos: OperationInfo[];
        reverseOps: HistoryOperation<P>[];
    }

  • getMessage returns the message of this change.

    -

    Returns undefined | string

  • getPresenceChange returns the presence change of this change.

    -

    Returns undefined | PresenceChange<P>

  • hasOperations returns whether this change has operations or not.

    -

    Returns boolean

  • hasPresenceChange returns whether this change has presence change or not.

    -

    Returns boolean

  • toTestString returns a string containing the meta data of this change.

    -

    Returns string

  • create creates a new instance of Change.

    -

    Type Parameters

    Parameters

    • __namedParameters: {
          id: ChangeID;
          message?: string;
          operations?: Operation[];
          presenceChange?: PresenceChange<P>;
      }
      • id: ChangeID
      • Optional message?: string
      • Optional operations?: Operation[]
      • Optional presenceChange?: PresenceChange<P>

    Returns Change<P>

\ No newline at end of file +

Constructors

  • Type Parameters

    Parameters

    • __namedParameters: {
          id: ChangeID;
          message?: string;
          operations?: Operation[];
          presenceChange?: PresenceChange<P>;
      }
      • id: ChangeID
      • Optional message?: string
      • Optional operations?: Operation[]
      • Optional presenceChange?: PresenceChange<P>

    Returns Change<P>

Properties

id: ChangeID
message?: string
operations: Operation[]
presenceChange?: PresenceChange<P>

Methods

  • execute executes the operations of this change to the given root.

    +

    Parameters

    • root: CRDTRoot
    • presences: Map<string, P>
    • source: OpSource

    Returns {
        opInfos: OperationInfo[];
        reverseOps: HistoryOperation<P>[];
    }

  • getMessage returns the message of this change.

    +

    Returns undefined | string

  • getPresenceChange returns the presence change of this change.

    +

    Returns undefined | PresenceChange<P>

  • hasOperations returns whether this change has operations or not.

    +

    Returns boolean

  • hasPresenceChange returns whether this change has presence change or not.

    +

    Returns boolean

  • toTestString returns a string containing the meta data of this change.

    +

    Returns string

  • create creates a new instance of Change.

    +

    Type Parameters

    Parameters

    • __namedParameters: {
          id: ChangeID;
          message?: string;
          operations?: Operation[];
          presenceChange?: PresenceChange<P>;
      }
      • id: ChangeID
      • Optional message?: string
      • Optional operations?: Operation[]
      • Optional presenceChange?: PresenceChange<P>

    Returns Change<P>

\ No newline at end of file diff --git a/api-reference/classes/Client.html b/api-reference/classes/Client.html index b81bf132e..46e81ef65 100644 --- a/api-reference/classes/Client.html +++ b/api-reference/classes/Client.html @@ -1,7 +1,7 @@ Client | yorkie-js-sdk

Client is a normal client that can communicate with the server. It has documents and sends changes of the documents in local to the server to synchronize with other replicas in remote.

-

Constructors

Constructors

Properties

Constructors

Properties

apiKey: string
attachmentMap: Map<string, Attachment<unknown, any>>
conditions: Record<ClientCondition, boolean>
id?: string
key: string
processing: boolean = false
reconnectStreamDelay: number
retrySyncLoopDelay: number
rpcClient: PromiseClient<{
    methods: {
        activateClient: {
            I: typeof ActivateClientRequest;
            O: typeof ActivateClientResponse;
            kind: Unary;
            name: "ActivateClient";
        };
        attachDocument: {
            I: typeof AttachDocumentRequest;
            O: typeof AttachDocumentResponse;
            kind: Unary;
            name: "AttachDocument";
        };
        broadcast: {
            I: typeof BroadcastRequest;
            O: typeof BroadcastResponse;
            kind: Unary;
            name: "Broadcast";
        };
        deactivateClient: {
            I: typeof DeactivateClientRequest;
            O: typeof DeactivateClientResponse;
            kind: Unary;
            name: "DeactivateClient";
        };
        detachDocument: {
            I: typeof DetachDocumentRequest;
            O: typeof DetachDocumentResponse;
            kind: Unary;
            name: "DetachDocument";
        };
        pushPullChanges: {
            I: typeof PushPullChangesRequest;
            O: typeof PushPullChangesResponse;
            kind: Unary;
            name: "PushPullChanges";
        };
        removeDocument: {
            I: typeof RemoveDocumentRequest;
            O: typeof RemoveDocumentResponse;
            kind: Unary;
            name: "RemoveDocument";
        };
        watchDocument: {
            I: typeof WatchDocumentRequest;
            O: typeof WatchDocumentResponse;
            kind: ServerStreaming;
            name: "WatchDocument";
        };
    };
    typeName: "yorkie.v1.YorkieService";
}>

Type declaration

  • Readonly methods: {
        activateClient: {
            I: typeof ActivateClientRequest;
            O: typeof ActivateClientResponse;
            kind: Unary;
            name: "ActivateClient";
        };
        attachDocument: {
            I: typeof AttachDocumentRequest;
            O: typeof AttachDocumentResponse;
            kind: Unary;
            name: "AttachDocument";
        };
        broadcast: {
            I: typeof BroadcastRequest;
            O: typeof BroadcastResponse;
            kind: Unary;
            name: "Broadcast";
        };
        deactivateClient: {
            I: typeof DeactivateClientRequest;
            O: typeof DeactivateClientResponse;
            kind: Unary;
            name: "DeactivateClient";
        };
        detachDocument: {
            I: typeof DetachDocumentRequest;
            O: typeof DetachDocumentResponse;
            kind: Unary;
            name: "DetachDocument";
        };
        pushPullChanges: {
            I: typeof PushPullChangesRequest;
            O: typeof PushPullChangesResponse;
            kind: Unary;
            name: "PushPullChanges";
        };
        removeDocument: {
            I: typeof RemoveDocumentRequest;
            O: typeof RemoveDocumentResponse;
            kind: Unary;
            name: "RemoveDocument";
        };
        watchDocument: {
            I: typeof WatchDocumentRequest;
            O: typeof WatchDocumentResponse;
            kind: ServerStreaming;
            name: "WatchDocument";
        };
    }
    • Readonly activateClient: {
          I: typeof ActivateClientRequest;
          O: typeof ActivateClientResponse;
          kind: Unary;
          name: "ActivateClient";
      }

      Generated

      from rpc yorkie.v1.YorkieService.ActivateClient

      +

Returns Client

Properties

apiKey: string
attachmentMap: Map<string, Attachment<unknown, any>>
conditions: Record<ClientCondition, boolean>
id?: string
key: string
processing: boolean = false
reconnectStreamDelay: number
retrySyncLoopDelay: number
rpcClient: PromiseClient<{
    methods: {
        activateClient: {
            I: typeof ActivateClientRequest;
            O: typeof ActivateClientResponse;
            kind: Unary;
            name: "ActivateClient";
        };
        attachDocument: {
            I: typeof AttachDocumentRequest;
            O: typeof AttachDocumentResponse;
            kind: Unary;
            name: "AttachDocument";
        };
        broadcast: {
            I: typeof BroadcastRequest;
            O: typeof BroadcastResponse;
            kind: Unary;
            name: "Broadcast";
        };
        deactivateClient: {
            I: typeof DeactivateClientRequest;
            O: typeof DeactivateClientResponse;
            kind: Unary;
            name: "DeactivateClient";
        };
        detachDocument: {
            I: typeof DetachDocumentRequest;
            O: typeof DetachDocumentResponse;
            kind: Unary;
            name: "DetachDocument";
        };
        pushPullChanges: {
            I: typeof PushPullChangesRequest;
            O: typeof PushPullChangesResponse;
            kind: Unary;
            name: "PushPullChanges";
        };
        removeDocument: {
            I: typeof RemoveDocumentRequest;
            O: typeof RemoveDocumentResponse;
            kind: Unary;
            name: "RemoveDocument";
        };
        watchDocument: {
            I: typeof WatchDocumentRequest;
            O: typeof WatchDocumentResponse;
            kind: ServerStreaming;
            name: "WatchDocument";
        };
    };
    typeName: "yorkie.v1.YorkieService";
}>

Type declaration

  • Readonly methods: {
        activateClient: {
            I: typeof ActivateClientRequest;
            O: typeof ActivateClientResponse;
            kind: Unary;
            name: "ActivateClient";
        };
        attachDocument: {
            I: typeof AttachDocumentRequest;
            O: typeof AttachDocumentResponse;
            kind: Unary;
            name: "AttachDocument";
        };
        broadcast: {
            I: typeof BroadcastRequest;
            O: typeof BroadcastResponse;
            kind: Unary;
            name: "Broadcast";
        };
        deactivateClient: {
            I: typeof DeactivateClientRequest;
            O: typeof DeactivateClientResponse;
            kind: Unary;
            name: "DeactivateClient";
        };
        detachDocument: {
            I: typeof DetachDocumentRequest;
            O: typeof DetachDocumentResponse;
            kind: Unary;
            name: "DetachDocument";
        };
        pushPullChanges: {
            I: typeof PushPullChangesRequest;
            O: typeof PushPullChangesResponse;
            kind: Unary;
            name: "PushPullChanges";
        };
        removeDocument: {
            I: typeof RemoveDocumentRequest;
            O: typeof RemoveDocumentResponse;
            kind: Unary;
            name: "RemoveDocument";
        };
        watchDocument: {
            I: typeof WatchDocumentRequest;
            O: typeof WatchDocumentResponse;
            kind: ServerStreaming;
            name: "WatchDocument";
        };
    }
    • Readonly activateClient: {
          I: typeof ActivateClientRequest;
          O: typeof ActivateClientResponse;
          kind: Unary;
          name: "ActivateClient";
      }

      Generated

      from rpc yorkie.v1.YorkieService.ActivateClient

      • Readonly I: typeof ActivateClientRequest
      • Readonly O: typeof ActivateClientResponse
      • Readonly kind: Unary
      • Readonly name: "ActivateClient"
    • Readonly attachDocument: {
          I: typeof AttachDocumentRequest;
          O: typeof AttachDocumentResponse;
          kind: Unary;
          name: "AttachDocument";
      }

      Generated

      from rpc yorkie.v1.YorkieService.AttachDocument

      • Readonly I: typeof AttachDocumentRequest
      • Readonly O: typeof AttachDocumentResponse
      • Readonly kind: Unary
      • Readonly name: "AttachDocument"
    • Readonly broadcast: {
          I: typeof BroadcastRequest;
          O: typeof BroadcastResponse;
          kind: Unary;
          name: "Broadcast";
      }

      Generated

      from rpc yorkie.v1.YorkieService.Broadcast

      • Readonly I: typeof BroadcastRequest
      • Readonly O: typeof BroadcastResponse
      • Readonly kind: Unary
      • Readonly name: "Broadcast"
    • Readonly deactivateClient: {
          I: typeof DeactivateClientRequest;
          O: typeof DeactivateClientResponse;
          kind: Unary;
          name: "DeactivateClient";
      }

      Generated

      from rpc yorkie.v1.YorkieService.DeactivateClient

      @@ -46,35 +46,35 @@
      • Readonly I: typeof DetachDocumentRequest
      • Readonly O: typeof DetachDocumentResponse
      • Readonly kind: Unary
      • Readonly name: "DetachDocument"
    • Readonly pushPullChanges: {
          I: typeof PushPullChangesRequest;
          O: typeof PushPullChangesResponse;
          kind: Unary;
          name: "PushPullChanges";
      }

      Generated

      from rpc yorkie.v1.YorkieService.PushPullChanges

      • Readonly I: typeof PushPullChangesRequest
      • Readonly O: typeof PushPullChangesResponse
      • Readonly kind: Unary
      • Readonly name: "PushPullChanges"
    • Readonly removeDocument: {
          I: typeof RemoveDocumentRequest;
          O: typeof RemoveDocumentResponse;
          kind: Unary;
          name: "RemoveDocument";
      }

      Generated

      from rpc yorkie.v1.YorkieService.RemoveDocument

      • Readonly I: typeof RemoveDocumentRequest
      • Readonly O: typeof RemoveDocumentResponse
      • Readonly kind: Unary
      • Readonly name: "RemoveDocument"
    • Readonly watchDocument: {
          I: typeof WatchDocumentRequest;
          O: typeof WatchDocumentResponse;
          kind: ServerStreaming;
          name: "WatchDocument";
      }

      Generated

      from rpc yorkie.v1.YorkieService.WatchDocument

      -
      • Readonly I: typeof WatchDocumentRequest
      • Readonly O: typeof WatchDocumentResponse
      • Readonly kind: ServerStreaming
      • Readonly name: "WatchDocument"
  • Readonly typeName: "yorkie.v1.YorkieService"
status: ClientStatus
syncLoopDuration: number
taskQueue: (() => Promise<any>)[]

Type declaration

    • (): Promise<any>
    • Returns Promise<any>

Methods

  • activate activates this client. That is, it registers itself to the server +

    • Readonly I: typeof WatchDocumentRequest
    • Readonly O: typeof WatchDocumentResponse
    • Readonly kind: ServerStreaming
    • Readonly name: "WatchDocument"
  • Readonly typeName: "yorkie.v1.YorkieService"
  • status: ClientStatus
    syncLoopDuration: number
    taskQueue: (() => Promise<any>)[]

    Type declaration

      • (): Promise<any>
      • Returns Promise<any>

    Methods

    • activate activates this client. That is, it registers itself to the server and receives a unique ID from the server. The given ID is used to distinguish different clients.

      -

      Returns Promise<void>

    • attach attaches the given document to this client. It tells the server that +

      Returns Promise<void>

    • attach attaches the given document to this client. It tells the server that this client will synchronize the given document.

      -

      Type Parameters

      Parameters

      • doc: Document<T, P>
      • options: {
            initialPresence?: P;
            initialRoot?: T;
            syncMode?: SyncMode;
        } = {}
        • Optional initialPresence?: P
        • Optional initialRoot?: T
        • Optional syncMode?: SyncMode

      Returns Promise<Document<T, P>>

    • broadcast broadcasts the given payload to the given topic.

      -

      Parameters

      • docKey: string
      • topic: string
      • payload: Json
      • Optional options: BroadcastOptions

      Returns Promise<void>

    • deactivate deactivates this client.

      -

      Returns Promise<void>

    • detach detaches the given document from this client. It tells the +

      Type Parameters

      Parameters

      • doc: Document<T, P>
      • options: {
            initialPresence?: P;
            initialRoot?: T;
            syncMode?: SyncMode;
        } = {}
        • Optional initialPresence?: P
        • Optional initialRoot?: T
        • Optional syncMode?: SyncMode

      Returns Promise<Document<T, P>>

    • broadcast broadcasts the given payload to the given topic.

      +

      Parameters

      • docKey: string
      • topic: string
      • payload: Json
      • Optional options: BroadcastOptions

      Returns Promise<void>

    • deactivate deactivates this client.

      +

      Returns Promise<void>

    • detach detaches the given document from this client. It tells the server that this client will no longer synchronize the given document.

      To collect garbage things like CRDT tombstones left on the document, all the changes should be applied to other replicas before GC time. For this, if the document is no longer used by this client, it should be detached.

      -

      Type Parameters

      Parameters

      • doc: Document<T, P>
      • options: {
            removeIfNotAttached?: boolean;
        } = {}
        • Optional removeIfNotAttached?: boolean

      Returns Promise<Document<T, P>>

    • enqueueTask enqueues the given task to the task queue.

      -

      Parameters

      • task: (() => Promise<any>)
          • (): Promise<any>
          • Returns Promise<any>

      Returns Promise<any>

    • getID returns a ActorID of client.

      -

      Returns undefined | string

    • handleConnectError handles the given error. If the given error can be +

      Type Parameters

      Parameters

      • doc: Document<T, P>
      • options: {
            removeIfNotAttached?: boolean;
        } = {}
        • Optional removeIfNotAttached?: boolean

      Returns Promise<Document<T, P>>

    • enqueueTask enqueues the given task to the task queue.

      +

      Parameters

      • task: (() => Promise<any>)
          • (): Promise<any>
          • Returns Promise<any>

      Returns Promise<any>

    • getID returns a ActorID of client.

      +

      Returns undefined | string

    • handleConnectError handles the given error. If the given error can be retried after handling, it returns true.

      -

      Parameters

      • err: any

      Returns boolean

    • Type Parameters

      Parameters

      • attachment: Attachment<T, P>
      • resp: WatchDocumentResponse

      Returns void

    • isActive checks if the client is active.

      -

      Returns boolean

    • processNext processes the next task in the task queue. This method is +

      Parameters

      • err: any

      Returns boolean

    • Type Parameters

      Parameters

      • attachment: Attachment<T, P>
      • resp: WatchDocumentResponse

      Returns void

    • isActive checks if the client is active.

      +

      Returns boolean

    • processNext processes the next task in the task queue. This method is part of enqueueTask.

      -

      Returns Promise<void>

    • runSyncLoop runs the sync loop. The sync loop pushes local changes to +

      Returns Promise<void>

    • runSyncLoop runs the sync loop. The sync loop pushes local changes to the server and pulls remote changes from the server.

      -

      Returns void

    • runWatchLoop runs the watch loop for the given document. The watch loop +

      Returns void

    • runWatchLoop runs the watch loop for the given document. The watch loop listens to the events of the given document from the server.

      -

      Parameters

      • docKey: string

      Returns Promise<void>

    • sync pushes local changes of the attached documents to the server and +

      Parameters

      • docKey: string

      Returns Promise<void>

    • sync pushes local changes of the attached documents to the server and receives changes of the remote replica from the server then apply them to local documents.

      -

      Type Parameters

      Parameters

      Returns Promise<Document<T, P>[]>

    \ No newline at end of file +

    Type Parameters

    Parameters

    Returns Promise<Document<T, P>[]>

    \ No newline at end of file diff --git a/api-reference/classes/Counter.html b/api-reference/classes/Counter.html index 477869c5d..93e5658fe 100644 --- a/api-reference/classes/Counter.html +++ b/api-reference/classes/Counter.html @@ -1,5 +1,5 @@ Counter | yorkie-js-sdk

    Counter is a custom data type that is used to counter.

    -

    Constructors

    Constructors

    Properties

    Constructors

    Properties

    context?: ChangeContext<Indexable>
    counter?: CRDTCounter
    value: number | Long
    valueType: CounterType

    Methods

    • Internal

      getValue returns the value of this counter;

      -

      Returns number | Long

    • getValueType returns the value type of this counter.

      -

      Returns CounterType

    • Internal

      initialize initialize this text with context and internal text.

      -

      Parameters

      • context: ChangeContext<Indexable>
      • counter: CRDTCounter

      Returns void

    \ No newline at end of file +

    Constructors

    Properties

    context?: ChangeContext<Indexable>
    counter?: CRDTCounter
    value: number | Long
    valueType: CounterType

    Methods

    • Internal

      getValue returns the value of this counter;

      +

      Returns number | Long

    • getValueType returns the value type of this counter.

      +

      Returns CounterType

    • Internal

      initialize initialize this text with context and internal text.

      +

      Parameters

      • context: ChangeContext<Indexable>
      • counter: CRDTCounter

      Returns void

    \ No newline at end of file diff --git a/api-reference/classes/Document.html b/api-reference/classes/Document.html index b61a10cf9..88182bdd8 100644 --- a/api-reference/classes/Document.html +++ b/api-reference/classes/Document.html @@ -1,6 +1,6 @@ Document | yorkie-js-sdk

    Class Document<T, P>

    Document is a CRDT-based data type. We can represent the model of the application and edit it even while offline.

    -

    Type Parameters

    Constructors

    Type Parameters

    Constructors

    Properties

    changeID: ChangeID
    checkpoint: Checkpoint
    clone?: {
        presences: Map<string, P>;
        root: CRDTRoot;
    }

    Type declaration

    • presences: Map<string, P>
    • root: CRDTRoot
    eventStreamObserver: Observer<TransactionEvent<P>>
    history: {
        canRedo: (() => boolean);
        canUndo: (() => boolean);
        redo: (() => void);
        undo: (() => void);
    }

    history is exposed to the user to manage undo/redo operations.

    +

    Constructors

    Properties

    changeID: ChangeID
    checkpoint: Checkpoint
    clone?: {
        presences: Map<string, P>;
        root: CRDTRoot;
    }

    Type declaration

    • presences: Map<string, P>
    • root: CRDTRoot
    eventStreamObserver: Observer<TransactionEvent<P>>
    history: {
        canRedo: (() => boolean);
        canUndo: (() => boolean);
        redo: (() => void);
        undo: (() => void);
    }

    history is exposed to the user to manage undo/redo operations.

    Type declaration

    • canRedo: (() => boolean)
        • (): boolean
        • canRedo returns whether there are any operations to redo.

          Returns boolean

    • canUndo: (() => boolean)
        • (): boolean
        • canUndo returns whether there are any operations to undo.

          Returns boolean

    • redo: (() => void)
        • (): void
        • redo redoes the last operation executed by the current client. It does not impact operations made by other clients.

          Returns void

    • undo: (() => void)
        • (): void
        • undo undoes the last operation executed by the current client. It does not impact operations made by other clients.

          -

          Returns void

    internalHistory: History<P>

    internalHistory is used to manage undo/redo operations internally.

    -
    isUpdating: boolean

    isUpdating is whether the document is updating by updater or not. It is +

    Returns void

    internalHistory: History<P>

    internalHistory is used to manage undo/redo operations internally.

    +
    isUpdating: boolean

    isUpdating is whether the document is updating by updater or not. It is used to prevent the updater from calling undo/redo.

    -
    key: string
    localChanges: Change<P>[]
    onlineClients: Set<string>

    onlineClients is a set of client IDs that are currently online.

    -
    opts: DocumentOptions
    presences: Map<string, P>

    presences is a map of client IDs to their presence information.

    -
    root: CRDTRoot

    Methods

    • Internal

      addOnlineClient adds the given clientID into the online client set.

      -

      Parameters

      • clientID: string

      Returns void

    • Internal

      applyChangePack applies the given change pack into this document.

      +
    key: string
    localChanges: Change<P>[]
    onlineClients: Set<string>

    onlineClients is a set of client IDs that are currently online.

    +
    opts: DocumentOptions
    presences: Map<string, P>

    presences is a map of client IDs to their presence information.

    +
    root: CRDTRoot

    Methods

    • Internal

      addOnlineClient adds the given clientID into the online client set.

      +

      Parameters

      • clientID: string

      Returns void

    • Internal

      applyChangePack applies the given change pack into this document.

      1. Remove local changes applied to server.
      2. Update the checkpoint.
      3. Do Garbage collection.

      Parameters

      • pack: ChangePack<P>

        change pack

        -

      Returns void

    • applySnapshot applies the given snapshot into this document.

      -

      Parameters

      • serverSeq: bigint
      • snapshotVector: VersionVector
      • Optional snapshot: Uint8Array

      Returns void

    • applyWatchStream applies the given watch stream response into this document.

      -

      Parameters

      • resp: WatchDocumentResponse

      Returns void

    • broadcast the payload to the given topic.

      -

      Parameters

      • topic: string
      • payload: Json
      • Optional options: BroadcastOptions

      Returns void

    • canRedo returns whether there are any operations to redo.

      -

      Returns boolean

    • canUndo returns whether there are any operations to undo.

      -

      Returns boolean

    • Internal

      createChangePack create change pack of the local changes to send to the +

    Returns void

    \ No newline at end of file +

    Returns void

    \ No newline at end of file diff --git a/api-reference/classes/Primitive.html b/api-reference/classes/Primitive.html index 82d871dea..d75f9aad4 100644 --- a/api-reference/classes/Primitive.html +++ b/api-reference/classes/Primitive.html @@ -1,6 +1,6 @@ Primitive | yorkie-js-sdk

    Class Primitive

    Primitive represents primitive data type including logical clock. It has a type and a value.

    -

    Hierarchy

    • CRDTElement
      • Primitive

    Constructors

    Hierarchy

    • CRDTElement
      • Primitive

    Constructors

    Properties

    Methods

    deepcopy @@ -25,27 +25,27 @@ isSupport of valueFromBytes -

    Constructors

    Properties

    valueType: PrimitiveType

    Methods

    • getPositionedAt returns the time of this element when it was positioned +

    Constructors

    Properties

    valueType: PrimitiveType

    Methods

    • getPositionedAt returns the time of this element when it was positioned in the document by undo/redo or move operation.

      -

      Returns TimeTicket

    • isRemoved check if this element was removed.

      -

      Returns boolean

    • setMovedAt sets the move time of this element.

      -

      Parameters

      Returns boolean

    • setRemovedAt sets the remove time of this element.

      -

      Parameters

      Returns void

    • toSortedJSON returns the sorted JSON encoding of the value.

      -

      Returns string

    • getPrimitiveType returns the primitive type of the value.

      -

      Parameters

      • value: unknown

      Returns undefined | PrimitiveType

    • isInteger checks if the given number is integer.

      -

      Parameters

      • num: number

      Returns boolean

    • isSupport check if the given value is supported type.

      -

      Parameters

      • value: unknown

      Returns boolean

    \ No newline at end of file +

    Returns TimeTicket

    \ No newline at end of file diff --git a/api-reference/classes/Text.html b/api-reference/classes/Text.html index 31edd9f9a..f5e18bae6 100644 --- a/api-reference/classes/Text.html +++ b/api-reference/classes/Text.html @@ -1,5 +1,5 @@ Text | yorkie-js-sdk

    Class Text<A>

    Text is an extended data type for the contents of a text editor.

    -

    Type Parameters

    Constructors

    Type Parameters

    Constructors

    Properties

    Accessors

    length @@ -19,23 +19,23 @@ toString toTestString values -

    Constructors

    Properties

    context?: ChangeContext<Indexable>
    text?: CRDTText<A>

    Accessors

    Methods

    • createRangeForTest returns pair of RGATreeSplitNodePos of the given indexes +

    Constructors

    Properties

    context?: ChangeContext<Indexable>
    text?: CRDTText<A>

    Accessors

    Methods

    • createRangeForTest returns pair of RGATreeSplitNodePos of the given indexes for testing purpose.

      -

      Parameters

      • fromIdx: number
      • toIdx: number

      Returns RGATreeSplitPosRange

    • delete deletes the text in the given range.

      -

      Parameters

      • fromIdx: number
      • toIdx: number

      Returns undefined | [number, number]

    • edit edits this text with the given content.

      -

      Parameters

      • fromIdx: number
      • toIdx: number
      • content: string
      • Optional attributes: A

      Returns undefined | [number, number]

    • empty makes the text empty.

      -

      Returns undefined | [number, number]

    • getTreeByID returns IDTree of the text for testing purpose.

      -

      Returns LLRBTree<RGATreeSplitNodeID, RGATreeSplitNode<CRDTTextValue>>

    • getTreeByIndex returns IndexTree of the text for testing purpose.

      -

      Returns SplayTree<CRDTTextValue>

    • Internal

      initialize initialize this text with context and internal text.

      -

      Parameters

      • context: ChangeContext<Indexable>
      • text: CRDTText<A>

      Returns void

    • setStyle styles this text with the given attributes.

      -

      Parameters

      • fromIdx: number
      • toIdx: number
      • attributes: A

      Returns boolean

    • toString returns the string representation of this text.

      -

      Returns string

    • toTestString returns a String containing the meta data of the node +

      Parameters

      • fromIdx: number
      • toIdx: number

      Returns RGATreeSplitPosRange

    • delete deletes the text in the given range.

      +

      Parameters

      • fromIdx: number
      • toIdx: number

      Returns undefined | [number, number]

    • edit edits this text with the given content.

      +

      Parameters

      • fromIdx: number
      • toIdx: number
      • content: string
      • Optional attributes: A

      Returns undefined | [number, number]

    • empty makes the text empty.

      +

      Returns undefined | [number, number]

    • getTreeByID returns IDTree of the text for testing purpose.

      +

      Returns LLRBTree<RGATreeSplitNodeID, RGATreeSplitNode<CRDTTextValue>>

    • getTreeByIndex returns IndexTree of the text for testing purpose.

      +

      Returns SplayTree<CRDTTextValue>

    • Internal

      initialize initialize this text with context and internal text.

      +

      Parameters

      • context: ChangeContext<Indexable>
      • text: CRDTText<A>

      Returns void

    • setStyle styles this text with the given attributes.

      +

      Parameters

      • fromIdx: number
      • toIdx: number
      • attributes: A

      Returns boolean

    • toString returns the string representation of this text.

      +

      Returns string

    • toTestString returns a String containing the meta data of the node for debugging purpose.

      -

      Returns string

    \ No newline at end of file +

    Returns string

    \ No newline at end of file diff --git a/api-reference/classes/TimeTicket.html b/api-reference/classes/TimeTicket.html index 7bb7fb652..429b5f717 100644 --- a/api-reference/classes/TimeTicket.html +++ b/api-reference/classes/TimeTicket.html @@ -1,6 +1,6 @@ TimeTicket | yorkie-js-sdk

    Class TimeTicket

    TimeTicket is a timestamp of the logical clock. Ticket is immutable. It is created by ChangeID.

    -

    Constructors

    Constructors

    Properties

    Constructors

    Properties

    actorID: string
    delimiter: number
    lamport: bigint

    Methods

    • compare returns an integer comparing two Ticket. +

    Constructors

    Properties

    actorID: string
    delimiter: number
    lamport: bigint

    Methods

    • compare returns an integer comparing two Ticket. The result will be 0 if id==other, -1 if id < other, and +1 if id > other. If the receiver or argument is nil, it would panic at runtime.

      -

      Parameters

      Returns number

    • toTestString returns a string containing the meta data of the ticket for debugging purpose.

      -

      Returns string

    \ No newline at end of file +

    Returns string

    \ No newline at end of file diff --git a/api-reference/classes/Tree.html b/api-reference/classes/Tree.html index b4c6c3ce2..69255ca9f 100644 --- a/api-reference/classes/Tree.html +++ b/api-reference/classes/Tree.html @@ -1,6 +1,6 @@ Tree | yorkie-js-sdk

    Tree is a CRDT-based tree structure that is used to represent the document tree of text-based editor such as ProseMirror.

    -

    Constructors

    Constructors

    Properties

    Constructors

    Properties

    context?: ChangeContext<Indexable>
    initialRoot?: ElementNode
    tree?: CRDTTree

    Methods

    • buildRoot builds the root of this tree with the given initial root +

    Constructors

    Properties

    context?: ChangeContext<Indexable>
    initialRoot?: ElementNode
    tree?: CRDTTree

    Methods

    • buildRoot builds the root of this tree with the given initial root which set by the user.

      -

      Parameters

      Returns CRDTTreeNode

    • edit edits this tree with the given nodes.

      -

      Parameters

      • fromIdx: number
      • toIdx: number
      • Optional content: TreeNode
      • splitLevel: number = 0

      Returns boolean

    • editBulk edits this tree with the given nodes.

      -

      Parameters

      • fromIdx: number
      • toIdx: number
      • contents: TreeNode[]
      • splitLevel: number = 0

      Returns boolean

    • editBulkByPath edits this tree with the given node and path.

      -

      Parameters

      • fromPath: number[]
      • toPath: number[]
      • contents: TreeNode[]
      • splitLevel: number = 0

      Returns boolean

    • editByPath edits this tree with the given node and path.

      -

      Parameters

      • fromPath: number[]
      • toPath: number[]
      • Optional content: TreeNode
      • splitLevel: number = 0

      Returns boolean

    • Parameters

      • fromPos: CRDTTreePos
      • toPos: CRDTTreePos
      • contents: TreeNode[]
      • splitLevel: number = 0

      Returns boolean

    • getIndexTree returns the index tree of this tree.

      -

      Returns IndexTree<CRDTTreeNode>

    • indexToPath returns the path of the given index.

      -

      Parameters

      • index: number

      Returns number[]

    • Internal

      initialize initialize this tree with context and internal tree.

      -

      Parameters

      • context: ChangeContext<Indexable>
      • tree: CRDTTree

      Returns void

    • pathToIndex returns the index of given path.

      -

      Parameters

      • path: number[]

      Returns number

    • posRangeToPathRange converts the position range into the path range.

      -

      Parameters

      Returns [number[], number[]]

    • removeStyle removes the attributes to the elements of the given range.

      -

      Parameters

      • fromIdx: number
      • toIdx: number
      • attributesToRemove: string[]

      Returns void

    • style sets the attributes to the elements of the given range.

      -

      Parameters

      • fromIdx: number
      • toIdx: number
      • attributes: {
            [key: string]: any;
        }
        • [key: string]: any

      Returns void

    • styleByPath sets the attributes to the elements of the given path.

      -

      Parameters

      • path: number[]
      • attributes: {
            [key: string]: any;
        }
        • [key: string]: any

      Returns void

    \ No newline at end of file +

    Parameters

    Returns CRDTTreeNode

    \ No newline at end of file diff --git a/api-reference/classes/VersionVector.html b/api-reference/classes/VersionVector.html index a0c7877f3..3cd054797 100644 --- a/api-reference/classes/VersionVector.html +++ b/api-reference/classes/VersionVector.html @@ -2,7 +2,7 @@ between changes whether they are causally related or concurrent. It is similar to vector clocks, but it is synced with lamport timestamp of the change.

    -

    Constructors

    Constructors

    Properties

    Methods

    [iterator] afterOrEqual @@ -13,12 +13,12 @@ maxLamport set size -

    Constructors

    Properties

    vector: Map<string, bigint>

    Methods

    • get gets the lamport timestamp of the given actor.

      -

      Parameters

      • actorID: string

      Returns undefined | bigint

    • set sets the lamport timestamp of the given actor.

      -

      Parameters

      • actorID: string
      • lamport: bigint

      Returns void

    \ No newline at end of file +

    Constructors

    Properties

    vector: Map<string, bigint>

    Methods

    • get gets the lamport timestamp of the given actor.

      +

      Parameters

      • actorID: string

      Returns undefined | bigint

    • set sets the lamport timestamp of the given actor.

      +

      Parameters

      • actorID: string
      • lamport: bigint

      Returns void

    \ No newline at end of file diff --git a/api-reference/enums/ClientCondition.html b/api-reference/enums/ClientCondition.html index 62037431d..826a78a25 100644 --- a/api-reference/enums/ClientCondition.html +++ b/api-reference/enums/ClientCondition.html @@ -1,6 +1,6 @@ ClientCondition | yorkie-js-sdk

    Enumeration ClientCondition

    ClientCondition represents the condition of the client.

    -

    Enumeration Members

    Enumeration Members

    Enumeration Members

    SyncLoop: "SyncLoop"

    SyncLoop is a key of the sync loop condition.

    -
    WatchLoop: "WatchLoop"

    WatchLoop is a key of the watch loop condition.

    -
    \ No newline at end of file +
    WatchLoop: "WatchLoop"

    WatchLoop is a key of the watch loop condition.

    +
    \ No newline at end of file diff --git a/api-reference/enums/ClientStatus.html b/api-reference/enums/ClientStatus.html index 1ff0f3bd3..5ae02c9bc 100644 --- a/api-reference/enums/ClientStatus.html +++ b/api-reference/enums/ClientStatus.html @@ -1,9 +1,9 @@ ClientStatus | yorkie-js-sdk

    Enumeration ClientStatus

    ClientStatus represents the status of the client.

    -

    Enumeration Members

    Enumeration Members

    Enumeration Members

    Activated: "activated"

    Activated means that the client is activated. If the client is activated, all Documents of the client are also ready to be used.

    -
    Deactivated: "deactivated"

    Deactivated means that the client is not activated. It is the initial +

    Deactivated: "deactivated"

    Deactivated means that the client is not activated. It is the initial status of the client. If the client is deactivated, all Documents of the client are also not used.

    -
    \ No newline at end of file +
    \ No newline at end of file diff --git a/api-reference/enums/DocEventType.html b/api-reference/enums/DocEventType.html index 3096f6767..9636ae427 100644 --- a/api-reference/enums/DocEventType.html +++ b/api-reference/enums/DocEventType.html @@ -1,5 +1,5 @@ DocEventType | yorkie-js-sdk

    Enumeration DocEventType

    DocEventType represents the type of the event that occurs in Document.

    -

    Enumeration Members

    Enumeration Members

    Enumeration Members

    Broadcast: "broadcast"

    Broadcast means that the broadcast event is received from the remote client.

    -
    ConnectionChanged: "connection-changed"

    ConnectionChanged means that the watch stream connection status has changed.

    -
    Initialized: "initialized"

    Initialized means that online clients have been loaded from the server.

    -
    LocalBroadcast: "local-broadcast"

    LocalBroadcast means that the broadcast event is sent from the local client.

    -
    LocalChange: "local-change"

    local document change event type

    -
    PresenceChanged: "presence-changed"

    PresenceChanged means that the presences of the client has updated.

    -
    RemoteChange: "remote-change"

    remote document change event type

    -
    Snapshot: "snapshot"

    snapshot event type

    -
    StatusChanged: "status-changed"

    status changed event type

    -
    SyncStatusChanged: "sync-status-changed"

    SyncStatusChanged means that the document sync status has changed.

    -
    Unwatched: "unwatched"

    Unwatched means that the connection has been disconnected.

    -
    Watched: "watched"

    Watched means that the client has established a connection with the server, +

    ConnectionChanged: "connection-changed"

    ConnectionChanged means that the watch stream connection status has changed.

    +
    Initialized: "initialized"

    Initialized means that online clients have been loaded from the server.

    +
    LocalBroadcast: "local-broadcast"

    LocalBroadcast means that the broadcast event is sent from the local client.

    +
    LocalChange: "local-change"

    local document change event type

    +
    PresenceChanged: "presence-changed"

    PresenceChanged means that the presences of the client has updated.

    +
    RemoteChange: "remote-change"

    remote document change event type

    +
    Snapshot: "snapshot"

    snapshot event type

    +
    StatusChanged: "status-changed"

    status changed event type

    +
    SyncStatusChanged: "sync-status-changed"

    SyncStatusChanged means that the document sync status has changed.

    +
    Unwatched: "unwatched"

    Unwatched means that the connection has been disconnected.

    +
    Watched: "watched"

    Watched means that the client has established a connection with the server, enabling real-time synchronization.

    -
    \ No newline at end of file +
    \ No newline at end of file diff --git a/api-reference/enums/DocumentStatus.html b/api-reference/enums/DocumentStatus.html index f179e16f1..c2534f37e 100644 --- a/api-reference/enums/DocumentStatus.html +++ b/api-reference/enums/DocumentStatus.html @@ -1,11 +1,11 @@ DocumentStatus | yorkie-js-sdk

    Enumeration DocumentStatus

    DocumentStatus represents the status of the document.

    -

    Enumeration Members

    Enumeration Members

    Enumeration Members

    Attached: "attached"

    Attached means that this document is attached to the client. The actor of the ticket is created with being assigned by the client.

    -
    Detached: "detached"

    Detached means that the document is not attached to the client. +

    Detached: "detached"

    Detached means that the document is not attached to the client. The actor of the ticket is created without being assigned.

    -
    Removed: "removed"

    Removed means that this document is removed. If the document is removed, +

    Removed: "removed"

    Removed means that this document is removed. If the document is removed, it cannot be edited.

    -
    \ No newline at end of file +
    \ No newline at end of file diff --git a/api-reference/enums/DocumentSyncStatus.html b/api-reference/enums/DocumentSyncStatus.html index 4b4d8fc61..a71dd27d3 100644 --- a/api-reference/enums/DocumentSyncStatus.html +++ b/api-reference/enums/DocumentSyncStatus.html @@ -1,6 +1,6 @@ DocumentSyncStatus | yorkie-js-sdk

    Enumeration DocumentSyncStatus

    DocumentSyncStatus represents the result of synchronizing the document with the server.

    -

    Enumeration Members

    Enumeration Members

    Enumeration Members

    SyncFailed: "sync-failed"

    SyncFiled means that document synchronization has failed.

    -
    Synced: "synced"

    Synced means that document synced successfully.

    -
    \ No newline at end of file +
    Synced: "synced"

    Synced means that document synced successfully.

    +
    \ No newline at end of file diff --git a/api-reference/enums/LogLevel.html b/api-reference/enums/LogLevel.html index b0f89490a..91c6fe30c 100644 --- a/api-reference/enums/LogLevel.html +++ b/api-reference/enums/LogLevel.html @@ -1,7 +1,7 @@ -LogLevel | yorkie-js-sdk

    Enumeration LogLevel

    Enumeration Members

    Debug +LogLevel | yorkie-js-sdk

    Enumeration LogLevel

    Enumeration Members

    Enumeration Members

    Debug: 1
    Error: 4
    Fatal: 5
    Info: 2
    Trivial: 0
    Warn: 3
    \ No newline at end of file +

    Enumeration Members

    Debug: 1
    Error: 4
    Fatal: 5
    Info: 2
    Trivial: 0
    Warn: 3
    \ No newline at end of file diff --git a/api-reference/enums/OpSource.html b/api-reference/enums/OpSource.html index 985217a57..73452e55e 100644 --- a/api-reference/enums/OpSource.html +++ b/api-reference/enums/OpSource.html @@ -1,7 +1,7 @@ OpSource | yorkie-js-sdk

    Enumeration OpSource

    OpSource represents the source of the operation. It is used to handle corner cases in the operations created by undo/redo allow the removed elements when executing them.

    -

    Enumeration Members

    Enumeration Members

    Enumeration Members

    Local: "local"
    Remote: "remote"
    UndoRedo: "undoredo"
    \ No newline at end of file +

    Enumeration Members

    Local: "local"
    Remote: "remote"
    UndoRedo: "undoredo"
    \ No newline at end of file diff --git a/api-reference/enums/StreamConnectionStatus.html b/api-reference/enums/StreamConnectionStatus.html index ba0ed0134..21d411135 100644 --- a/api-reference/enums/StreamConnectionStatus.html +++ b/api-reference/enums/StreamConnectionStatus.html @@ -1,6 +1,6 @@ StreamConnectionStatus | yorkie-js-sdk

    Enumeration StreamConnectionStatus

    StreamConnectionStatus represents whether the stream connection is connected or not.

    -

    Enumeration Members

    Enumeration Members

    Enumeration Members

    Connected: "connected"

    Connected means that the stream connection is connected.

    -
    Disconnected: "disconnected"

    Disconnected means that the stream connection is disconnected.

    -
    \ No newline at end of file +
    Disconnected: "disconnected"

    Disconnected means that the stream connection is disconnected.

    +
    \ No newline at end of file diff --git a/api-reference/enums/SyncMode.html b/api-reference/enums/SyncMode.html index 6507ccb68..ea2c530c7 100644 --- a/api-reference/enums/SyncMode.html +++ b/api-reference/enums/SyncMode.html @@ -1,11 +1,11 @@ SyncMode | yorkie-js-sdk

    Enumeration SyncMode

    SyncMode defines synchronization modes for the PushPullChanges API.

    -

    Enumeration Members

    Enumeration Members

    Manual: "manual"

    Manual mode indicates that changes are not automatically pushed or pulled.

    -
    Realtime: "realtime"

    Realtime mode indicates that changes are automatically pushed and pulled.

    -
    RealtimePushOnly: "realtime-pushonly"

    RealtimePushOnly mode indicates that only local changes are automatically pushed.

    -
    RealtimeSyncOff: "realtime-syncoff"

    RealtimeSyncOff mode indicates that changes are not automatically pushed or pulled, +

    Realtime: "realtime"

    Realtime mode indicates that changes are automatically pushed and pulled.

    +
    RealtimePushOnly: "realtime-pushonly"

    RealtimePushOnly mode indicates that only local changes are automatically pushed.

    +
    RealtimeSyncOff: "realtime-syncoff"

    RealtimeSyncOff mode indicates that changes are not automatically pushed or pulled, but the watch stream is kept active.

    -
    \ No newline at end of file +
    \ No newline at end of file diff --git a/api-reference/enums/TreeChangeType.html b/api-reference/enums/TreeChangeType.html index 2a69e8406..2d7a837f2 100644 --- a/api-reference/enums/TreeChangeType.html +++ b/api-reference/enums/TreeChangeType.html @@ -1,5 +1,5 @@ TreeChangeType | yorkie-js-sdk

    Enumeration TreeChangeType

    TreeChangeType represents the type of change in the tree.

    -

    Enumeration Members

    Enumeration Members

    Enumeration Members

    Content: "content"
    RemoveStyle: "removeStyle"
    Style: "style"
    \ No newline at end of file +

    Enumeration Members

    Content: "content"
    RemoveStyle: "removeStyle"
    Style: "style"
    \ No newline at end of file diff --git a/api-reference/interfaces/ChangeInfo.html b/api-reference/interfaces/ChangeInfo.html index 2043049db..cd35c3f34 100644 --- a/api-reference/interfaces/ChangeInfo.html +++ b/api-reference/interfaces/ChangeInfo.html @@ -1,8 +1,8 @@ ChangeInfo | yorkie-js-sdk

    Interface ChangeInfo<T>

    ChangeInfo represents the modifications made during a document update and the message passed.

    -
    interface ChangeInfo<T> {
        actor: string;
        clientSeq: number;
        message: string;
        operations: T[];
        serverSeq: string;
    }

    Type Parameters

    Properties

    interface ChangeInfo<T> {
        actor: string;
        clientSeq: number;
        message: string;
        operations: T[];
        serverSeq: string;
    }

    Type Parameters

    Properties

    actor: string
    clientSeq: number
    message: string
    operations: T[]
    serverSeq: string
    \ No newline at end of file +

    Properties

    actor: string
    clientSeq: number
    message: string
    operations: T[]
    serverSeq: string
    \ No newline at end of file diff --git a/api-reference/interfaces/ClientOptions.html b/api-reference/interfaces/ClientOptions.html index 2daa2ade3..524bbe623 100644 --- a/api-reference/interfaces/ClientOptions.html +++ b/api-reference/interfaces/ClientOptions.html @@ -1,5 +1,5 @@ ClientOptions | yorkie-js-sdk

    Interface ClientOptions

    ClientOptions are user-settable options used when defining clients.

    -
    interface ClientOptions {
        apiKey?: string;
        key?: string;
        reconnectStreamDelay?: number;
        retrySyncLoopDelay?: number;
        syncLoopDuration?: number;
        token?: string;
    }

    Properties

    interface ClientOptions {
        apiKey?: string;
        key?: string;
        reconnectStreamDelay?: number;
        retrySyncLoopDelay?: number;
        syncLoopDuration?: number;
        token?: string;
    }

    Properties

    apiKey?: string

    apiKey is the API key of the project. It is used to identify the project. If not set, API key of the default project is used.

    -
    key?: string

    key is the client key. It is used to identify the client. +

    key?: string

    key is the client key. It is used to identify the client. If not set, a random key is generated.

    -
    reconnectStreamDelay?: number

    reconnectStreamDelay is the delay of the reconnect stream. If the stream +

    reconnectStreamDelay?: number

    reconnectStreamDelay is the delay of the reconnect stream. If the stream is disconnected, the client waits for the delay to reconnect the stream. The default value is 1000(ms).

    -
    retrySyncLoopDelay?: number

    retrySyncLoopDelay is the delay of the retry sync loop. If the sync loop +

    retrySyncLoopDelay?: number

    retrySyncLoopDelay is the delay of the retry sync loop. If the sync loop fails, the client waits for the delay to retry the sync loop. The default value is 1000(ms).

    -
    syncLoopDuration?: number

    syncLoopDuration is the duration of the sync loop. After each sync loop, +

    syncLoopDuration?: number

    syncLoopDuration is the duration of the sync loop. After each sync loop, the client waits for the duration to next sync. The default value is 50(ms).

    -
    token?: string

    token is the authentication token of this client. It is used to identify +

    token?: string

    token is the authentication token of this client. It is used to identify the user of the client.

    -
    \ No newline at end of file +
    \ No newline at end of file diff --git a/api-reference/interfaces/ConnectionChangedEvent.html b/api-reference/interfaces/ConnectionChangedEvent.html index 5ae9e8be0..c4cd6fd49 100644 --- a/api-reference/interfaces/ConnectionChangedEvent.html +++ b/api-reference/interfaces/ConnectionChangedEvent.html @@ -1,5 +1,5 @@ ConnectionChangedEvent | yorkie-js-sdk

    Interface ConnectionChangedEvent

    ConnectionChangedEvent is an event that occurs when the stream connection state changes.

    -
    interface ConnectionChangedEvent {
        type: ConnectionChanged;
        value: StreamConnectionStatus;
    }

    Hierarchy

    • BaseDocEvent
      • ConnectionChangedEvent

    Properties

    interface ConnectionChangedEvent {
        type: ConnectionChanged;
        value: StreamConnectionStatus;
    }

    Hierarchy

    • BaseDocEvent
      • ConnectionChangedEvent

    Properties

    Properties

    enum DocEventType.ConnectionChanged

    -
    \ No newline at end of file +
    \ No newline at end of file diff --git a/api-reference/interfaces/InitializedEvent.html b/api-reference/interfaces/InitializedEvent.html index 510da9d9e..ad1068e55 100644 --- a/api-reference/interfaces/InitializedEvent.html +++ b/api-reference/interfaces/InitializedEvent.html @@ -1,4 +1,4 @@ -InitializedEvent | yorkie-js-sdk

    Interface InitializedEvent<P>

    interface InitializedEvent<P> {
        source: Local;
        type: Initialized;
        value: {
            clientID: string;
            presence: P;
        }[];
    }

    Type Parameters

    Hierarchy

    • BaseDocEvent
      • InitializedEvent

    Properties

    source +InitializedEvent | yorkie-js-sdk

    Interface InitializedEvent<P>

    interface InitializedEvent<P> {
        source: Local;
        type: Initialized;
        value: {
            clientID: string;
            presence: P;
        }[];
    }

    Type Parameters

    Hierarchy

    • BaseDocEvent
      • InitializedEvent

    Properties

    Properties

    source: Local
    value: {
        clientID: string;
        presence: P;
    }[]

    Type declaration

    • clientID: string
    • presence: P
    \ No newline at end of file +

    Properties

    source: Local
    value: {
        clientID: string;
        presence: P;
    }[]

    Type declaration

    • clientID: string
    • presence: P
    \ No newline at end of file diff --git a/api-reference/interfaces/LocalChangeEvent.html b/api-reference/interfaces/LocalChangeEvent.html index e691cc87a..90f03e2fd 100644 --- a/api-reference/interfaces/LocalChangeEvent.html +++ b/api-reference/interfaces/LocalChangeEvent.html @@ -1,8 +1,8 @@ LocalChangeEvent | yorkie-js-sdk

    Interface LocalChangeEvent<T, P>

    LocalChangeEvent is an event that occurs when the document is changed by local changes.

    -
    interface LocalChangeEvent<T, P> {
        rawChange?: ChangeStruct<P>;
        source: Local | UndoRedo;
        type: LocalChange;
        value: ChangeInfo<T>;
    }

    Type Parameters

    Hierarchy

    • BaseDocEvent
      • LocalChangeEvent

    Properties

    interface LocalChangeEvent<T, P> {
        rawChange?: ChangeStruct<P>;
        source: Local | UndoRedo;
        type: LocalChange;
        value: ChangeInfo<T>;
    }

    Type Parameters

    Hierarchy

    • BaseDocEvent
      • LocalChangeEvent

    Properties

    rawChange?: ChangeStruct<P>
    source: Local | UndoRedo

    enum DocEventType.LocalChange

    -
    value: ChangeInfo<T>
    \ No newline at end of file +

    Properties

    rawChange?: ChangeStruct<P>
    source: Local | UndoRedo

    enum DocEventType.LocalChange

    +
    value: ChangeInfo<T>
    \ No newline at end of file diff --git a/api-reference/interfaces/Observable.html b/api-reference/interfaces/Observable.html index 81b12e4b5..bda2485ea 100644 --- a/api-reference/interfaces/Observable.html +++ b/api-reference/interfaces/Observable.html @@ -1,3 +1,3 @@ -Observable | yorkie-js-sdk

    Interface Observable<T>

    interface Observable<T> {
        getProxy?: (() => ObserverProxy<T>);
        subscribe: SubscribeFn<T>;
    }

    Type Parameters

    • T

    Properties

    getProxy? +Observable | yorkie-js-sdk

    Interface Observable<T>

    interface Observable<T> {
        getProxy?: (() => ObserverProxy<T>);
        subscribe: SubscribeFn<T>;
    }

    Type Parameters

    • T

    Properties

    Properties

    getProxy?: (() => ObserverProxy<T>)

    Type declaration

      • (): ObserverProxy<T>
      • Returns ObserverProxy<T>

    subscribe: SubscribeFn<T>
    \ No newline at end of file +

    Properties

    getProxy?: (() => ObserverProxy<T>)

    Type declaration

      • (): ObserverProxy<T>
      • Returns ObserverProxy<T>

    subscribe: SubscribeFn<T>
    \ No newline at end of file diff --git a/api-reference/interfaces/Observer.html b/api-reference/interfaces/Observer.html index 5cbbe0c21..fc4972599 100644 --- a/api-reference/interfaces/Observer.html +++ b/api-reference/interfaces/Observer.html @@ -1,4 +1,4 @@ -Observer | yorkie-js-sdk

    Interface Observer<T>

    interface Observer<T> {
        complete?: CompleteFn;
        error?: ErrorFn;
        next: NextFn<T>;
    }

    Type Parameters

    • T

    Properties

    complete? +Observer | yorkie-js-sdk

    Interface Observer<T>

    interface Observer<T> {
        complete?: CompleteFn;
        error?: ErrorFn;
        next: NextFn<T>;
    }

    Type Parameters

    • T

    Properties

    Properties

    complete?: CompleteFn
    error?: ErrorFn
    next: NextFn<T>
    \ No newline at end of file +

    Properties

    complete?: CompleteFn
    error?: ErrorFn
    next: NextFn<T>
    \ No newline at end of file diff --git a/api-reference/interfaces/PresenceChangedEvent.html b/api-reference/interfaces/PresenceChangedEvent.html index d130c9c83..45f3d3e8d 100644 --- a/api-reference/interfaces/PresenceChangedEvent.html +++ b/api-reference/interfaces/PresenceChangedEvent.html @@ -1,4 +1,4 @@ -PresenceChangedEvent | yorkie-js-sdk

    Interface PresenceChangedEvent<P>

    interface PresenceChangedEvent<P> {
        source: OpSource;
        type: PresenceChanged;
        value: {
            clientID: string;
            presence: P;
        };
    }

    Type Parameters

    Hierarchy

    • BaseDocEvent
      • PresenceChangedEvent

    Properties

    source +PresenceChangedEvent | yorkie-js-sdk

    Interface PresenceChangedEvent<P>

    interface PresenceChangedEvent<P> {
        source: OpSource;
        type: PresenceChanged;
        value: {
            clientID: string;
            presence: P;
        };
    }

    Type Parameters

    Hierarchy

    • BaseDocEvent
      • PresenceChangedEvent

    Properties

    Properties

    source: OpSource
    value: {
        clientID: string;
        presence: P;
    }

    Type declaration

    • clientID: string
    • presence: P
    \ No newline at end of file +

    Properties

    source: OpSource
    value: {
        clientID: string;
        presence: P;
    }

    Type declaration

    • clientID: string
    • presence: P
    \ No newline at end of file diff --git a/api-reference/interfaces/RemoteChangeEvent.html b/api-reference/interfaces/RemoteChangeEvent.html index 2c56ec64f..34d156a73 100644 --- a/api-reference/interfaces/RemoteChangeEvent.html +++ b/api-reference/interfaces/RemoteChangeEvent.html @@ -1,8 +1,8 @@ RemoteChangeEvent | yorkie-js-sdk

    Interface RemoteChangeEvent<T, P>

    RemoteChangeEvent is an event that occurs when the document is changed by remote changes.

    -
    interface RemoteChangeEvent<T, P> {
        rawChange?: ChangeStruct<P>;
        source: Remote;
        type: RemoteChange;
        value: ChangeInfo<T>;
    }

    Type Parameters

    Hierarchy

    • BaseDocEvent
      • RemoteChangeEvent

    Properties

    interface RemoteChangeEvent<T, P> {
        rawChange?: ChangeStruct<P>;
        source: Remote;
        type: RemoteChange;
        value: ChangeInfo<T>;
    }

    Type Parameters

    Hierarchy

    • BaseDocEvent
      • RemoteChangeEvent

    Properties

    rawChange?: ChangeStruct<P>
    source: Remote

    enum DocEventType.RemoteChange

    -
    value: ChangeInfo<T>
    \ No newline at end of file +

    Properties

    rawChange?: ChangeStruct<P>
    source: Remote

    enum DocEventType.RemoteChange

    +
    value: ChangeInfo<T>
    \ No newline at end of file diff --git a/api-reference/interfaces/SnapshotEvent.html b/api-reference/interfaces/SnapshotEvent.html index 9d8ea7b54..72e702359 100644 --- a/api-reference/interfaces/SnapshotEvent.html +++ b/api-reference/interfaces/SnapshotEvent.html @@ -1,7 +1,7 @@ SnapshotEvent | yorkie-js-sdk

    Interface SnapshotEvent

    SnapshotEvent is an event that occurs when a snapshot is received from the server.

    -
    interface SnapshotEvent {
        source: Remote;
        type: Snapshot;
        value: {
            serverSeq: string;
            snapshot: undefined | string;
            snapshotVector: string;
        };
    }

    Hierarchy

    • BaseDocEvent
      • SnapshotEvent

    Properties

    interface SnapshotEvent {
        source: Remote;
        type: Snapshot;
        value: {
            serverSeq: string;
            snapshot: undefined | string;
            snapshotVector: string;
        };
    }

    Hierarchy

    • BaseDocEvent
      • SnapshotEvent

    Properties

    Properties

    source: Remote
    type: Snapshot

    enum DocEventType.Snapshot

    -
    value: {
        serverSeq: string;
        snapshot: undefined | string;
        snapshotVector: string;
    }

    Type declaration

    • serverSeq: string
    • snapshot: undefined | string
    • snapshotVector: string
    \ No newline at end of file +

    Properties

    source: Remote
    type: Snapshot

    enum DocEventType.Snapshot

    +
    value: {
        serverSeq: string;
        snapshot: undefined | string;
        snapshotVector: string;
    }

    Type declaration

    • serverSeq: string
    • snapshot: undefined | string
    • snapshotVector: string
    \ No newline at end of file diff --git a/api-reference/interfaces/SyncStatusChangedEvent.html b/api-reference/interfaces/SyncStatusChangedEvent.html index 7c8a6fefe..dcb802c79 100644 --- a/api-reference/interfaces/SyncStatusChangedEvent.html +++ b/api-reference/interfaces/SyncStatusChangedEvent.html @@ -1,5 +1,5 @@ SyncStatusChangedEvent | yorkie-js-sdk

    Interface SyncStatusChangedEvent

    SyncStatusChangedEvent is an event that occurs when document is synced with the server.

    -
    interface SyncStatusChangedEvent {
        type: SyncStatusChanged;
        value: DocumentSyncStatus;
    }

    Hierarchy

    • BaseDocEvent
      • SyncStatusChangedEvent

    Properties

    interface SyncStatusChangedEvent {
        type: SyncStatusChanged;
        value: DocumentSyncStatus;
    }

    Hierarchy

    • BaseDocEvent
      • SyncStatusChangedEvent

    Properties

    Properties

    enum DocEventType.SyncStatusChanged

    -
    \ No newline at end of file +
    \ No newline at end of file diff --git a/api-reference/interfaces/UnwatchedEvent.html b/api-reference/interfaces/UnwatchedEvent.html index 50242c9d4..f9d793984 100644 --- a/api-reference/interfaces/UnwatchedEvent.html +++ b/api-reference/interfaces/UnwatchedEvent.html @@ -1,4 +1,4 @@ -UnwatchedEvent | yorkie-js-sdk

    Interface UnwatchedEvent<P>

    interface UnwatchedEvent<P> {
        source: Remote;
        type: Unwatched;
        value: {
            clientID: string;
            presence: P;
        };
    }

    Type Parameters

    Hierarchy

    • BaseDocEvent
      • UnwatchedEvent

    Properties

    source +UnwatchedEvent | yorkie-js-sdk

    Interface UnwatchedEvent<P>

    interface UnwatchedEvent<P> {
        source: Remote;
        type: Unwatched;
        value: {
            clientID: string;
            presence: P;
        };
    }

    Type Parameters

    Hierarchy

    • BaseDocEvent
      • UnwatchedEvent

    Properties

    Properties

    source: Remote
    type: Unwatched
    value: {
        clientID: string;
        presence: P;
    }

    Type declaration

    • clientID: string
    • presence: P
    \ No newline at end of file +

    Properties

    source: Remote
    type: Unwatched
    value: {
        clientID: string;
        presence: P;
    }

    Type declaration

    • clientID: string
    • presence: P
    \ No newline at end of file diff --git a/api-reference/interfaces/WatchedEvent.html b/api-reference/interfaces/WatchedEvent.html index 8880e0174..39f5b6e3c 100644 --- a/api-reference/interfaces/WatchedEvent.html +++ b/api-reference/interfaces/WatchedEvent.html @@ -1,4 +1,4 @@ -WatchedEvent | yorkie-js-sdk

    Interface WatchedEvent<P>

    interface WatchedEvent<P> {
        source: Remote;
        type: Watched;
        value: {
            clientID: string;
            presence: P;
        };
    }

    Type Parameters

    Hierarchy

    • BaseDocEvent
      • WatchedEvent

    Properties

    source +WatchedEvent | yorkie-js-sdk

    Interface WatchedEvent<P>

    interface WatchedEvent<P> {
        source: Remote;
        type: Watched;
        value: {
            clientID: string;
            presence: P;
        };
    }

    Type Parameters

    Hierarchy

    • BaseDocEvent
      • WatchedEvent

    Properties

    Properties

    source: Remote
    type: Watched
    value: {
        clientID: string;
        presence: P;
    }

    Type declaration

    • clientID: string
    • presence: P
    \ No newline at end of file +

    Properties

    source: Remote
    type: Watched
    value: {
        clientID: string;
        presence: P;
    }

    Type declaration

    • clientID: string
    • presence: P
    \ No newline at end of file diff --git a/api-reference/modules/Devtools.html b/api-reference/modules/Devtools.html index a008115aa..56604dbd0 100644 --- a/api-reference/modules/Devtools.html +++ b/api-reference/modules/Devtools.html @@ -1,4 +1,4 @@ -Devtools | yorkie-js-sdk

    Namespace Devtools

    Index

    Type Aliases

    Client +Devtools | yorkie-js-sdk

    Namespace Devtools

    Index

    Type Aliases

    Client ContainerValue JSONElement TreeNodeInfo diff --git a/api-reference/types/ActorID.html b/api-reference/types/ActorID.html index 39f239f7f..b22e3de6d 100644 --- a/api-reference/types/ActorID.html +++ b/api-reference/types/ActorID.html @@ -1,3 +1,3 @@ ActorID | yorkie-js-sdk

    Type alias ActorID

    ActorID: string

    ActorID is used to identify who is making changes to the document. It is a hexadecimal string and should be generated by a unique value.

    -
    \ No newline at end of file +
    \ No newline at end of file diff --git a/api-reference/types/AddOpInfo.html b/api-reference/types/AddOpInfo.html index 5dfa16db8..a1e1ee2fc 100644 --- a/api-reference/types/AddOpInfo.html +++ b/api-reference/types/AddOpInfo.html @@ -1,2 +1,2 @@ AddOpInfo | yorkie-js-sdk

    Type alias AddOpInfo

    AddOpInfo: {
        index: number;
        path: string;
        type: "add";
    }

    AddOpInfo represents the information of the add operation.

    -

    Type declaration

    • index: number
    • path: string
    • type: "add"
    \ No newline at end of file +

    Type declaration

    • index: number
    • path: string
    • type: "add"
    \ No newline at end of file diff --git a/api-reference/types/ArrayOperationInfo.html b/api-reference/types/ArrayOperationInfo.html index 9f8d282d3..bc95e9b3f 100644 --- a/api-reference/types/ArrayOperationInfo.html +++ b/api-reference/types/ArrayOperationInfo.html @@ -1,2 +1,2 @@ ArrayOperationInfo | yorkie-js-sdk

    Type alias ArrayOperationInfo

    ArrayOperationInfo: AddOpInfo | RemoveOpInfo | MoveOpInfo

    ArrayOperationInfo represents the OperationInfo for the JSONArray.

    -
    \ No newline at end of file +
    \ No newline at end of file diff --git a/api-reference/types/CRDTTreeNodeIDStruct.html b/api-reference/types/CRDTTreeNodeIDStruct.html index 6bef35a31..c6e9f1bf8 100644 --- a/api-reference/types/CRDTTreeNodeIDStruct.html +++ b/api-reference/types/CRDTTreeNodeIDStruct.html @@ -1,3 +1,3 @@ CRDTTreeNodeIDStruct | yorkie-js-sdk

    Type alias CRDTTreeNodeIDStruct

    CRDTTreeNodeIDStruct: {
        createdAt: TimeTicketStruct;
        offset: number;
    }

    CRDTTreeNodeIDStruct represents the structure of CRDTTreeNodeID. It is used to serialize and deserialize the CRDTTreeNodeID.

    -

    Type declaration

    \ No newline at end of file +

    Type declaration

    \ No newline at end of file diff --git a/api-reference/types/CompleteFn.html b/api-reference/types/CompleteFn.html index 09a497d9f..0700d783f 100644 --- a/api-reference/types/CompleteFn.html +++ b/api-reference/types/CompleteFn.html @@ -1 +1 @@ -CompleteFn | yorkie-js-sdk

    Type alias CompleteFn

    CompleteFn: (() => void)

    Type declaration

      • (): void
      • Returns void

    \ No newline at end of file +CompleteFn | yorkie-js-sdk

    Type alias CompleteFn

    CompleteFn: (() => void)

    Type declaration

      • (): void
      • Returns void

    \ No newline at end of file diff --git a/api-reference/types/CounterOperationInfo.html b/api-reference/types/CounterOperationInfo.html index 1db1676e6..a01142181 100644 --- a/api-reference/types/CounterOperationInfo.html +++ b/api-reference/types/CounterOperationInfo.html @@ -1,2 +1,2 @@ CounterOperationInfo | yorkie-js-sdk

    Type alias CounterOperationInfo

    CounterOperationInfo: IncreaseOpInfo

    CounterOperationInfo represents the OperationInfo for the yorkie.Counter.

    -
    \ No newline at end of file +
    \ No newline at end of file diff --git a/api-reference/types/CounterValue.html b/api-reference/types/CounterValue.html index e6327f0fe..d0259f9b6 100644 --- a/api-reference/types/CounterValue.html +++ b/api-reference/types/CounterValue.html @@ -1 +1 @@ -CounterValue | yorkie-js-sdk

    Type alias CounterValue

    CounterValue: number | Long
    \ No newline at end of file +CounterValue | yorkie-js-sdk

    Type alias CounterValue

    CounterValue: number | Long
    \ No newline at end of file diff --git a/api-reference/types/Devtools.Client.html b/api-reference/types/Devtools.Client.html index a362db7d5..5c32ddf7c 100644 --- a/api-reference/types/Devtools.Client.html +++ b/api-reference/types/Devtools.Client.html @@ -1,2 +1,2 @@ Client | yorkie-js-sdk
    Client: {
        clientID: string;
        presence: Json;
    }

    Client represents a client value in devtools.

    -

    Type declaration

    • clientID: string
    • presence: Json
    \ No newline at end of file +

    Type declaration

    \ No newline at end of file diff --git a/api-reference/types/Devtools.ContainerValue.html b/api-reference/types/Devtools.ContainerValue.html index 2a50b256f..cc5173744 100644 --- a/api-reference/types/Devtools.ContainerValue.html +++ b/api-reference/types/Devtools.ContainerValue.html @@ -1,3 +1,3 @@ ContainerValue | yorkie-js-sdk

    Type alias ContainerValue

    ContainerValue: {
        [key: string]: Devtools.JSONElement;
    }

    ContainerValue represents the result of Array.toJSForTest() and Object.toJSForTest().

    -

    Type declaration

    \ No newline at end of file +

    Type declaration

    \ No newline at end of file diff --git a/api-reference/types/Devtools.JSONElement.html b/api-reference/types/Devtools.JSONElement.html index 95c6dcb55..2644a4eec 100644 --- a/api-reference/types/Devtools.JSONElement.html +++ b/api-reference/types/Devtools.JSONElement.html @@ -1,2 +1,2 @@ JSONElement | yorkie-js-sdk

    Type alias JSONElement

    JSONElement: {
        createdAt: string;
        key?: string;
        type: JSONElementType;
        value: JSONElementValue;
    }

    JSONElement represents the result of Element.toJSForTest().

    -

    Type declaration

    • createdAt: string
    • Optional key?: string
    • type: JSONElementType
    • value: JSONElementValue
    \ No newline at end of file +

    Type declaration

    \ No newline at end of file diff --git a/api-reference/types/Devtools.TreeNodeInfo.html b/api-reference/types/Devtools.TreeNodeInfo.html index b9cb1ec13..0e5564195 100644 --- a/api-reference/types/Devtools.TreeNodeInfo.html +++ b/api-reference/types/Devtools.TreeNodeInfo.html @@ -1,2 +1,2 @@ TreeNodeInfo | yorkie-js-sdk

    Type alias TreeNodeInfo

    TreeNodeInfo: {
        attributes?: object;
        children: TreeNodeInfo[];
        depth: number;
        id: string;
        index?: number;
        insNext?: string;
        insPrev?: string;
        isRemoved: boolean;
        parent?: string;
        path?: number[];
        pos?: CRDTTreePosStruct;
        removedAt?: string;
        size: number;
        type: string;
        value?: string;
    }

    TreeNodeInfo represents the crdt tree node information in devtools.

    -

    Type declaration

    • Optional attributes?: object
    • children: TreeNodeInfo[]
    • depth: number
    • id: string
    • Optional index?: number
    • Optional insNext?: string
    • Optional insPrev?: string
    • isRemoved: boolean
    • Optional parent?: string
    • Optional path?: number[]
    • Optional pos?: CRDTTreePosStruct
    • Optional removedAt?: string
    • size: number
    • type: string
    • Optional value?: string
    \ No newline at end of file +

    Type declaration

    \ No newline at end of file diff --git a/api-reference/types/DocEvent.html b/api-reference/types/DocEvent.html index a1d6d66cf..87887761c 100644 --- a/api-reference/types/DocEvent.html +++ b/api-reference/types/DocEvent.html @@ -1,3 +1,3 @@ DocEvent | yorkie-js-sdk

    Type alias DocEvent<P, T>

    DocEvent<P, T>: StatusChangedEvent | ConnectionChangedEvent | SyncStatusChangedEvent | SnapshotEvent | LocalChangeEvent<T, P> | RemoteChangeEvent<T, P> | InitializedEvent<P> | WatchedEvent<P> | UnwatchedEvent<P> | PresenceChangedEvent<P> | BroadcastEvent | LocalBroadcastEvent

    DocEvent is an event that occurs in Document. It can be delivered using Document.subscribe().

    -

    Type Parameters

    \ No newline at end of file +

    Type Parameters

    \ No newline at end of file diff --git a/api-reference/types/EditOpInfo.html b/api-reference/types/EditOpInfo.html index c84f8f05a..4ef8a4362 100644 --- a/api-reference/types/EditOpInfo.html +++ b/api-reference/types/EditOpInfo.html @@ -1,2 +1,2 @@ EditOpInfo | yorkie-js-sdk

    Type alias EditOpInfo

    EditOpInfo: {
        from: number;
        path: string;
        to: number;
        type: "edit";
        value: {
            attributes: Indexable;
            content: string;
        };
    }

    EditOpInfo represents the information of the edit operation.

    -

    Type declaration

    • from: number
    • path: string
    • to: number
    • type: "edit"
    • value: {
          attributes: Indexable;
          content: string;
      }
    \ No newline at end of file +

    Type declaration

    \ No newline at end of file diff --git a/api-reference/types/ElementNode.html b/api-reference/types/ElementNode.html index aa1f44c72..2cd3351e6 100644 --- a/api-reference/types/ElementNode.html +++ b/api-reference/types/ElementNode.html @@ -1,2 +1,2 @@ ElementNode | yorkie-js-sdk

    Type alias ElementNode<A>

    ElementNode<A>: {
        attributes?: A;
        children: TreeNode[];
        type: TreeNodeType;
    }

    ElementNode represents an element node. It has an attributes and children.

    -

    Type Parameters

    Type declaration

    • Optional attributes?: A
    • children: TreeNode[]
    • type: TreeNodeType
    \ No newline at end of file +

    Type Parameters

    Type declaration

    \ No newline at end of file diff --git a/api-reference/types/ErrorFn.html b/api-reference/types/ErrorFn.html index 737955c4a..be71cad91 100644 --- a/api-reference/types/ErrorFn.html +++ b/api-reference/types/ErrorFn.html @@ -1 +1 @@ -ErrorFn | yorkie-js-sdk

    Type alias ErrorFn

    ErrorFn: ((error) => void)

    Type declaration

      • (error): void
      • Parameters

        • error: Error

        Returns void

    \ No newline at end of file +ErrorFn | yorkie-js-sdk

    Type alias ErrorFn

    ErrorFn: ((error) => void)

    Type declaration

      • (error): void
      • Parameters

        • error: Error

        Returns void

    \ No newline at end of file diff --git a/api-reference/types/FullPanelToSDKMessage.html b/api-reference/types/FullPanelToSDKMessage.html index bbe5c49af..ae39cb7e8 100644 --- a/api-reference/types/FullPanelToSDKMessage.html +++ b/api-reference/types/FullPanelToSDKMessage.html @@ -1 +1 @@ -FullPanelToSDKMessage | yorkie-js-sdk

    Type alias FullPanelToSDKMessage

    FullPanelToSDKMessage: PanelToSDKMessage & {
        source: "yorkie-devtools-panel";
    }

    Type declaration

    • source: "yorkie-devtools-panel"
    \ No newline at end of file +FullPanelToSDKMessage | yorkie-js-sdk

    Type alias FullPanelToSDKMessage

    FullPanelToSDKMessage: PanelToSDKMessage & {
        source: "yorkie-devtools-panel";
    }

    Type declaration

    • source: "yorkie-devtools-panel"
    \ No newline at end of file diff --git a/api-reference/types/FullSDKToPanelMessage.html b/api-reference/types/FullSDKToPanelMessage.html index a7ee2cc12..234386834 100644 --- a/api-reference/types/FullSDKToPanelMessage.html +++ b/api-reference/types/FullSDKToPanelMessage.html @@ -1 +1 @@ -FullSDKToPanelMessage | yorkie-js-sdk

    Type alias FullSDKToPanelMessage

    FullSDKToPanelMessage: SDKToPanelMessage & {
        source: "yorkie-devtools-sdk";
    }

    Type declaration

    • source: "yorkie-devtools-sdk"
    \ No newline at end of file +FullSDKToPanelMessage | yorkie-js-sdk

    Type alias FullSDKToPanelMessage

    FullSDKToPanelMessage: SDKToPanelMessage & {
        source: "yorkie-devtools-sdk";
    }

    Type declaration

    • source: "yorkie-devtools-sdk"
    \ No newline at end of file diff --git a/api-reference/types/IncreaseOpInfo.html b/api-reference/types/IncreaseOpInfo.html index f760fbfb9..ad8b781f5 100644 --- a/api-reference/types/IncreaseOpInfo.html +++ b/api-reference/types/IncreaseOpInfo.html @@ -1,2 +1,2 @@ IncreaseOpInfo | yorkie-js-sdk

    Type alias IncreaseOpInfo

    IncreaseOpInfo: {
        path: string;
        type: "increase";
        value: number;
    }

    IncreaseOpInfo represents the information of the increase operation.

    -

    Type declaration

    • path: string
    • type: "increase"
    • value: number
    \ No newline at end of file +

    Type declaration

    \ No newline at end of file diff --git a/api-reference/types/Indexable.html b/api-reference/types/Indexable.html index 2d3d27968..9d84a8e94 100644 --- a/api-reference/types/Indexable.html +++ b/api-reference/types/Indexable.html @@ -1,3 +1,3 @@ Indexable | yorkie-js-sdk

    Type alias Indexable

    Indexable: Record<string, Json>

    Indexable represents the type of the indexable object. It is used to represent the presence information of the client.

    -
    \ No newline at end of file +
    \ No newline at end of file diff --git a/api-reference/types/JSONArray.html b/api-reference/types/JSONArray.html index 0dedebac4..a43d373c3 100644 --- a/api-reference/types/JSONArray.html +++ b/api-reference/types/JSONArray.html @@ -1,17 +1,17 @@ JSONArray | yorkie-js-sdk

    Type alias JSONArray<T>

    JSONArray<T>: {
        deleteByID?(createdAt): WrappedElement<T>;
        getElementByID?(createdAt): WrappedElement<T>;
        getElementByIndex?(index): WrappedElement<T>;
        getID?(): TimeTicket;
        getLast?(): WrappedElement<T>;
        insertAfter?(prevID, value): WrappedElement<T>;
        insertBefore?(nextID, value): WrappedElement<T>;
        moveAfter?(prevID, id): void;
        moveBefore?(nextID, id): void;
        moveFront?(id): void;
        moveLast?(id): void;
        toJSForTest?(): Devtools.JSONElement;
        toTestString?(): string;
    } & T[]

    JSONArray represents JSON array, but unlike regular JSON, it has time tickets created by a logical clock to resolve conflicts.

    Type Parameters

    • T

    Type declaration

    \ No newline at end of file +

    Returns string

    \ No newline at end of file diff --git a/api-reference/types/JSONElement.html b/api-reference/types/JSONElement.html index a4049c62f..6650dfe7c 100644 --- a/api-reference/types/JSONElement.html +++ b/api-reference/types/JSONElement.html @@ -1,3 +1,3 @@ JSONElement | yorkie-js-sdk

    Type alias JSONElement<T, A>

    JSONElement<T, A>: PrimitiveValue | JSONObject<T> | JSONArray<T> | Text<A> | Counter | Tree

    JSONElement is a wrapper for CRDTElement that provides users with an easy-to-use interface for manipulating Documents.

    -

    Type Parameters

    \ No newline at end of file +

    Type Parameters

    \ No newline at end of file diff --git a/api-reference/types/JSONObject.html b/api-reference/types/JSONObject.html index bb0d9d397..09408a6ef 100644 --- a/api-reference/types/JSONObject.html +++ b/api-reference/types/JSONObject.html @@ -1,7 +1,7 @@ JSONObject | yorkie-js-sdk

    Type alias JSONObject<T>

    JSONObject<T>: {
        getID?(): TimeTicket;
        toJS?(): T;
        toJSForTest?(): Devtools.JSONElement;
        toJSON?(): string;
    } & T

    JSONObject represents a JSON object, but unlike regular JSON, it has time tickets created by a logical clock to resolve conflicts.

    Type Parameters

    • T

    Type declaration

    \ No newline at end of file +

    Returns TimeTicket

  • toJS?:function
  • toJSForTest?:function
  • toJSON?:function
  • \ No newline at end of file diff --git a/api-reference/types/MoveOpInfo.html b/api-reference/types/MoveOpInfo.html index 13826b898..c6dd3a5b5 100644 --- a/api-reference/types/MoveOpInfo.html +++ b/api-reference/types/MoveOpInfo.html @@ -1,2 +1,2 @@ MoveOpInfo | yorkie-js-sdk

    Type alias MoveOpInfo

    MoveOpInfo: {
        index: number;
        path: string;
        previousIndex: number;
        type: "move";
    }

    MoveOpInfo represents the information of the move operation.

    -

    Type declaration

    • index: number
    • path: string
    • previousIndex: number
    • type: "move"
    \ No newline at end of file +

    Type declaration

    \ No newline at end of file diff --git a/api-reference/types/NextFn.html b/api-reference/types/NextFn.html index f763ca5be..1fb84d2e4 100644 --- a/api-reference/types/NextFn.html +++ b/api-reference/types/NextFn.html @@ -1 +1 @@ -NextFn | yorkie-js-sdk

    Type alias NextFn<T>

    NextFn<T>: ((value) => void)

    Type Parameters

    • T

    Type declaration

      • (value): void
      • Parameters

        • value: T

        Returns void

    \ No newline at end of file +NextFn | yorkie-js-sdk

    Type alias NextFn<T>

    NextFn<T>: ((value) => void)

    Type Parameters

    • T

    Type declaration

      • (value): void
      • Parameters

        • value: T

        Returns void

    \ No newline at end of file diff --git a/api-reference/types/ObjectOperationInfo.html b/api-reference/types/ObjectOperationInfo.html index cba824ef2..36cb57817 100644 --- a/api-reference/types/ObjectOperationInfo.html +++ b/api-reference/types/ObjectOperationInfo.html @@ -1,2 +1,2 @@ ObjectOperationInfo | yorkie-js-sdk

    Type alias ObjectOperationInfo

    ObjectOperationInfo: SetOpInfo | RemoveOpInfo

    ObjectOperationInfo represents the OperationInfo for the JSONObject.

    -
    \ No newline at end of file +
    \ No newline at end of file diff --git a/api-reference/types/OperationInfo.html b/api-reference/types/OperationInfo.html index 3694867bc..35fbb2535 100644 --- a/api-reference/types/OperationInfo.html +++ b/api-reference/types/OperationInfo.html @@ -1,3 +1,3 @@ OperationInfo | yorkie-js-sdk

    Type alias OperationInfo

    OperationInfo represents the information of an operation. It is used to inform to the user what kind of operation was executed.

    -
    \ No newline at end of file +
    \ No newline at end of file diff --git a/api-reference/types/PanelToSDKMessage.html b/api-reference/types/PanelToSDKMessage.html index 3cdf8ffbd..837eef680 100644 --- a/api-reference/types/PanelToSDKMessage.html +++ b/api-reference/types/PanelToSDKMessage.html @@ -1,2 +1,2 @@ PanelToSDKMessage | yorkie-js-sdk

    Type alias PanelToSDKMessage

    PanelToSDKMessage: {
        msg: "devtools::connect";
    } | {
        msg: "devtools::disconnect";
    } | {
        docKey: string;
        msg: "devtools::subscribe";
    }

    PanelToSDKMessage is a message sent from the Devtools panel to the SDK.

    -

    Type declaration

    • msg: "devtools::connect"

    Type declaration

    • msg: "devtools::disconnect"

    Type declaration

    • docKey: string
    • msg: "devtools::subscribe"
    \ No newline at end of file +

    Type declaration

    Type declaration

    Type declaration

    \ No newline at end of file diff --git a/api-reference/types/PrimitiveValue.html b/api-reference/types/PrimitiveValue.html index f0f29515f..92fa1dc2e 100644 --- a/api-reference/types/PrimitiveValue.html +++ b/api-reference/types/PrimitiveValue.html @@ -1,3 +1,3 @@ PrimitiveValue | yorkie-js-sdk

    Type alias PrimitiveValue

    PrimitiveValue: null | boolean | number | Long | string | Uint8Array | Date

    PrimitiveValue represents a value of primitive type. Only values of type included in PrimitiveValue can be set to the document.

    -
    \ No newline at end of file +
    \ No newline at end of file diff --git a/api-reference/types/RemoveOpInfo.html b/api-reference/types/RemoveOpInfo.html index a3aa7e428..3b2d01025 100644 --- a/api-reference/types/RemoveOpInfo.html +++ b/api-reference/types/RemoveOpInfo.html @@ -1,2 +1,2 @@ RemoveOpInfo | yorkie-js-sdk

    Type alias RemoveOpInfo

    RemoveOpInfo: {
        index?: number;
        key?: string;
        path: string;
        type: "remove";
    }

    RemoveOpInfo represents the information of the remove operation.

    -

    Type declaration

    • Optional index?: number
    • Optional key?: string
    • path: string
    • type: "remove"
    \ No newline at end of file +

    Type declaration

    \ No newline at end of file diff --git a/api-reference/types/SDKToPanelMessage.html b/api-reference/types/SDKToPanelMessage.html index 9f1ac3019..87b8f310b 100644 --- a/api-reference/types/SDKToPanelMessage.html +++ b/api-reference/types/SDKToPanelMessage.html @@ -1,2 +1,2 @@ SDKToPanelMessage | yorkie-js-sdk

    Type alias SDKToPanelMessage

    SDKToPanelMessage: {
        msg: "refresh-devtools";
    } | {
        docKey: string;
        msg: "doc::available";
    } | {
        docKey: string;
        events: TransactionEvent[];
        msg: "doc::sync::full";
    } | {
        docKey: string;
        event: TransactionEvent;
        msg: "doc::sync::partial";
    }

    Definition of all messages the SDK can send to the Devtools panel.

    -

    Type declaration

    • msg: "refresh-devtools"

    Type declaration

    • docKey: string
    • msg: "doc::available"

    Type declaration

    Type declaration

    \ No newline at end of file +

    Type declaration

    Type declaration

    Type declaration

    Type declaration

    \ No newline at end of file diff --git a/api-reference/types/SetOpInfo.html b/api-reference/types/SetOpInfo.html index 2d2d5a4ae..1fcccfe04 100644 --- a/api-reference/types/SetOpInfo.html +++ b/api-reference/types/SetOpInfo.html @@ -1,2 +1,2 @@ SetOpInfo | yorkie-js-sdk

    Type alias SetOpInfo

    SetOpInfo: {
        key: string;
        path: string;
        type: "set";
    }

    SetOpInfo represents the information of the set operation.

    -

    Type declaration

    • key: string
    • path: string
    • type: "set"
    \ No newline at end of file +

    Type declaration

    \ No newline at end of file diff --git a/api-reference/types/StyleOpInfo.html b/api-reference/types/StyleOpInfo.html index a196f542c..c7d491c61 100644 --- a/api-reference/types/StyleOpInfo.html +++ b/api-reference/types/StyleOpInfo.html @@ -1,2 +1,2 @@ StyleOpInfo | yorkie-js-sdk

    Type alias StyleOpInfo

    StyleOpInfo: {
        from: number;
        path: string;
        to: number;
        type: "style";
        value: {
            attributes: Indexable;
        };
    }

    StyleOpInfo represents the information of the style operation.

    -

    Type declaration

    • from: number
    • path: string
    • to: number
    • type: "style"
    • value: {
          attributes: Indexable;
      }
    \ No newline at end of file +

    Type declaration

    \ No newline at end of file diff --git a/api-reference/types/TextNode.html b/api-reference/types/TextNode.html index 971d36e3b..d0a902c78 100644 --- a/api-reference/types/TextNode.html +++ b/api-reference/types/TextNode.html @@ -1,2 +1,2 @@ TextNode | yorkie-js-sdk

    Type alias TextNode

    TextNode: {
        type: typeof DefaultTextType;
        value: string;
    }

    TextNode represents a text node. It has a string value.

    -

    Type declaration

    • type: typeof DefaultTextType
    • value: string
    \ No newline at end of file +

    Type declaration

    \ No newline at end of file diff --git a/api-reference/types/TextOperationInfo.html b/api-reference/types/TextOperationInfo.html index 0fd7c27fb..c3343a490 100644 --- a/api-reference/types/TextOperationInfo.html +++ b/api-reference/types/TextOperationInfo.html @@ -1,2 +1,2 @@ TextOperationInfo | yorkie-js-sdk

    Type alias TextOperationInfo

    TextOperationInfo: EditOpInfo | StyleOpInfo

    TextOperationInfo represents the OperationInfo for the yorkie.Text.

    -
    \ No newline at end of file +
    \ No newline at end of file diff --git a/api-reference/types/TextPosStruct.html b/api-reference/types/TextPosStruct.html index 46c7c768a..5532c7722 100644 --- a/api-reference/types/TextPosStruct.html +++ b/api-reference/types/TextPosStruct.html @@ -1,3 +1,3 @@ TextPosStruct | yorkie-js-sdk

    Type alias TextPosStruct

    TextPosStruct: {
        id: {
            createdAt: TimeTicketStruct;
            offset: number;
        };
        relativeOffset: number;
    }

    TextPosStruct represents the structure of RGATreeSplitPos. It is used to serialize and deserialize the RGATreeSplitPos.

    -

    Type declaration

    \ No newline at end of file +

    Type declaration

    \ No newline at end of file diff --git a/api-reference/types/TextPosStructRange.html b/api-reference/types/TextPosStructRange.html index b750efe30..b397030c7 100644 --- a/api-reference/types/TextPosStructRange.html +++ b/api-reference/types/TextPosStructRange.html @@ -1,3 +1,3 @@ TextPosStructRange | yorkie-js-sdk

    Type alias TextPosStructRange

    TextPosStructRange: [TextPosStruct, TextPosStruct]

    TextPosStructRange represents the structure of RGATreeSplitPosRange. It is used to serialize and deserialize the RGATreeSplitPosRange.

    -
    \ No newline at end of file +
    \ No newline at end of file diff --git a/api-reference/types/TimeTicketStruct.html b/api-reference/types/TimeTicketStruct.html index d76ebb62b..d75cf8515 100644 --- a/api-reference/types/TimeTicketStruct.html +++ b/api-reference/types/TimeTicketStruct.html @@ -1,3 +1,3 @@ TimeTicketStruct | yorkie-js-sdk

    Type alias TimeTicketStruct

    TimeTicketStruct: {
        actorID: ActorID;
        delimiter: number;
        lamport: string;
    }

    TimeTicketStruct is a structure represents the meta data of the ticket. It is used to serialize and deserialize the ticket.

    -

    Type declaration

    • actorID: ActorID
    • delimiter: number
    • lamport: string
    \ No newline at end of file +

    Type declaration

    \ No newline at end of file diff --git a/api-reference/types/TransactionEvent.html b/api-reference/types/TransactionEvent.html index 62b795584..77515f9b3 100644 --- a/api-reference/types/TransactionEvent.html +++ b/api-reference/types/TransactionEvent.html @@ -1,3 +1,3 @@ TransactionEvent | yorkie-js-sdk

    Type alias TransactionEvent<P>

    TransactionEvent<P>: DocEvent<P>[]

    TransactionEvent represents document events that occur within a single transaction (e.g., doc.update).

    -

    Type Parameters

    \ No newline at end of file +

    Type Parameters

    \ No newline at end of file diff --git a/api-reference/types/TreeChange.html b/api-reference/types/TreeChange.html index 29468a9ae..3635563c3 100644 --- a/api-reference/types/TreeChange.html +++ b/api-reference/types/TreeChange.html @@ -1,2 +1,2 @@ TreeChange | yorkie-js-sdk

    Type alias TreeChange

    TreeChange: {
        actor: ActorID;
        from: number;
        fromPath: number[];
        splitLevel?: number;
        to: number;
        toPath: number[];
        type: Content;
        value?: TreeNode[];
    } | {
        actor: ActorID;
        from: number;
        fromPath: number[];
        splitLevel?: number;
        to: number;
        toPath: number[];
        type: Style;
        value: {
            [key: string]: string;
        };
    } | {
        actor: ActorID;
        from: number;
        fromPath: number[];
        splitLevel?: number;
        to: number;
        toPath: number[];
        type: RemoveStyle;
        value?: string[];
    }

    TreeChange represents the change in the tree.

    -

    Type declaration

    • actor: ActorID
    • from: number
    • fromPath: number[]
    • Optional splitLevel?: number
    • to: number
    • toPath: number[]
    • type: Content
    • Optional value?: TreeNode[]

    Type declaration

    • actor: ActorID
    • from: number
    • fromPath: number[]
    • Optional splitLevel?: number
    • to: number
    • toPath: number[]
    • type: Style
    • value: {
          [key: string]: string;
      }
      • [key: string]: string

    Type declaration

    • actor: ActorID
    • from: number
    • fromPath: number[]
    • Optional splitLevel?: number
    • to: number
    • toPath: number[]
    • type: RemoveStyle
    • Optional value?: string[]
    \ No newline at end of file +

    Type declaration

    Type declaration

    Type declaration

    \ No newline at end of file diff --git a/api-reference/types/TreeEditOpInfo.html b/api-reference/types/TreeEditOpInfo.html index c4e31c83a..40e5145a3 100644 --- a/api-reference/types/TreeEditOpInfo.html +++ b/api-reference/types/TreeEditOpInfo.html @@ -1,2 +1,2 @@ TreeEditOpInfo | yorkie-js-sdk

    Type alias TreeEditOpInfo

    TreeEditOpInfo: {
        from: number;
        fromPath: number[];
        path: string;
        splitLevel?: number;
        to: number;
        toPath: number[];
        type: "tree-edit";
        value?: TreeNode[];
    }

    TreeEditOpInfo represents the information of the tree edit operation.

    -

    Type declaration

    • from: number
    • fromPath: number[]
    • path: string
    • Optional splitLevel?: number
    • to: number
    • toPath: number[]
    • type: "tree-edit"
    • Optional value?: TreeNode[]
    \ No newline at end of file +

    Type declaration

    \ No newline at end of file diff --git a/api-reference/types/TreeNode.html b/api-reference/types/TreeNode.html index 4af60079a..3e36dcb98 100644 --- a/api-reference/types/TreeNode.html +++ b/api-reference/types/TreeNode.html @@ -1,2 +1,2 @@ TreeNode | yorkie-js-sdk

    Type alias TreeNode

    TreeNode: TextNode | ElementNode

    TreeNode represents a node in the tree.

    -
    \ No newline at end of file +
    \ No newline at end of file diff --git a/api-reference/types/TreeOperationInfo.html b/api-reference/types/TreeOperationInfo.html index c60a492ad..a292261e7 100644 --- a/api-reference/types/TreeOperationInfo.html +++ b/api-reference/types/TreeOperationInfo.html @@ -1,2 +1,2 @@ TreeOperationInfo | yorkie-js-sdk

    Type alias TreeOperationInfo

    TreeOperationInfo: TreeEditOpInfo | TreeStyleOpInfo

    TreeOperationInfo represents the OperationInfo for the yorkie.Tree.

    -
    \ No newline at end of file +
    \ No newline at end of file diff --git a/api-reference/types/TreePosStructRange.html b/api-reference/types/TreePosStructRange.html index 8a81b8f0a..6a28b3968 100644 --- a/api-reference/types/TreePosStructRange.html +++ b/api-reference/types/TreePosStructRange.html @@ -1,3 +1,3 @@ TreePosStructRange | yorkie-js-sdk

    Type alias TreePosStructRange

    TreePosStructRange: [CRDTTreePosStruct, CRDTTreePosStruct]

    TreePosStructRange represents the structure of TreeRange. It is used to serialize and deserialize the TreeRange.

    -
    \ No newline at end of file +
    \ No newline at end of file diff --git a/api-reference/types/TreeStyleOpInfo.html b/api-reference/types/TreeStyleOpInfo.html index b8c778ddc..b0f928147 100644 --- a/api-reference/types/TreeStyleOpInfo.html +++ b/api-reference/types/TreeStyleOpInfo.html @@ -1,2 +1,2 @@ TreeStyleOpInfo | yorkie-js-sdk

    Type alias TreeStyleOpInfo

    TreeStyleOpInfo: {
        from: number;
        fromPath: number[];
        path: string;
        to: number;
        toPath: number[];
        type: "tree-style";
        value: {
            attributes?: Indexable;
            attributesToRemove?: string[];
        };
    }

    TreeStyleOpInfo represents the information of the tree style operation.

    -

    Type declaration

    • from: number
    • fromPath: number[]
    • path: string
    • to: number
    • toPath: number[]
    • type: "tree-style"
    • value: {
          attributes?: Indexable;
          attributesToRemove?: string[];
      }
      • Optional attributes?: Indexable
      • Optional attributesToRemove?: string[]
    \ No newline at end of file +

    Type declaration

    \ No newline at end of file diff --git a/api-reference/types/Unsubscribe.html b/api-reference/types/Unsubscribe.html index 25f1fe5a7..00fcf2846 100644 --- a/api-reference/types/Unsubscribe.html +++ b/api-reference/types/Unsubscribe.html @@ -1 +1 @@ -Unsubscribe | yorkie-js-sdk

    Type alias Unsubscribe

    Unsubscribe: (() => void)

    Type declaration

      • (): void
      • Returns void

    \ No newline at end of file +Unsubscribe | yorkie-js-sdk

    Type alias Unsubscribe

    Unsubscribe: (() => void)

    Type declaration

      • (): void
      • Returns void

    \ No newline at end of file diff --git a/api-reference/types/WrappedElement.html b/api-reference/types/WrappedElement.html index 14e3576ae..b24a65cd6 100644 --- a/api-reference/types/WrappedElement.html +++ b/api-reference/types/WrappedElement.html @@ -1,2 +1,2 @@ WrappedElement | yorkie-js-sdk

    Type alias WrappedElement<T, A>

    WrappedElement<T, A>: Primitive | JSONObject<T> | JSONArray<T> | Text<A> | Counter | Tree

    WrappedElement is a wrapper of JSONElement that provides getID().

    -

    Type Parameters

    \ No newline at end of file +

    Type Parameters

    \ No newline at end of file diff --git a/api-reference/variables/EventSourceDevPanel.html b/api-reference/variables/EventSourceDevPanel.html index 9fdbbf074..977df0a9d 100644 --- a/api-reference/variables/EventSourceDevPanel.html +++ b/api-reference/variables/EventSourceDevPanel.html @@ -1,3 +1,3 @@ EventSourceDevPanel | yorkie-js-sdk

    Variable EventSourceDevPanelConst

    EventSourceDevPanel: "yorkie-devtools-panel" = 'yorkie-devtools-panel'

    EventSourceDevPanel is the name of the source representing messages from the Devtools panel.

    -
    \ No newline at end of file +
    \ No newline at end of file diff --git a/api-reference/variables/EventSourceSDK.html b/api-reference/variables/EventSourceSDK.html index d0ed2159e..651052b5d 100644 --- a/api-reference/variables/EventSourceSDK.html +++ b/api-reference/variables/EventSourceSDK.html @@ -1,3 +1,3 @@ EventSourceSDK | yorkie-js-sdk

    Variable EventSourceSDKConst

    EventSourceSDK: "yorkie-devtools-sdk" = 'yorkie-devtools-sdk'

    EventSourceSDK is the name of the source representing messages from the SDK.

    -
    \ No newline at end of file +
    \ No newline at end of file diff --git a/api-reference/variables/converter.html b/api-reference/variables/converter.html index 007823f49..d4e7873b7 100644 --- a/api-reference/variables/converter.html +++ b/api-reference/variables/converter.html @@ -19,4 +19,4 @@

    Parameters

    Returns PbOperation

  • toTreeNodes: ((node) => PbTreeNode[])
  • toUint8Array: ((hex) => Uint8Array)
  • versionVectorToHex: ((vector) => string)
  • \ No newline at end of file +

    Parameters

    Returns string

    \ No newline at end of file diff --git a/api-reference/variables/default.html b/api-reference/variables/default.html index 7d7070f53..d3ef2fa5e 100644 --- a/api-reference/variables/default.html +++ b/api-reference/variables/default.html @@ -3,4 +3,4 @@ assigned to the yorkie global.

    e.g) new yorkie.Client(...);

    Type declaration

    \ No newline at end of file +

    Parameters

    Returns void

    \ No newline at end of file diff --git a/examples/nextjs-scheduler/404.html b/examples/nextjs-scheduler/404.html index ecffac18d..2035607b6 100644 --- a/examples/nextjs-scheduler/404.html +++ b/examples/nextjs-scheduler/404.html @@ -1 +1 @@ -Next.js react-calendar example

    404 not found

    \ No newline at end of file +Next.js react-calendar example

    404 not found

    \ No newline at end of file diff --git a/examples/nextjs-scheduler/_next/static/chunks/app/page-a4871ed0264d2385.js b/examples/nextjs-scheduler/_next/static/chunks/app/page-ae882aa4f8b3039b.js similarity index 85% rename from examples/nextjs-scheduler/_next/static/chunks/app/page-a4871ed0264d2385.js rename to examples/nextjs-scheduler/_next/static/chunks/app/page-ae882aa4f8b3039b.js index 0958cb12a..b7c0cbd0d 100644 --- a/examples/nextjs-scheduler/_next/static/chunks/app/page-a4871ed0264d2385.js +++ b/examples/nextjs-scheduler/_next/static/chunks/app/page-ae882aa4f8b3039b.js @@ -1 +1 @@ -(self.webpackChunk_N_E=self.webpackChunk_N_E||[]).push([[931],{4629:function(e,t,r){Promise.resolve().then(r.bind(r,1802))},1802:function(e,t,r){"use strict";r.r(t),r.d(t,{default:function(){return nv}});var n,i,s,o,a,c,l,h,d,u,g,f,m,p,y,v,w,A,T,S,I,C,x,P,E,b,k,D,R,N,O,B,J,L,_,M,q,z,K=r(3165),F=r(7397),V=r.n(F),U=r(6189);let j=["Alice","Bob","Carol","Chuck","Dave","Erin","Frank","Grace","Ivan","Justin","Matilda","Oscar","Steve","Victor","Zoe"];function W(e){let[t,r,n]=e.toLocaleDateString("en").split("/");return t=Number(t)>9?t:"0"+t,r=Number(r)>9?r:"0"+r,n=n.slice(2),"".concat(r,"-").concat(t,"-").concat(n)}var G=r(8358),H=r(6390),Y=r(4715),Z=r(1582),X=r(8728),Q=r(601),$=r(1089),ee=r(6731),et=r(9782);(n=S||(S={}))[n.NULL=0]="NULL",n[n.BOOLEAN=1]="BOOLEAN",n[n.INTEGER=2]="INTEGER",n[n.LONG=3]="LONG",n[n.DOUBLE=4]="DOUBLE",n[n.STRING=5]="STRING",n[n.BYTES=6]="BYTES",n[n.DATE=7]="DATE",n[n.JSON_OBJECT=8]="JSON_OBJECT",n[n.JSON_ARRAY=9]="JSON_ARRAY",n[n.TEXT=10]="TEXT",n[n.INTEGER_CNT=11]="INTEGER_CNT",n[n.LONG_CNT=12]="LONG_CNT",n[n.TREE=13]="TREE",Q.w.util.setEnumType(S,"yorkie.v1.ValueType",[{no:0,name:"VALUE_TYPE_NULL"},{no:1,name:"VALUE_TYPE_BOOLEAN"},{no:2,name:"VALUE_TYPE_INTEGER"},{no:3,name:"VALUE_TYPE_LONG"},{no:4,name:"VALUE_TYPE_DOUBLE"},{no:5,name:"VALUE_TYPE_STRING"},{no:6,name:"VALUE_TYPE_BYTES"},{no:7,name:"VALUE_TYPE_DATE"},{no:8,name:"VALUE_TYPE_JSON_OBJECT"},{no:9,name:"VALUE_TYPE_JSON_ARRAY"},{no:10,name:"VALUE_TYPE_TEXT"},{no:11,name:"VALUE_TYPE_INTEGER_CNT"},{no:12,name:"VALUE_TYPE_LONG_CNT"},{no:13,name:"VALUE_TYPE_TREE"}]),(i=I||(I={}))[i.DOCUMENT_CHANGED=0]="DOCUMENT_CHANGED",i[i.DOCUMENT_WATCHED=1]="DOCUMENT_WATCHED",i[i.DOCUMENT_UNWATCHED=2]="DOCUMENT_UNWATCHED",i[i.DOCUMENT_BROADCAST=3]="DOCUMENT_BROADCAST",Q.w.util.setEnumType(I,"yorkie.v1.DocEventType",[{no:0,name:"DOC_EVENT_TYPE_DOCUMENT_CHANGED"},{no:1,name:"DOC_EVENT_TYPE_DOCUMENT_WATCHED"},{no:2,name:"DOC_EVENT_TYPE_DOCUMENT_UNWATCHED"},{no:3,name:"DOC_EVENT_TYPE_DOCUMENT_BROADCAST"}]);class er extends X.v{static fromBinary(e,t){return new er().fromBinary(e,t)}static fromJson(e,t){return new er().fromJson(e,t)}static fromJsonString(e,t){return new er().fromJsonString(e,t)}static equals(e,t){return Q.w.util.equals(er,e,t)}constructor(e){super(),this.presences={},Q.w.util.initPartial(e,this)}}er.runtime=Q.w,er.typeName="yorkie.v1.Snapshot",er.fields=Q.w.util.newFieldList(()=>[{no:1,name:"root",kind:"message",T:eA},{no:2,name:"presences",kind:"map",K:9,V:{kind:"message",T:eF}}]);class en extends X.v{static fromBinary(e,t){return new en().fromBinary(e,t)}static fromJson(e,t){return new en().fromJson(e,t)}static fromJsonString(e,t){return new en().fromJsonString(e,t)}static equals(e,t){return Q.w.util.equals(en,e,t)}constructor(e){super(),this.documentKey="",this.snapshot=new Uint8Array(0),this.changes=[],this.isRemoved=!1,Q.w.util.initPartial(e,this)}}en.runtime=Q.w,en.typeName="yorkie.v1.ChangePack",en.fields=Q.w.util.newFieldList(()=>[{no:1,name:"document_key",kind:"scalar",T:9},{no:2,name:"checkpoint",kind:"message",T:eV},{no:3,name:"snapshot",kind:"scalar",T:12},{no:4,name:"changes",kind:"message",T:ei,repeated:!0},{no:5,name:"min_synced_ticket",kind:"message",T:ej},{no:6,name:"is_removed",kind:"scalar",T:8},{no:7,name:"version_vector",kind:"message",T:eo}]);class ei extends X.v{static fromBinary(e,t){return new ei().fromBinary(e,t)}static fromJson(e,t){return new ei().fromJson(e,t)}static fromJsonString(e,t){return new ei().fromJsonString(e,t)}static equals(e,t){return Q.w.util.equals(ei,e,t)}constructor(e){super(),this.message="",this.operations=[],Q.w.util.initPartial(e,this)}}ei.runtime=Q.w,ei.typeName="yorkie.v1.Change",ei.fields=Q.w.util.newFieldList(()=>[{no:1,name:"id",kind:"message",T:es},{no:2,name:"message",kind:"scalar",T:9},{no:3,name:"operations",kind:"message",T:ea,repeated:!0},{no:4,name:"presence_change",kind:"message",T:eK}]);class es extends X.v{static fromBinary(e,t){return new es().fromBinary(e,t)}static fromJson(e,t){return new es().fromJson(e,t)}static fromJsonString(e,t){return new es().fromJsonString(e,t)}static equals(e,t){return Q.w.util.equals(es,e,t)}constructor(e){super(),this.clientSeq=0,this.serverSeq=$.q.zero,this.lamport=$.q.zero,this.actorId=new Uint8Array(0),Q.w.util.initPartial(e,this)}}es.runtime=Q.w,es.typeName="yorkie.v1.ChangeID",es.fields=Q.w.util.newFieldList(()=>[{no:1,name:"client_seq",kind:"scalar",T:13},{no:2,name:"server_seq",kind:"scalar",T:3},{no:3,name:"lamport",kind:"scalar",T:3},{no:4,name:"actor_id",kind:"scalar",T:12},{no:5,name:"version_vector",kind:"message",T:eo}]);class eo extends X.v{static fromBinary(e,t){return new eo().fromBinary(e,t)}static fromJson(e,t){return new eo().fromJson(e,t)}static fromJsonString(e,t){return new eo().fromJsonString(e,t)}static equals(e,t){return Q.w.util.equals(eo,e,t)}constructor(e){super(),this.vector={},Q.w.util.initPartial(e,this)}}eo.runtime=Q.w,eo.typeName="yorkie.v1.VersionVector",eo.fields=Q.w.util.newFieldList(()=>[{no:1,name:"vector",kind:"map",K:9,V:{kind:"scalar",T:3}}]);class ea extends X.v{static fromBinary(e,t){return new ea().fromBinary(e,t)}static fromJson(e,t){return new ea().fromJson(e,t)}static fromJsonString(e,t){return new ea().fromJsonString(e,t)}static equals(e,t){return Q.w.util.equals(ea,e,t)}constructor(e){super(),this.body={case:void 0},Q.w.util.initPartial(e,this)}}ea.runtime=Q.w,ea.typeName="yorkie.v1.Operation",ea.fields=Q.w.util.newFieldList(()=>[{no:1,name:"set",kind:"message",T:ec,oneof:"body"},{no:2,name:"add",kind:"message",T:el,oneof:"body"},{no:3,name:"move",kind:"message",T:eh,oneof:"body"},{no:4,name:"remove",kind:"message",T:ed,oneof:"body"},{no:5,name:"edit",kind:"message",T:eu,oneof:"body"},{no:6,name:"select",kind:"message",T:eg,oneof:"body"},{no:7,name:"style",kind:"message",T:ef,oneof:"body"},{no:8,name:"increase",kind:"message",T:em,oneof:"body"},{no:9,name:"tree_edit",kind:"message",T:ep,oneof:"body"},{no:10,name:"tree_style",kind:"message",T:ey,oneof:"body"},{no:11,name:"array_set",kind:"message",T:ev,oneof:"body"}]);class ec extends X.v{static fromBinary(e,t){return new ec().fromBinary(e,t)}static fromJson(e,t){return new ec().fromJson(e,t)}static fromJsonString(e,t){return new ec().fromJsonString(e,t)}static equals(e,t){return Q.w.util.equals(ec,e,t)}constructor(e){super(),this.key="",Q.w.util.initPartial(e,this)}}ec.runtime=Q.w,ec.typeName="yorkie.v1.Operation.Set",ec.fields=Q.w.util.newFieldList(()=>[{no:1,name:"parent_created_at",kind:"message",T:ej},{no:2,name:"key",kind:"scalar",T:9},{no:3,name:"value",kind:"message",T:ew},{no:4,name:"executed_at",kind:"message",T:ej}]);class el extends X.v{static fromBinary(e,t){return new el().fromBinary(e,t)}static fromJson(e,t){return new el().fromJson(e,t)}static fromJsonString(e,t){return new el().fromJsonString(e,t)}static equals(e,t){return Q.w.util.equals(el,e,t)}constructor(e){super(),Q.w.util.initPartial(e,this)}}el.runtime=Q.w,el.typeName="yorkie.v1.Operation.Add",el.fields=Q.w.util.newFieldList(()=>[{no:1,name:"parent_created_at",kind:"message",T:ej},{no:2,name:"prev_created_at",kind:"message",T:ej},{no:3,name:"value",kind:"message",T:ew},{no:4,name:"executed_at",kind:"message",T:ej}]);class eh extends X.v{static fromBinary(e,t){return new eh().fromBinary(e,t)}static fromJson(e,t){return new eh().fromJson(e,t)}static fromJsonString(e,t){return new eh().fromJsonString(e,t)}static equals(e,t){return Q.w.util.equals(eh,e,t)}constructor(e){super(),Q.w.util.initPartial(e,this)}}eh.runtime=Q.w,eh.typeName="yorkie.v1.Operation.Move",eh.fields=Q.w.util.newFieldList(()=>[{no:1,name:"parent_created_at",kind:"message",T:ej},{no:2,name:"prev_created_at",kind:"message",T:ej},{no:3,name:"created_at",kind:"message",T:ej},{no:4,name:"executed_at",kind:"message",T:ej}]);class ed extends X.v{static fromBinary(e,t){return new ed().fromBinary(e,t)}static fromJson(e,t){return new ed().fromJson(e,t)}static fromJsonString(e,t){return new ed().fromJsonString(e,t)}static equals(e,t){return Q.w.util.equals(ed,e,t)}constructor(e){super(),Q.w.util.initPartial(e,this)}}ed.runtime=Q.w,ed.typeName="yorkie.v1.Operation.Remove",ed.fields=Q.w.util.newFieldList(()=>[{no:1,name:"parent_created_at",kind:"message",T:ej},{no:2,name:"created_at",kind:"message",T:ej},{no:3,name:"executed_at",kind:"message",T:ej}]);class eu extends X.v{static fromBinary(e,t){return new eu().fromBinary(e,t)}static fromJson(e,t){return new eu().fromJson(e,t)}static fromJsonString(e,t){return new eu().fromJsonString(e,t)}static equals(e,t){return Q.w.util.equals(eu,e,t)}constructor(e){super(),this.createdAtMapByActor={},this.content="",this.attributes={},Q.w.util.initPartial(e,this)}}eu.runtime=Q.w,eu.typeName="yorkie.v1.Operation.Edit",eu.fields=Q.w.util.newFieldList(()=>[{no:1,name:"parent_created_at",kind:"message",T:ej},{no:2,name:"from",kind:"message",T:eU},{no:3,name:"to",kind:"message",T:eU},{no:4,name:"created_at_map_by_actor",kind:"map",K:9,V:{kind:"message",T:ej}},{no:5,name:"content",kind:"scalar",T:9},{no:6,name:"executed_at",kind:"message",T:ej},{no:7,name:"attributes",kind:"map",K:9,V:{kind:"scalar",T:9}}]);class eg extends X.v{static fromBinary(e,t){return new eg().fromBinary(e,t)}static fromJson(e,t){return new eg().fromJson(e,t)}static fromJsonString(e,t){return new eg().fromJsonString(e,t)}static equals(e,t){return Q.w.util.equals(eg,e,t)}constructor(e){super(),Q.w.util.initPartial(e,this)}}eg.runtime=Q.w,eg.typeName="yorkie.v1.Operation.Select",eg.fields=Q.w.util.newFieldList(()=>[{no:1,name:"parent_created_at",kind:"message",T:ej},{no:2,name:"from",kind:"message",T:eU},{no:3,name:"to",kind:"message",T:eU},{no:4,name:"executed_at",kind:"message",T:ej}]);class ef extends X.v{static fromBinary(e,t){return new ef().fromBinary(e,t)}static fromJson(e,t){return new ef().fromJson(e,t)}static fromJsonString(e,t){return new ef().fromJsonString(e,t)}static equals(e,t){return Q.w.util.equals(ef,e,t)}constructor(e){super(),this.attributes={},this.createdAtMapByActor={},Q.w.util.initPartial(e,this)}}ef.runtime=Q.w,ef.typeName="yorkie.v1.Operation.Style",ef.fields=Q.w.util.newFieldList(()=>[{no:1,name:"parent_created_at",kind:"message",T:ej},{no:2,name:"from",kind:"message",T:eU},{no:3,name:"to",kind:"message",T:eU},{no:4,name:"attributes",kind:"map",K:9,V:{kind:"scalar",T:9}},{no:5,name:"executed_at",kind:"message",T:ej},{no:6,name:"created_at_map_by_actor",kind:"map",K:9,V:{kind:"message",T:ej}}]);class em extends X.v{static fromBinary(e,t){return new em().fromBinary(e,t)}static fromJson(e,t){return new em().fromJson(e,t)}static fromJsonString(e,t){return new em().fromJsonString(e,t)}static equals(e,t){return Q.w.util.equals(em,e,t)}constructor(e){super(),Q.w.util.initPartial(e,this)}}em.runtime=Q.w,em.typeName="yorkie.v1.Operation.Increase",em.fields=Q.w.util.newFieldList(()=>[{no:1,name:"parent_created_at",kind:"message",T:ej},{no:2,name:"value",kind:"message",T:ew},{no:3,name:"executed_at",kind:"message",T:ej}]);class ep extends X.v{static fromBinary(e,t){return new ep().fromBinary(e,t)}static fromJson(e,t){return new ep().fromJson(e,t)}static fromJsonString(e,t){return new ep().fromJsonString(e,t)}static equals(e,t){return Q.w.util.equals(ep,e,t)}constructor(e){super(),this.createdAtMapByActor={},this.contents=[],this.splitLevel=0,Q.w.util.initPartial(e,this)}}ep.runtime=Q.w,ep.typeName="yorkie.v1.Operation.TreeEdit",ep.fields=Q.w.util.newFieldList(()=>[{no:1,name:"parent_created_at",kind:"message",T:ej},{no:2,name:"from",kind:"message",T:eJ},{no:3,name:"to",kind:"message",T:eJ},{no:4,name:"created_at_map_by_actor",kind:"map",K:9,V:{kind:"message",T:ej}},{no:5,name:"contents",kind:"message",T:eO,repeated:!0},{no:7,name:"split_level",kind:"scalar",T:5},{no:6,name:"executed_at",kind:"message",T:ej}]);class ey extends X.v{static fromBinary(e,t){return new ey().fromBinary(e,t)}static fromJson(e,t){return new ey().fromJson(e,t)}static fromJsonString(e,t){return new ey().fromJsonString(e,t)}static equals(e,t){return Q.w.util.equals(ey,e,t)}constructor(e){super(),this.attributes={},this.attributesToRemove=[],this.createdAtMapByActor={},Q.w.util.initPartial(e,this)}}ey.runtime=Q.w,ey.typeName="yorkie.v1.Operation.TreeStyle",ey.fields=Q.w.util.newFieldList(()=>[{no:1,name:"parent_created_at",kind:"message",T:ej},{no:2,name:"from",kind:"message",T:eJ},{no:3,name:"to",kind:"message",T:eJ},{no:4,name:"attributes",kind:"map",K:9,V:{kind:"scalar",T:9}},{no:5,name:"executed_at",kind:"message",T:ej},{no:6,name:"attributes_to_remove",kind:"scalar",T:9,repeated:!0},{no:7,name:"created_at_map_by_actor",kind:"map",K:9,V:{kind:"message",T:ej}}]);class ev extends X.v{static fromBinary(e,t){return new ev().fromBinary(e,t)}static fromJson(e,t){return new ev().fromJson(e,t)}static fromJsonString(e,t){return new ev().fromJsonString(e,t)}static equals(e,t){return Q.w.util.equals(ev,e,t)}constructor(e){super(),Q.w.util.initPartial(e,this)}}ev.runtime=Q.w,ev.typeName="yorkie.v1.Operation.ArraySet",ev.fields=Q.w.util.newFieldList(()=>[{no:1,name:"parent_created_at",kind:"message",T:ej},{no:2,name:"created_at",kind:"message",T:ej},{no:3,name:"value",kind:"message",T:ew},{no:4,name:"executed_at",kind:"message",T:ej}]);class ew extends X.v{static fromBinary(e,t){return new ew().fromBinary(e,t)}static fromJson(e,t){return new ew().fromJson(e,t)}static fromJsonString(e,t){return new ew().fromJsonString(e,t)}static equals(e,t){return Q.w.util.equals(ew,e,t)}constructor(e){super(),this.type=0,this.value=new Uint8Array(0),Q.w.util.initPartial(e,this)}}ew.runtime=Q.w,ew.typeName="yorkie.v1.JSONElementSimple",ew.fields=Q.w.util.newFieldList(()=>[{no:1,name:"created_at",kind:"message",T:ej},{no:2,name:"moved_at",kind:"message",T:ej},{no:3,name:"removed_at",kind:"message",T:ej},{no:4,name:"type",kind:"enum",T:Q.w.getEnumType(S)},{no:5,name:"value",kind:"scalar",T:12}]);class eA extends X.v{static fromBinary(e,t){return new eA().fromBinary(e,t)}static fromJson(e,t){return new eA().fromJson(e,t)}static fromJsonString(e,t){return new eA().fromJsonString(e,t)}static equals(e,t){return Q.w.util.equals(eA,e,t)}constructor(e){super(),this.body={case:void 0},Q.w.util.initPartial(e,this)}}eA.runtime=Q.w,eA.typeName="yorkie.v1.JSONElement",eA.fields=Q.w.util.newFieldList(()=>[{no:1,name:"json_object",kind:"message",T:eT,oneof:"body"},{no:2,name:"json_array",kind:"message",T:eS,oneof:"body"},{no:3,name:"primitive",kind:"message",T:eI,oneof:"body"},{no:5,name:"text",kind:"message",T:eC,oneof:"body"},{no:6,name:"counter",kind:"message",T:ex,oneof:"body"},{no:7,name:"tree",kind:"message",T:eP,oneof:"body"}]);class eT extends X.v{static fromBinary(e,t){return new eT().fromBinary(e,t)}static fromJson(e,t){return new eT().fromJson(e,t)}static fromJsonString(e,t){return new eT().fromJsonString(e,t)}static equals(e,t){return Q.w.util.equals(eT,e,t)}constructor(e){super(),this.nodes=[],Q.w.util.initPartial(e,this)}}eT.runtime=Q.w,eT.typeName="yorkie.v1.JSONElement.JSONObject",eT.fields=Q.w.util.newFieldList(()=>[{no:1,name:"nodes",kind:"message",T:eE,repeated:!0},{no:2,name:"created_at",kind:"message",T:ej},{no:3,name:"moved_at",kind:"message",T:ej},{no:4,name:"removed_at",kind:"message",T:ej}]);class eS extends X.v{static fromBinary(e,t){return new eS().fromBinary(e,t)}static fromJson(e,t){return new eS().fromJson(e,t)}static fromJsonString(e,t){return new eS().fromJsonString(e,t)}static equals(e,t){return Q.w.util.equals(eS,e,t)}constructor(e){super(),this.nodes=[],Q.w.util.initPartial(e,this)}}eS.runtime=Q.w,eS.typeName="yorkie.v1.JSONElement.JSONArray",eS.fields=Q.w.util.newFieldList(()=>[{no:1,name:"nodes",kind:"message",T:eb,repeated:!0},{no:2,name:"created_at",kind:"message",T:ej},{no:3,name:"moved_at",kind:"message",T:ej},{no:4,name:"removed_at",kind:"message",T:ej}]);class eI extends X.v{static fromBinary(e,t){return new eI().fromBinary(e,t)}static fromJson(e,t){return new eI().fromJson(e,t)}static fromJsonString(e,t){return new eI().fromJsonString(e,t)}static equals(e,t){return Q.w.util.equals(eI,e,t)}constructor(e){super(),this.type=0,this.value=new Uint8Array(0),Q.w.util.initPartial(e,this)}}eI.runtime=Q.w,eI.typeName="yorkie.v1.JSONElement.Primitive",eI.fields=Q.w.util.newFieldList(()=>[{no:1,name:"type",kind:"enum",T:Q.w.getEnumType(S)},{no:2,name:"value",kind:"scalar",T:12},{no:3,name:"created_at",kind:"message",T:ej},{no:4,name:"moved_at",kind:"message",T:ej},{no:5,name:"removed_at",kind:"message",T:ej}]);class eC extends X.v{static fromBinary(e,t){return new eC().fromBinary(e,t)}static fromJson(e,t){return new eC().fromJson(e,t)}static fromJsonString(e,t){return new eC().fromJsonString(e,t)}static equals(e,t){return Q.w.util.equals(eC,e,t)}constructor(e){super(),this.nodes=[],Q.w.util.initPartial(e,this)}}eC.runtime=Q.w,eC.typeName="yorkie.v1.JSONElement.Text",eC.fields=Q.w.util.newFieldList(()=>[{no:1,name:"nodes",kind:"message",T:eD,repeated:!0},{no:2,name:"created_at",kind:"message",T:ej},{no:3,name:"moved_at",kind:"message",T:ej},{no:4,name:"removed_at",kind:"message",T:ej}]);class ex extends X.v{static fromBinary(e,t){return new ex().fromBinary(e,t)}static fromJson(e,t){return new ex().fromJson(e,t)}static fromJsonString(e,t){return new ex().fromJsonString(e,t)}static equals(e,t){return Q.w.util.equals(ex,e,t)}constructor(e){super(),this.type=0,this.value=new Uint8Array(0),Q.w.util.initPartial(e,this)}}ex.runtime=Q.w,ex.typeName="yorkie.v1.JSONElement.Counter",ex.fields=Q.w.util.newFieldList(()=>[{no:1,name:"type",kind:"enum",T:Q.w.getEnumType(S)},{no:2,name:"value",kind:"scalar",T:12},{no:3,name:"created_at",kind:"message",T:ej},{no:4,name:"moved_at",kind:"message",T:ej},{no:5,name:"removed_at",kind:"message",T:ej}]);class eP extends X.v{static fromBinary(e,t){return new eP().fromBinary(e,t)}static fromJson(e,t){return new eP().fromJson(e,t)}static fromJsonString(e,t){return new eP().fromJsonString(e,t)}static equals(e,t){return Q.w.util.equals(eP,e,t)}constructor(e){super(),this.nodes=[],Q.w.util.initPartial(e,this)}}eP.runtime=Q.w,eP.typeName="yorkie.v1.JSONElement.Tree",eP.fields=Q.w.util.newFieldList(()=>[{no:1,name:"nodes",kind:"message",T:eN,repeated:!0},{no:2,name:"created_at",kind:"message",T:ej},{no:3,name:"moved_at",kind:"message",T:ej},{no:4,name:"removed_at",kind:"message",T:ej}]);class eE extends X.v{static fromBinary(e,t){return new eE().fromBinary(e,t)}static fromJson(e,t){return new eE().fromJson(e,t)}static fromJsonString(e,t){return new eE().fromJsonString(e,t)}static equals(e,t){return Q.w.util.equals(eE,e,t)}constructor(e){super(),this.key="",Q.w.util.initPartial(e,this)}}eE.runtime=Q.w,eE.typeName="yorkie.v1.RHTNode",eE.fields=Q.w.util.newFieldList(()=>[{no:1,name:"key",kind:"scalar",T:9},{no:2,name:"element",kind:"message",T:eA}]);class eb extends X.v{static fromBinary(e,t){return new eb().fromBinary(e,t)}static fromJson(e,t){return new eb().fromJson(e,t)}static fromJsonString(e,t){return new eb().fromJsonString(e,t)}static equals(e,t){return Q.w.util.equals(eb,e,t)}constructor(e){super(),Q.w.util.initPartial(e,this)}}eb.runtime=Q.w,eb.typeName="yorkie.v1.RGANode",eb.fields=Q.w.util.newFieldList(()=>[{no:1,name:"next",kind:"message",T:eb},{no:2,name:"element",kind:"message",T:eA}]);class ek extends X.v{static fromBinary(e,t){return new ek().fromBinary(e,t)}static fromJson(e,t){return new ek().fromJson(e,t)}static fromJsonString(e,t){return new ek().fromJsonString(e,t)}static equals(e,t){return Q.w.util.equals(ek,e,t)}constructor(e){super(),this.value="",this.isRemoved=!1,Q.w.util.initPartial(e,this)}}ek.runtime=Q.w,ek.typeName="yorkie.v1.NodeAttr",ek.fields=Q.w.util.newFieldList(()=>[{no:1,name:"value",kind:"scalar",T:9},{no:2,name:"updated_at",kind:"message",T:ej},{no:3,name:"is_removed",kind:"scalar",T:8}]);class eD extends X.v{static fromBinary(e,t){return new eD().fromBinary(e,t)}static fromJson(e,t){return new eD().fromJson(e,t)}static fromJsonString(e,t){return new eD().fromJsonString(e,t)}static equals(e,t){return Q.w.util.equals(eD,e,t)}constructor(e){super(),this.value="",this.attributes={},Q.w.util.initPartial(e,this)}}eD.runtime=Q.w,eD.typeName="yorkie.v1.TextNode",eD.fields=Q.w.util.newFieldList(()=>[{no:1,name:"id",kind:"message",T:eR},{no:2,name:"value",kind:"scalar",T:9},{no:3,name:"removed_at",kind:"message",T:ej},{no:4,name:"ins_prev_id",kind:"message",T:eR},{no:5,name:"attributes",kind:"map",K:9,V:{kind:"message",T:ek}}]);class eR extends X.v{static fromBinary(e,t){return new eR().fromBinary(e,t)}static fromJson(e,t){return new eR().fromJson(e,t)}static fromJsonString(e,t){return new eR().fromJsonString(e,t)}static equals(e,t){return Q.w.util.equals(eR,e,t)}constructor(e){super(),this.offset=0,Q.w.util.initPartial(e,this)}}eR.runtime=Q.w,eR.typeName="yorkie.v1.TextNodeID",eR.fields=Q.w.util.newFieldList(()=>[{no:1,name:"created_at",kind:"message",T:ej},{no:2,name:"offset",kind:"scalar",T:5}]);class eN extends X.v{static fromBinary(e,t){return new eN().fromBinary(e,t)}static fromJson(e,t){return new eN().fromJson(e,t)}static fromJsonString(e,t){return new eN().fromJsonString(e,t)}static equals(e,t){return Q.w.util.equals(eN,e,t)}constructor(e){super(),this.type="",this.value="",this.depth=0,this.attributes={},Q.w.util.initPartial(e,this)}}eN.runtime=Q.w,eN.typeName="yorkie.v1.TreeNode",eN.fields=Q.w.util.newFieldList(()=>[{no:1,name:"id",kind:"message",T:eB},{no:2,name:"type",kind:"scalar",T:9},{no:3,name:"value",kind:"scalar",T:9},{no:4,name:"removed_at",kind:"message",T:ej},{no:5,name:"ins_prev_id",kind:"message",T:eB},{no:6,name:"ins_next_id",kind:"message",T:eB},{no:7,name:"depth",kind:"scalar",T:5},{no:8,name:"attributes",kind:"map",K:9,V:{kind:"message",T:ek}}]);class eO extends X.v{static fromBinary(e,t){return new eO().fromBinary(e,t)}static fromJson(e,t){return new eO().fromJson(e,t)}static fromJsonString(e,t){return new eO().fromJsonString(e,t)}static equals(e,t){return Q.w.util.equals(eO,e,t)}constructor(e){super(),this.content=[],Q.w.util.initPartial(e,this)}}eO.runtime=Q.w,eO.typeName="yorkie.v1.TreeNodes",eO.fields=Q.w.util.newFieldList(()=>[{no:1,name:"content",kind:"message",T:eN,repeated:!0}]);class eB extends X.v{static fromBinary(e,t){return new eB().fromBinary(e,t)}static fromJson(e,t){return new eB().fromJson(e,t)}static fromJsonString(e,t){return new eB().fromJsonString(e,t)}static equals(e,t){return Q.w.util.equals(eB,e,t)}constructor(e){super(),this.offset=0,Q.w.util.initPartial(e,this)}}eB.runtime=Q.w,eB.typeName="yorkie.v1.TreeNodeID",eB.fields=Q.w.util.newFieldList(()=>[{no:1,name:"created_at",kind:"message",T:ej},{no:2,name:"offset",kind:"scalar",T:5}]);class eJ extends X.v{static fromBinary(e,t){return new eJ().fromBinary(e,t)}static fromJson(e,t){return new eJ().fromJson(e,t)}static fromJsonString(e,t){return new eJ().fromJsonString(e,t)}static equals(e,t){return Q.w.util.equals(eJ,e,t)}constructor(e){super(),Q.w.util.initPartial(e,this)}}eJ.runtime=Q.w,eJ.typeName="yorkie.v1.TreePos",eJ.fields=Q.w.util.newFieldList(()=>[{no:1,name:"parent_id",kind:"message",T:eB},{no:2,name:"left_sibling_id",kind:"message",T:eB}]);class eL extends X.v{static fromBinary(e,t){return new eL().fromBinary(e,t)}static fromJson(e,t){return new eL().fromJson(e,t)}static fromJsonString(e,t){return new eL().fromJsonString(e,t)}static equals(e,t){return Q.w.util.equals(eL,e,t)}constructor(e){super(),this.id="",this.username="",Q.w.util.initPartial(e,this)}}eL.runtime=Q.w,eL.typeName="yorkie.v1.User",eL.fields=Q.w.util.newFieldList(()=>[{no:1,name:"id",kind:"scalar",T:9},{no:2,name:"username",kind:"scalar",T:9},{no:3,name:"created_at",kind:"message",T:ee.E}]);class e_ extends X.v{static fromBinary(e,t){return new e_().fromBinary(e,t)}static fromJson(e,t){return new e_().fromJson(e,t)}static fromJsonString(e,t){return new e_().fromJsonString(e,t)}static equals(e,t){return Q.w.util.equals(e_,e,t)}constructor(e){super(),this.id="",this.name="",this.publicKey="",this.secretKey="",this.authWebhookUrl="",this.authWebhookMethods=[],this.clientDeactivateThreshold="",Q.w.util.initPartial(e,this)}}e_.runtime=Q.w,e_.typeName="yorkie.v1.Project",e_.fields=Q.w.util.newFieldList(()=>[{no:1,name:"id",kind:"scalar",T:9},{no:2,name:"name",kind:"scalar",T:9},{no:3,name:"public_key",kind:"scalar",T:9},{no:4,name:"secret_key",kind:"scalar",T:9},{no:5,name:"auth_webhook_url",kind:"scalar",T:9},{no:6,name:"auth_webhook_methods",kind:"scalar",T:9,repeated:!0},{no:7,name:"client_deactivate_threshold",kind:"scalar",T:9},{no:8,name:"created_at",kind:"message",T:ee.E},{no:9,name:"updated_at",kind:"message",T:ee.E}]);class eM extends X.v{static fromBinary(e,t){return new eM().fromBinary(e,t)}static fromJson(e,t){return new eM().fromJson(e,t)}static fromJsonString(e,t){return new eM().fromJsonString(e,t)}static equals(e,t){return Q.w.util.equals(eM,e,t)}constructor(e){super(),Q.w.util.initPartial(e,this)}}eM.runtime=Q.w,eM.typeName="yorkie.v1.UpdatableProjectFields",eM.fields=Q.w.util.newFieldList(()=>[{no:1,name:"name",kind:"message",T:et.Gm},{no:2,name:"auth_webhook_url",kind:"message",T:et.Gm},{no:3,name:"auth_webhook_methods",kind:"message",T:eq},{no:4,name:"client_deactivate_threshold",kind:"message",T:et.Gm}]);class eq extends X.v{static fromBinary(e,t){return new eq().fromBinary(e,t)}static fromJson(e,t){return new eq().fromJson(e,t)}static fromJsonString(e,t){return new eq().fromJsonString(e,t)}static equals(e,t){return Q.w.util.equals(eq,e,t)}constructor(e){super(),this.methods=[],Q.w.util.initPartial(e,this)}}eq.runtime=Q.w,eq.typeName="yorkie.v1.UpdatableProjectFields.AuthWebhookMethods",eq.fields=Q.w.util.newFieldList(()=>[{no:1,name:"methods",kind:"scalar",T:9,repeated:!0}]);class ez extends X.v{static fromBinary(e,t){return new ez().fromBinary(e,t)}static fromJson(e,t){return new ez().fromJson(e,t)}static fromJsonString(e,t){return new ez().fromJsonString(e,t)}static equals(e,t){return Q.w.util.equals(ez,e,t)}constructor(e){super(),this.id="",this.key="",this.snapshot="",Q.w.util.initPartial(e,this)}}ez.runtime=Q.w,ez.typeName="yorkie.v1.DocumentSummary",ez.fields=Q.w.util.newFieldList(()=>[{no:1,name:"id",kind:"scalar",T:9},{no:2,name:"key",kind:"scalar",T:9},{no:3,name:"snapshot",kind:"scalar",T:9},{no:4,name:"created_at",kind:"message",T:ee.E},{no:5,name:"accessed_at",kind:"message",T:ee.E},{no:6,name:"updated_at",kind:"message",T:ee.E}]);class eK extends X.v{static fromBinary(e,t){return new eK().fromBinary(e,t)}static fromJson(e,t){return new eK().fromJson(e,t)}static fromJsonString(e,t){return new eK().fromJsonString(e,t)}static equals(e,t){return Q.w.util.equals(eK,e,t)}constructor(e){super(),this.type=0,Q.w.util.initPartial(e,this)}}eK.runtime=Q.w,eK.typeName="yorkie.v1.PresenceChange",eK.fields=Q.w.util.newFieldList(()=>[{no:1,name:"type",kind:"enum",T:Q.w.getEnumType(C)},{no:2,name:"presence",kind:"message",T:eF}]),(s=C||(C={}))[s.UNSPECIFIED=0]="UNSPECIFIED",s[s.PUT=1]="PUT",s[s.DELETE=2]="DELETE",s[s.CLEAR=3]="CLEAR",Q.w.util.setEnumType(C,"yorkie.v1.PresenceChange.ChangeType",[{no:0,name:"CHANGE_TYPE_UNSPECIFIED"},{no:1,name:"CHANGE_TYPE_PUT"},{no:2,name:"CHANGE_TYPE_DELETE"},{no:3,name:"CHANGE_TYPE_CLEAR"}]);class eF extends X.v{static fromBinary(e,t){return new eF().fromBinary(e,t)}static fromJson(e,t){return new eF().fromJson(e,t)}static fromJsonString(e,t){return new eF().fromJsonString(e,t)}static equals(e,t){return Q.w.util.equals(eF,e,t)}constructor(e){super(),this.data={},Q.w.util.initPartial(e,this)}}eF.runtime=Q.w,eF.typeName="yorkie.v1.Presence",eF.fields=Q.w.util.newFieldList(()=>[{no:1,name:"data",kind:"map",K:9,V:{kind:"scalar",T:9}}]);class eV extends X.v{static fromBinary(e,t){return new eV().fromBinary(e,t)}static fromJson(e,t){return new eV().fromJson(e,t)}static fromJsonString(e,t){return new eV().fromJsonString(e,t)}static equals(e,t){return Q.w.util.equals(eV,e,t)}constructor(e){super(),this.serverSeq=$.q.zero,this.clientSeq=0,Q.w.util.initPartial(e,this)}}eV.runtime=Q.w,eV.typeName="yorkie.v1.Checkpoint",eV.fields=Q.w.util.newFieldList(()=>[{no:1,name:"server_seq",kind:"scalar",T:3},{no:2,name:"client_seq",kind:"scalar",T:13}]);class eU extends X.v{static fromBinary(e,t){return new eU().fromBinary(e,t)}static fromJson(e,t){return new eU().fromJson(e,t)}static fromJsonString(e,t){return new eU().fromJsonString(e,t)}static equals(e,t){return Q.w.util.equals(eU,e,t)}constructor(e){super(),this.offset=0,this.relativeOffset=0,Q.w.util.initPartial(e,this)}}eU.runtime=Q.w,eU.typeName="yorkie.v1.TextNodePos",eU.fields=Q.w.util.newFieldList(()=>[{no:1,name:"created_at",kind:"message",T:ej},{no:2,name:"offset",kind:"scalar",T:5},{no:3,name:"relative_offset",kind:"scalar",T:5}]);class ej extends X.v{static fromBinary(e,t){return new ej().fromBinary(e,t)}static fromJson(e,t){return new ej().fromJson(e,t)}static fromJsonString(e,t){return new ej().fromJsonString(e,t)}static equals(e,t){return Q.w.util.equals(ej,e,t)}constructor(e){super(),this.lamport=$.q.zero,this.delimiter=0,this.actorId=new Uint8Array(0),Q.w.util.initPartial(e,this)}}ej.runtime=Q.w,ej.typeName="yorkie.v1.TimeTicket",ej.fields=Q.w.util.newFieldList(()=>[{no:1,name:"lamport",kind:"scalar",T:3},{no:2,name:"delimiter",kind:"scalar",T:13},{no:3,name:"actor_id",kind:"scalar",T:12}]);class eW extends X.v{static fromBinary(e,t){return new eW().fromBinary(e,t)}static fromJson(e,t){return new eW().fromJson(e,t)}static fromJsonString(e,t){return new eW().fromJsonString(e,t)}static equals(e,t){return Q.w.util.equals(eW,e,t)}constructor(e){super(),this.topic="",this.payload=new Uint8Array(0),Q.w.util.initPartial(e,this)}}eW.runtime=Q.w,eW.typeName="yorkie.v1.DocEventBody",eW.fields=Q.w.util.newFieldList(()=>[{no:1,name:"topic",kind:"scalar",T:9},{no:2,name:"payload",kind:"scalar",T:12}]);class eG extends X.v{static fromBinary(e,t){return new eG().fromBinary(e,t)}static fromJson(e,t){return new eG().fromJson(e,t)}static fromJsonString(e,t){return new eG().fromJsonString(e,t)}static equals(e,t){return Q.w.util.equals(eG,e,t)}constructor(e){super(),this.type=0,this.publisher="",Q.w.util.initPartial(e,this)}}eG.runtime=Q.w,eG.typeName="yorkie.v1.DocEvent",eG.fields=Q.w.util.newFieldList(()=>[{no:1,name:"type",kind:"enum",T:Q.w.getEnumType(I)},{no:2,name:"publisher",kind:"scalar",T:9},{no:3,name:"body",kind:"message",T:eW}]);class eH extends X.v{static fromBinary(e,t){return new eH().fromBinary(e,t)}static fromJson(e,t){return new eH().fromJson(e,t)}static fromJsonString(e,t){return new eH().fromJsonString(e,t)}static equals(e,t){return Q.w.util.equals(eH,e,t)}constructor(e){super(),this.clientKey="",Q.w.util.initPartial(e,this)}}eH.runtime=Q.w,eH.typeName="yorkie.v1.ActivateClientRequest",eH.fields=Q.w.util.newFieldList(()=>[{no:1,name:"client_key",kind:"scalar",T:9}]);class eY extends X.v{static fromBinary(e,t){return new eY().fromBinary(e,t)}static fromJson(e,t){return new eY().fromJson(e,t)}static fromJsonString(e,t){return new eY().fromJsonString(e,t)}static equals(e,t){return Q.w.util.equals(eY,e,t)}constructor(e){super(),this.clientId="",Q.w.util.initPartial(e,this)}}eY.runtime=Q.w,eY.typeName="yorkie.v1.ActivateClientResponse",eY.fields=Q.w.util.newFieldList(()=>[{no:1,name:"client_id",kind:"scalar",T:9}]);class eZ extends X.v{static fromBinary(e,t){return new eZ().fromBinary(e,t)}static fromJson(e,t){return new eZ().fromJson(e,t)}static fromJsonString(e,t){return new eZ().fromJsonString(e,t)}static equals(e,t){return Q.w.util.equals(eZ,e,t)}constructor(e){super(),this.clientId="",Q.w.util.initPartial(e,this)}}eZ.runtime=Q.w,eZ.typeName="yorkie.v1.DeactivateClientRequest",eZ.fields=Q.w.util.newFieldList(()=>[{no:1,name:"client_id",kind:"scalar",T:9}]);class eX extends X.v{static fromBinary(e,t){return new eX().fromBinary(e,t)}static fromJson(e,t){return new eX().fromJson(e,t)}static fromJsonString(e,t){return new eX().fromJsonString(e,t)}static equals(e,t){return Q.w.util.equals(eX,e,t)}constructor(e){super(),Q.w.util.initPartial(e,this)}}eX.runtime=Q.w,eX.typeName="yorkie.v1.DeactivateClientResponse",eX.fields=Q.w.util.newFieldList(()=>[]);class eQ extends X.v{static fromBinary(e,t){return new eQ().fromBinary(e,t)}static fromJson(e,t){return new eQ().fromJson(e,t)}static fromJsonString(e,t){return new eQ().fromJsonString(e,t)}static equals(e,t){return Q.w.util.equals(eQ,e,t)}constructor(e){super(),this.clientId="",Q.w.util.initPartial(e,this)}}eQ.runtime=Q.w,eQ.typeName="yorkie.v1.AttachDocumentRequest",eQ.fields=Q.w.util.newFieldList(()=>[{no:1,name:"client_id",kind:"scalar",T:9},{no:2,name:"change_pack",kind:"message",T:en}]);class e$ extends X.v{static fromBinary(e,t){return new e$().fromBinary(e,t)}static fromJson(e,t){return new e$().fromJson(e,t)}static fromJsonString(e,t){return new e$().fromJsonString(e,t)}static equals(e,t){return Q.w.util.equals(e$,e,t)}constructor(e){super(),this.documentId="",Q.w.util.initPartial(e,this)}}e$.runtime=Q.w,e$.typeName="yorkie.v1.AttachDocumentResponse",e$.fields=Q.w.util.newFieldList(()=>[{no:1,name:"document_id",kind:"scalar",T:9},{no:2,name:"change_pack",kind:"message",T:en}]);class e0 extends X.v{static fromBinary(e,t){return new e0().fromBinary(e,t)}static fromJson(e,t){return new e0().fromJson(e,t)}static fromJsonString(e,t){return new e0().fromJsonString(e,t)}static equals(e,t){return Q.w.util.equals(e0,e,t)}constructor(e){super(),this.clientId="",this.documentId="",this.removeIfNotAttached=!1,Q.w.util.initPartial(e,this)}}e0.runtime=Q.w,e0.typeName="yorkie.v1.DetachDocumentRequest",e0.fields=Q.w.util.newFieldList(()=>[{no:1,name:"client_id",kind:"scalar",T:9},{no:2,name:"document_id",kind:"scalar",T:9},{no:3,name:"change_pack",kind:"message",T:en},{no:4,name:"remove_if_not_attached",kind:"scalar",T:8}]);class e1 extends X.v{static fromBinary(e,t){return new e1().fromBinary(e,t)}static fromJson(e,t){return new e1().fromJson(e,t)}static fromJsonString(e,t){return new e1().fromJsonString(e,t)}static equals(e,t){return Q.w.util.equals(e1,e,t)}constructor(e){super(),Q.w.util.initPartial(e,this)}}e1.runtime=Q.w,e1.typeName="yorkie.v1.DetachDocumentResponse",e1.fields=Q.w.util.newFieldList(()=>[{no:2,name:"change_pack",kind:"message",T:en}]);class e2 extends X.v{static fromBinary(e,t){return new e2().fromBinary(e,t)}static fromJson(e,t){return new e2().fromJson(e,t)}static fromJsonString(e,t){return new e2().fromJsonString(e,t)}static equals(e,t){return Q.w.util.equals(e2,e,t)}constructor(e){super(),this.clientId="",this.documentId="",Q.w.util.initPartial(e,this)}}e2.runtime=Q.w,e2.typeName="yorkie.v1.WatchDocumentRequest",e2.fields=Q.w.util.newFieldList(()=>[{no:1,name:"client_id",kind:"scalar",T:9},{no:2,name:"document_id",kind:"scalar",T:9}]);class e3 extends X.v{static fromBinary(e,t){return new e3().fromBinary(e,t)}static fromJson(e,t){return new e3().fromJson(e,t)}static fromJsonString(e,t){return new e3().fromJsonString(e,t)}static equals(e,t){return Q.w.util.equals(e3,e,t)}constructor(e){super(),this.body={case:void 0},Q.w.util.initPartial(e,this)}}e3.runtime=Q.w,e3.typeName="yorkie.v1.WatchDocumentResponse",e3.fields=Q.w.util.newFieldList(()=>[{no:1,name:"initialization",kind:"message",T:e9,oneof:"body"},{no:2,name:"event",kind:"message",T:eG,oneof:"body"}]);class e9 extends X.v{static fromBinary(e,t){return new e9().fromBinary(e,t)}static fromJson(e,t){return new e9().fromJson(e,t)}static fromJsonString(e,t){return new e9().fromJsonString(e,t)}static equals(e,t){return Q.w.util.equals(e9,e,t)}constructor(e){super(),this.clientIds=[],Q.w.util.initPartial(e,this)}}e9.runtime=Q.w,e9.typeName="yorkie.v1.WatchDocumentResponse.Initialization",e9.fields=Q.w.util.newFieldList(()=>[{no:1,name:"client_ids",kind:"scalar",T:9,repeated:!0}]);class e4 extends X.v{static fromBinary(e,t){return new e4().fromBinary(e,t)}static fromJson(e,t){return new e4().fromJson(e,t)}static fromJsonString(e,t){return new e4().fromJsonString(e,t)}static equals(e,t){return Q.w.util.equals(e4,e,t)}constructor(e){super(),this.clientId="",this.documentId="",Q.w.util.initPartial(e,this)}}e4.runtime=Q.w,e4.typeName="yorkie.v1.RemoveDocumentRequest",e4.fields=Q.w.util.newFieldList(()=>[{no:1,name:"client_id",kind:"scalar",T:9},{no:2,name:"document_id",kind:"scalar",T:9},{no:3,name:"change_pack",kind:"message",T:en}]);class e8 extends X.v{static fromBinary(e,t){return new e8().fromBinary(e,t)}static fromJson(e,t){return new e8().fromJson(e,t)}static fromJsonString(e,t){return new e8().fromJsonString(e,t)}static equals(e,t){return Q.w.util.equals(e8,e,t)}constructor(e){super(),Q.w.util.initPartial(e,this)}}e8.runtime=Q.w,e8.typeName="yorkie.v1.RemoveDocumentResponse",e8.fields=Q.w.util.newFieldList(()=>[{no:1,name:"change_pack",kind:"message",T:en}]);class e5 extends X.v{static fromBinary(e,t){return new e5().fromBinary(e,t)}static fromJson(e,t){return new e5().fromJson(e,t)}static fromJsonString(e,t){return new e5().fromJsonString(e,t)}static equals(e,t){return Q.w.util.equals(e5,e,t)}constructor(e){super(),this.clientId="",this.documentId="",this.pushOnly=!1,Q.w.util.initPartial(e,this)}}e5.runtime=Q.w,e5.typeName="yorkie.v1.PushPullChangesRequest",e5.fields=Q.w.util.newFieldList(()=>[{no:1,name:"client_id",kind:"scalar",T:9},{no:2,name:"document_id",kind:"scalar",T:9},{no:3,name:"change_pack",kind:"message",T:en},{no:4,name:"push_only",kind:"scalar",T:8}]);class e6 extends X.v{static fromBinary(e,t){return new e6().fromBinary(e,t)}static fromJson(e,t){return new e6().fromJson(e,t)}static fromJsonString(e,t){return new e6().fromJsonString(e,t)}static equals(e,t){return Q.w.util.equals(e6,e,t)}constructor(e){super(),Q.w.util.initPartial(e,this)}}e6.runtime=Q.w,e6.typeName="yorkie.v1.PushPullChangesResponse",e6.fields=Q.w.util.newFieldList(()=>[{no:1,name:"change_pack",kind:"message",T:en}]);class e7 extends X.v{static fromBinary(e,t){return new e7().fromBinary(e,t)}static fromJson(e,t){return new e7().fromJson(e,t)}static fromJsonString(e,t){return new e7().fromJsonString(e,t)}static equals(e,t){return Q.w.util.equals(e7,e,t)}constructor(e){super(),this.clientId="",this.documentId="",this.topic="",this.payload=new Uint8Array(0),Q.w.util.initPartial(e,this)}}e7.runtime=Q.w,e7.typeName="yorkie.v1.BroadcastRequest",e7.fields=Q.w.util.newFieldList(()=>[{no:1,name:"client_id",kind:"scalar",T:9},{no:2,name:"document_id",kind:"scalar",T:9},{no:3,name:"topic",kind:"scalar",T:9},{no:4,name:"payload",kind:"scalar",T:12}]);class te extends X.v{static fromBinary(e,t){return new te().fromBinary(e,t)}static fromJson(e,t){return new te().fromJson(e,t)}static fromJsonString(e,t){return new te().fromJsonString(e,t)}static equals(e,t){return Q.w.util.equals(te,e,t)}constructor(e){super(),Q.w.util.initPartial(e,this)}}te.runtime=Q.w,te.typeName="yorkie.v1.BroadcastResponse",te.fields=Q.w.util.newFieldList(()=>[]);var tt=r(6438);let tr={typeName:"yorkie.v1.YorkieService",methods:{activateClient:{name:"ActivateClient",I:eH,O:eY,kind:tt.t.Unary},deactivateClient:{name:"DeactivateClient",I:eZ,O:eX,kind:tt.t.Unary},attachDocument:{name:"AttachDocument",I:eQ,O:e$,kind:tt.t.Unary},detachDocument:{name:"DetachDocument",I:e0,O:e1,kind:tt.t.Unary},removeDocument:{name:"RemoveDocument",I:e4,O:e8,kind:tt.t.Unary},pushPullChanges:{name:"PushPullChanges",I:e5,O:e6,kind:tt.t.Unary},watchDocument:{name:"WatchDocument",I:e2,O:e3,kind:tt.t.ServerStreaming},broadcast:{name:"Broadcast",I:e7,O:te,kind:tt.t.Unary}}};var tn=r(624);(o=x||(x={})).Ok="ok",o.ErrClientNotActivated="ErrClientNotActivated",o.ErrClientNotFound="ErrClientNotFound",o.ErrUnimplemented="ErrUnimplemented",o.ErrInvalidType="ErrInvalidType",o.ErrDummy="ErrDummy",o.ErrDocumentNotAttached="ErrDocumentNotAttached",o.ErrDocumentNotDetached="ErrDocumentNotDetached",o.ErrDocumentRemoved="ErrDocumentRemoved",o.ErrInvalidObjectKey="ErrInvalidObjectKey",o.ErrInvalidArgument="ErrInvalidArgument",o.ErrNotInitialized="ErrNotInitialized",o.ErrNotReady="ErrNotReady",o.ErrRefused="ErrRefused",o.ErrContextNotProvided="ErrContextNotProvided";class ti extends Error{constructor(e,t){super(t),this.code=e,this.message=t,this.name="YorkieError",this.toString=()=>"[code=".concat(this.code,"]: ").concat(this.message)}}function ts(e){if(e instanceof Map){let t=Array.from(e);return new Map(JSON.parse(JSON.stringify(t)))}return JSON.parse(JSON.stringify(e))}let to=e=>!e||0===Object.entries(e).length,ta=e=>{let t={};for(let[r,n]of Object.entries(e))t[r]=JSON.stringify(n);return t},tc=e=>{let t={};for(let[r,n]of Object.entries(e))t[r]=JSON.parse(n);return t};(a=P||(P={})).Put="put",a.Clear="clear";class tl{set(e,t){for(let t of Object.keys(e))this.presence[t]=e[t];this.context.setPresenceChange({type:"put",presence:ts(this.presence)}),this.context.setReversePresence(e,t)}get(e){return this.presence[e]}clear(){this.presence={},this.context.setPresenceChange({type:"clear"})}constructor(e,t){this.context=e,this.presence=t}}let th="000000000000000000000000";class td{static of(e,t,r){return new td(e,t,r)}static fromStruct(e){return td.of(BigInt(e.lamport),e.delimiter,e.actorID)}toIDString(){return"".concat(this.lamport.toString(),":").concat(this.actorID,":").concat(this.delimiter)}toStruct(){return{lamport:this.getLamportAsString(),delimiter:this.getDelimiter(),actorID:this.getActorID()}}toTestString(){return"".concat(this.lamport.toString(),":").concat(this.actorID.slice(-2),":").concat(this.delimiter)}setActor(e){return new td(this.lamport,this.delimiter,e)}getLamportAsString(){return this.lamport.toString()}getLamport(){return this.lamport}getDelimiter(){return this.delimiter}getActorID(){return this.actorID}after(e){return this.compare(e)>0}equals(e){return 0===this.compare(e)}compare(e){if(this.lamport>e.lamport)return 1;if(e.lamport>this.lamport)return -1;let t=this.actorID.localeCompare(e.actorID);return 0!==t?t:this.delimiter>e.delimiter?1:e.delimiter>this.delimiter?-1:0}constructor(e,t,r){this.lamport=e,this.delimiter=t,this.actorID=r}}let tu=new td(0n,0,th),tg=new td(0x7fffffffffffffffn,4294967295,"FFFFFFFFFFFFFFFFFFFFFFFF");function tf(e){return e.replace(/["'\\\n\r\f\b\t\u2028\u2029]/g,function(e){switch(e){case'"':case"\\":return"\\"+e;case"\n":return"\\n";case"\r":return"\\r";case"\f":return"\\f";case"\b":return"\\b";case" ":return"\\t";case"\u2028":return"\\u2028";case"\u2029":return"\\u2029";default:return e}})}class tm{getCreatedAt(){return this.createdAt}getID(){return this.createdAt}getMovedAt(){return this.movedAt}getRemovedAt(){return this.removedAt}getPositionedAt(){return this.movedAt?this.movedAt:this.createdAt}setMovedAt(e){return!!(!this.movedAt||e&&e.after(this.movedAt))&&(this.movedAt=e,!0)}setRemovedAt(e){this.removedAt=e}remove(e){return!!(e&&e.after(this.getPositionedAt())&&(!this.removedAt||e.after(this.removedAt)))&&(this.removedAt=e,!0)}isRemoved(){return!!this.removedAt}constructor(e){this.createdAt=e}}class tp extends tm{constructor(e){super(e)}}class ty{static of(e,t){return new ty(e,t)}isRemoved(){return this.value.isRemoved()}getStrKey(){return this.strKey}getValue(){return this.value}remove(e){return this.value.remove(e)}constructor(e,t){this.strKey=e,this.value=t}}class tv{static create(){return new tv}set(e,t,r){let n;let i=this.nodeMapByKey.get(e);null!=i&&!i.isRemoved()&&i.remove(r)&&(n=i.getValue());let s=ty.of(e,t);return this.nodeMapByCreatedAt.set(t.getCreatedAt().toIDString(),s),(null==i||r.after(i.getValue().getPositionedAt()))&&(this.nodeMapByKey.set(e,s),t.setMovedAt(r)),n}delete(e,t){if(!this.nodeMapByCreatedAt.has(e.toIDString()))throw new ti(x.ErrInvalidArgument,"fail to find ".concat(e.toIDString()));let r=this.nodeMapByCreatedAt.get(e.toIDString());return r.remove(t),r.getValue()}subPathOf(e){let t=this.nodeMapByCreatedAt.get(e.toIDString());if(t)return t.getStrKey()}purge(e){let t=this.nodeMapByCreatedAt.get(e.getCreatedAt().toIDString());if(!t)throw new ti(x.ErrInvalidArgument,"fail to find ".concat(e.getCreatedAt().toIDString()));let r=this.nodeMapByKey.get(t.getStrKey());t===r&&this.nodeMapByKey.delete(r.getStrKey()),this.nodeMapByCreatedAt.delete(t.getValue().getCreatedAt().toIDString())}deleteByKey(e,t){let r=this.nodeMapByKey.get(e);if(null!=r&&r.remove(t))return r.getValue()}has(e){let t=this.nodeMapByKey.get(e);return null!=t&&!t.isRemoved()}getByID(e){return this.nodeMapByCreatedAt.get(e.toIDString())}get(e){let t=this.nodeMapByKey.get(e);if(!(!t||t.isRemoved()))return t}*[Symbol.iterator](){for(let[,e]of this.nodeMapByKey)yield e}constructor(){this.nodeMapByKey=new Map,this.nodeMapByCreatedAt=new Map}}class tw extends tp{static create(e,t){if(!t)return new tw(e,tv.create());let r=tv.create();for(let[e,n]of Object.entries(t))r.set(e,n.deepcopy(),n.getCreatedAt());return new tw(e,r)}subPathOf(e){return this.memberNodes.subPathOf(e)}purge(e){this.memberNodes.purge(e)}set(e,t,r){return this.memberNodes.set(e,t,r)}delete(e,t){return this.memberNodes.delete(e,t)}deleteByKey(e,t){return this.memberNodes.deleteByKey(e,t)}get(e){let t=this.memberNodes.get(e);return null==t?void 0:t.getValue()}getByID(e){let t=this.memberNodes.getByID(e);return null==t?void 0:t.getValue()}has(e){return this.memberNodes.has(e)}toJSON(){let e=[];for(let[t,r]of this)e.push('"'.concat(tf(t),'":').concat(r.toJSON()));return"{".concat(e.join(","),"}")}toJS(){return JSON.parse(this.toJSON())}toJSForTest(){let e={};for(let[t,r]of this){let{createdAt:n,value:i,type:s}=r.toJSForTest();e[t]={key:t,createdAt:n,value:i,type:s}}return{createdAt:this.getCreatedAt().toTestString(),value:e,type:"YORKIE_OBJECT"}}getKeys(){let e=[];for(let[t]of this)e.push(t);return e}toSortedJSON(){let e=[];for(let[t]of this)e.push(t);let t=[];for(let n of e.sort()){var r;let e=null===(r=this.memberNodes.get(n))||void 0===r?void 0:r.getValue();t.push('"'.concat(tf(n),'":').concat(e.toSortedJSON()))}return"{".concat(t.join(","),"}")}getRHT(){return this.memberNodes}deepcopy(){let e=tw.create(this.getCreatedAt());for(let t of this.memberNodes)e.memberNodes.set(t.getStrKey(),t.getValue().deepcopy(),this.getPositionedAt());return e.remove(this.getRemovedAt()),e}getDescendants(e){for(let t of this.memberNodes){let r=t.getValue();if(e(r,this))return;r instanceof tp&&r.getDescendants(e)}}*[Symbol.iterator](){let e=new Set;for(let t of this.memberNodes)e.has(t.getStrKey())||(e.add(t.getStrKey()),t.isRemoved()||(yield[t.getStrKey(),t.getValue()]))}constructor(e,t){super(e),this.memberNodes=t}}(c=E||(E={})).Local="local",c.Remote="remote",c.UndoRedo="undoredo";class tA{getParentCreatedAt(){return this.parentCreatedAt}getExecutedAt(){if(!this.executedAt)throw new ti(x.ErrNotReady,"executedAt is not set yet");return this.executedAt}setActor(e){this.executedAt&&(this.executedAt=this.executedAt.setActor(e))}setExecutedAt(e){this.executedAt=e}constructor(e,t){this.parentCreatedAt=e,this.executedAt=t}}class tT{getNodeString(){return"".concat(this.weight).concat(this.value)}getValue(){return this.value}getLeftWeight(){return this.hasLeft()?this.left.getWeight():0}getRightWeight(){return this.hasRight()?this.right.getWeight():0}getWeight(){return this.weight}getLeft(){return this.left}getRight(){return this.right}getParent(){return this.parent}hasLeft(){return!!this.left}hasRight(){return!!this.right}hasParent(){return!!this.parent}setLeft(e){this.left=e}setRight(e){this.right=e}setParent(e){this.parent=e}unlink(){this.parent=void 0,this.right=void 0,this.left=void 0}hasLinks(){return this.hasParent()||this.hasLeft()||this.hasRight()}increaseWeight(e){this.weight+=e}initWeight(){this.weight=this.getLength()}constructor(e){this.value=e,this.initWeight()}}class tS{get length(){return this.root?this.root.getWeight():0}find(e){if(!this.root||e<0)return[void 0,0];let t=this.root;for(;;)if(t.hasLeft()&&e<=t.getLeftWeight())t=t.getLeft();else if(t.hasRight()&&t.getLeftWeight()+t.getLength()t.getLength())throw new ti(x.ErrInvalidArgument,"out of index range: pos: ".concat(e," > node.length: ").concat(t.getLength()));return this.splayNode(t),[t,e]}indexOf(e){return e&&(e===this.root||e.hasLinks())?(this.splayNode(e),this.root.getLeftWeight()):-1}getRoot(){return this.root}insert(e){return this.insertAfter(this.root,e)}insertAfter(e,t){return e?(this.splayNode(e),this.root=t,t.setRight(e.getRight()),e.hasRight()&&e.getRight().setParent(t),t.setLeft(e),e.setParent(t),e.setRight(),this.updateWeight(e),this.updateWeight(t)):this.root=t,t}updateWeight(e){e.initWeight(),e.hasLeft()&&e.increaseWeight(e.getLeftWeight()),e.hasRight()&&e.increaseWeight(e.getRightWeight())}updateTreeWeight(e){for(;e;)this.updateWeight(e),e=e.getParent()}splayNode(e){if(e)for(;;)if(this.isLeftChild(e.getParent())&&this.isRightChild(e))this.rotateLeft(e),this.rotateRight(e);else if(this.isRightChild(e.getParent())&&this.isLeftChild(e))this.rotateRight(e),this.rotateLeft(e);else if(this.isLeftChild(e.getParent())&&this.isLeftChild(e))this.rotateRight(e.getParent()),this.rotateRight(e);else if(this.isRightChild(e.getParent())&&this.isRightChild(e))this.rotateLeft(e.getParent()),this.rotateLeft(e);else{this.isLeftChild(e)?this.rotateRight(e):this.isRightChild(e)&&this.rotateLeft(e),this.updateWeight(e);return}}delete(e){this.splayNode(e);let t=new tS(e.getLeft());t.root&&t.root.setParent();let r=new tS(e.getRight());if(r.root&&r.root.setParent(),t.root){let e=t.getRightmost();t.splayNode(e),t.root.setRight(r.root),r.root&&r.root.setParent(t.root),this.root=t.root}else this.root=r.root;e.unlink(),this.root&&this.updateWeight(this.root)}deleteRange(e,t){if(!t){this.splayNode(e),this.cutOffRight(e);return}this.splayNode(e),this.splayNode(t),t.getLeft()!=e&&this.rotateRight(e),this.cutOffRight(e)}cutOffRight(e){let t=[];for(let r of(this.traversePostorder(e.getRight(),t),t))r.initWeight();this.updateTreeWeight(e)}toTestString(){let e=[];return this.traverseInorder(this.root,e),e.map(e=>"[".concat(e.getWeight(),",").concat(e.getLength(),"]").concat(e.getValue()||"")).join("")}checkWeight(){let e=[];for(let t of(this.traverseInorder(this.root,e),e))if(t.getWeight()!=t.getLength()+t.getLeftWeight()+t.getRightWeight())return!1;return!0}getRightmost(){let e=this.root;for(;e.hasRight();)e=e.getRight();return e}traverseInorder(e,t){e&&(this.traverseInorder(e.getLeft(),t),t.push(e),this.traverseInorder(e.getRight(),t))}traversePostorder(e,t){e&&(this.traversePostorder(e.getLeft(),t),this.traversePostorder(e.getRight(),t),t.push(e))}rotateLeft(e){let t=e.getParent();t.hasParent()?t===t.getParent().getLeft()?t.getParent().setLeft(e):t.getParent().setRight(e):this.root=e,e.setParent(t.getParent()),t.setRight(e.getLeft()),t.hasRight()&&t.getRight().setParent(t),e.setLeft(t),e.getLeft().setParent(e),this.updateWeight(t),this.updateWeight(e)}rotateRight(e){let t=e.getParent();t.hasParent()?t===t.getParent().getLeft()?t.getParent().setLeft(e):t.getParent().setRight(e):this.root=e,e.setParent(t.getParent()),t.setLeft(e.getRight()),t.hasLeft()&&t.getLeft().setParent(t),e.setRight(t),e.getRight().setParent(e),this.updateWeight(t),this.updateWeight(e)}isLeftChild(e){return!!(e&&e.hasParent())&&e.getParent().getLeft()===e}isRightChild(e){return!!(e&&e.hasParent())&&e.getParent().getRight()===e}constructor(e){this.root=e}}var tI=r(7319);(l=b||(b={}))[l.Null=0]="Null",l[l.Boolean=1]="Boolean",l[l.Integer=2]="Integer",l[l.Long=3]="Long",l[l.Double=4]="Double",l[l.String=5]="String",l[l.Bytes=6]="Bytes",l[l.Date=7]="Date";class tC extends tm{static of(e,t){return new tC(e,t)}static valueFromBytes(e,t){switch(e){case 0:return null;case 1:return!!t[0];case 2:return t[0]|t[1]<<8|t[2]<<16|t[3]<<24;case 4:{let e=new DataView(t.buffer);return t.forEach(function(t,r){e.setUint8(r,t)}),e.getFloat64(0,!0)}case 5:return new TextDecoder("utf-8").decode(t);case 3:return tI.Z.fromBytesLE(Array.from(t));case 6:return t;case 7:return new Date(tI.Z.fromBytesLE(Array.from(t),!0).toNumber());default:throw new ti(x.ErrUnimplemented,"unimplemented type: ".concat(e))}}toJSON(){return 5===this.valueType?'"'.concat(tf(this.value),'"'):"".concat(this.value)}toSortedJSON(){return this.toJSON()}toJSForTest(){return{createdAt:this.getCreatedAt().toTestString(),value:this.value,type:"YORKIE_PRIMITIVE"}}deepcopy(){let e=tC.of(this.value,this.getCreatedAt());return e.setMovedAt(this.getMovedAt()),e.setRemovedAt(this.getRemovedAt()),e}getType(){return this.valueType}static getPrimitiveType(e){switch(typeof e){case"undefined":return 0;case"boolean":return 1;case"number":if(this.isInteger(e))return 2;return 4;case"string":return 5;case"object":if(null===e)return 0;if(e instanceof tI.Z)return 3;if(e instanceof Uint8Array)return 6;if(e instanceof Date)return 7}}static isSupport(e){return void 0!==tC.getPrimitiveType(e)}static isInteger(e){return e%1==0}isNumericType(){let e=this.valueType;return 2===e||3===e||4===e}getValue(){return this.value}toBytes(){switch(this.valueType){case 0:return new Uint8Array;case 1:{let e=this.value;return new Uint8Array(e?[1]:[0])}case 2:{let e=this.value;return new Uint8Array([255&e,e>>8&255,e>>16&255,e>>24&255])}case 4:{let e=this.value,t=new Uint8Array(8);return new DataView(t.buffer).setFloat64(0,e,!0),t}case 5:return new TextEncoder().encode(this.value);case 3:{let e=this.value.toBytesLE();return Uint8Array.from(e)}case 6:return this.value;case 7:{let e=this.value,t=tI.Z.fromNumber(e.getTime(),!0).toBytesLE();return Uint8Array.from(t)}default:throw new ti(x.ErrUnimplemented,"unimplemented type: ".concat(this.valueType))}}constructor(e,t){super(t),this.valueType=tC.getPrimitiveType(e),this.value=void 0===e?null:e}}class tx extends tT{static createAfter(e,t){let r=new tx(t),n=e.next;return e.next=r,r.prev=e,r.next=n,n&&(n.prev=r),r}remove(e){return this.value.remove(e)}getCreatedAt(){return this.value.getCreatedAt()}getPositionedAt(){return this.value.getPositionedAt()}release(){this.prev&&(this.prev.next=this.next),this.next&&(this.next.prev=this.prev),this.prev=void 0,this.next=void 0}getLength(){return this.value.isRemoved()?0:1}getPrev(){return this.prev}getNext(){return this.next}getValue(){return this.value}isRemoved(){return this.value.isRemoved()}constructor(e){super(e),this.value=e}}class tP{static create(){return new tP}get length(){return this.nodeMapByIndex.length}findNextBeforeExecutedAt(e,t){let r=this.nodeMapByCreatedAt.get(e.toIDString());if(!r)throw new ti(x.ErrInvalidArgument,"cant find the given node: ".concat(e.toIDString()));for(;r.getNext()&&r.getNext().getPositionedAt().after(t);)r=r.getNext();return r}release(e){this.last===e&&(this.last=e.getPrev()),e.release(),this.nodeMapByIndex.delete(e),this.nodeMapByCreatedAt.delete(e.getValue().getCreatedAt().toIDString())}insertAfter(e,t){let r=arguments.length>2&&void 0!==arguments[2]?arguments[2]:t.getCreatedAt(),n=this.findNextBeforeExecutedAt(e,r),i=tx.createAfter(n,t);n===this.last&&(this.last=i),this.nodeMapByIndex.insertAfter(n,i),this.nodeMapByCreatedAt.set(i.getCreatedAt().toIDString(),i)}moveAfter(e,t,r){let n=this.nodeMapByCreatedAt.get(e.toIDString());if(!n)throw new ti(x.ErrInvalidArgument,"cant find the given node: ".concat(e.toIDString()));let i=this.nodeMapByCreatedAt.get(t.toIDString());if(!i)throw new ti(x.ErrInvalidArgument,"cant find the given node: ".concat(t.toIDString()));n!==i&&(!i.getValue().getMovedAt()||r.after(i.getValue().getMovedAt()))&&(this.release(i),this.insertAfter(n.getCreatedAt(),i.getValue(),r),i.getValue().setMovedAt(r))}insert(e){this.insertAfter(this.last.getCreatedAt(),e)}getByID(e){return this.nodeMapByCreatedAt.get(e.toIDString())}subPathOf(e){let t=this.nodeMapByCreatedAt.get(e.toIDString());if(t)return String(this.nodeMapByIndex.indexOf(t))}purge(e){let t=this.nodeMapByCreatedAt.get(e.getCreatedAt().toIDString());if(!t)throw new ti(x.ErrInvalidArgument,"fail to find the given createdAt: ".concat(e.getCreatedAt().toIDString()));this.release(t)}getByIndex(e){if(e>=this.length)return;let[t,r]=this.nodeMapByIndex.find(e),n=t;if(0===e&&t===this.dummyHead||r>0)do n&&(n=n.getNext());while(n&&n.isRemoved());return n}getPrevCreatedAt(e){let t=this.nodeMapByCreatedAt.get(e.toIDString());do t=t.getPrev();while(this.dummyHead!==t&&t.isRemoved());return t.getValue().getCreatedAt()}delete(e,t){let r=this.nodeMapByCreatedAt.get(e.toIDString()),n=r.isRemoved();return r.remove(t)&&!n&&this.nodeMapByIndex.splayNode(r),r.getValue()}deleteByIndex(e,t){let r=this.getByIndex(e);if(r)return r.remove(t)&&this.nodeMapByIndex.splayNode(r),r.getValue()}getHead(){return this.dummyHead.getValue()}getLast(){return this.last.getValue()}getLastCreatedAt(){return this.last.getCreatedAt()}toTestString(){let e=[];for(let t of this){let r="".concat(t.getCreatedAt().toIDString(),":").concat(t.getValue().toJSON());t.isRemoved()?e.push("{".concat(r,"}")):e.push("[".concat(r,"]"))}return e.join("")}*[Symbol.iterator](){let e=this.dummyHead.getNext();for(;e;)yield e,e=e.getNext()}constructor(){let e=tC.of(0,tu);e.setRemovedAt(tu),this.dummyHead=new tx(e),this.last=this.dummyHead,this.nodeMapByIndex=new tS,this.nodeMapByCreatedAt=new Map,this.nodeMapByIndex.insert(this.dummyHead),this.nodeMapByCreatedAt.set(this.dummyHead.getCreatedAt().toIDString(),this.dummyHead)}}class tE extends tp{static create(e,t){if(!t)return new tE(e,tP.create());let r=tP.create();for(let e of t)r.insertAfter(r.getLastCreatedAt(),e.deepcopy());return new tE(e,r)}subPathOf(e){return this.elements.subPathOf(e)}purge(e){this.elements.purge(e)}insertAfter(e,t){this.elements.insertAfter(e,t)}moveAfter(e,t,r){this.elements.moveAfter(e,t,r)}get(e){let t=this.elements.getByIndex(e);return null==t?void 0:t.getValue()}getByID(e){let t=this.elements.getByID(e);return null==t?void 0:t.getValue()}getHead(){return this.elements.getHead()}getLast(){return this.elements.getLast()}getPrevCreatedAt(e){return this.elements.getPrevCreatedAt(e)}delete(e,t){return this.elements.delete(e,t)}deleteByIndex(e,t){return this.elements.deleteByIndex(e,t)}getLastCreatedAt(){return this.elements.getLastCreatedAt()}get length(){return this.elements.length}*[Symbol.iterator](){for(let e of this.elements)e.isRemoved()||(yield e.getValue())}toTestString(){return this.elements.toTestString()}getDescendants(e){for(let t of this.elements){let r=t.getValue();if(e(r,this))return;r instanceof tp&&r.getDescendants(e)}}toJSON(){let e=[];for(let t of this)e.push(t.toJSON());return"[".concat(e.join(","),"]")}toJS(){return JSON.parse(this.toJSON())}toJSForTest(){let e={};for(let t=0;t({...e,value:e.value?{attributes:tc(e.value.getAttributes()),content:e.value.getContent()}:{attributes:void 0,content:""},type:"content"})),c,[o,o]]}setStyle(e,t,r,n){let[,i]=this.rgaTreeSplit.findNodeWithSplit(e[1],r),[,s]=this.rgaTreeSplit.findNodeWithSplit(e[0],r),o=[],a=this.rgaTreeSplit.findBetween(s,i),c=new Map,l=[];for(let e of a){let t=e.getCreatedAt().getActorID(),i=(null==n?void 0:n.size)?n.has(t)?n.get(t):tu:tg;if(e.canStyle(r,i)){let r=c.get(t),n=e.getCreatedAt();(!r||n.after(r))&&c.set(t,n),l.push(e)}}let h=[];for(let e of l){if(e.isRemoved())continue;let[n,i]=this.rgaTreeSplit.findIndexesFromRange(e.createPosRange());for(let[s,a]of(o.push({type:"style",actor:r.getActorID(),from:n,to:i,value:{attributes:tc(t)}}),Object.entries(t))){let[t]=e.getValue().setAttr(s,a,r);void 0!==t&&h.push({parent:e.getValue(),child:t})}}return[c,h,o]}indexRangeToPosRange(e,t){let r=this.rgaTreeSplit.indexToPos(e);return e===t?[r,r]:[r,this.rgaTreeSplit.indexToPos(t)]}get length(){return this.rgaTreeSplit.length}getTreeByIndex(){return this.rgaTreeSplit.getTreeByIndex()}getTreeByID(){return this.rgaTreeSplit.getTreeByID()}toJSON(){let e=[];for(let t of this.rgaTreeSplit)t.isRemoved()||e.push(t.getValue().toJSON());return"[".concat(e.join(","),"]")}toSortedJSON(){return this.toJSON()}toJSForTest(){return{createdAt:this.getCreatedAt().toTestString(),value:JSON.parse(this.toJSON()),type:"YORKIE_TEXT"}}toString(){return this.rgaTreeSplit.toString()}values(){let e=[];for(let t of this.rgaTreeSplit)if(!t.isRemoved()){let r=t.getValue();e.push({attributes:tc(r.getAttributes()),content:r.getContent()})}return e}getRGATreeSplit(){return this.rgaTreeSplit}toTestString(){return this.rgaTreeSplit.toTestString()}deepcopy(){let e=new tJ(this.rgaTreeSplit.deepcopy(),this.getCreatedAt());return e.remove(this.getRemovedAt()),e}findIndexesFromRange(e){return this.rgaTreeSplit.findIndexesFromRange(e)}getGCPairs(){let e=[];for(let t of this.rgaTreeSplit)for(let r of(t.getRemovedAt()&&e.push({parent:this.rgaTreeSplit,child:t}),t.getValue().getGCPairs()))e.push(r);return e}constructor(e,t){super(t),this.rgaTreeSplit=e}}class tL extends tA{static create(e,t,r,n,i,s,o){return new tL(e,t,r,n,i,s,o)}execute(e){let t=e.findByCreatedAt(this.getParentCreatedAt());if(!t)throw new ti(x.ErrInvalidArgument,"fail to find ".concat(this.getParentCreatedAt()));if(!(t instanceof tJ))throw new ti(x.ErrInvalidArgument,"fail to execute, only Text can execute edit");let[,r,n]=t.edit([this.fromPos,this.toPos],this.content,this.getExecutedAt(),Object.fromEntries(this.attributes),this.maxCreatedAtMapByActor);for(let t of n)e.registerGCPair(t);return{opInfos:r.map(t=>{let{from:r,to:n,value:i}=t;return{type:"edit",from:r,to:n,value:i,path:e.createPath(this.getParentCreatedAt())}})}}getEffectedCreatedAt(){return this.getParentCreatedAt()}toTestString(){let e=this.getParentCreatedAt().toTestString(),t=this.fromPos.toTestString(),r=this.toPos.toTestString(),n=this.content;return"".concat(e,".EDIT(").concat(t,",").concat(r,",").concat(n,")")}getFromPos(){return this.fromPos}getToPos(){return this.toPos}getContent(){return this.content}getAttributes(){return this.attributes||new Map}getMaxCreatedAtMapByActor(){return this.maxCreatedAtMapByActor}constructor(e,t,r,n,i,s,o){super(e,o),this.fromPos=t,this.toPos=r,this.maxCreatedAtMapByActor=n,this.content=i,this.attributes=s}}class t_ extends tA{static create(e,t,r,n,i,s){return new t_(e,t,r,n,i,s)}execute(e){let t=e.findByCreatedAt(this.getParentCreatedAt());if(!t)throw new ti(x.ErrInvalidArgument,"fail to find ".concat(this.getParentCreatedAt()));if(!(t instanceof tJ))throw new ti(x.ErrInvalidArgument,"fail to execute, only Text can execute edit");let[,r,n]=t.setStyle([this.fromPos,this.toPos],this.attributes?Object.fromEntries(this.attributes):{},this.getExecutedAt(),this.maxCreatedAtMapByActor);for(let t of r)e.registerGCPair(t);return{opInfos:n.map(t=>{let{from:r,to:n,value:i}=t;return{type:"style",from:r,to:n,value:i,path:e.createPath(this.getParentCreatedAt())}})}}getEffectedCreatedAt(){return this.getParentCreatedAt()}toTestString(){let e=this.getParentCreatedAt().toTestString(),t=this.fromPos.toTestString(),r=this.toPos.toTestString(),n=this.attributes;return"".concat(e,".STYL(").concat(t,",").concat(r,",").concat(JSON.stringify(n),")")}getFromPos(){return this.fromPos}getToPos(){return this.toPos}getAttributes(){return this.attributes}getMaxCreatedAtMapByActor(){return this.maxCreatedAtMapByActor}constructor(e,t,r,n,i,s){super(e,s),this.fromPos=t,this.toPos=r,this.maxCreatedAtMapByActor=n,this.attributes=i}}let tM="text";function tq(e,t){let r=0,n=e.children;for(let e=0;e!e.isRemoved)}get allChildren(){return[...this._children]}hasTextChild(){return this.children.length>0&&this.children.every(e=>e.isText)}append(){for(var e=arguments.length,t=Array(e),r=0;re+t.paddedSize,0),r.size=r._children.reduce((e,t)=>e+t.paddedSize,0),r._children))e.parent=r;return r}insertAfterInternal(e,t){if(this.isText)throw new ti(x.ErrRefused,"Text node cannot have children");let r=this._children.indexOf(t);if(-1===r)throw new ti(x.ErrInvalidArgument,"child not found");this.insertAtInternal(e,r+1)}insertAtInternal(e,t){if(this.isText)throw new ti(x.ErrRefused,"Text node cannot have children");this._children.splice(t,0,e),e.parent=this}findOffset(e){if(this.isText)throw new ti(x.ErrRefused,"Text node cannot have children");if(e.isRemoved){let t=this._children.indexOf(e);return this.allChildren.splice(0,t).filter(e=>!e.isRemoved).length}return this.children.indexOf(e)}findBranchOffset(e){if(this.isText)throw new ti(x.ErrRefused,"Text node cannot have children");let t=e;for(;t;){let e=this._children.indexOf(t);if(-1!==e)return e;t=t.parent}return -1}constructor(e,t=[]){if(this.type=e,this.size=0,this._children=t,this.isText&&this._children.length>0)throw new ti(x.ErrRefused,"Text node cannot have children")}}function tK(e,t){let r=arguments.length>2&&void 0!==arguments[2]?arguments[2]:0;for(let n of e._children)tK(n,t,r+1);t(e,r)}(d=D||(D={})).Start="Start",d.End="End",d.Text="Text";class tF{tokensBetween(e,t,r){!function e(t,r,n,i){if(r>n)throw new ti(x.ErrInvalidArgument,"from is greater than to: ".concat(r," > ").concat(n));if(r>t.size)throw new ti(x.ErrInvalidArgument,"from is out of range: ".concat(r," > ").concat(t.size));if(n>t.size)throw new ti(x.ErrInvalidArgument,"to is out of range: ".concat(n," > ").concat(t.size));if(r===n)return;let s=0;for(let o of t.children){if(r-o.paddedSizeo.size;(o.isText||c)&&i([o,o.isText?"Text":"Start"],l),e(o,Math.max(0,t),Math.min(a,o.size),i),l&&i([o,"End"],l)}s+=o.paddedSize}}(this.root,e,t,r)}traverse(e){!function e(t,r){let n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:0;for(let i of t.children)e(i,r,n+1);r(t,n)}(this.root,e,0)}traverseAll(e){tK(this.root,e,0)}findTreePos(e){let t=!(arguments.length>1)||void 0===arguments[1]||arguments[1];return function e(t,r){let n=!(arguments.length>2)||void 0===arguments[2]||arguments[2];if(r>t.size)throw new ti(x.ErrInvalidArgument,"index is out of range: ".concat(r," > ").concat(t.size));if(t.isText)return{node:t,offset:r};let i=0,s=0;for(let o of t.children){if(n&&o.isText&&o.size>=r-s)return e(o,r-s,n);if(r===s)break;if(!n&&o.paddedSize===r-s)return{node:t,offset:i+1};if(o.paddedSize>r-s)return e(o,r-s-1,n);s+=o.paddedSize,i+=1}return{node:t,offset:i}}(this.root,e,t)}treePosToPath(e){let t=[],r=e.node;if(r.isText){let n=r.parent.findOffset(r);if(-1===n)throw new ti(x.ErrInvalidArgument,"invalid treePos");let i=tq(r.parent,n);t.push(i+e.offset),r=r.parent}else if(r.hasTextChild()){let n=tq(r,e.offset);t.push(n)}else t.push(e.offset);for(;r.parent;){let e=r.parent.findOffset(r);if(-1===e)throw new ti(x.ErrInvalidArgument,"invalid treePos");t.push(e),r=r.parent}return t.reverse()}pathToIndex(e){let t=this.pathToTreePos(e);return this.indexOf(t)}pathToTreePos(e){if(!e.length)throw new ti(x.ErrInvalidArgument,"unacceptable path");let t=this.root;for(let r=0;re===t?0:e0){if(!t.right)return t;t.right.parent=t,t=t.right}else if(!(r<0))return t;else if(t.left)t.left.parent=t,t=t.left;else{let e=t.parent,r=t;for(;e&&r===e.left;)r=e,e=e.parent;return e}}}lastEntry(){if(!this.root)return this.root;let e=this.root;for(;e.right;)e=e.right;return e}size(){return this.counter}isEmpty(){return 0===this.counter}getInternal(e,t){for(;t;){let r=this.comparator(e,t.key);if(0===r)return t;r<0?t=t.left:r>0&&(t=t.right)}}putInternal(e,t,r){if(!r)return this.counter+=1,new tU(e,t,!0);let n=this.comparator(e,r.key);return n<0?r.left=this.putInternal(e,t,r.left):n>0?r.right=this.putInternal(e,t,r.right):r.value=t,this.isRed(r.right)&&!this.isRed(r.left)&&(r=this.rotateLeft(r)),this.isRed(r.left)&&this.isRed(r.left.left)&&(r=this.rotateRight(r)),this.isRed(r.left)&&this.isRed(r.right)&&this.flipColors(r),r}removeInternal(e,t){if(0>this.comparator(t,e.key))this.isRed(e.left)||this.isRed(e.left.left)||(e=this.moveRedLeft(e)),e.left=this.removeInternal(e.left,t);else{if(this.isRed(e.left)&&(e=this.rotateRight(e)),0===this.comparator(t,e.key)&&!e.right){this.counter-=1;return}if(this.isRed(e.right)||this.isRed(e.right.left)||(e=this.moveRedRight(e)),0===this.comparator(t,e.key)){this.counter-=1;let t=this.min(e.right);e.value=t.value,e.key=t.key,e.right=this.removeMin(e.right)}else e.right=this.removeInternal(e.right,t)}return this.fixUp(e)}min(e){return e.left?this.min(e.left):e}removeMin(e){if(e.left)return this.isRed(e.left)||this.isRed(e.left.left)||(e=this.moveRedLeft(e)),e.left=this.removeMin(e.left),this.fixUp(e)}fixUp(e){return this.isRed(e.right)&&(e=this.rotateLeft(e)),this.isRed(e.left)&&this.isRed(e.left.left)&&(e=this.rotateRight(e)),this.isRed(e.left)&&this.isRed(e.right)&&this.flipColors(e),e}moveRedLeft(e){return this.flipColors(e),this.isRed(e.right.left)&&(e.right=this.rotateRight(e.right),e=this.rotateLeft(e),this.flipColors(e)),e}moveRedRight(e){return this.flipColors(e),this.isRed(e.left.left)&&(e=this.rotateRight(e),this.flipColors(e)),e}isRed(e){return e&&e.isRed}rotateLeft(e){let t=e.right;return e.right=t.left,t.left=e,t.isRed=t.left.isRed,t.left.isRed=!0,t}rotateRight(e){let t=e.left;return e.left=t.right,t.right=e,t.isRed=t.right.isRed,t.right.isRed=!0,t}flipColors(e){e.isRed=!e.isRed,e.left.isRed=!e.left.isRed,e.right.isRed=!e.right.isRed}constructor(e){this.comparator=void 0!==e?e:tV,this.counter=0}}(u=R||(R={})).Content="content",u.Style="style",u.RemoveStyle="removeStyle";class tG{static of(e,t){return new tG(e,t)}static fromTreePos(e){let t;let{offset:r}=e,{node:n}=e;return n.isText?(t=n.parent.children[0]===n&&0===r?n.parent:n,n=n.parent):t=0===r?n:n.children[r-1],tG.of(n.id,tH.of(t.getCreatedAt(),t.getOffset()+r))}getParentID(){return this.parentID}static fromStruct(e){return tG.of(tH.of(td.fromStruct(e.parentID.createdAt),e.parentID.offset),tH.of(td.fromStruct(e.leftSiblingID.createdAt),e.leftSiblingID.offset))}toStruct(){return{parentID:{createdAt:this.getParentID().getCreatedAt().toStruct(),offset:this.getParentID().getOffset()},leftSiblingID:{createdAt:this.getLeftSiblingID().getCreatedAt().toStruct(),offset:this.getLeftSiblingID().getOffset()}}}toTreeNodePair(e){let t=this.getParentID(),r=this.getLeftSiblingID(),n=e.findFloorNode(t),i=e.findFloorNode(r);if(!n||!i)throw new ti(x.ErrRefused,"cannot find node of CRDTTreePos(".concat(t.toTestString(),", ").concat(r.toTestString(),")"));return!r.equals(t)&&r.getOffset()>0&&r.getOffset()===i.id.getOffset()&&i.insPrevID&&(i=e.findFloorNode(i.insPrevID)),[n,i]}getLeftSiblingID(){return this.leftSiblingID}equals(e){return this.getParentID().getCreatedAt().equals(e.getParentID().getCreatedAt())&&this.getParentID().getOffset()===e.getParentID().getOffset()&&this.getLeftSiblingID().getCreatedAt().equals(e.getLeftSiblingID().getCreatedAt())&&this.getLeftSiblingID().getOffset()===e.getLeftSiblingID().getOffset()}constructor(e,t){this.parentID=e,this.leftSiblingID=t}}class tH{static of(e,t){return new tH(e,t)}static fromStruct(e){return tH.of(td.fromStruct(e.createdAt),e.offset)}static createComparator(){return(e,t)=>{let r=e.getCreatedAt().compare(t.getCreatedAt());return 0!==r?r:e.getOffset()>t.getOffset()?1:e.getOffset(){let r=e.deepcopy();return r.parent=t,r}),t.insPrevID=this.insPrevID,t.insNextID=this.insNextID,t}get value(){if(!this.isText)throw new ti(x.ErrInvalidType,"cannot get value of element node: ".concat(this.type));return this._value}set value(e){if(!this.isText)throw new ti(x.ErrInvalidType,"cannot set value of element node: ".concat(this.type));this._value=e,this.size=e.length}get isRemoved(){return!!this.removedAt}remove(e){let t=!this.removedAt;(!this.removedAt||this.removedAt.compare(e)>0)&&(this.removedAt=e),t&&this.updateAncestorsSize()}cloneText(e){return new tY(tH.of(this.id.getCreatedAt(),e),this.type,void 0,void 0,this.removedAt)}cloneElement(e){return new tY(tH.of(e(),0),this.type,void 0,void 0,this.removedAt)}split(e,t,r){let n=this.isText?this.splitText(t,this.id.getOffset()):this.splitElement(t,r);return n&&(n.insPrevID=this.id,this.insNextID&&(e.findFloorNode(this.insNextID).insPrevID=n.id,n.insNextID=this.insNextID),this.insNextID=n.id,e.registerNode(n)),n}getCreatedAt(){return this.id.getCreatedAt()}getOffset(){return this.id.getOffset()}canDelete(e,t){return!this.getCreatedAt().after(t)&&(!this.removedAt||e.after(this.removedAt))}canStyle(e,t){return!this.isText&&!this.getCreatedAt().after(t)&&(!this.removedAt||e.after(this.removedAt))}setAttrs(e,t){this.attrs||(this.attrs=new tO);let r=[];for(let[n,i]of Object.entries(e))r.push(this.attrs.set(n,i,t));return r}purge(e){this.attrs&&this.attrs.purge(e)}getGCPairs(){let e=[];if(!this.attrs)return e;for(let t of this.attrs)t.getRemovedAt()&&e.push({parent:this,child:t});return e}constructor(e,t,r,n,i){super(t),this._value="",this.id=e,this.removedAt=i,n&&(this.attrs=n),"string"==typeof r?this.value=r:Array.isArray(r)&&(this._children=r)}}function tZ(e){if(e.isText)return{type:e.type,value:e.value};let t={type:e.type,children:e.children.map(tZ)};if(e.attrs){var r;t.attributes=tc(null===(r=e.attrs)||void 0===r?void 0:r.toObject())}return t}function tX(e){if(e.isText)return e.value;let t="";return e.attrs&&e.attrs.size()&&(t=" "+Array.from(e.attrs).filter(e=>!e.isRemoved()).sort((e,t)=>e.getKey().localeCompare(t.getKey())).map(e=>{let t=JSON.parse(e.getValue());return"string"==typeof t?"".concat(e.getKey(),'="').concat(t,'"'):"".concat(e.getKey(),'="').concat(tf(e.getValue()),'"')}).join(" ")),"<".concat(e.type).concat(t,">").concat(e.children.map(e=>tX(e)).join(""),"")}class tQ extends tm{static create(e,t){return new tQ(e,t)}findFloorNode(e){let t=this.nodeMapByID.floorEntry(e);if(t&&t.key.getCreatedAt().equals(e.getCreatedAt()))return t.value}registerNode(e){this.nodeMapByID.put(e.id,e)}findNodesAndSplitText(e,t){let[r,n]=e.toTreeNodePair(this),i=n,s=r===i,o=i.parent&&!s?i.parent:r;if(i.isText&&i.split(this,e.getLeftSiblingID().getOffset()-i.id.getOffset()),t){let e=o.allChildren,r=s?0:e.indexOf(i)+1;for(let n=r;n{let[i]=e,s=i.getCreatedAt().getActorID(),o=n?n.has(s)?n.get(s):tu:tg;if(i.canStyle(r,o)&&t){let e=h.get(s),n=i.getCreatedAt();(!e||n.after(e))&&h.set(s,n);let o=i.setAttrs(t,r),a=o.reduce((e,t)=>{let[,r]=t;return r&&(e[r.getKey()]=l[r.getKey()]),e},{}),u=i.parent,g=i.prevSibling||i.parent;for(let[e]of(Object.keys(a).length>0&&c.push({type:"style",from:this.toIndex(u,g),to:this.toIndex(i,i),fromPath:this.toPath(u,g),toPath:this.toPath(i,i),actor:r.getActorID(),value:a}),o))e&&d.push({parent:i,child:e})}}),[h,d,c]}removeStyle(e,t,r,n){let[i,s]=this.findNodesAndSplitText(e[0],r),[o,a]=this.findNodesAndSplitText(e[1],r),c=[],l=new Map,h=[];return this.traverseInPosRange(i,s,o,a,e=>{let[i]=e,s=i.getCreatedAt().getActorID(),o=n?n.has(s)?n.get(s):tu:tg;if(i.canStyle(r,o)&&t){let e=l.get(s),n=i.getCreatedAt();for(let o of((!e||n.after(e))&&l.set(s,n),i.attrs||(i.attrs=new tO),t))for(let e of i.attrs.remove(o,r))h.push({parent:i,child:e});let o=i.parent,a=i.prevSibling||i.parent;c.push({actor:r.getActorID(),type:"removeStyle",from:this.toIndex(o,a),to:this.toIndex(i,i),fromPath:this.toPath(o,a),toPath:this.toPath(i,i),value:t})}}),[l,h,c]}edit(e,t,r,n,i,s){let[o,a]=this.findNodesAndSplitText(e[0],n),[c,l]=this.findNodesAndSplitText(e[1],n),h=this.toIndex(o,a),d=this.toPath(o,a),u=[],g=[],f=[],m=new Map;this.traverseInPosRange(o,a,c,l,(e,t)=>{let[r,i]=e;if(i===D.Start&&!t)for(let e of r.children)f.push(e);let o=r.getCreatedAt().getActorID(),a=s?s.has(o)?s.get(o):tu:tg;if(r.canDelete(n,a)||u.includes(r.parent)){let e=m.get(o),t=r.getCreatedAt();(!e||t.after(e))&&m.set(o,t),(i===D.Text||i===D.Start)&&u.push(r),g.push([r,i])}});let p=this.makeDeletionChanges(g,n),y=[];for(let e of u)e.remove(n),e.isRemoved&&y.push({parent:this,child:e});for(let e of f)e.removedAt||o.append(e);if(r>0){let e=0,t=o,s=a;for(;e{o.isRemoved&&(e.remove(n),y.push({parent:this,child:e})),this.nodeMapByID.put(e.id,e)}),i.isRemoved||e.push(i);if(e.length){let t=e.map(e=>tZ(e));p.length&&p[p.length-1].from===h?p[p.length-1].value=t:p.push({type:"content",from:h,to:h,fromPath:d,toPath:d,actor:n.getActorID(),value:t})}}return[p,y,m]}editT(e,t,r,n,i){let s=this.findPos(e[0]),o=this.findPos(e[1]);this.edit([s,o],t,r,n,i)}move(e,t,r){throw new ti(x.ErrUnimplemented,"not implemented: ".concat(e,", ").concat(t,", ").concat(r))}purge(e){var t;null===(t=e.parent)||void 0===t||t.removeChild(e),this.nodeMapByID.remove(e.id);let r=e.insPrevID,n=e.insNextID;r&&(this.findFloorNode(r).insNextID=n),n&&(this.findFloorNode(n).insPrevID=r),e.insPrevID=void 0,e.insNextID=void 0}getGCPairs(){let e=[];return this.indexTree.traverse(t=>{for(let r of(t.getRemovedAt()&&e.push({parent:this,child:t}),t.getGCPairs()))e.push(r)}),e}findPos(e){let t=!(arguments.length>1)||void 0===arguments[1]||arguments[1],r=this.indexTree.findTreePos(e,t);return tG.fromTreePos(r)}pathToPosRange(e){let t=this.pathToIndex(e);return[this.findPos(t),this.findPos(t+1)]}pathToPos(e){let t=this.indexTree.pathToIndex(e);return this.findPos(t)}getRoot(){return this.indexTree.getRoot()}getSize(){return this.indexTree.size}getNodeSize(){return this.nodeMapByID.size()}getIndexTree(){return this.indexTree}toXML(){return tX(this.indexTree.getRoot())}toJSON(){return JSON.stringify(this.getRootTreeNode())}toJSForTest(){return{createdAt:this.getCreatedAt().toTestString(),value:JSON.parse(this.toJSON()),type:"YORKIE_TREE"}}toJSInfoForTest(){var e=this;let t=this.indexTree.getRoot(),r=function(t){var n,i,s,o;let a,c,l,h=arguments.length>1&&void 0!==arguments[1]?arguments[1]:void 0,d=arguments.length>2&&void 0!==arguments[2]?arguments[2]:void 0,u=arguments.length>3&&void 0!==arguments[3]?arguments[3]:0,g=t.isText?{node:t,offset:0}:h&&d?e.toTreePos(h,d):null;g&&(a=e.indexTree.indexOf(g),c=e.indexTree.treePosToPath(g),l=tG.fromTreePos(g).toStruct());let f={type:t.type,parent:null==h?void 0:h.id.toTestString(),size:t.size,id:t.id.toTestString(),removedAt:null===(n=t.removedAt)||void 0===n?void 0:n.toTestString(),insPrev:null===(i=t.insPrevID)||void 0===i?void 0:i.toTestString(),insNext:null===(s=t.insNextID)||void 0===s?void 0:s.toTestString(),value:t.isText?t.value:void 0,isRemoved:t.isRemoved,children:[],depth:u,attributes:t.attrs?tc(null===(o=t.attrs)||void 0===o?void 0:o.toObject()):void 0,index:a,path:c,pos:l};for(let e=0;e0&&d===r[r.length-1].to?(r[r.length-1].to=u,r[r.length-1].toPath=this.toPath(h,a)):r.push({type:"content",from:d,to:u,fromPath:this.toPath(l,s),toPath:this.toPath(h,a),actor:t.getActorID()}))}return r.reverse()}findRightToken(e){let[t,r]=e;if(r===D.Start){let e=t.allChildren;return e.length>0?[e[0],e[0].isText?D.Text:D.Start]:[t,D.End]}let n=t.parent,i=n.allChildren,s=i.indexOf(t);if(n&&s===i.length-1)return[n,D.End];let o=i[s+1];return[o,o.isText?D.Text:D.Start]}findLeftToken(e){let[t,r]=e;if(r===D.End){let e=t.allChildren;if(e.length>0){let t=e[e.length-1];return[t,t.isText?D.Text:D.End]}return[t,D.Start]}let n=t.parent,i=n.allChildren,s=i.indexOf(t);if(n&&0===s)return[n,D.Start];let o=i[s-1];return[o,o.isText?D.Text:D.End]}constructor(e,t){super(t),this.indexTree=new tF(e),this.nodeMapByID=new tW(tH.createComparator()),this.indexTree.traverseAll(e=>{this.nodeMapByID.put(e.id,e)})}}class t$ extends tA{static create(e,t,r,n,i,s,o){return new t$(e,t,r,n,i,s,o)}execute(e){var t;let r=e.findByCreatedAt(this.getParentCreatedAt());if(!r)throw new ti(x.ErrInvalidArgument,"fail to find ".concat(this.getParentCreatedAt()));if(!(r instanceof tQ))throw new ti(x.ErrInvalidArgument,"fail to execute, only Tree can execute edit");let n=this.getExecutedAt(),[i,s]=r.edit([this.fromPos,this.toPos],null===(t=this.contents)||void 0===t?void 0:t.map(e=>e.deepcopy()),this.splitLevel,n,(()=>{let e=n.getDelimiter();return void 0!==this.contents&&(e+=this.contents.length),()=>td.of(n.getLamport(),++e,n.getActorID())})(),this.maxCreatedAtMapByActor);for(let t of s)e.registerGCPair(t);return{opInfos:i.map(t=>{let{from:r,to:n,value:i,splitLevel:s,fromPath:o,toPath:a}=t;return{type:"tree-edit",path:e.createPath(this.getParentCreatedAt()),from:r,to:n,value:i,splitLevel:s,fromPath:o,toPath:a}})}}getEffectedCreatedAt(){return this.getParentCreatedAt()}toTestString(){let e=this.getParentCreatedAt().toTestString(),t="".concat(this.fromPos.getLeftSiblingID().getCreatedAt().toTestString(),"/").concat(this.fromPos.getLeftSiblingID().getOffset()),r="".concat(this.toPos.getLeftSiblingID().getCreatedAt().toTestString(),"/").concat(this.toPos.getLeftSiblingID().getOffset()),n=this.contents||[];return"".concat(e,".EDIT(").concat(t,",").concat(r,",").concat(n.map(e=>tX(e)).join(""),")")}getFromPos(){return this.fromPos}getToPos(){return this.toPos}getContents(){return this.contents}getSplitLevel(){return this.splitLevel}getMaxCreatedAtMapByActor(){return this.maxCreatedAtMapByActor}constructor(e,t,r,n,i,s,o){super(e,o),this.fromPos=t,this.toPos=r,this.contents=n,this.splitLevel=i,this.maxCreatedAtMapByActor=s}}class t0{set(e,t){this.vector.set(e,t)}get(e){return this.vector.get(e)}maxLamport(){let e=BigInt(0);for(let[,t]of this)t>e&&(e=t);return e}max(e){let t=new Map;for(let[r,n]of e){let e=this.vector.get(r),i=e&&e>n?e:n;t.set(r,i)}for(let[r,n]of this){let i=e.get(r),s=i&&i>n?i:n;t.set(r,s)}return new t0(t)}afterOrEqual(e){let t=this.vector.get(e.getActorID());return void 0!==t&&t>=e.getLamport()}deepcopy(){let e=new Map;for(let[t,r]of this.vector)e.set(t,r);return new t0(e)}filter(e){let t=new Map;for(let[r]of e){let e=this.vector.get(r);void 0!==e&&t.set(r,e)}return new t0(t)}size(){return this.vector.size}*[Symbol.iterator](){for(let[e,t]of this.vector)yield[e,t]}constructor(e){this.vector=e||new Map}}let t1=new t0(new Map);class t2{static of(e,t,r,n,i){return new t2(e,t,r,n,i)}next(){let e=this.versionVector.deepcopy();return e.set(this.actor,this.lamport+1n),new t2(this.clientSeq+1,this.lamport+1n,this.actor,e)}syncClocks(e){let t=e.lamport>this.lamport?e.lamport+1n:this.lamport+1n,r=this.versionVector.max(e.versionVector),n=new t2(this.clientSeq,t,this.actor,r);return n.versionVector.set(this.actor,t),n}setClocks(e,t){let r=e>this.lamport?e:this.lamport+1n,n=this.versionVector.max(t);return n.set(this.actor,r),t2.of(this.clientSeq,r,this.actor,n)}createTimeTicket(e){return td.of(this.lamport,e,this.actor)}setActor(e){return new t2(this.clientSeq,this.lamport,e,this.versionVector,this.serverSeq)}setVersionVector(e){return new t2(this.clientSeq,this.lamport,this.actor,e,this.serverSeq)}getClientSeq(){return this.clientSeq}getServerSeq(){return this.serverSeq?this.serverSeq.toString():""}getLamport(){return this.lamport}getLamportAsString(){return this.lamport.toString()}getActorID(){return this.actor}getVersionVector(){return this.versionVector}toTestString(){return"".concat(this.lamport.toString(),":").concat(this.actor.slice(-2),":").concat(this.clientSeq)}constructor(e,t,r,n,i){this.clientSeq=e,this.serverSeq=i,this.lamport=t,this.versionVector=n,this.actor=r}}let t3=new t2(0,0n,th,t1);class t9{static create(e){let{id:t,operations:r,presenceChange:n,message:i}=e;return new t9({id:t,operations:r,presenceChange:n,message:i})}getID(){return this.id}getMessage(){return this.message}hasOperations(){return this.operations.length>0}getOperations(){return this.operations}setActor(e){for(let t of this.operations)t.setActor(e);this.id=this.id.setActor(e)}hasPresenceChange(){return void 0!==this.presenceChange}getPresenceChange(){return this.presenceChange}execute(e,t,r){let n=[],i=[];for(let t of this.operations){let s=t.execute(e,r);if(!s)continue;let{opInfos:o,reverseOp:a}=s;n.push(...o),a&&i.unshift(a)}return this.presenceChange&&(this.presenceChange.type===P.Put?t.set(this.id.getActorID(),ts(this.presenceChange.presence)):t.delete(this.id.getActorID())),{opInfos:n,reverseOps:i}}toTestString(){return"".concat(this.operations.map(e=>e.toTestString()).join(","))}toStruct(){return{changeID:rU.bytesToHex(rU.toChangeID(this.getID()).toBinary()),message:this.getMessage(),operations:this.getOperations().map(e=>rU.bytesToHex(rU.toOperation(e).toBinary())),presenceChange:this.getPresenceChange()}}static fromStruct(e){let{changeID:t,operations:r,presenceChange:n,message:i}=e;return t9.create({id:rU.bytesToChangeID(rU.hexToBytes(t)),operations:null==r?void 0:r.map(e=>rU.bytesToOperation(rU.hexToBytes(e))),presenceChange:n,message:i})}constructor({id:e,operations:t,presenceChange:r,message:n}){this.id=e,this.operations=t||[],this.presenceChange=r,this.message=n}}class t4{static create(e,t,r,n,i,s,o){return new t4(e,t,r,n,i,s,o)}getDocumentKey(){return this.documentKey}getCheckpoint(){return this.checkpoint}getIsRemoved(){return this.isRemoved}getChanges(){return this.changes}hasChanges(){return this.changes.length>0}getChangeSize(){return this.changes.length}hasSnapshot(){return!!this.snapshot&&!!this.snapshot.length}getSnapshot(){return this.snapshot}getMinSyncedTicket(){return this.minSyncedTicket}getVersionVector(){return this.versionVector}constructor(e,t,r,n,i,s,o){this.documentKey=e,this.checkpoint=t,this.isRemoved=r,this.changes=n,this.snapshot=s,this.minSyncedTicket=o,this.versionVector=i}}class t8{static of(e,t){return new t8(e,t)}increaseClientSeq(e){return 0===e?this:new t8(this.serverSeq,this.clientSeq+e)}forward(e){if(this.equals(e))return this;let t=this.serverSeq>e.serverSeq?this.serverSeq:e.serverSeq,r=Math.max(this.clientSeq,e.clientSeq);return t8.of(t,r)}getServerSeqAsString(){return this.serverSeq.toString()}getClientSeq(){return this.clientSeq}getServerSeq(){return this.serverSeq}equals(e){return this.clientSeq===e.clientSeq&&this.serverSeq==e.serverSeq}toTestString(){return"serverSeq=".concat(this.serverSeq,", clientSeq=").concat(this.clientSeq)}constructor(e,t){this.serverSeq=e,this.clientSeq=t}}let t5=new t8(0n,0);class t6{static of(e,t){return new t6(e,t)}static fromStruct(e){return t6.of(td.fromStruct(e.createdAt),e.offset)}getCreatedAt(){return this.createdAt}getOffset(){return this.offset}equals(e){return 0===this.createdAt.compare(e.createdAt)&&this.offset===e.offset}hasSameCreatedAt(e){return 0===this.createdAt.compare(e.createdAt)}split(e){return new t6(this.createdAt,this.offset+e)}toStruct(){return{createdAt:this.createdAt.toStruct(),offset:this.offset}}toTestString(){return"".concat(this.createdAt.toTestString(),":").concat(this.offset)}toIDString(){return"".concat(this.createdAt.toIDString(),":").concat(this.offset)}constructor(e,t){this.createdAt=e,this.offset=t}}let t7=t6.of(tu,0);class re{static of(e,t){return new re(e,t)}static fromStruct(e){let t=t6.fromStruct(e.id);return re.of(t,e.relativeOffset)}getID(){return this.id}getRelativeOffset(){return this.relativeOffset}getAbsoluteID(){return t6.of(this.id.getCreatedAt(),this.id.getOffset()+this.relativeOffset)}toTestString(){return"".concat(this.id.toTestString(),":").concat(this.relativeOffset)}toStruct(){return{id:this.id.toStruct(),relativeOffset:this.relativeOffset}}equals(e){return!!this.id.equals(e.id)&&this.relativeOffset===e.relativeOffset}constructor(e,t){this.id=e,this.relativeOffset=t}}class rt extends tT{static create(e,t){return new rt(e,t)}static createComparator(){return(e,t)=>{let r=e.getCreatedAt().compare(t.getCreatedAt());return 0!==r?r:e.getOffset()>t.getOffset()?1:e.getOffset()0&&t.getID().getOffset()==e.getOffset()){if(!t.hasInsPrev())return t;t=t.getInsPrev()}return t}findFloorNode(e){let t=this.treeByID.floorEntry(e);if(t&&(t.key.equals(e)||t.key.hasSameCreatedAt(e)))return t.value}findBetween(e,t){let r=[],n=e;for(;n&&n!==t;)r.push(n),n=n.getNext();return r}splitNode(e,t){if(t>e.getContentLength())throw new ti(x.ErrInvalidArgument,"offset should be less than or equal to length");if(0===t)return e;if(t===e.getContentLength())return e.getNext();let r=e.split(t);this.treeByIndex.updateWeight(r),this.insertAfter(e,r);let n=e.getInsNext();return n&&n.setInsPrev(r),r.setInsPrev(e),r}deleteNodes(e,t,r){if(!e.length)return[[],new Map,new Map];let[n,i]=this.filterNodes(e,t,r),s=new Map,o=new Map,a=this.makeChanges(i,t);for(let e of n){let r=e.getCreatedAt().getActorID();(!s.has(r)||e.getID().getCreatedAt().after(s.get(r)))&&s.set(r,e.getID().getCreatedAt()),o.set(e.getID().toIDString(),e),e.remove(t)}return this.deleteIndexNodes(i),[a,s,o]}filterNodes(e,t,r){let n=!!r,i=[],s=[],[o,a]=this.findEdgesOfCandidates(e);for(let a of(s.push(o),e)){let e=a.getCreatedAt().getActorID(),o=n?r.has(e)?r.get(e):tu:tg;a.canDelete(t,o)?i.push(a):s.push(a)}return s.push(a),[i,s]}findEdgesOfCandidates(e){return[e[0].getPrev(),e[e.length-1].getNext()]}makeChanges(e,t){let r,n;let i=[];for(let s=0;se<0?Math.ceil(e):Math.floor(e);(g=N||(N={}))[g.IntegerCnt=0]="IntegerCnt",g[g.LongCnt=1]="LongCnt";class ri extends tm{static create(e,t,r){return new ri(e,t,r)}static valueFromBytes(e,t){switch(e){case 0:return t[0]|t[1]<<8|t[2]<<16|t[3]<<24;case 1:return tI.Z.fromBytesLE(Array.from(t));default:throw new ti(x.ErrUnimplemented,"unimplemented type: ".concat(e))}}toJSON(){return"".concat(this.value)}toSortedJSON(){return this.toJSON()}toJSForTest(){return{createdAt:this.getCreatedAt().toTestString(),value:this.value,type:"YORKIE_COUNTER"}}deepcopy(){let e=ri.create(this.valueType,this.value,this.getCreatedAt());return e.setMovedAt(this.getMovedAt()),e}getType(){return this.valueType}static getCounterType(e){switch(typeof e){case"object":if(e instanceof tI.Z)return 1;return;case"number":if(e>2147483647||e<-2147483648)return 1;return 0;default:return}}static isSupport(e){return!!ri.getCounterType(e)}static isInteger(e){return e%1==0}isNumericType(){let e=this.valueType;return 0===e||1===e}getValueType(){return this.valueType}getValue(){return this.value}toBytes(){switch(this.valueType){case 0:{let e=this.value;return new Uint8Array([255&e,e>>8&255,e>>16&255,e>>24&255])}case 1:{let e=this.value.toBytesLE();return Uint8Array.from(e)}default:throw new ti(x.ErrUnimplemented,"unimplemented type: ".concat(this.valueType))}}increase(e){function t(e){if(!e.isNumericType())throw TypeError("Unsupported type of value: ".concat(typeof e.getValue()))}return t(this),t(e),1===this.valueType?this.value=this.value.add(e.getValue()):e.getType()===b.Long?this.value=this.value+e.getValue().toInt():this.value=tI.Z.fromNumber(this.value+rn(e.getValue())).toInt(),this}constructor(e,t,r){switch(super(r),this.valueType=e,e){case 0:"number"==typeof t?t>2147483647||t<-2147483648?this.value=tI.Z.fromNumber(t).toInt():this.value=rn(t):this.value=t.toInt();break;case 1:"number"==typeof t?this.value=tI.Z.fromNumber(t):this.value=t;break;default:throw new ti(x.ErrUnimplemented,"unimplemented type: ".concat(e))}}}class rs extends tA{static create(e,t,r){return new rs(e,t,r)}execute(e){let t=e.findByCreatedAt(this.getParentCreatedAt());if(!t)throw new ti(x.ErrInvalidArgument,"fail to find ".concat(this.getParentCreatedAt()));if(!(t instanceof ri))throw new ti(x.ErrInvalidArgument,"fail to execute, only Counter can execute increase");let r=this.value.deepcopy();return t.increase(r),{opInfos:[{type:"increase",path:e.createPath(this.getParentCreatedAt()),value:r.getValue()}],reverseOp:this.toReverseOperation()}}toReverseOperation(){let e=this.value.deepcopy(),t=e.getType()===b.Long?e.getValue().multiply(-1):-1*e.getValue();return rs.create(this.getParentCreatedAt(),tC.of(t,e.getCreatedAt()))}getEffectedCreatedAt(){return this.getParentCreatedAt()}toTestString(){return"".concat(this.getParentCreatedAt().toTestString(),".INCREASE.").concat(this.value.toJSON())}getValue(){return this.value}constructor(e,t,r){super(e,r),this.value=t}}class ro extends tA{static create(e,t,r,n,i,s){return new ro(e,t,r,n,i,[],s)}static createTreeRemoveStyleOperation(e,t,r,n,i,s){return new ro(e,t,r,n,new Map,i,s)}execute(e){let t,r;let n=e.findByCreatedAt(this.getParentCreatedAt());if(!n)throw new ti(x.ErrInvalidArgument,"fail to find ".concat(this.getParentCreatedAt()));if(!(n instanceof tQ))throw new ti(x.ErrInvalidArgument,"fail to execute, only Tree can execute edit");if(this.attributes.size){let e={};[...this.attributes].forEach(t=>{let[r,n]=t;return e[r]=n}),[,r,t]=n.style([this.fromPos,this.toPos],e,this.getExecutedAt(),this.maxCreatedAtMapByActor)}else{let e=this.attributesToRemove;[,r,t]=n.removeStyle([this.fromPos,this.toPos],e,this.getExecutedAt(),this.maxCreatedAtMapByActor)}for(let t of r)e.registerGCPair(t);return{opInfos:t.map(t=>{let{from:r,to:n,value:i,fromPath:s,toPath:o}=t;return{type:"tree-style",from:r,to:n,value:this.attributes.size?{attributes:i}:{attributesToRemove:i},fromPath:s,toPath:o,path:e.createPath(this.getParentCreatedAt())}})}}getEffectedCreatedAt(){return this.getParentCreatedAt()}toTestString(){let e=this.getParentCreatedAt().toTestString(),t="".concat(this.fromPos.getLeftSiblingID().getCreatedAt().toTestString(),":").concat(this.fromPos.getLeftSiblingID().getOffset()),r="".concat(this.toPos.getLeftSiblingID().getCreatedAt().toTestString(),":").concat(this.toPos.getLeftSiblingID().getOffset());return"".concat(e,".STYLE(").concat(t,",").concat(r,",").concat(Object.entries(this.attributes||{}).map(e=>{let[t,r]=e;return"".concat(t,':"').concat(r,'"')}).join(" "),")")}getFromPos(){return this.fromPos}getToPos(){return this.toPos}getAttributes(){return this.attributes}getAttributesToRemove(){return this.attributesToRemove}getMaxCreatedAtMapByActor(){return this.maxCreatedAtMapByActor}constructor(e,t,r,n,i,s,o){super(e,o),this.fromPos=t,this.toPos=r,this.maxCreatedAtMapByActor=n,this.attributes=i,this.attributesToRemove=s}}function ra(e){return new es({clientSeq:e.getClientSeq(),lamport:e.getLamport(),actorId:rV(e.getActorID()),versionVector:rl(e.getVersionVector())})}function rc(e){if(e)return new ej({lamport:e.getLamport(),delimiter:e.getDelimiter(),actorId:rV(e.getActorID())})}function rl(e){if(!e)return;let t=new eo;for(let[r,n]of e)t.vector[r]=BigInt(n.toString());return t}function rh(e){switch(e){case b.Null:return S.NULL;case b.Boolean:return S.BOOLEAN;case b.Integer:return S.INTEGER;case b.Long:return S.LONG;case b.Double:return S.DOUBLE;case b.String:return S.STRING;case b.Bytes:return S.BYTES;case b.Date:return S.DATE;default:throw new ti(x.ErrInvalidType,"unsupported type: ".concat(e))}}function rd(e){switch(e){case N.IntegerCnt:return S.INTEGER_CNT;case N.LongCnt:return S.LONG_CNT;default:throw new ti(x.ErrInvalidType,"unsupported type: ".concat(e))}}function ru(e){if(e instanceof tw)return new ew({type:S.JSON_OBJECT,createdAt:rc(e.getCreatedAt()),value:rK(e)});if(e instanceof tE)return new ew({type:S.JSON_ARRAY,createdAt:rc(e.getCreatedAt()),value:rv(e).toBinary()});if(e instanceof tJ)return new ew({type:S.TEXT,createdAt:rc(e.getCreatedAt())});if(e instanceof tC)return new ew({type:rh(e.getType()),createdAt:rc(e.getCreatedAt()),value:e.toBytes()});if(e instanceof ri)return new ew({type:rd(e.getType()),createdAt:rc(e.getCreatedAt()),value:e.toBytes()});if(e instanceof tQ)return new ew({type:S.TREE,createdAt:rc(e.getCreatedAt()),value:rw(e).toBinary()});throw new ti(x.ErrUnimplemented,"unimplemented element")}function rg(e){return new eU({createdAt:rc(e.getID().getCreatedAt()),offset:e.getID().getOffset(),relativeOffset:e.getRelativeOffset()})}function rf(e){return new eJ({parentId:rm(e.getParentID()),leftSiblingId:rm(e.getLeftSiblingID())})}function rm(e){return new eB({createdAt:rc(e.getCreatedAt()),offset:e.getOffset()})}function rp(e){let t=new ea;if(e instanceof tk){let r=new ec;r.parentCreatedAt=rc(e.getParentCreatedAt()),r.key=e.getKey(),r.value=ru(e.getValue()),r.executedAt=rc(e.getExecutedAt()),t.body.case="set",t.body.value=r}else if(e instanceof tD){let r=new el;r.parentCreatedAt=rc(e.getParentCreatedAt()),r.prevCreatedAt=rc(e.getPrevCreatedAt()),r.value=ru(e.getValue()),r.executedAt=rc(e.getExecutedAt()),t.body.case="add",t.body.value=r}else if(e instanceof tR){let r=new eh;r.parentCreatedAt=rc(e.getParentCreatedAt()),r.prevCreatedAt=rc(e.getPrevCreatedAt()),r.createdAt=rc(e.getCreatedAt()),r.executedAt=rc(e.getExecutedAt()),t.body.case="move",t.body.value=r}else if(e instanceof tb){let r=new ed;r.parentCreatedAt=rc(e.getParentCreatedAt()),r.createdAt=rc(e.getCreatedAt()),r.executedAt=rc(e.getExecutedAt()),t.body.case="remove",t.body.value=r}else if(e instanceof tL){let r=new eu;r.parentCreatedAt=rc(e.getParentCreatedAt()),r.from=rg(e.getFromPos()),r.to=rg(e.getToPos());let n=r.createdAtMapByActor;for(let[t,r]of e.getMaxCreatedAtMapByActor())n[t]=rc(r);r.content=e.getContent();let i=r.attributes;for(let[t,r]of e.getAttributes())i[t]=r;r.executedAt=rc(e.getExecutedAt()),t.body.case="edit",t.body.value=r}else if(e instanceof t_){let r=new ef;r.parentCreatedAt=rc(e.getParentCreatedAt()),r.from=rg(e.getFromPos()),r.to=rg(e.getToPos());let n=r.createdAtMapByActor;for(let[t,r]of e.getMaxCreatedAtMapByActor())n[t]=rc(r);let i=r.attributes;for(let[t,r]of e.getAttributes())i[t]=r;r.executedAt=rc(e.getExecutedAt()),t.body.case="style",t.body.value=r}else if(e instanceof rs){let r=new em;r.parentCreatedAt=rc(e.getParentCreatedAt()),r.value=ru(e.getValue()),r.executedAt=rc(e.getExecutedAt()),t.body.case="increase",t.body.value=r}else if(e instanceof t$){let r=new ep,n=r.createdAtMapByActor;for(let[t,r]of e.getMaxCreatedAtMapByActor())n[t]=rc(r);r.parentCreatedAt=rc(e.getParentCreatedAt()),r.from=rf(e.getFromPos()),r.to=rf(e.getToPos()),r.contents=function(e){let t=[];if(!e||!e.length)return t;for(let r of e)t.push(new eO({content:ry(r)}));return t}(e.getContents()),r.splitLevel=e.getSplitLevel(),r.executedAt=rc(e.getExecutedAt()),t.body.case="treeEdit",t.body.value=r}else if(e instanceof ro){let r=new ey;r.parentCreatedAt=rc(e.getParentCreatedAt()),r.from=rf(e.getFromPos()),r.to=rf(e.getToPos());let n=r.createdAtMapByActor;for(let[t,r]of e.getMaxCreatedAtMapByActor())n[t]=rc(r);let i=e.getAttributesToRemove();if(i.length>0)r.attributesToRemove=i;else{let t=r.attributes;for(let[r,n]of e.getAttributes())t[r]=n}r.executedAt=rc(e.getExecutedAt()),t.body.case="treeStyle",t.body.value=r}else throw new ti(x.ErrUnimplemented,"unimplemented operation");return t}function ry(e){if(!e)return[];let t=[];return tK(e,(e,r)=>{let n=new eN({id:rm(e.id),type:e.type,removedAt:rc(e.removedAt),depth:r});e.isText&&(n.value=e.value),e.insPrevID&&(n.insPrevId=rm(e.insPrevID)),e.insNextID&&(n.insNextId=rm(e.insNextID)),e.attrs&&(n.attributes=function(e){let t={};for(let r of e)t[r.getKey()]=new ek({value:r.getValue(),updatedAt:rc(r.getUpdatedAt()),isRemoved:r.isRemoved()});return t}(e.attrs)),t.push(n)}),t}function rv(e){let t=new eA;return t.body.case="jsonArray",t.body.value=new eS({nodes:function(e){let t=[];for(let r of e)t.push(new eb({element:rA(r.getValue())}));return t}(e.getElements()),createdAt:rc(e.getCreatedAt()),movedAt:rc(e.getMovedAt()),removedAt:rc(e.getRemovedAt())}),t}function rw(e){let t=new eA;return t.body.case="tree",t.body.value=new eP({nodes:ry(e.getRoot()),createdAt:rc(e.getCreatedAt()),movedAt:rc(e.getMovedAt()),removedAt:rc(e.getRemovedAt())}),t}function rA(e){if(e instanceof tw)return function(e){let t=new eA;return t.body.case="jsonObject",t.body.value=new eT({nodes:function(e){let t=[];for(let r of e)t.push(new eE({key:r.getStrKey(),element:rA(r.getValue())}));return t}(e.getRHT()),createdAt:rc(e.getCreatedAt()),movedAt:rc(e.getMovedAt()),removedAt:rc(e.getRemovedAt())}),t}(e);if(e instanceof tE)return rv(e);if(e instanceof tC)return function(e){let t=new eA;return t.body.case="primitive",t.body.value=new eI({type:rh(e.getType()),value:e.toBytes(),createdAt:rc(e.getCreatedAt()),movedAt:rc(e.getMovedAt()),removedAt:rc(e.getRemovedAt())}),t}(e);if(e instanceof tJ)return function(e){let t=new eA;return t.body.case="text",t.body.value=new eC({nodes:function(e){let t=[];for(let n of e){var r;let e=new eD;e.id=new eR({createdAt:rc((r=n.getID()).getCreatedAt()),offset:r.getOffset()}),e.value=n.getValue().getContent(),e.removedAt=rc(n.getRemovedAt());let i=e.attributes;for(let e of n.getValue().getAttrs()){let t=new ek;t.value=e.getValue(),t.updatedAt=rc(e.getUpdatedAt()),i[e.getKey()]=t}t.push(e)}return t}(e.getRGATreeSplit()),createdAt:rc(e.getCreatedAt()),movedAt:rc(e.getMovedAt()),removedAt:rc(e.getRemovedAt())}),t}(e);if(e instanceof ri)return function(e){let t=new eA;return t.body.case="counter",t.body.value=new ex({type:rd(e.getType()),value:e.toBytes(),createdAt:rc(e.getCreatedAt()),movedAt:rc(e.getMovedAt()),removedAt:rc(e.getRemovedAt())}),t}(e);if(e instanceof tQ)return rw(e);throw new ti(x.ErrUnimplemented,"unimplemented element")}function rT(e){for(let t of e.findDetails(tn.Qf))if(t.metadata.code)return t.metadata.code;return""}function rS(e){return t2.of(e.clientSeq,BigInt(e.lamport),rF(e.actorId),rI(e.versionVector),BigInt(e.serverSeq))}function rI(e){if(!e)return;let t=new t0;return Object.entries(e.vector).forEach(e=>{let[r,n]=e;t.set(r,BigInt(n.toString()))}),t}function rC(e){if(e)return td.of(BigInt(e.lamport),e.delimiter,rF(e.actorId))}function rx(e){let t={};return Object.entries(e.data).forEach(e=>{let[r,n]=e;t[r]=JSON.parse(n)}),t}function rP(e){switch(e){case S.NULL:return b.Null;case S.BOOLEAN:return b.Boolean;case S.INTEGER:return b.Integer;case S.LONG:return b.Long;case S.DOUBLE:return b.Double;case S.STRING:return b.String;case S.BYTES:return b.Bytes;case S.DATE:return b.Date}throw new ti(x.ErrUnimplemented,"unimplemented value type: ".concat(e))}function rE(e){switch(e){case S.INTEGER_CNT:return N.IntegerCnt;case S.LONG_CNT:return N.LongCnt}throw new ti(x.ErrUnimplemented,"unimplemented value type: ".concat(e))}function rb(e){switch(e.type){case S.JSON_OBJECT:if(!e.value)return tw.create(rC(e.createdAt));return rz(e.value);case S.JSON_ARRAY:if(!e.value)return tE.create(rC(e.createdAt));return function(e){if(!e)throw new ti(x.ErrInvalidArgument,"bytes is empty");return r_(eA.fromBinary(e).body.value)}(e.value);case S.TEXT:return tJ.create(rr.create(),rC(e.createdAt));case S.TREE:return function(e){if(!e)throw new ti(x.ErrInvalidArgument,"bytes is empty");return rM(eA.fromBinary(e).body.value)}(e.value);case S.NULL:case S.BOOLEAN:case S.INTEGER:case S.LONG:case S.DOUBLE:case S.STRING:case S.BYTES:case S.DATE:return tC.of(tC.valueFromBytes(rP(e.type),e.value),rC(e.createdAt));case S.INTEGER_CNT:case S.LONG_CNT:return ri.create(rE(e.type),ri.valueFromBytes(rE(e.type),e.value),rC(e.createdAt))}}function rk(e){return re.of(t6.of(rC(e.createdAt),e.offset),e.relativeOffset)}function rD(e){return t6.of(rC(e.createdAt),e.offset)}function rR(e){return tG.of(rN(e.parentId),rN(e.leftSiblingId))}function rN(e){return tH.of(rC(e.createdAt),e.offset)}function rO(e){if(0===e.length)return;let t=[];for(let r of e)t.push(function(e){let t=rN(e.id),r=tY.create(t,e.type),n=Object.entries(e.attributes);return r.isText?r.value=e.value:n.length&&(r.attrs=function(e){let t=tO.create();for(let[r,n]of Object.entries(e))t.setInternal(r,n.value,rC(n.updatedAt),n.isRemoved);return t}(e.attributes)),e.insPrevId&&(r.insPrevID=rN(e.insPrevId)),e.insNextId&&(r.insNextID=rN(e.insNextId)),r.removedAt=rC(e.removedAt),r}(r));let r=t[t.length-1],n=new Map;n.set(e[t.length-1].depth,t[t.length-1]);for(let r=t.length-2;r>=0;r--)n.get(e[r].depth-1).prepend(t[r]),n.set(e[r].depth,t[r]);return r.updateDescendantsSize(),tQ.create(r,tu).getRoot()}function rB(e){if("set"===e.body.case){let t=e.body.value;return tk.create(t.key,rb(t.value),rC(t.parentCreatedAt),rC(t.executedAt))}if("add"===e.body.case){let t=e.body.value;return tD.create(rC(t.parentCreatedAt),rC(t.prevCreatedAt),rb(t.value),rC(t.executedAt))}if("move"===e.body.case){let t=e.body.value;return tR.create(rC(t.parentCreatedAt),rC(t.prevCreatedAt),rC(t.createdAt),rC(t.executedAt))}if("remove"===e.body.case){let t=e.body.value;return tb.create(rC(t.parentCreatedAt),rC(t.createdAt),rC(t.executedAt))}if("edit"===e.body.case){let t=e.body.value,r=new Map;Object.entries(t.createdAtMapByActor).forEach(e=>{let[t,n]=e;r.set(t,rC(n))});let n=new Map;return Object.entries(t.attributes).forEach(e=>{let[t,r]=e;n.set(t,r)}),tL.create(rC(t.parentCreatedAt),rk(t.from),rk(t.to),r,t.content,n,rC(t.executedAt))}if("style"===e.body.case){let t=e.body.value,r=new Map;Object.entries(t.createdAtMapByActor).forEach(e=>{let[t,n]=e;r.set(t,rC(n))});let n=new Map;return Object.entries(t.attributes).forEach(e=>{let[t,r]=e;n.set(t,r)}),t_.create(rC(t.parentCreatedAt),rk(t.from),rk(t.to),r,n,rC(t.executedAt))}if("select"===e.body.case)return;else if("increase"===e.body.case){let t=e.body.value;return rs.create(rC(t.parentCreatedAt),rb(t.value),rC(t.executedAt))}else if("treeEdit"===e.body.case){let t=e.body.value,r=new Map;return Object.entries(t.createdAtMapByActor).forEach(e=>{let[t,n]=e;r.set(t,rC(n))}),t$.create(rC(t.parentCreatedAt),rR(t.from),rR(t.to),function(e){if(!e.length)return;let t=[];return e.forEach(e=>{let r=rO(e.content);t.push(r)}),t}(t.contents),t.splitLevel,r,rC(t.executedAt))}else if("treeStyle"===e.body.case){let t=e.body.value,r=new Map,n=t.attributesToRemove,i=new Map;return((null==t?void 0:t.createdAtMapByActor)&&Object.entries(t.createdAtMapByActor).forEach(e=>{let[t,r]=e;i.set(t,rC(r))}),(null==n?void 0:n.length)>0)?ro.createTreeRemoveStyleOperation(rC(t.parentCreatedAt),rR(t.from),rR(t.to),i,n,rC(t.executedAt)):(Object.entries(t.attributes).forEach(e=>{let[t,n]=e;r.set(t,n)}),ro.create(rC(t.parentCreatedAt),rR(t.from),rR(t.to),i,r,rC(t.executedAt)))}else throw new ti(x.ErrUnimplemented,"unimplemented operation")}function rJ(e){let t=[];for(let r of e)t.push(t9.create({id:rS(r.id),operations:function(e){let t=[];for(let r of e){let e=rB(r);e&&t.push(e)}return t}(r.operations),presenceChange:r.presenceChange?function(e){let t=e.type;if(t===C.PUT){let t=rx(e.presence);return{type:P.Put,presence:t}}if(t===C.CLEAR)return{type:P.Clear};throw new ti(x.ErrInvalidType,"unsupported type: ".concat(t))}(r.presenceChange):void 0,message:r.message}));return t}function rL(e){let t=new tv;for(let r of e.nodes){let e=rq(r.element);t.set(r.key,e,e.getPositionedAt())}let r=new tw(rC(e.createdAt),t);return r.setMovedAt(rC(e.movedAt)),r.setRemovedAt(rC(e.removedAt)),r}function r_(e){let t=new tP;for(let r of e.nodes)t.insert(rq(r.element));let r=new tE(rC(e.createdAt),t);return r.setMovedAt(rC(e.movedAt)),r.setRemovedAt(rC(e.removedAt)),r}function rM(e){let t=rO(e.nodes);return tQ.create(t,rC(e.createdAt))}function rq(e){if("jsonObject"===e.body.case)return rL(e.body.value);if("jsonArray"===e.body.case)return r_(e.body.value);if("primitive"===e.body.case)return function(e){let t=tC.of(tC.valueFromBytes(rP(e.type),e.value),rC(e.createdAt));return t.setMovedAt(rC(e.movedAt)),t.setRemovedAt(rC(e.removedAt)),t}(e.body.value);if("text"===e.body.case)return function(e){let t=new rr,r=t.getHead();for(let n of e.nodes){let e=t.insertAfter(r,function(e){let t=tB.create(e.value);Object.entries(e.attributes).forEach(e=>{let[r,n]=e;t.setAttr(r,n.value,rC(n.updatedAt))});let r=rt.create(rD(e.id),t);return r.remove(rC(e.removedAt)),r}(n));n.insPrevId&&e.setInsPrev(t.findNode(rD(n.insPrevId))),r=e}let n=new tJ(t,rC(e.createdAt));return n.setMovedAt(rC(e.movedAt)),n.setRemovedAt(rC(e.removedAt)),n}(e.body.value);if("counter"===e.body.case)return function(e){let t=ri.create(rE(e.type),ri.valueFromBytes(rE(e.type),e.value),rC(e.createdAt));return t.setMovedAt(rC(e.movedAt)),t.setRemovedAt(rC(e.removedAt)),t}(e.body.value);if("tree"===e.body.case)return rM(e.body.value);throw new ti(x.ErrUnimplemented,"unimplemented element")}function rz(e){if(!e)throw new ti(x.ErrInvalidArgument,"bytes is empty");return rL(eA.fromBinary(e).body.value)}function rK(e){return rA(e).toBinary()}function rF(e){return e?Array.from(e).map(e=>e.toString(16).padStart(2,"0")).join(""):""}function rV(e){return new Uint8Array(e.match(/.{1,2}/g).map(e=>parseInt(e,16)))}let rU={fromPresence:rx,toChangePack:function(e){var t;return new en({documentKey:e.getDocumentKey(),checkpoint:new eV({serverSeq:(t=e.getCheckpoint()).getServerSeq(),clientSeq:t.getClientSeq()}),isRemoved:e.getIsRemoved(),changes:function(e){let t=[];for(let r of e)t.push(function(e){let t=new ei({id:ra(e.getID()),message:e.getMessage()});return e.hasOperations()&&(t.operations=function(e){let t=[];for(let r of e)t.push(rp(r));return t}(e.getOperations())),e.hasPresenceChange()&&(t.presenceChange=function(e){if(e.type===P.Put)return new eK({type:C.PUT,presence:function(e){let t=new eF,r=t.data;for(let[t,n]of Object.entries(e))r[t]=JSON.stringify(n);return t}(e.presence)});if(e.type===P.Clear)return new eK({type:C.CLEAR});throw new ti(x.ErrUnimplemented,"unimplemented type")}(e.getPresenceChange())),t}(r));return t}(e.getChanges()),snapshot:e.getSnapshot(),versionVector:rl(e.getVersionVector()),minSyncedTicket:rc(e.getMinSyncedTicket())})},fromChangePack:function(e){var t;return t4.create(e.documentKey,(t=e.checkpoint,t8.of(BigInt(t.serverSeq),t.clientSeq)),e.isRemoved,rJ(e.changes),rI(e.versionVector),e.snapshot,rC(e.minSyncedTicket))},fromChanges:rJ,toTreeNodes:ry,fromTreeNodes:rO,objectToBytes:rK,bytesToObject:rz,bytesToSnapshot:function(e){if(!e)return{root:tw.create(tu),presences:new Map};let t=er.fromBinary(e);return{root:rq(t.root),presences:function(e){let t=new Map;return Object.entries(e).forEach(e=>{let[r,n]=e;t.set(r,rx(n))}),t}(t.presences)}},bytesToHex:rF,hexToBytes:rV,toHexString:function(e){return rF(e)},toUint8Array:function(e){return rV(e)},toOperation:rp,toChangeID:ra,PbChangeID:es,bytesToChangeID:function(e){return rS(es.fromBinary(e))},bytesToOperation:function(e){return rB(ea.fromBinary(e))},versionVectorToHex:function(e){return rF(rl(e).toBinary())},hexToVersionVector:function(e){let t=rV(e);return rI(eo.fromBinary(t))}};(f=O||(O={}))[f.Trivial=0]="Trivial",f[f.Debug=1]="Debug",f[f.Info=2]="Info",f[f.Warn=3]="Warn",f[f.Error=4]="Error",f[f.Fatal=5]="Fatal";let rj=3;function rW(e){rj=e}let rG={trivial:function(){for(var e=arguments.length,t=Array(e),r=0;r0||"undefined"==typeof console||console.log("YORKIE T:",...t)},debug:function(){for(var e=arguments.length,t=Array(e),r=0;r1||"undefined"==typeof console||console.log("YORKIE D:",...t)},info:function(){for(var e=arguments.length,t=Array(e),r=0;r2||"undefined"==typeof console||console.log("YORKIE I:",...t)},warn:function(){for(var e=arguments.length,t=Array(e),r=0;r3||"undefined"==typeof console||(void 0!==console.warn?console.warn("YORKIE W:",...t):console.log("YORKIE W:",...t))},error:function(){for(var e=arguments.length,t=Array(e),r=0;r4||"undefined"==typeof console||(void 0!==console.error?console.error("YORKIE E:",...t):console.log("YORKIE E:",...t))},fatal:function(){for(var e=arguments.length,t=Array(e),r=0;rrj<=e};function rH(){return"xxxxxxxx-xxxx-4xxxy-xxxx-xxxxxxxxxxx".replace(/[xy]/g,e=>{let t=16*Math.random()|0;return("x"===e?t:3&t|8).toString(16)})}class rY{changeSyncMode(e){this.syncMode=e}needRealtimeSync(){return this.syncMode!==M.RealtimeSyncOff&&(this.syncMode===M.RealtimePushOnly?this.doc.hasLocalChanges():this.syncMode!==M.Manual&&(this.doc.hasLocalChanges()||this.remoteChangeEventReceived))}async runWatchLoop(e){let t=async()=>{if(this.watchStream)return Promise.resolve();this.watchLoopTimerID&&(clearTimeout(this.watchLoopTimerID),this.watchLoopTimerID=void 0);try{[this.watchStream,this.watchAbortController]=await e(()=>{this.watchStream=void 0,this.watchAbortController=void 0,this.watchLoopTimerID=setTimeout(t,this.reconnectStreamDelay)})}catch(e){}};await t()}cancelWatchStream(){this.watchStream&&this.watchAbortController&&(this.watchAbortController.abort(),this.watchStream=void 0,this.watchAbortController=void 0),clearTimeout(this.watchLoopTimerID),this.watchLoopTimerID=void 0}constructor(e,t,r,n,i){this.reconnectStreamDelay=e,this.doc=t,this.docID=r,this.syncMode=n,this.remoteChangeEventReceived=!1,this.unsubscribeBroadcastEvent=i}}let rZ=()=>{};class rX{next(e){this.forEachObserver(t=>{t.next(e)})}error(e){this.forEachObserver(t=>{t.error(e)}),this.close(e)}complete(){this.forEachObserver(e=>{e.complete()}),this.close()}subscribe(e,t,r){let n;if(!e)throw new ti(x.ErrInvalidArgument,"missing observer");if(this.finalized)throw new ti(x.ErrRefused,"observable is finalized due to previous error");void 0===(n="object"==typeof e?e:{next:e,error:t,complete:r}).next&&(n.next=rZ),void 0===n.error&&(n.error=rZ),void 0===n.complete&&(n.complete=rZ);let i=rH(),s=this.unsubscribeOne.bind(this,i);if(this.observers.push({subscriptionID:i,observer:n}),this.finalized)try{this.finalError?n.error(this.finalError):n.complete()}catch(e){rG.warn(e)}return s}unsubscribeOne(e){var t;this.observers=null===(t=this.observers)||void 0===t?void 0:t.filter(t=>t.subscriptionID!==e)}forEachObserver(e){if(!this.finalized)for(let t=0;t0||void 0!==this.presenceChange}setPresenceChange(e){this.presenceChange=e}setReversePresence(e,t){for(let r of Object.keys(e))(null==t?void 0:t.addToHistory)?this.reversePresenceKeys.add(r):this.reversePresenceKeys.delete(r)}getReversePresence(){if(0===this.reversePresenceKeys.size)return;let e={};for(let t of this.reversePresenceKeys)e[t]=this.previousPresence[t];return e}issueTimeTicket(){return this.delimiter+=1,this.id.createTimeTicket(this.delimiter)}getLastTimeTicket(){return this.id.createTimeTicket(this.delimiter)}constructor(e,t,r,n){this.id=e,this.delimiter=0,this.root=t,this.operations=[],this.previousPresence=ts(r),this.presenceChange=void 0,this.reversePresenceKeys=new Set,this.message=n}}class r${static create(){return new r$(tw.create(tu))}findByCreatedAt(e){let t=this.elementPairMapByCreatedAt.get(e.toIDString());if(t)return t.element}findElementPairByCreatedAt(e){return this.elementPairMapByCreatedAt.get(e.toIDString())}createSubPaths(e){let t=this.elementPairMapByCreatedAt.get(e.toIDString());if(!t)return[];let r=[];for(;t.parent;){let e=t.element.getCreatedAt(),n=t.parent.subPathOf(e);if(void 0===n)throw new ti(x.ErrInvalidArgument,"cant find the given element: ".concat(e.toIDString()));r.unshift(n),t=this.elementPairMapByCreatedAt.get(t.parent.getCreatedAt().toIDString())}return r.unshift("$"),r}createPath(e){return this.createSubPaths(e).join(".")}registerElement(e,t){this.elementPairMapByCreatedAt.set(e.getCreatedAt().toIDString(),{parent:t,element:e}),e instanceof tp&&e.getDescendants((e,t)=>(this.registerElement(e,t),!1))}deregisterElement(e){let t=0,r=e=>{let r=e.getCreatedAt().toIDString();this.elementPairMapByCreatedAt.delete(r),this.gcElementSetByCreatedAt.delete(r),t++};return r(e),e instanceof tp&&e.getDescendants(e=>(r(e),!1)),t}registerRemovedElement(e){this.gcElementSetByCreatedAt.add(e.getCreatedAt().toIDString())}registerGCPair(e){if(this.gcPairMap.get(e.child.toIDString())){this.gcPairMap.delete(e.child.toIDString());return}this.gcPairMap.set(e.child.toIDString(),e)}getElementMapSize(){return this.elementPairMapByCreatedAt.size}getGarbageElementSetSize(){let e=new Set;for(let t of this.gcElementSetByCreatedAt){e.add(t);let r=this.elementPairMapByCreatedAt.get(t);r.element instanceof tp&&r.element.getDescendants(t=>(e.add(t.getCreatedAt().toIDString()),!1))}return e.size}getObject(){return this.rootObject}getGarbageLen(){return this.getGarbageElementSetSize()+this.gcPairMap.size}deepcopy(){return new r$(this.rootObject.deepcopy())}garbageCollect(e){let t=0;for(let r of this.gcElementSetByCreatedAt){let n=this.elementPairMapByCreatedAt.get(r),i=n.element.getRemovedAt();i&&(null==e?void 0:e.afterOrEqual(i))&&(n.parent.purge(n.element),t+=this.deregisterElement(n.element))}for(let[,r]of this.gcPairMap){let n=r.child.getRemovedAt();n&&(null==e?void 0:e.afterOrEqual(n))&&(r.parent.purge(r.child),this.gcPairMap.delete(r.child.toIDString()),t+=1)}return t}toJSON(){return this.rootObject.toJSON()}toSortedJSON(){return this.rootObject.toSortedJSON()}getStats(){return{elements:this.getElementMapSize(),gcPairs:this.gcPairMap.size,gcElements:this.getGarbageElementSetSize()}}constructor(e){this.rootObject=e,this.elementPairMapByCreatedAt=new Map,this.gcElementSetByCreatedAt=new Set,this.gcPairMap=new Map,this.registerElement(e,void 0),e.getDescendants(e=>{if(e.getRemovedAt()&&this.registerRemovedElement(e),e instanceof tJ||e instanceof tQ)for(let t of e.getGCPairs())this.registerGCPair(t);return!1})}}function r0(e,t){let r=new r1(e);return new Proxy(t,r.getHandlers())}class r1{static setInternal(e,t,r,n){if(r.includes("."))throw new ti(x.ErrInvalidObjectKey,"key must not contain the '.'.");let i=e.issueTimeTicket(),s=nt(e,n,i),o=t.set(r,s,i);e.registerElement(s,t),o&&e.registerRemovedElement(o),e.push(tk.create(r,s.deepcopy(),t.getCreatedAt(),i))}static buildObjectMembers(e,t){let r={};for(let[n,i]of Object.entries(t)){if(n.includes("."))throw new ti(x.ErrInvalidObjectKey,"key must not contain the '.'.");let t=e.issueTimeTicket(),s=nt(e,i,t);r[n]=s}return r}static deleteInternal(e,t,r){let n=e.issueTimeTicket(),i=t.deleteByKey(r,n);i&&(e.push(tb.create(t.getCreatedAt(),i.getCreatedAt(),n)),e.registerRemovedElement(i))}getHandlers(){return this.handlers}constructor(e){this.context=e,this.handlers={set:(t,r,n)=>(rG.isEnabled(O.Trivial)&&rG.trivial("obj[".concat(r,"]=").concat(JSON.stringify(n))),r1.setInternal(e,t,r,n),!0),get:(t,r)=>(rG.isEnabled(O.Trivial)&&rG.trivial("obj[".concat(r,"]")),"getID"===r)?()=>t.getCreatedAt():"toJSON"===r||"toString"===r?()=>t.toJSON():"toJS"===r?()=>t.toJS():"toJSForTest"===r?()=>t.toJSForTest():ne(e,t.get(r)),ownKeys:e=>e.getKeys(),getOwnPropertyDescriptor:()=>({enumerable:!0,configurable:!0}),deleteProperty:(t,r)=>(rG.isEnabled(O.Trivial)&&rG.trivial("obj[".concat(r,"]")),r1.deleteInternal(e,t,r),!0)}}}class r2{static*iteratorInternal(e,t){for(let r of t)yield r7(e,r)}static buildArrayElements(e,t){let r=[];for(let n of t){let t=e.issueTimeTicket(),i=nt(e,n,t);r.push(i)}return r}static pushInternal(e,t,r){return r2.insertAfterInternal(e,t,t.getLastCreatedAt(),r),t.length}static moveBeforeInternal(e,t,r,n){let i=e.issueTimeTicket(),s=t.getPrevCreatedAt(r);t.moveAfter(s,n,i),e.push(tR.create(t.getCreatedAt(),s,n,i))}static moveAfterInternal(e,t,r,n){let i=e.issueTimeTicket();t.moveAfter(r,n,i),e.push(tR.create(t.getCreatedAt(),r,n,i))}static moveFrontInternal(e,t,r){let n=e.issueTimeTicket(),i=t.getHead();t.moveAfter(i.getCreatedAt(),r,n),e.push(tR.create(t.getCreatedAt(),i.getCreatedAt(),r,n))}static moveLastInternal(e,t,r){let n=e.issueTimeTicket(),i=t.getLastCreatedAt();t.moveAfter(i,r,n),e.push(tR.create(t.getCreatedAt(),i,r,n))}static insertAfterInternal(e,t,r,n){let i=e.issueTimeTicket(),s=nt(e,n,i);return t.insertAfter(r,s),e.registerElement(s,t),e.push(tD.create(t.getCreatedAt(),r,s.deepcopy(),i)),s}static insertBeforeInternal(e,t,r,n){return r2.insertAfterInternal(e,t,t.getPrevCreatedAt(r),n)}static deleteInternalByIndex(e,t,r){let n=e.issueTimeTicket(),i=t.deleteByIndex(r,n);if(i)return e.push(tb.create(t.getCreatedAt(),i.getCreatedAt(),n)),e.registerRemovedElement(i),i}static deleteInternalByID(e,t,r){let n=e.issueTimeTicket(),i=t.delete(r,n);return e.push(tb.create(t.getCreatedAt(),i.getCreatedAt(),n)),e.registerRemovedElement(i),i}static splice(e,t,r,n){for(var i=arguments.length,s=Array(i>4?i-4:0),o=4;o=0?Math.min(r,a):Math.max(a+r,0),l=void 0===n?a:n<0?c:Math.min(c+n,a),h=[];for(let r=c;r=i)return!1;if(tC.isSupport(r))return Array.from(t).map(t=>ne(e,t)).includes(r,s);for(let e=s;e=i)return -1;if(tC.isSupport(r))return Array.from(t).map(t=>ne(e,t)).indexOf(r,s);for(let e=s;e=i?i-1:n<0?n+i:n;if(s<0)return -1;if(tC.isSupport(r))return Array.from(t).map(t=>ne(e,t)).lastIndexOf(r,s);for(let e=s;e>0;e--){var o;if((null===(o=t.get(e))||void 0===o?void 0:o.getID())===r.getID())return e}return -1}static toTestString(e){return e.toTestString()}getHandlers(){return this.handlers}constructor(e,t){this.context=e,this.array=t,this.handlers={get:(t,r,n)=>"getID"===r?()=>t.getCreatedAt():"getElementByID"===r?r=>{let n=t.getByID(r);if(!(!n||n.isRemoved()))return r7(e,n)}:"getElementByIndex"===r?r=>r7(e,t.get(r)):"getLast"===r?()=>r7(e,t.getLast()):"deleteByID"===r?r=>{let n=r2.deleteInternalByID(e,t,r);return r7(e,n)}:"insertAfter"===r?(r,n)=>{let i=r2.insertAfterInternal(e,t,r,n);return r7(e,i)}:"insertBefore"===r?(r,n)=>{let i=r2.insertBeforeInternal(e,t,r,n);return r7(e,i)}:"moveBefore"===r?(r,n)=>{r2.moveBeforeInternal(e,t,r,n)}:"moveAfter"===r?(r,n)=>{r2.moveAfterInternal(e,t,r,n)}:"moveFront"===r?r=>{r2.moveFrontInternal(e,t,r)}:"moveLast"===r?r=>{r2.moveLastInternal(e,t,r)}:("string"==typeof r||r instanceof String)&&!isNaN(r)?ne(e,t.get(Number(r))):"push"===r?r=>r2.pushInternal(e,t,r):"splice"===r?function(r,n){for(var i=arguments.length,s=Array(i>2?i-2:0),o=2;or2.includes(e,t,r,n):"indexOf"===r?(r,n)=>r2.indexOf(e,t,r,n):"lastIndexOf"===r?(r,n)=>r2.lastIndexOf(e,t,r,n):"toJSForTest"===r?()=>t.toJSForTest():"toTestString"===r?()=>r2.toTestString(t):"string"==typeof r&&["concat","entries","every","filter","find","findIndex","forEach","join","keys","map","reduce","reduceRight","slice","some","toLocaleString","toString","values"].includes(r)?function(){for(var n=arguments.length,i=Array(n),s=0;sne(e,t));return Array.prototype[r].apply(o,i)}:Reflect.get(t,r,n),deleteProperty:(t,r)=>(rG.isEnabled(O.Trivial)&&rG.trivial("array[".concat(r,"]")),r2.deleteInternalByIndex(e,t,Number.parseInt(r)),!0)}}}class r3{initialize(e,t){this.context=e,this.text=t}getID(){return this.text.getID()}edit(e,t,r,n){if(!this.context||!this.text)throw new ti(x.ErrNotInitialized,"Text is not initialized yet");if(e>t)throw new ti(x.ErrInvalidArgument,"from should be less than or equal to to");let i=this.text.indexRangeToPosRange(e,t);rG.isEnabled(O.Debug)&&rG.debug("EDIT: f:".concat(e,"->").concat(i[0].toTestString(),", t:").concat(t,"->").concat(i[1].toTestString()," c:").concat(r));let s=n?ta(n):void 0,o=this.context.issueTimeTicket(),[a,,c,l]=this.text.edit(i,r,o,s);for(let e of c)this.context.registerGCPair(e);return this.context.push(new tL(this.text.getCreatedAt(),i[0],i[1],a,r,s?new Map(Object.entries(s)):new Map,o)),this.text.findIndexesFromRange(l)}delete(e,t){return this.edit(e,t,"")}empty(){return this.edit(0,this.length,"")}setStyle(e,t,r){if(!this.context||!this.text)throw new ti(x.ErrNotInitialized,"Text is not initialized yet");if(e>t)throw new ti(x.ErrInvalidArgument,"from should be less than or equal to to");let n=this.text.indexRangeToPosRange(e,t);rG.isEnabled(O.Debug)&&rG.debug("STYL: f:".concat(e,"->").concat(n[0].toTestString(),", t:").concat(t,"->").concat(n[1].toTestString()," a:").concat(JSON.stringify(r)));let i=ta(r),s=this.context.issueTimeTicket(),[o,a]=this.text.setStyle(n,i,s);for(let e of a)this.context.registerGCPair(e);return this.context.push(new t_(this.text.getCreatedAt(),n[0],n[1],o,new Map(Object.entries(i)),s)),!0}indexRangeToPosRange(e){if(!this.context||!this.text)throw new ti(x.ErrNotInitialized,"Text is not initialized yet");let t=this.text.indexRangeToPosRange(e[0],e[1]);return[t[0].toStruct(),t[1].toStruct()]}posRangeToIndexRange(e){if(!this.context||!this.text)throw new ti(x.ErrNotInitialized,"Text is not initialized yet");let t=this.text.findIndexesFromRange([re.fromStruct(e[0]),re.fromStruct(e[1])]);return[t[0],t[1]]}toTestString(){if(!this.context||!this.text)throw new ti(x.ErrNotInitialized,"Text is not initialized yet");return this.text.toTestString()}values(){if(!this.context||!this.text)throw new ti(x.ErrNotInitialized,"Text is not initialized yet");return this.text.values()}get length(){return this.text.length}getTreeByIndex(){return this.text.getTreeByIndex()}getTreeByID(){return this.text.getTreeByID()}toString(){if(!this.context||!this.text)throw new ti(x.ErrNotInitialized,"Text is not initialized yet");return this.text.toString()}toJSON(){if(!this.context||!this.text)throw new ti(x.ErrNotInitialized,"Text is not initialized yet");return this.text.toJSON()}toJSForTest(){if(!this.context||!this.text)throw new ti(x.ErrNotInitialized,"Text is not initialized yet");return this.text.toJSForTest()}createRangeForTest(e,t){if(!this.context||!this.text)throw new ti(x.ErrNotInitialized,"Text is not initialized yet");return this.text.indexRangeToPosRange(e,t)}constructor(e,t){this.context=e,this.text=t}}class r9{initialize(e,t){this.valueType=t.getValueType(),this.context=e,this.counter=t,this.value=t.getValue()}getID(){return this.counter.getID()}getValue(){return this.value}getValueType(){return this.valueType}increase(e){if(!this.context||!this.counter)throw new ti(x.ErrNotInitialized,"Counter is not initialized yet");let t=this.context.issueTimeTicket(),r=tC.of(e,t);if(!r.isNumericType())throw TypeError("Unsupported type of value: ".concat(typeof r.getValue()));return this.counter.increase(r),this.context.push(rs.create(this.counter.getCreatedAt(),r,t)),this}toJSForTest(){if(!this.context||!this.counter)throw new ti(x.ErrNotInitialized,"Counter is not initialized yet");return this.counter.toJSForTest()}constructor(e,t){this.valueType=e,this.value=t}}function r4(e,t,r){let{type:n}=e,i=r.issueTimeTicket();if(n===tM){r8(e);let{value:r}=e,s=tY.create(tH.of(i,0),n,r);t.append(s)}else{let s;let{children:o=[]}=e,{attributes:a}=e;if("object"==typeof a&&!to(a)){let e=ta(a);for(let[t,r]of(s=new tO,Object.entries(e)))s.set(t,r,i)}let c=tY.create(tH.of(i,0),n,void 0,s);for(let e of(t.append(c),o))r4(e,c,r)}}function r8(e){if(!e.value.length)throw new ti(x.ErrInvalidArgument,"text node cannot have empty value");return!0}function r5(e){if(!e.length)return!0;if(e[0].type===tM)for(let t of e){let{type:e}=t;if(e!==tM)throw new ti(x.ErrInvalidArgument,"element node and text node cannot be passed together");r8(t)}else for(let t of e){let{type:e}=t;if(e===tM)throw new ti(x.ErrInvalidArgument,"element node and text node cannot be passed together")}return!0}class r6{initialize(e,t){this.context=e,this.tree=t}getID(){return this.tree.getID()}buildRoot(e){if(!this.initialRoot)return tY.create(tH.of(e.issueTimeTicket(),0),"root");let t=tY.create(tH.of(e.issueTimeTicket(),0),this.initialRoot.type);for(let r of this.initialRoot.children)r4(r,t,e);return t}getSize(){if(!this.context||!this.tree)throw new ti(x.ErrNotInitialized,"Tree is not initialized yet");return this.tree.getSize()}getNodeSize(){if(!this.context||!this.tree)throw new ti(x.ErrNotInitialized,"Tree is not initialized yet");return this.tree.getNodeSize()}getIndexTree(){if(!this.context||!this.tree)throw new ti(x.ErrNotInitialized,"Tree is not initialized yet");return this.tree.getIndexTree()}styleByPath(e,t){if(!this.context||!this.tree)throw new ti(x.ErrNotInitialized,"Tree is not initialized yet");if(!e.length)throw new ti(x.ErrInvalidArgument,"path should not be empty");let[r,n]=this.tree.pathToPosRange(e),i=this.context.issueTimeTicket(),s=t?ta(t):void 0,[o]=this.tree.style([r,n],s,i);this.context.push(ro.create(this.tree.getCreatedAt(),r,n,o,s?new Map(Object.entries(s)):new Map,i))}style(e,t,r){if(!this.context||!this.tree)throw new ti(x.ErrNotInitialized,"Tree is not initialized yet");if(e>t)throw new ti(x.ErrInvalidArgument,"from should be less than or equal to to");let n=this.tree.findPos(e),i=this.tree.findPos(t),s=this.context.issueTimeTicket(),o=r?ta(r):void 0,[a,c]=this.tree.style([n,i],o,s);for(let e of c)this.context.registerGCPair(e);this.context.push(ro.create(this.tree.getCreatedAt(),n,i,a,o?new Map(Object.entries(o)):new Map,s))}removeStyle(e,t,r){if(!this.context||!this.tree)throw new ti(x.ErrNotInitialized,"Tree is not initialized yet");if(e>t)throw new ti(x.ErrInvalidArgument,"from should be less than or equal to to");let n=this.tree.findPos(e),i=this.tree.findPos(t),s=this.context.issueTimeTicket(),[o,a]=this.tree.removeStyle([n,i],r,s);for(let e of a)this.context.registerGCPair(e);this.context.push(ro.createTreeRemoveStyleOperation(this.tree.getCreatedAt(),n,i,o,r,s))}editInternal(e,t,r){var n;let i=arguments.length>3&&void 0!==arguments[3]?arguments[3]:0;if(0!==r.length&&r[0]&&(r5(r),r[0].type!==tM))for(let e of r){let{children:t=[]}=e;r5(t)}let s=this.context.getLastTimeTicket(),o=[];if((null===(n=r[0])||void 0===n?void 0:n.type)===tM){let e="";for(let t of r){let{value:r}=t;e+=r}o.push(tY.create(tH.of(this.context.issueTimeTicket(),0),tM,e))}else o=r.map(e=>e&&function(e,t){let r;let{type:n}=t,i=e.issueTimeTicket();if(t.type===tM){let{value:e}=t;r=tY.create(tH.of(i,0),n,e)}else if(t){let s;let{children:o=[]}=t,{attributes:a}=t;if("object"==typeof a&&!to(a)){let e=ta(a);for(let[t,r]of(s=new tO,Object.entries(e)))s.set(t,r,i)}for(let t of(r=tY.create(tH.of(e.issueTimeTicket(),0),n,void 0,s),o))r4(t,r,e)}return r}(this.context,e)).filter(e=>e);let[,a,c]=this.tree.edit([e,t],o.length?o.map(e=>null==e?void 0:e.deepcopy()):void 0,i,s,()=>this.context.issueTimeTicket());for(let e of a)this.context.registerGCPair(e);return this.context.push(t$.create(this.tree.getCreatedAt(),e,t,o.length?o:void 0,i,c,s)),!0}editByPath(e,t,r){let n=arguments.length>3&&void 0!==arguments[3]?arguments[3]:0;if(!this.context||!this.tree)throw new ti(x.ErrNotInitialized,"Tree is not initialized yet");if(e.length!==t.length)throw new ti(x.ErrInvalidArgument,"path length should be equal");if(!e.length||!t.length)throw new ti(x.ErrInvalidArgument,"path should not be empty");let i=this.tree.pathToPos(e),s=this.tree.pathToPos(t);return this.editInternal(i,s,r?[r]:[],n)}editBulkByPath(e,t,r){let n=arguments.length>3&&void 0!==arguments[3]?arguments[3]:0;if(!this.context||!this.tree)throw new ti(x.ErrNotInitialized,"Tree is not initialized yet");if(e.length!==t.length)throw new ti(x.ErrInvalidArgument,"path length should be equal");if(!e.length||!t.length)throw new ti(x.ErrInvalidArgument,"path should not be empty");let i=this.tree.pathToPos(e),s=this.tree.pathToPos(t);return this.editInternal(i,s,r,n)}edit(e,t,r){let n=arguments.length>3&&void 0!==arguments[3]?arguments[3]:0;if(!this.context||!this.tree)throw new ti(x.ErrNotInitialized,"Tree is not initialized yet");if(e>t)throw new ti(x.ErrInvalidArgument,"from should be less than or equal to to");let i=this.tree.findPos(e),s=this.tree.findPos(t);return this.editInternal(i,s,r?[r]:[],n)}editBulk(e,t,r){let n=arguments.length>3&&void 0!==arguments[3]?arguments[3]:0;if(!this.context||!this.tree)throw new ti(x.ErrNotInitialized,"Tree is not initialized yet");if(e>t)throw new ti(x.ErrInvalidArgument,"from should be less than or equal to to");let i=this.tree.findPos(e),s=this.tree.findPos(t);return this.editInternal(i,s,r,n)}toXML(){if(!this.context||!this.tree)throw new ti(x.ErrNotInitialized,"Tree is not initialized yet");return this.tree.toXML()}toJSON(){if(!this.context||!this.tree)throw new ti(x.ErrNotInitialized,"Tree is not initialized yet");return this.tree.toJSON()}toJSForTest(){if(!this.context||!this.tree)throw new ti(x.ErrNotInitialized,"Tree is not initialized yet");return this.tree.toJSForTest()}toJSInfoForTest(){if(!this.context||!this.tree)throw new ti(x.ErrNotInitialized,"Tree is not initialized yet");return this.tree.toJSInfoForTest()}getRootTreeNode(){if(!this.context||!this.tree)throw new ti(x.ErrNotInitialized,"Tree is not initialized yet");return this.tree.getRootTreeNode()}indexToPath(e){if(!this.context||!this.tree)throw new ti(x.ErrNotInitialized,"Tree is not initialized yet");return this.tree.indexToPath(e)}pathToIndex(e){if(!this.context||!this.tree)throw new ti(x.ErrNotInitialized,"Tree is not initialized yet");return this.tree.pathToIndex(e)}pathRangeToPosRange(e){if(!this.context||!this.tree)throw new ti(x.ErrNotInitialized,"Tree is not initialized yet");let t=[this.tree.pathToIndex(e[0]),this.tree.pathToIndex(e[1])],r=this.tree.indexRangeToPosRange(t);return[r[0].toStruct(),r[1].toStruct()]}indexRangeToPosRange(e){if(!this.context||!this.tree)throw new ti(x.ErrNotInitialized,"Tree is not initialized yet");return this.tree.indexRangeToPosStructRange(e)}posRangeToIndexRange(e){if(!this.context||!this.tree)throw new ti(x.ErrNotInitialized,"Tree is not initialized yet");let t=[tG.fromStruct(e[0]),tG.fromStruct(e[1])];return this.tree.posRangeToIndexRange(t)}posRangeToPathRange(e){if(!this.context||!this.tree)throw new ti(x.ErrNotInitialized,"Tree is not initialized yet");let t=[tG.fromStruct(e[0]),tG.fromStruct(e[1])];return this.tree.posRangeToPathRange(t)}constructor(e){this.initialRoot=e}}function r7(e,t){if(t){if(t instanceof tC)return t;if(t instanceof tw)return r0(e,t);if(t instanceof tE)return function(e,t){let r=new r2(e,t);return new Proxy(t,r.getHandlers())}(e,t);if(t instanceof tJ)return new r3(e,t);else if(t instanceof ri){let r=new r9(N.IntegerCnt,0);return r.initialize(e,t),r}else if(t instanceof tQ){let r=new r6;return r.initialize(e,t),r}throw TypeError("Unsupported type of element: ".concat(typeof t))}}function ne(e,t){let r=r7(e,t);return r instanceof tC?r.getValue():r}function nt(e,t,r){let n;if(tC.isSupport(t))n=tC.of(t,r);else if(Array.isArray(t))n=tE.create(r,r2.buildArrayElements(e,t));else if("object"==typeof t)t instanceof r3?(n=tJ.create(rr.create(),r),t.initialize(e,n)):t instanceof r9?(n=ri.create(t.getValueType(),t.getValue(),r),t.initialize(e,n)):t instanceof r6?(n=tQ.create(t.buildRoot(e),r),t.initialize(e,n)):n=tw.create(r,r1.buildObjectMembers(e,t));else throw TypeError("Unsupported type of value: ".concat(typeof t));return n}class nr{hasUndo(){return this.undoStack.length>0}hasRedo(){return this.redoStack.length>0}pushUndo(e){this.undoStack.length>=50&&this.undoStack.shift(),this.undoStack.push(e)}popUndo(){return this.undoStack.pop()}pushRedo(e){this.redoStack.length>=50&&this.redoStack.shift(),this.redoStack.push(e)}popRedo(){return this.redoStack.pop()}clearRedo(){this.redoStack=[]}getUndoStackForTest(){return this.undoStack}getRedoStackForTest(){return this.redoStack}constructor(){this.undoStack=[],this.redoStack=[]}}let nn="disconnected",ni=new Map,ns=new Map;function no(e,t){((null==t?void 0:t.force)||"disconnected"!==nn)&&window.postMessage({source:"yorkie-devtools-sdk",...e},"*")}window.transactionEventsByDocKey=ns,(m=B||(B={})).Detached="detached",m.Attached="attached",m.Removed="removed",(p=J||(J={})).StatusChanged="status-changed",p.ConnectionChanged="connection-changed",p.SyncStatusChanged="sync-status-changed",p.Snapshot="snapshot",p.LocalChange="local-change",p.RemoteChange="remote-change",p.Initialized="initialized",p.Watched="watched",p.Unwatched="unwatched",p.PresenceChanged="presence-changed",p.Broadcast="broadcast",p.LocalBroadcast="local-broadcast",(y=L||(L={})).Connected="connected",y.Disconnected="disconnected",(v=_||(_={})).Synced="synced",v.SyncFailed="sync-failed";class na{update(e,t){if("removed"===this.getStatus())throw new ti(x.ErrDocumentRemoved,"".concat(this.key," is removed"));this.ensureClone();let r=this.changeID.getActorID(),n=rQ.create(this.changeID.next(),this.clone.root,this.clone.presences.get(r)||{},t);try{var i;let t=(i=this.clone.root.getObject(),r0(n,i));this.presences.has(r)||this.clone.presences.set(r,{}),this.isUpdating=!0,e(t,new tl(n,this.clone.presences.get(r)))}catch(e){throw this.clone=void 0,e}finally{this.isUpdating=!1}if(n.hasChange()){rG.isEnabled(O.Trivial)&&rG.trivial("trying to update a local change: ".concat(this.toJSON()));let e=n.getChange(),{opInfos:t,reverseOps:i}=e.execute(this.root,this.presences,E.Local),s=n.getReversePresence();s&&i.push({type:"presence",value:s}),this.localChanges.push(e),i.length>0&&this.internalHistory.pushUndo(i),t.length>0&&this.internalHistory.clearRedo(),this.changeID=e.getID();let o=[];t.length>0&&o.push({type:"local-change",source:E.Local,value:{message:e.getMessage()||"",operations:t,actor:r,clientSeq:e.getID().getClientSeq(),serverSeq:e.getID().getServerSeq()},rawChange:this.isEnableDevtools()?e.toStruct():void 0}),e.hasPresenceChange()&&o.push({type:"presence-changed",source:E.Local,value:{clientID:r,presence:this.getPresence(r)}}),this.publish(o),rG.isEnabled(O.Trivial)&&rG.trivial("after update a local change: ".concat(this.toJSON()))}}subscribe(e,t,r,n){if("string"==typeof e){if("function"!=typeof t)throw new ti(x.ErrInvalidArgument,"Second argument must be a callback function");return"presence"===e?this.eventStream.subscribe(e=>{for(let r of e)("initialized"===r.type||"watched"===r.type||"unwatched"===r.type||"presence-changed"===r.type)&&t(r)},r,n):"my-presence"===e?this.eventStream.subscribe(e=>{for(let r of e)("initialized"===r.type||"presence-changed"===r.type)&&("presence-changed"!==r.type||r.value.clientID===this.changeID.getActorID())&&t(r)},r,n):"others"===e?this.eventStream.subscribe(e=>{for(let r of e)("watched"===r.type||"unwatched"===r.type||"presence-changed"===r.type)&&r.value.clientID!==this.changeID.getActorID()&&t(r)},r,n):"connection"===e?this.eventStream.subscribe(e=>{for(let r of e)"connection-changed"===r.type&&t(r)},r,n):"status"===e?this.eventStream.subscribe(e=>{for(let r of e)"status-changed"===r.type&&t(r)},r,n):"sync"===e?this.eventStream.subscribe(e=>{for(let r of e)"sync-status-changed"===r.type&&t(r)},r,n):"local-broadcast"===e?this.eventStream.subscribe(e=>{for(let r of e)"local-broadcast"===r.type&&t(r)},r):"broadcast"===e?this.eventStream.subscribe(e=>{for(let r of e)"broadcast"===r.type&&t(r)},r):"all"===e?this.eventStream.subscribe(t,r,n):this.eventStream.subscribe(r=>{for(let n of r){if("local-change"!==n.type&&"remote-change"!==n.type)continue;let r=[];for(let t of n.value.operations)this.isSameElementOrChildOf(t.path,e)&&r.push(t);r.length&&t({...n,value:{...n.value,operations:r}})}},r,n)}if("function"==typeof e)return this.eventStream.subscribe(t=>{for(let r of t)("snapshot"===r.type||"local-change"===r.type||"remote-change"===r.type)&&e(r)},t,r);throw new ti(x.ErrInvalidArgument,'"'.concat(e,'" is not a valid'))}publish(e){this.eventStreamObserver&&this.eventStreamObserver.next(e)}isSameElementOrChildOf(e,t){if(t===e)return!0;let r=e.split(".");return t.split(".").every((e,t)=>e===r[t])}applyChangePack(e){let t=e.hasSnapshot();for(t?this.applySnapshot(e.getCheckpoint().getServerSeq(),e.getVersionVector(),e.getSnapshot()):e.hasChanges()&&this.applyChanges(e.getChanges(),E.Remote);this.localChanges.length&&!(this.localChanges[0].getID().getClientSeq()>e.getCheckpoint().getClientSeq());)this.localChanges.shift();t&&this.applyChanges(this.localChanges,E.Remote),this.checkpoint=this.checkpoint.forward(e.getCheckpoint()),t||this.garbageCollect(e.getVersionVector()),t||this.filterVersionVector(e.getVersionVector()),e.getIsRemoved()&&this.applyStatus("removed"),rG.isEnabled(O.Trivial)&&rG.trivial("".concat(this.root.toJSON()))}getCheckpoint(){return this.checkpoint}getChangeID(){return this.changeID}hasLocalChanges(){return this.localChanges.length>0}ensureClone(){this.clone||(this.clone={root:this.root.deepcopy(),presences:ts(this.presences)})}createChangePack(){let e=Array.from(this.localChanges),t=this.checkpoint.increaseClientSeq(e.length);return t4.create(this.key,t,!1,e,this.getVersionVector())}setActor(e){for(let t of this.localChanges)t.setActor(e);this.changeID=this.changeID.setActor(e)}isEnableDevtools(){return!!this.opts.enableDevtools}getKey(){return this.key}getStatus(){return this.status}getCloneRoot(){if(this.clone)return this.clone.root.getObject()}getRoot(){return this.ensureClone(),r0(rQ.create(this.changeID.next(),this.clone.root,this.clone.presences.get(this.changeID.getActorID())||{}),this.clone.root.getObject())}garbageCollect(e){return this.opts.disableGC?0:(this.clone&&this.clone.root.garbageCollect(e),this.root.garbageCollect(e))}getRootObject(){return this.root.getObject()}getGarbageLen(){return this.root.getGarbageLen()}getGarbageLenFromClone(){return this.clone.root.getGarbageLen()}toJSON(){return this.root.toJSON()}toSortedJSON(){return this.root.toSortedJSON()}getStats(){return this.root.getStats()}toJSForTest(){return{...this.getRoot().toJSForTest(),key:"root"}}applySnapshot(e,t,r){let{root:n,presences:i}=rU.bytesToSnapshot(r);this.root=new r$(n),this.presences=i,this.changeID=this.changeID.setClocks(e,t),this.clone=void 0,this.publish([{type:"snapshot",source:E.Remote,value:{serverSeq:e.toString(),snapshot:this.isEnableDevtools()?rU.bytesToHex(r):void 0,snapshotVector:rU.versionVectorToHex(t)}}])}applyChanges(e,t){for(let r of(rG.isEnabled(O.Debug)&&rG.debug("trying to apply ".concat(e.length," remote changes.")+"elements:".concat(this.root.getElementMapSize(),", ")+"removeds:".concat(this.root.getGarbageElementSetSize())),rG.isEnabled(O.Trivial)&&rG.trivial(e.map(e=>"".concat(e.getID().toTestString()," ").concat(e.toTestString())).join("\n")),e))this.applyChange(r,t);rG.isEnabled(O.Debug)&&rG.debug("after appling ".concat(e.length," remote changes.")+"elements:".concat(this.root.getElementMapSize(),", ")+" removeds:".concat(this.root.getGarbageElementSetSize()))}applyChange(e,t){this.ensureClone(),e.execute(this.clone.root,this.clone.presences,t);let r=[],n=e.getID().getActorID();if(e.hasPresenceChange()&&this.onlineClients.has(n)){let i=e.getPresenceChange();switch(i.type){case P.Put:r.push(this.presences.has(n)?{type:"presence-changed",source:t,value:{clientID:n,presence:i.presence}}:{type:"watched",source:E.Remote,value:{clientID:n,presence:i.presence}});break;case P.Clear:r.push({type:"unwatched",source:E.Remote,value:{clientID:n,presence:this.getPresence(n)}}),this.removeOnlineClient(n)}}let{opInfos:i}=e.execute(this.root,this.presences,t);if(this.changeID=this.changeID.syncClocks(e.getID()),i.length>0){let s=this.isEnableDevtools()?e.toStruct():void 0;r.push(t===E.Remote?{type:"remote-change",source:t,value:{actor:n,clientSeq:e.getID().getClientSeq(),serverSeq:e.getID().getServerSeq(),message:e.getMessage()||"",operations:i},rawChange:s}:{type:"local-change",source:t,value:{actor:n,clientSeq:e.getID().getClientSeq(),serverSeq:e.getID().getServerSeq(),message:e.getMessage()||"",operations:i},rawChange:s})}r.length>0&&this.publish(r)}applyWatchStream(e){if("initialization"===e.body.case){let t=e.body.value.clientIds,r=new Set;for(let e of t)e!==this.changeID.getActorID()&&r.add(e);this.setOnlineClients(r),this.publish([{type:"initialized",source:E.Local,value:this.getPresences()}]);return}if("event"===e.body.case){let{type:t,publisher:r}=e.body.value,n=[];if(t===I.DOCUMENT_WATCHED){if(this.onlineClients.has(r)&&this.hasPresence(r))return;this.addOnlineClient(r),this.hasPresence(r)&&n.push({type:"watched",source:E.Remote,value:{clientID:r,presence:this.getPresence(r)}})}else if(t===I.DOCUMENT_UNWATCHED){let e=this.getPresence(r);this.removeOnlineClient(r),e&&n.push({type:"unwatched",source:E.Remote,value:{clientID:r,presence:e}})}else if(t===I.DOCUMENT_BROADCAST&&e.body.value.body){let{topic:t,payload:i}=e.body.value.body,s=new TextDecoder;n.push({type:"broadcast",value:{clientID:r,topic:t,payload:JSON.parse(s.decode(i))}})}n.length>0&&this.publish(n)}}applyStatus(e){this.status=e,"detached"===e&&this.setActor(th),this.publish([{source:"removed"===e?E.Remote:E.Local,type:"status-changed",value:"attached"===e?{status:e,actorID:this.changeID.getActorID()}:{status:e}}])}applyDocEvent(e){if("status-changed"===e.type){this.applyStatus(e.value.status),"attached"===e.value.status&&this.setActor(e.value.actorID);return}if("snapshot"===e.type){let{snapshot:t,serverSeq:r,snapshotVector:n}=e.value;if(!t)return;this.applySnapshot(BigInt(r),rU.hexToVersionVector(n),rU.hexToBytes(t));return}if("local-change"===e.type||"remote-change"===e.type){if(!e.rawChange)return;let t=t9.fromStruct(e.rawChange);this.applyChange(t,e.source)}if("initialized"===e.type){let t=new Set;for(let{clientID:r,presence:n}of e.value)t.add(r),this.presences.set(r,n);this.setOnlineClients(t);return}if("watched"===e.type){let{clientID:t,presence:r}=e.value;this.addOnlineClient(t),this.presences.set(t,r);return}if("unwatched"===e.type){let{clientID:t}=e.value;this.removeOnlineClient(t),this.presences.delete(t)}if("presence-changed"===e.type){let{clientID:t,presence:r}=e.value;this.presences.set(t,r)}}applyTransactionEvent(e){for(let t of e)this.applyDocEvent(t)}getValueByPath(e){if(!e.startsWith("$"))throw new ti(x.ErrInvalidArgument,'path must start with "$"');let t=e.split(".");t.shift();let r=this.getRoot();for(let e of t)if(void 0===(r=r[e]))return;return r}setOnlineClients(e){this.onlineClients=e}resetOnlineClients(){this.onlineClients=new Set}addOnlineClient(e){this.onlineClients.add(e)}removeOnlineClient(e){this.onlineClients.delete(e)}hasPresence(e){return this.presences.has(e)}getMyPresence(){if("attached"!==this.status)return{};let e=this.presences.get(this.changeID.getActorID());return e?ts(e):{}}getPresence(e){if(e===this.changeID.getActorID())return this.getMyPresence();if(!this.onlineClients.has(e))return;let t=this.presences.get(e);return t?ts(t):void 0}getPresenceForTest(e){let t=this.presences.get(e);return t?ts(t):void 0}getPresences(){let e=[];for(let t of(e.push({clientID:this.changeID.getActorID(),presence:ts(this.getMyPresence())}),this.onlineClients))this.presences.has(t)&&e.push({clientID:t,presence:ts(this.presences.get(t))});return e}getSelfForTest(){return{clientID:this.getChangeID().getActorID(),presence:this.getMyPresence()}}getOthersForTest(){let e=this.getChangeID().getActorID();return this.getPresences().filter(t=>t.clientID!==e).sort((e,t)=>e.clientID>t.clientID?1:-1)}canUndo(){return this.internalHistory.hasUndo()&&!this.isUpdating}filterVersionVector(e){let t=this.changeID.getVersionVector().filter(e);this.changeID=this.changeID.setVersionVector(t)}canRedo(){return this.internalHistory.hasRedo()&&!this.isUpdating}undo(){if(this.isUpdating)throw new ti(x.ErrRefused,"Undo is not allowed during an update");let e=this.internalHistory.popUndo();if(void 0===e)throw new ti(x.ErrRefused,"There is no operation to be undone");this.ensureClone();let t=rQ.create(this.changeID.next(),this.clone.root,this.clone.presences.get(this.changeID.getActorID())||{});for(let r of e){if(!(r instanceof tA)){new tl(t,ts(this.clone.presences.get(this.changeID.getActorID()))).set(r.value,{addToHistory:!0});continue}let e=t.issueTimeTicket();r.setExecutedAt(e),t.push(r)}let r=t.getChange();r.execute(this.clone.root,this.clone.presences,E.UndoRedo);let{opInfos:n,reverseOps:i}=r.execute(this.root,this.presences,E.UndoRedo),s=t.getReversePresence();if(s&&i.push({type:"presence",value:s}),i.length>0&&this.internalHistory.pushRedo(i),!r.hasPresenceChange()&&0===n.length)return;this.localChanges.push(r),this.changeID=r.getID();let o=this.changeID.getActorID(),a=[];n.length>0&&a.push({type:"local-change",source:E.UndoRedo,value:{message:r.getMessage()||"",operations:n,actor:o,clientSeq:r.getID().getClientSeq(),serverSeq:r.getID().getServerSeq()},rawChange:this.isEnableDevtools()?r.toStruct():void 0}),r.hasPresenceChange()&&a.push({type:"presence-changed",source:E.UndoRedo,value:{clientID:o,presence:this.getPresence(o)}}),this.publish(a)}redo(){if(this.isUpdating)throw new ti(x.ErrRefused,"Redo is not allowed during an update");let e=this.internalHistory.popRedo();if(void 0===e)throw new ti(x.ErrRefused,"There is no operation to be redone");this.ensureClone();let t=rQ.create(this.changeID.next(),this.clone.root,this.clone.presences.get(this.changeID.getActorID())||{});for(let r of e){if(!(r instanceof tA)){new tl(t,ts(this.clone.presences.get(this.changeID.getActorID()))).set(r.value,{addToHistory:!0});continue}let e=t.issueTimeTicket();r.setExecutedAt(e),t.push(r)}let r=t.getChange();r.execute(this.clone.root,this.clone.presences,E.UndoRedo);let{opInfos:n,reverseOps:i}=r.execute(this.root,this.presences,E.UndoRedo),s=t.getReversePresence();if(s&&i.push({type:"presence",value:s}),i.length>0&&this.internalHistory.pushUndo(i),!r.hasPresenceChange()&&0===n.length)return;this.localChanges.push(r),this.changeID=r.getID();let o=this.changeID.getActorID(),a=[];n.length>0&&a.push({type:"local-change",source:E.UndoRedo,value:{message:r.getMessage()||"",operations:n,actor:o,clientSeq:r.getID().getClientSeq(),serverSeq:r.getID().getServerSeq()},rawChange:this.isEnableDevtools()?r.toStruct():void 0}),r.hasPresenceChange()&&a.push({type:"presence-changed",source:E.UndoRedo,value:{clientID:o,presence:this.getPresence(o)}}),this.publish(a)}getUndoStackForTest(){return this.internalHistory.getUndoStackForTest()}getRedoStackForTest(){return this.internalHistory.getRedoStackForTest()}broadcast(e,t,r){this.publish([{type:"local-broadcast",value:{topic:e,payload:t},options:r}])}getVersionVector(){return this.changeID.getVersionVector()}constructor(e,t){this.opts=t||{},this.key=e,this.status="detached",this.root=r$.create(),this.changeID=t3,this.checkpoint=t5,this.localChanges=[],this.eventStream=function(e){let t=new rX(e);return{subscribe:t.subscribe.bind(t),getProxy:()=>t}}(e=>{this.eventStreamObserver=e}),this.onlineClients=new Set,this.presences=new Map,this.isUpdating=!1,this.internalHistory=new nr,this.history={canUndo:this.canUndo.bind(this),canRedo:this.canRedo.bind(this),undo:this.undo.bind(this),redo:this.redo.bind(this)},function(e){if(!e.isEnableDevtools()||ni.has(e.getKey()))return;ns.set(e.getKey(),[]);let t=e.subscribe("all",t=>{t.some(e=>e.type!==J.StatusChanged&&e.type!==J.Snapshot&&e.type!==J.LocalChange&&e.type!==J.RemoteChange&&e.type!==J.Initialized&&e.type!==J.Watched&&e.type!==J.Unwatched&&e.type!==J.PresenceChanged)||(ns.get(e.getKey()).push(t),"synced"===nn&&no({msg:"doc::sync::partial",docKey:e.getKey(),event:t}))});ni.set(e.getKey(),[t]),no({msg:"refresh-devtools"},{force:!0}),window.addEventListener("message",t=>{var r;if((null===(r=t.data)||void 0===r?void 0:r.source)==="yorkie-devtools-panel")switch(t.data.msg){case"devtools::connect":if("disconnected"!==nn)break;nn="connected",no({msg:"doc::available",docKey:e.getKey()}),rG.info("[YD] Devtools connected. Doc: ".concat(e.getKey()));break;case"devtools::disconnect":nn="disconnected",rG.info("[YD] Devtools disconnected. Doc: ".concat(e.getKey()));break;case"devtools::subscribe":nn="synced",no({msg:"doc::sync::full",docKey:e.getKey(),events:ns.get(e.getKey())}),rG.info("[YD] Devtools subscribed. Doc: ".concat(e.getKey()))}})}(this)}}var nc=JSON.parse('{"u2":"yorkie-js-sdk","i8":"0.5.4"}');let nl=e=>{try{let t=JSON.stringify(e);if(void 0===t)return!1}catch(e){return!1}return!0};(w=M||(M={})).Manual="manual",w.Realtime="realtime",w.RealtimePushOnly="realtime-pushonly",w.RealtimeSyncOff="realtime-syncoff",(A=q||(q={})).Deactivated="deactivated",A.Activated="activated",(T=z||(z={})).SyncLoop="SyncLoop",T.WatchLoop="WatchLoop";let nh={syncLoopDuration:50,retrySyncLoopDelay:1e3,reconnectStreamDelay:1e3},nd={maxRetries:1/0,initialRetryInterval:1e3,maxBackoff:2e4};class nu{activate(){return this.isActive()?Promise.resolve():this.enqueueTask(async()=>this.rpcClient.activateClient({clientKey:this.key},{headers:{"x-shard-key":this.apiKey}}).then(e=>{this.id=e.clientId,this.status="activated",this.runSyncLoop(),rG.info('[AC] c:"'.concat(this.getKey(),'" activated, id:"').concat(this.id,'"'))}).catch(e=>{throw rG.error('[AC] c:"'.concat(this.getKey(),'" err :'),e),this.handleConnectError(e),e}))}deactivate(){return"deactivated"===this.status?Promise.resolve():this.enqueueTask(async()=>this.rpcClient.deactivateClient({clientId:this.id},{headers:{"x-shard-key":this.apiKey}}).then(()=>{this.deactivateInternal(),rG.info('[DC] c"'.concat(this.getKey(),'" deactivated'))}).catch(e=>{throw rG.error('[DC] c:"'.concat(this.getKey(),'" err :'),e),this.handleConnectError(e),e}))}attach(e){var t;let r=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};if(!this.isActive())throw new ti(x.ErrClientNotActivated,"".concat(this.key," is not active"));if(e.getStatus()!==B.Detached)throw new ti(x.ErrDocumentNotDetached,"".concat(e.getKey()," is not detached"));e.setActor(this.id),e.update((e,t)=>t.set(r.initialPresence||{}));let n=e.subscribe("local-broadcast",async t=>{var r;let{topic:n,payload:i}=t.value,s=null===(r=t.options)||void 0===r?void 0:r.error,o=t.options;try{await this.broadcast(e.getKey(),n,i,o)}catch(e){e instanceof Error&&(null==s||s(e))}}),i=null!==(t=r.syncMode)&&void 0!==t?t:"realtime";return this.enqueueTask(async()=>this.rpcClient.attachDocument({clientId:this.id,changePack:rU.toChangePack(e.createChangePack())},{headers:{"x-shard-key":"".concat(this.apiKey,"/").concat(e.getKey())}}).then(async t=>{let s=rU.fromChangePack(t.changePack);if(e.applyChangePack(s),e.getStatus()===B.Removed)return e;e.applyStatus(B.Attached),this.attachmentMap.set(e.getKey(),new rY(this.reconnectStreamDelay,e,t.documentId,i,n)),"manual"!==i&&await this.runWatchLoop(e.getKey()),rG.info('[AD] c:"'.concat(this.getKey(),'" attaches d:"').concat(e.getKey(),'"'));let o=e.getRootObject();if(r.initialRoot){let t=r.initialRoot;e.update(e=>{for(let[r,n]of Object.entries(t))o.has(r)||(e[r]=n)})}return e}).catch(e=>{throw rG.error('[AD] c:"'.concat(this.getKey(),'" err :'),e),this.handleConnectError(e),e}))}detach(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};if(!this.isActive())throw new ti(x.ErrClientNotActivated,"".concat(this.key," is not active"));let r=this.attachmentMap.get(e.getKey());if(!r)throw new ti(x.ErrDocumentNotAttached,"".concat(e.getKey()," is not attached"));return e.update((e,t)=>t.clear()),this.enqueueTask(async()=>{var n;return this.rpcClient.detachDocument({clientId:this.id,documentId:r.docID,changePack:rU.toChangePack(e.createChangePack()),removeIfNotAttached:null!==(n=t.removeIfNotAttached)&&void 0!==n&&n},{headers:{"x-shard-key":"".concat(this.apiKey,"/").concat(e.getKey())}}).then(t=>{let r=rU.fromChangePack(t.changePack);return e.applyChangePack(r),e.getStatus()!==B.Removed&&e.applyStatus(B.Detached),this.detachInternal(e.getKey()),rG.info('[DD] c:"'.concat(this.getKey(),'" detaches d:"').concat(e.getKey(),'"')),e}).catch(e=>{throw rG.error('[DD] c:"'.concat(this.getKey(),'" err :'),e),this.handleConnectError(e),e})})}async changeSyncMode(e,t){if(!this.isActive())throw new ti(x.ErrClientNotActivated,"".concat(this.key," is not active"));let r=this.attachmentMap.get(e.getKey());if(!r)throw new ti(x.ErrDocumentNotAttached,"".concat(e.getKey()," is not attached"));let n=r.syncMode;return n===t||((r.changeSyncMode(t),"manual"===t)?r.cancelWatchStream():("realtime"===t&&(r.remoteChangeEventReceived=!0),"manual"===n&&await this.runWatchLoop(e.getKey()))),e}sync(e){if(!this.isActive())throw new ti(x.ErrClientNotActivated,"".concat(this.key," is not active"));if(e){let t=this.attachmentMap.get(e.getKey());if(!t)throw new ti(x.ErrDocumentNotAttached,"".concat(e.getKey()," is not attached"));return this.enqueueTask(async()=>this.syncInternal(t,"realtime").catch(e=>{throw rG.error('[SY] c:"'.concat(this.getKey(),'" err :'),e),this.handleConnectError(e),e}))}return this.enqueueTask(async()=>{let e=[];for(let[,t]of this.attachmentMap)e.push(this.syncInternal(t,t.syncMode));return Promise.all(e).catch(e=>{throw rG.error('[SY] c:"'.concat(this.getKey(),'" err :'),e),this.handleConnectError(e),e})})}remove(e){if(!this.isActive())throw new ti(x.ErrClientNotActivated,"".concat(this.key," is not active"));let t=this.attachmentMap.get(e.getKey());if(!t)throw new ti(x.ErrDocumentNotAttached,"".concat(e.getKey()," is not attached"));e.setActor(this.id);let r=rU.toChangePack(e.createChangePack());return r.isRemoved=!0,this.enqueueTask(async()=>this.rpcClient.removeDocument({clientId:this.id,documentId:t.docID,changePack:r},{headers:{"x-shard-key":"".concat(this.apiKey,"/").concat(e.getKey())}}).then(t=>{let r=rU.fromChangePack(t.changePack);e.applyChangePack(r),this.detachInternal(e.getKey()),rG.info('[RD] c:"'.concat(this.getKey(),'" removes d:"').concat(e.getKey(),'"'))}).catch(e=>{throw rG.error('[RD] c:"'.concat(this.getKey(),'" err :'),e),this.handleConnectError(e),e}))}getID(){return this.id}getKey(){return this.key}isActive(){return"activated"===this.status}getStatus(){return this.status}getCondition(e){return this.conditions[e]}broadcast(e,t,r,n){var i;if(!this.isActive())throw new ti(x.ErrClientNotActivated,"".concat(this.key," is not active"));let s=this.attachmentMap.get(e);if(!s)throw new ti(x.ErrDocumentNotAttached,"".concat(e," is not attached"));if(!nl(r))throw new ti(x.ErrInvalidArgument,"payload is not serializable");let o=null!==(i=null==n?void 0:n.maxRetries)&&void 0!==i?i:nd.maxRetries,a=nd.maxBackoff,c=0,l=e=>Math.min(nd.initialRetryInterval*2**e,a),h=async()=>this.enqueueTask(async()=>this.rpcClient.broadcast({clientId:this.id,documentId:s.docID,topic:t,payload:new TextEncoder().encode(JSON.stringify(r))},{headers:{"x-shard-key":"".concat(this.apiKey,"/").concat(e)}}).then(()=>{rG.info('[BC] c:"'.concat(this.getKey(),'" broadcasts d:"').concat(e,'" t:"').concat(t,'"'))}).catch(e=>{if(rG.error('[BC] c:"'.concat(this.getKey(),'" err:'),e),this.handleConnectError(e)){if(ch(),l(++c-1)),rG.info('[BC] c:"'.concat(this.getKey(),'" retry attempt ').concat(c,"/").concat(o));else throw rG.error('[BC] c:"'.concat(this.getKey(),'" exceeded maximum retry attempts')),e}else throw e}));return h()}runSyncLoop(){let e=()=>{if(!this.isActive()){rG.debug('[SL] c:"'.concat(this.getKey(),'" exit sync loop')),this.conditions.SyncLoop=!1;return}let t=[];for(let[,e]of this.attachmentMap)e.needRealtimeSync()&&(e.remoteChangeEventReceived=!1,t.push(this.syncInternal(e,e.syncMode)));Promise.all(t).then(()=>setTimeout(e,this.syncLoopDuration)).catch(t=>{rG.error('[SL] c:"'.concat(this.getKey(),'" sync failed:'),t),this.handleConnectError(t)?setTimeout(e,this.retrySyncLoopDelay):this.conditions.SyncLoop=!1})};rG.debug('[SL] c:"'.concat(this.getKey(),'" run sync loop')),this.conditions.SyncLoop=!0,e()}async runWatchLoop(e){let t=this.attachmentMap.get(e);if(!t)throw new ti(x.ErrDocumentNotAttached,"".concat(e," is not attached"));return this.conditions.WatchLoop=!0,t.runWatchLoop(r=>{if(!this.isActive())return this.conditions.WatchLoop=!1,Promise.reject(new ti(x.ErrClientNotActivated,"".concat(this.key," is not active")));let n=new AbortController,i=this.rpcClient.watchDocument({clientId:this.id,documentId:t.docID},{headers:{"x-shard-key":"".concat(this.apiKey,"/").concat(e)},signal:n.signal});return t.doc.publish([{type:J.ConnectionChanged,value:L.Connected}]),rG.info('[WD] c:"'.concat(this.getKey(),'" watches d:"').concat(e,'"')),new Promise((e,s)=>{(async()=>{try{for await(let r of i)this.handleWatchDocumentsResponse(t,r),"initialization"===r.body.case&&e([i,n])}catch(e){t.doc.resetOnlineClients(),t.doc.publish([{type:J.Initialized,source:E.Local,value:t.doc.getPresences()}]),t.doc.publish([{type:J.ConnectionChanged,value:L.Disconnected}]),rG.debug('[WD] c:"'.concat(this.getKey(),'" unwatches')),this.handleConnectError(e)?r():this.conditions.WatchLoop=!1,s(e)}})()})})}handleWatchDocumentsResponse(e,t){if("event"===t.body.case&&t.body.value.type===I.DOCUMENT_CHANGED){e.remoteChangeEventReceived=!0;return}e.doc.applyWatchStream(t)}deactivateInternal(){for(let[e,t]of(this.status="deactivated",this.attachmentMap))this.detachInternal(e),t.doc.applyStatus(B.Detached)}detachInternal(e){let t=this.attachmentMap.get(e);t&&(t.cancelWatchStream(),t.unsubscribeBroadcastEvent(),this.attachmentMap.delete(e))}syncInternal(e,t){let{doc:r,docID:n}=e,i=r.createChangePack();return this.rpcClient.pushPullChanges({clientId:this.id,documentId:n,changePack:rU.toChangePack(i),pushOnly:"realtime-pushonly"===t},{headers:{"x-shard-key":"".concat(this.apiKey,"/").concat(r.getKey())}}).then(t=>{let n=rU.fromChangePack(t.changePack);if(n.hasChanges()&&("realtime-pushonly"===e.syncMode||"realtime-syncoff"===e.syncMode))return r;r.applyChangePack(n),e.doc.publish([{type:J.SyncStatusChanged,value:_.Synced}]),r.getStatus()===B.Removed&&this.detachInternal(r.getKey());let s=r.getKey(),o=n.getChangeSize();return rG.info('[PP] c:"'.concat(this.getKey(),'" sync d:"').concat(s,'", push:').concat(i.getChangeSize()," pull:").concat(o," cp:").concat(n.getCheckpoint().toTestString())),r}).catch(e=>{throw r.publish([{type:J.SyncStatusChanged,value:_.SyncFailed}]),rG.error('[PP] c:"'.concat(this.getKey(),'" err :'),e),e})}handleConnectError(e){return e instanceof G.K&&(e.code===H.E.Canceled||e.code===H.E.Unknown||e.code===H.E.ResourceExhausted||e.code===H.E.Unavailable||((rT(e)===x.ErrClientNotActivated||rT(e)===x.ErrClientNotFound)&&this.deactivateInternal(),!1))}enqueueTask(e){return new Promise((t,r)=>{this.taskQueue.push(()=>e().then(t).catch(r)),this.processing||this.processNext()})}async processNext(){if(0===this.taskQueue.length){this.processing=!1;return}try{this.processing=!0;let e=this.taskQueue.shift();await e()}catch(e){rG.error('[TQ] c:"'.concat(this.getKey(),'" process failed, id:"').concat(this.id,'"'))}this.processNext()}constructor(e,t){var r,n;this.processing=!1,t=t||nh,this.key=t.key?t.key:rH(),this.status="deactivated",this.attachmentMap=new Map,this.apiKey=t.apiKey||"",this.conditions={SyncLoop:!1,WatchLoop:!1},this.syncLoopDuration=t.syncLoopDuration||nh.syncLoopDuration,this.reconnectStreamDelay=t.reconnectStreamDelay||nh.reconnectStreamDelay,this.retrySyncLoopDelay=t.retrySyncLoopDelay||nh.retrySyncLoopDelay,this.rpcClient=(0,Y.Hb)(tr,(0,Z.u)({baseUrl:e,interceptors:[(r=t.apiKey,n=t.token,e=>async t=>(r&&t.header.set("x-api-key",r),n&&t.header.set("authorization",n),await e(t))),e=>async t=>(t.header.set("x-yorkie-user-agent",nc.u2+"/"+nc.i8),await e(t))]})),this.taskQueue=[]}}var ng={Client:nu,Document:na,Primitive:tC,Text:r3,Counter:r9,Tree:r6,LogLevel:O,setLogLevel:rW,IntType:N.IntegerCnt,LongType:N.LongCnt};"undefined"!=typeof globalThis&&(globalThis.yorkie={Client:nu,Document:na,Primitive:tC,Text:r3,Counter:r9,Tree:r6,LogLevel:O,setLogLevel:rW,IntType:N.IntegerCnt,LongType:N.LongCnt}),r(109);var nf=r(6182);function nm(e){let{content:t,actions:r}=e,[n,i]=(0,U.useState)(new Date),[s,o]=(0,U.useState)("Enter text here!"),a=n?W(new Date(n.toString())):"",c=e=>{let n=!1;switch(e){case"PUSH":n=!1,t.forEach(e=>{if(e.date===a)return n=!n,0}),n?r.updateContent(a,s):r.addContent(a,s),o("Enter text here!");break;case"DELETE":r.deleteContent(a)}};return(0,K.jsx)("article",{children:(0,K.jsxs)("div",{children:[(0,K.jsx)(nf.ZP,{onChange:i,value:n,locale:"en-EN",showNeighboringMonth:!1,formatDay:(e,t)=>t.toLocaleString("en",{day:"numeric"}),tileClassName:e=>{let{date:r}=e;return t.find(e=>e.date===W(r))?"highlight":""}}),(0,K.jsxs)("p",{children:["selected day : ",a]}),(0,K.jsx)("div",{className:V().memo,children:t.map((e,t)=>{if(e.date===a)return(0,K.jsx)("p",{children:e.text},t)})}),(0,K.jsxs)("div",{className:V().inputForm_editor,children:[(0,K.jsx)("h3",{children:"input form"}),(0,K.jsx)("textarea",{className:V().textArea,value:s,onChange:e=>o(e.target.value)})]}),(0,K.jsx)("button",{className:"button",onClick:()=>c("PUSH"),children:"push"}),(0,K.jsx)("button",{className:"button",onClick:()=>c("DELETE"),children:"pop"})]})})}let np=[{date:W(new Date).replace(/^\d{2}/,"01"),text:"payday"},{date:W(new Date).replace(/^\d{2}/,"17"),text:"Garry's birthday"}],ny="next.js-Scheduler-".concat(W(new Date));function nv(){let[e,t]=(0,U.useState)([]),[r,n]=(0,U.useState)(np),[i]=(0,U.useState)(()=>new ng.Document(ny));return(0,U.useEffect)(()=>{let e=new ng.Client("https://api.yorkie.dev",{apiKey:"cedaovjuioqlk4pjqn6g"});i.subscribe("presence",e=>{e.type!==J.PresenceChanged&&t(function(e){let t=[];for(let{presence:r}of e)t.push(r.userName);return t}(i.getPresences()))}),async function(t,r){await e.activate(),await e.attach(t,{initialPresence:{userName:function(){let e=Math.floor(Math.random()*j.length);return j[e]}()}}),t.update(e=>{e.content||(e.content=np)},"create default content if not exists"),t.subscribe(()=>{r(t.getRoot().content)}),r(t.getRoot().content)}(i,e=>n(e))},[]),(0,K.jsxs)("main",{className:V().main,children:[(0,K.jsxs)("p",{children:["peers : [",e.map((e,t)=>(0,K.jsxs)("span",{children:[" ",e,", "]},t))," ","]"]}),(0,K.jsx)(nm,{content:r,actions:{addContent(e,t){i.update(r=>{r.content.push({date:e,text:t})})},deleteContent(e){i.update(t=>{let r;for(let n of t.content)if(n.date===e){r=n;break}r&&t.content.deleteByID(r.getID())})},updateContent(e,t){i.update(r=>{let n;for(let t of r.content)if(t.date===e){n=t;break}n&&(n.text=t)})}}})]})}},109:function(){},7397:function(e){e.exports={main:"page_main__s_E_L",textArea:"page_textArea__sVKfA",memo:"page_memo__V0Ipn",inputForm_editor:"page_inputForm_editor__Tk7dD"}}},function(e){e.O(0,[662,828,852,744],function(){return e(e.s=4629)}),_N_E=e.O()}]); \ No newline at end of file +(self.webpackChunk_N_E=self.webpackChunk_N_E||[]).push([[931],{4629:function(e,t,r){Promise.resolve().then(r.bind(r,1802))},1802:function(e,t,r){"use strict";r.r(t),r.d(t,{default:function(){return nv}});var n,i,s,o,a,c,l,h,d,u,g,f,m,p,y,v,w,A,T,S,I,C,x,P,E,b,k,D,R,N,O,B,J,L,_,M,q,z,K=r(3165),F=r(7397),V=r.n(F),U=r(6189);let j=["Alice","Bob","Carol","Chuck","Dave","Erin","Frank","Grace","Ivan","Justin","Matilda","Oscar","Steve","Victor","Zoe"];function W(e){let[t,r,n]=e.toLocaleDateString("en").split("/");return t=Number(t)>9?t:"0"+t,r=Number(r)>9?r:"0"+r,n=n.slice(2),"".concat(r,"-").concat(t,"-").concat(n)}var G=r(8358),H=r(6390),Y=r(4715),Z=r(1582),X=r(8728),Q=r(601),$=r(1089),ee=r(6731),et=r(9782);(n=S||(S={}))[n.NULL=0]="NULL",n[n.BOOLEAN=1]="BOOLEAN",n[n.INTEGER=2]="INTEGER",n[n.LONG=3]="LONG",n[n.DOUBLE=4]="DOUBLE",n[n.STRING=5]="STRING",n[n.BYTES=6]="BYTES",n[n.DATE=7]="DATE",n[n.JSON_OBJECT=8]="JSON_OBJECT",n[n.JSON_ARRAY=9]="JSON_ARRAY",n[n.TEXT=10]="TEXT",n[n.INTEGER_CNT=11]="INTEGER_CNT",n[n.LONG_CNT=12]="LONG_CNT",n[n.TREE=13]="TREE",Q.w.util.setEnumType(S,"yorkie.v1.ValueType",[{no:0,name:"VALUE_TYPE_NULL"},{no:1,name:"VALUE_TYPE_BOOLEAN"},{no:2,name:"VALUE_TYPE_INTEGER"},{no:3,name:"VALUE_TYPE_LONG"},{no:4,name:"VALUE_TYPE_DOUBLE"},{no:5,name:"VALUE_TYPE_STRING"},{no:6,name:"VALUE_TYPE_BYTES"},{no:7,name:"VALUE_TYPE_DATE"},{no:8,name:"VALUE_TYPE_JSON_OBJECT"},{no:9,name:"VALUE_TYPE_JSON_ARRAY"},{no:10,name:"VALUE_TYPE_TEXT"},{no:11,name:"VALUE_TYPE_INTEGER_CNT"},{no:12,name:"VALUE_TYPE_LONG_CNT"},{no:13,name:"VALUE_TYPE_TREE"}]),(i=I||(I={}))[i.DOCUMENT_CHANGED=0]="DOCUMENT_CHANGED",i[i.DOCUMENT_WATCHED=1]="DOCUMENT_WATCHED",i[i.DOCUMENT_UNWATCHED=2]="DOCUMENT_UNWATCHED",i[i.DOCUMENT_BROADCAST=3]="DOCUMENT_BROADCAST",Q.w.util.setEnumType(I,"yorkie.v1.DocEventType",[{no:0,name:"DOC_EVENT_TYPE_DOCUMENT_CHANGED"},{no:1,name:"DOC_EVENT_TYPE_DOCUMENT_WATCHED"},{no:2,name:"DOC_EVENT_TYPE_DOCUMENT_UNWATCHED"},{no:3,name:"DOC_EVENT_TYPE_DOCUMENT_BROADCAST"}]);class er extends X.v{static fromBinary(e,t){return new er().fromBinary(e,t)}static fromJson(e,t){return new er().fromJson(e,t)}static fromJsonString(e,t){return new er().fromJsonString(e,t)}static equals(e,t){return Q.w.util.equals(er,e,t)}constructor(e){super(),this.presences={},Q.w.util.initPartial(e,this)}}er.runtime=Q.w,er.typeName="yorkie.v1.Snapshot",er.fields=Q.w.util.newFieldList(()=>[{no:1,name:"root",kind:"message",T:eA},{no:2,name:"presences",kind:"map",K:9,V:{kind:"message",T:eF}}]);class en extends X.v{static fromBinary(e,t){return new en().fromBinary(e,t)}static fromJson(e,t){return new en().fromJson(e,t)}static fromJsonString(e,t){return new en().fromJsonString(e,t)}static equals(e,t){return Q.w.util.equals(en,e,t)}constructor(e){super(),this.documentKey="",this.snapshot=new Uint8Array(0),this.changes=[],this.isRemoved=!1,Q.w.util.initPartial(e,this)}}en.runtime=Q.w,en.typeName="yorkie.v1.ChangePack",en.fields=Q.w.util.newFieldList(()=>[{no:1,name:"document_key",kind:"scalar",T:9},{no:2,name:"checkpoint",kind:"message",T:eV},{no:3,name:"snapshot",kind:"scalar",T:12},{no:4,name:"changes",kind:"message",T:ei,repeated:!0},{no:5,name:"min_synced_ticket",kind:"message",T:ej},{no:6,name:"is_removed",kind:"scalar",T:8},{no:7,name:"version_vector",kind:"message",T:eo}]);class ei extends X.v{static fromBinary(e,t){return new ei().fromBinary(e,t)}static fromJson(e,t){return new ei().fromJson(e,t)}static fromJsonString(e,t){return new ei().fromJsonString(e,t)}static equals(e,t){return Q.w.util.equals(ei,e,t)}constructor(e){super(),this.message="",this.operations=[],Q.w.util.initPartial(e,this)}}ei.runtime=Q.w,ei.typeName="yorkie.v1.Change",ei.fields=Q.w.util.newFieldList(()=>[{no:1,name:"id",kind:"message",T:es},{no:2,name:"message",kind:"scalar",T:9},{no:3,name:"operations",kind:"message",T:ea,repeated:!0},{no:4,name:"presence_change",kind:"message",T:eK}]);class es extends X.v{static fromBinary(e,t){return new es().fromBinary(e,t)}static fromJson(e,t){return new es().fromJson(e,t)}static fromJsonString(e,t){return new es().fromJsonString(e,t)}static equals(e,t){return Q.w.util.equals(es,e,t)}constructor(e){super(),this.clientSeq=0,this.serverSeq=$.q.zero,this.lamport=$.q.zero,this.actorId=new Uint8Array(0),Q.w.util.initPartial(e,this)}}es.runtime=Q.w,es.typeName="yorkie.v1.ChangeID",es.fields=Q.w.util.newFieldList(()=>[{no:1,name:"client_seq",kind:"scalar",T:13},{no:2,name:"server_seq",kind:"scalar",T:3},{no:3,name:"lamport",kind:"scalar",T:3},{no:4,name:"actor_id",kind:"scalar",T:12},{no:5,name:"version_vector",kind:"message",T:eo}]);class eo extends X.v{static fromBinary(e,t){return new eo().fromBinary(e,t)}static fromJson(e,t){return new eo().fromJson(e,t)}static fromJsonString(e,t){return new eo().fromJsonString(e,t)}static equals(e,t){return Q.w.util.equals(eo,e,t)}constructor(e){super(),this.vector={},Q.w.util.initPartial(e,this)}}eo.runtime=Q.w,eo.typeName="yorkie.v1.VersionVector",eo.fields=Q.w.util.newFieldList(()=>[{no:1,name:"vector",kind:"map",K:9,V:{kind:"scalar",T:3}}]);class ea extends X.v{static fromBinary(e,t){return new ea().fromBinary(e,t)}static fromJson(e,t){return new ea().fromJson(e,t)}static fromJsonString(e,t){return new ea().fromJsonString(e,t)}static equals(e,t){return Q.w.util.equals(ea,e,t)}constructor(e){super(),this.body={case:void 0},Q.w.util.initPartial(e,this)}}ea.runtime=Q.w,ea.typeName="yorkie.v1.Operation",ea.fields=Q.w.util.newFieldList(()=>[{no:1,name:"set",kind:"message",T:ec,oneof:"body"},{no:2,name:"add",kind:"message",T:el,oneof:"body"},{no:3,name:"move",kind:"message",T:eh,oneof:"body"},{no:4,name:"remove",kind:"message",T:ed,oneof:"body"},{no:5,name:"edit",kind:"message",T:eu,oneof:"body"},{no:6,name:"select",kind:"message",T:eg,oneof:"body"},{no:7,name:"style",kind:"message",T:ef,oneof:"body"},{no:8,name:"increase",kind:"message",T:em,oneof:"body"},{no:9,name:"tree_edit",kind:"message",T:ep,oneof:"body"},{no:10,name:"tree_style",kind:"message",T:ey,oneof:"body"},{no:11,name:"array_set",kind:"message",T:ev,oneof:"body"}]);class ec extends X.v{static fromBinary(e,t){return new ec().fromBinary(e,t)}static fromJson(e,t){return new ec().fromJson(e,t)}static fromJsonString(e,t){return new ec().fromJsonString(e,t)}static equals(e,t){return Q.w.util.equals(ec,e,t)}constructor(e){super(),this.key="",Q.w.util.initPartial(e,this)}}ec.runtime=Q.w,ec.typeName="yorkie.v1.Operation.Set",ec.fields=Q.w.util.newFieldList(()=>[{no:1,name:"parent_created_at",kind:"message",T:ej},{no:2,name:"key",kind:"scalar",T:9},{no:3,name:"value",kind:"message",T:ew},{no:4,name:"executed_at",kind:"message",T:ej}]);class el extends X.v{static fromBinary(e,t){return new el().fromBinary(e,t)}static fromJson(e,t){return new el().fromJson(e,t)}static fromJsonString(e,t){return new el().fromJsonString(e,t)}static equals(e,t){return Q.w.util.equals(el,e,t)}constructor(e){super(),Q.w.util.initPartial(e,this)}}el.runtime=Q.w,el.typeName="yorkie.v1.Operation.Add",el.fields=Q.w.util.newFieldList(()=>[{no:1,name:"parent_created_at",kind:"message",T:ej},{no:2,name:"prev_created_at",kind:"message",T:ej},{no:3,name:"value",kind:"message",T:ew},{no:4,name:"executed_at",kind:"message",T:ej}]);class eh extends X.v{static fromBinary(e,t){return new eh().fromBinary(e,t)}static fromJson(e,t){return new eh().fromJson(e,t)}static fromJsonString(e,t){return new eh().fromJsonString(e,t)}static equals(e,t){return Q.w.util.equals(eh,e,t)}constructor(e){super(),Q.w.util.initPartial(e,this)}}eh.runtime=Q.w,eh.typeName="yorkie.v1.Operation.Move",eh.fields=Q.w.util.newFieldList(()=>[{no:1,name:"parent_created_at",kind:"message",T:ej},{no:2,name:"prev_created_at",kind:"message",T:ej},{no:3,name:"created_at",kind:"message",T:ej},{no:4,name:"executed_at",kind:"message",T:ej}]);class ed extends X.v{static fromBinary(e,t){return new ed().fromBinary(e,t)}static fromJson(e,t){return new ed().fromJson(e,t)}static fromJsonString(e,t){return new ed().fromJsonString(e,t)}static equals(e,t){return Q.w.util.equals(ed,e,t)}constructor(e){super(),Q.w.util.initPartial(e,this)}}ed.runtime=Q.w,ed.typeName="yorkie.v1.Operation.Remove",ed.fields=Q.w.util.newFieldList(()=>[{no:1,name:"parent_created_at",kind:"message",T:ej},{no:2,name:"created_at",kind:"message",T:ej},{no:3,name:"executed_at",kind:"message",T:ej}]);class eu extends X.v{static fromBinary(e,t){return new eu().fromBinary(e,t)}static fromJson(e,t){return new eu().fromJson(e,t)}static fromJsonString(e,t){return new eu().fromJsonString(e,t)}static equals(e,t){return Q.w.util.equals(eu,e,t)}constructor(e){super(),this.createdAtMapByActor={},this.content="",this.attributes={},Q.w.util.initPartial(e,this)}}eu.runtime=Q.w,eu.typeName="yorkie.v1.Operation.Edit",eu.fields=Q.w.util.newFieldList(()=>[{no:1,name:"parent_created_at",kind:"message",T:ej},{no:2,name:"from",kind:"message",T:eU},{no:3,name:"to",kind:"message",T:eU},{no:4,name:"created_at_map_by_actor",kind:"map",K:9,V:{kind:"message",T:ej}},{no:5,name:"content",kind:"scalar",T:9},{no:6,name:"executed_at",kind:"message",T:ej},{no:7,name:"attributes",kind:"map",K:9,V:{kind:"scalar",T:9}}]);class eg extends X.v{static fromBinary(e,t){return new eg().fromBinary(e,t)}static fromJson(e,t){return new eg().fromJson(e,t)}static fromJsonString(e,t){return new eg().fromJsonString(e,t)}static equals(e,t){return Q.w.util.equals(eg,e,t)}constructor(e){super(),Q.w.util.initPartial(e,this)}}eg.runtime=Q.w,eg.typeName="yorkie.v1.Operation.Select",eg.fields=Q.w.util.newFieldList(()=>[{no:1,name:"parent_created_at",kind:"message",T:ej},{no:2,name:"from",kind:"message",T:eU},{no:3,name:"to",kind:"message",T:eU},{no:4,name:"executed_at",kind:"message",T:ej}]);class ef extends X.v{static fromBinary(e,t){return new ef().fromBinary(e,t)}static fromJson(e,t){return new ef().fromJson(e,t)}static fromJsonString(e,t){return new ef().fromJsonString(e,t)}static equals(e,t){return Q.w.util.equals(ef,e,t)}constructor(e){super(),this.attributes={},this.createdAtMapByActor={},Q.w.util.initPartial(e,this)}}ef.runtime=Q.w,ef.typeName="yorkie.v1.Operation.Style",ef.fields=Q.w.util.newFieldList(()=>[{no:1,name:"parent_created_at",kind:"message",T:ej},{no:2,name:"from",kind:"message",T:eU},{no:3,name:"to",kind:"message",T:eU},{no:4,name:"attributes",kind:"map",K:9,V:{kind:"scalar",T:9}},{no:5,name:"executed_at",kind:"message",T:ej},{no:6,name:"created_at_map_by_actor",kind:"map",K:9,V:{kind:"message",T:ej}}]);class em extends X.v{static fromBinary(e,t){return new em().fromBinary(e,t)}static fromJson(e,t){return new em().fromJson(e,t)}static fromJsonString(e,t){return new em().fromJsonString(e,t)}static equals(e,t){return Q.w.util.equals(em,e,t)}constructor(e){super(),Q.w.util.initPartial(e,this)}}em.runtime=Q.w,em.typeName="yorkie.v1.Operation.Increase",em.fields=Q.w.util.newFieldList(()=>[{no:1,name:"parent_created_at",kind:"message",T:ej},{no:2,name:"value",kind:"message",T:ew},{no:3,name:"executed_at",kind:"message",T:ej}]);class ep extends X.v{static fromBinary(e,t){return new ep().fromBinary(e,t)}static fromJson(e,t){return new ep().fromJson(e,t)}static fromJsonString(e,t){return new ep().fromJsonString(e,t)}static equals(e,t){return Q.w.util.equals(ep,e,t)}constructor(e){super(),this.createdAtMapByActor={},this.contents=[],this.splitLevel=0,Q.w.util.initPartial(e,this)}}ep.runtime=Q.w,ep.typeName="yorkie.v1.Operation.TreeEdit",ep.fields=Q.w.util.newFieldList(()=>[{no:1,name:"parent_created_at",kind:"message",T:ej},{no:2,name:"from",kind:"message",T:eJ},{no:3,name:"to",kind:"message",T:eJ},{no:4,name:"created_at_map_by_actor",kind:"map",K:9,V:{kind:"message",T:ej}},{no:5,name:"contents",kind:"message",T:eO,repeated:!0},{no:7,name:"split_level",kind:"scalar",T:5},{no:6,name:"executed_at",kind:"message",T:ej}]);class ey extends X.v{static fromBinary(e,t){return new ey().fromBinary(e,t)}static fromJson(e,t){return new ey().fromJson(e,t)}static fromJsonString(e,t){return new ey().fromJsonString(e,t)}static equals(e,t){return Q.w.util.equals(ey,e,t)}constructor(e){super(),this.attributes={},this.attributesToRemove=[],this.createdAtMapByActor={},Q.w.util.initPartial(e,this)}}ey.runtime=Q.w,ey.typeName="yorkie.v1.Operation.TreeStyle",ey.fields=Q.w.util.newFieldList(()=>[{no:1,name:"parent_created_at",kind:"message",T:ej},{no:2,name:"from",kind:"message",T:eJ},{no:3,name:"to",kind:"message",T:eJ},{no:4,name:"attributes",kind:"map",K:9,V:{kind:"scalar",T:9}},{no:5,name:"executed_at",kind:"message",T:ej},{no:6,name:"attributes_to_remove",kind:"scalar",T:9,repeated:!0},{no:7,name:"created_at_map_by_actor",kind:"map",K:9,V:{kind:"message",T:ej}}]);class ev extends X.v{static fromBinary(e,t){return new ev().fromBinary(e,t)}static fromJson(e,t){return new ev().fromJson(e,t)}static fromJsonString(e,t){return new ev().fromJsonString(e,t)}static equals(e,t){return Q.w.util.equals(ev,e,t)}constructor(e){super(),Q.w.util.initPartial(e,this)}}ev.runtime=Q.w,ev.typeName="yorkie.v1.Operation.ArraySet",ev.fields=Q.w.util.newFieldList(()=>[{no:1,name:"parent_created_at",kind:"message",T:ej},{no:2,name:"created_at",kind:"message",T:ej},{no:3,name:"value",kind:"message",T:ew},{no:4,name:"executed_at",kind:"message",T:ej}]);class ew extends X.v{static fromBinary(e,t){return new ew().fromBinary(e,t)}static fromJson(e,t){return new ew().fromJson(e,t)}static fromJsonString(e,t){return new ew().fromJsonString(e,t)}static equals(e,t){return Q.w.util.equals(ew,e,t)}constructor(e){super(),this.type=0,this.value=new Uint8Array(0),Q.w.util.initPartial(e,this)}}ew.runtime=Q.w,ew.typeName="yorkie.v1.JSONElementSimple",ew.fields=Q.w.util.newFieldList(()=>[{no:1,name:"created_at",kind:"message",T:ej},{no:2,name:"moved_at",kind:"message",T:ej},{no:3,name:"removed_at",kind:"message",T:ej},{no:4,name:"type",kind:"enum",T:Q.w.getEnumType(S)},{no:5,name:"value",kind:"scalar",T:12}]);class eA extends X.v{static fromBinary(e,t){return new eA().fromBinary(e,t)}static fromJson(e,t){return new eA().fromJson(e,t)}static fromJsonString(e,t){return new eA().fromJsonString(e,t)}static equals(e,t){return Q.w.util.equals(eA,e,t)}constructor(e){super(),this.body={case:void 0},Q.w.util.initPartial(e,this)}}eA.runtime=Q.w,eA.typeName="yorkie.v1.JSONElement",eA.fields=Q.w.util.newFieldList(()=>[{no:1,name:"json_object",kind:"message",T:eT,oneof:"body"},{no:2,name:"json_array",kind:"message",T:eS,oneof:"body"},{no:3,name:"primitive",kind:"message",T:eI,oneof:"body"},{no:5,name:"text",kind:"message",T:eC,oneof:"body"},{no:6,name:"counter",kind:"message",T:ex,oneof:"body"},{no:7,name:"tree",kind:"message",T:eP,oneof:"body"}]);class eT extends X.v{static fromBinary(e,t){return new eT().fromBinary(e,t)}static fromJson(e,t){return new eT().fromJson(e,t)}static fromJsonString(e,t){return new eT().fromJsonString(e,t)}static equals(e,t){return Q.w.util.equals(eT,e,t)}constructor(e){super(),this.nodes=[],Q.w.util.initPartial(e,this)}}eT.runtime=Q.w,eT.typeName="yorkie.v1.JSONElement.JSONObject",eT.fields=Q.w.util.newFieldList(()=>[{no:1,name:"nodes",kind:"message",T:eE,repeated:!0},{no:2,name:"created_at",kind:"message",T:ej},{no:3,name:"moved_at",kind:"message",T:ej},{no:4,name:"removed_at",kind:"message",T:ej}]);class eS extends X.v{static fromBinary(e,t){return new eS().fromBinary(e,t)}static fromJson(e,t){return new eS().fromJson(e,t)}static fromJsonString(e,t){return new eS().fromJsonString(e,t)}static equals(e,t){return Q.w.util.equals(eS,e,t)}constructor(e){super(),this.nodes=[],Q.w.util.initPartial(e,this)}}eS.runtime=Q.w,eS.typeName="yorkie.v1.JSONElement.JSONArray",eS.fields=Q.w.util.newFieldList(()=>[{no:1,name:"nodes",kind:"message",T:eb,repeated:!0},{no:2,name:"created_at",kind:"message",T:ej},{no:3,name:"moved_at",kind:"message",T:ej},{no:4,name:"removed_at",kind:"message",T:ej}]);class eI extends X.v{static fromBinary(e,t){return new eI().fromBinary(e,t)}static fromJson(e,t){return new eI().fromJson(e,t)}static fromJsonString(e,t){return new eI().fromJsonString(e,t)}static equals(e,t){return Q.w.util.equals(eI,e,t)}constructor(e){super(),this.type=0,this.value=new Uint8Array(0),Q.w.util.initPartial(e,this)}}eI.runtime=Q.w,eI.typeName="yorkie.v1.JSONElement.Primitive",eI.fields=Q.w.util.newFieldList(()=>[{no:1,name:"type",kind:"enum",T:Q.w.getEnumType(S)},{no:2,name:"value",kind:"scalar",T:12},{no:3,name:"created_at",kind:"message",T:ej},{no:4,name:"moved_at",kind:"message",T:ej},{no:5,name:"removed_at",kind:"message",T:ej}]);class eC extends X.v{static fromBinary(e,t){return new eC().fromBinary(e,t)}static fromJson(e,t){return new eC().fromJson(e,t)}static fromJsonString(e,t){return new eC().fromJsonString(e,t)}static equals(e,t){return Q.w.util.equals(eC,e,t)}constructor(e){super(),this.nodes=[],Q.w.util.initPartial(e,this)}}eC.runtime=Q.w,eC.typeName="yorkie.v1.JSONElement.Text",eC.fields=Q.w.util.newFieldList(()=>[{no:1,name:"nodes",kind:"message",T:eD,repeated:!0},{no:2,name:"created_at",kind:"message",T:ej},{no:3,name:"moved_at",kind:"message",T:ej},{no:4,name:"removed_at",kind:"message",T:ej}]);class ex extends X.v{static fromBinary(e,t){return new ex().fromBinary(e,t)}static fromJson(e,t){return new ex().fromJson(e,t)}static fromJsonString(e,t){return new ex().fromJsonString(e,t)}static equals(e,t){return Q.w.util.equals(ex,e,t)}constructor(e){super(),this.type=0,this.value=new Uint8Array(0),Q.w.util.initPartial(e,this)}}ex.runtime=Q.w,ex.typeName="yorkie.v1.JSONElement.Counter",ex.fields=Q.w.util.newFieldList(()=>[{no:1,name:"type",kind:"enum",T:Q.w.getEnumType(S)},{no:2,name:"value",kind:"scalar",T:12},{no:3,name:"created_at",kind:"message",T:ej},{no:4,name:"moved_at",kind:"message",T:ej},{no:5,name:"removed_at",kind:"message",T:ej}]);class eP extends X.v{static fromBinary(e,t){return new eP().fromBinary(e,t)}static fromJson(e,t){return new eP().fromJson(e,t)}static fromJsonString(e,t){return new eP().fromJsonString(e,t)}static equals(e,t){return Q.w.util.equals(eP,e,t)}constructor(e){super(),this.nodes=[],Q.w.util.initPartial(e,this)}}eP.runtime=Q.w,eP.typeName="yorkie.v1.JSONElement.Tree",eP.fields=Q.w.util.newFieldList(()=>[{no:1,name:"nodes",kind:"message",T:eN,repeated:!0},{no:2,name:"created_at",kind:"message",T:ej},{no:3,name:"moved_at",kind:"message",T:ej},{no:4,name:"removed_at",kind:"message",T:ej}]);class eE extends X.v{static fromBinary(e,t){return new eE().fromBinary(e,t)}static fromJson(e,t){return new eE().fromJson(e,t)}static fromJsonString(e,t){return new eE().fromJsonString(e,t)}static equals(e,t){return Q.w.util.equals(eE,e,t)}constructor(e){super(),this.key="",Q.w.util.initPartial(e,this)}}eE.runtime=Q.w,eE.typeName="yorkie.v1.RHTNode",eE.fields=Q.w.util.newFieldList(()=>[{no:1,name:"key",kind:"scalar",T:9},{no:2,name:"element",kind:"message",T:eA}]);class eb extends X.v{static fromBinary(e,t){return new eb().fromBinary(e,t)}static fromJson(e,t){return new eb().fromJson(e,t)}static fromJsonString(e,t){return new eb().fromJsonString(e,t)}static equals(e,t){return Q.w.util.equals(eb,e,t)}constructor(e){super(),Q.w.util.initPartial(e,this)}}eb.runtime=Q.w,eb.typeName="yorkie.v1.RGANode",eb.fields=Q.w.util.newFieldList(()=>[{no:1,name:"next",kind:"message",T:eb},{no:2,name:"element",kind:"message",T:eA}]);class ek extends X.v{static fromBinary(e,t){return new ek().fromBinary(e,t)}static fromJson(e,t){return new ek().fromJson(e,t)}static fromJsonString(e,t){return new ek().fromJsonString(e,t)}static equals(e,t){return Q.w.util.equals(ek,e,t)}constructor(e){super(),this.value="",this.isRemoved=!1,Q.w.util.initPartial(e,this)}}ek.runtime=Q.w,ek.typeName="yorkie.v1.NodeAttr",ek.fields=Q.w.util.newFieldList(()=>[{no:1,name:"value",kind:"scalar",T:9},{no:2,name:"updated_at",kind:"message",T:ej},{no:3,name:"is_removed",kind:"scalar",T:8}]);class eD extends X.v{static fromBinary(e,t){return new eD().fromBinary(e,t)}static fromJson(e,t){return new eD().fromJson(e,t)}static fromJsonString(e,t){return new eD().fromJsonString(e,t)}static equals(e,t){return Q.w.util.equals(eD,e,t)}constructor(e){super(),this.value="",this.attributes={},Q.w.util.initPartial(e,this)}}eD.runtime=Q.w,eD.typeName="yorkie.v1.TextNode",eD.fields=Q.w.util.newFieldList(()=>[{no:1,name:"id",kind:"message",T:eR},{no:2,name:"value",kind:"scalar",T:9},{no:3,name:"removed_at",kind:"message",T:ej},{no:4,name:"ins_prev_id",kind:"message",T:eR},{no:5,name:"attributes",kind:"map",K:9,V:{kind:"message",T:ek}}]);class eR extends X.v{static fromBinary(e,t){return new eR().fromBinary(e,t)}static fromJson(e,t){return new eR().fromJson(e,t)}static fromJsonString(e,t){return new eR().fromJsonString(e,t)}static equals(e,t){return Q.w.util.equals(eR,e,t)}constructor(e){super(),this.offset=0,Q.w.util.initPartial(e,this)}}eR.runtime=Q.w,eR.typeName="yorkie.v1.TextNodeID",eR.fields=Q.w.util.newFieldList(()=>[{no:1,name:"created_at",kind:"message",T:ej},{no:2,name:"offset",kind:"scalar",T:5}]);class eN extends X.v{static fromBinary(e,t){return new eN().fromBinary(e,t)}static fromJson(e,t){return new eN().fromJson(e,t)}static fromJsonString(e,t){return new eN().fromJsonString(e,t)}static equals(e,t){return Q.w.util.equals(eN,e,t)}constructor(e){super(),this.type="",this.value="",this.depth=0,this.attributes={},Q.w.util.initPartial(e,this)}}eN.runtime=Q.w,eN.typeName="yorkie.v1.TreeNode",eN.fields=Q.w.util.newFieldList(()=>[{no:1,name:"id",kind:"message",T:eB},{no:2,name:"type",kind:"scalar",T:9},{no:3,name:"value",kind:"scalar",T:9},{no:4,name:"removed_at",kind:"message",T:ej},{no:5,name:"ins_prev_id",kind:"message",T:eB},{no:6,name:"ins_next_id",kind:"message",T:eB},{no:7,name:"depth",kind:"scalar",T:5},{no:8,name:"attributes",kind:"map",K:9,V:{kind:"message",T:ek}}]);class eO extends X.v{static fromBinary(e,t){return new eO().fromBinary(e,t)}static fromJson(e,t){return new eO().fromJson(e,t)}static fromJsonString(e,t){return new eO().fromJsonString(e,t)}static equals(e,t){return Q.w.util.equals(eO,e,t)}constructor(e){super(),this.content=[],Q.w.util.initPartial(e,this)}}eO.runtime=Q.w,eO.typeName="yorkie.v1.TreeNodes",eO.fields=Q.w.util.newFieldList(()=>[{no:1,name:"content",kind:"message",T:eN,repeated:!0}]);class eB extends X.v{static fromBinary(e,t){return new eB().fromBinary(e,t)}static fromJson(e,t){return new eB().fromJson(e,t)}static fromJsonString(e,t){return new eB().fromJsonString(e,t)}static equals(e,t){return Q.w.util.equals(eB,e,t)}constructor(e){super(),this.offset=0,Q.w.util.initPartial(e,this)}}eB.runtime=Q.w,eB.typeName="yorkie.v1.TreeNodeID",eB.fields=Q.w.util.newFieldList(()=>[{no:1,name:"created_at",kind:"message",T:ej},{no:2,name:"offset",kind:"scalar",T:5}]);class eJ extends X.v{static fromBinary(e,t){return new eJ().fromBinary(e,t)}static fromJson(e,t){return new eJ().fromJson(e,t)}static fromJsonString(e,t){return new eJ().fromJsonString(e,t)}static equals(e,t){return Q.w.util.equals(eJ,e,t)}constructor(e){super(),Q.w.util.initPartial(e,this)}}eJ.runtime=Q.w,eJ.typeName="yorkie.v1.TreePos",eJ.fields=Q.w.util.newFieldList(()=>[{no:1,name:"parent_id",kind:"message",T:eB},{no:2,name:"left_sibling_id",kind:"message",T:eB}]);class eL extends X.v{static fromBinary(e,t){return new eL().fromBinary(e,t)}static fromJson(e,t){return new eL().fromJson(e,t)}static fromJsonString(e,t){return new eL().fromJsonString(e,t)}static equals(e,t){return Q.w.util.equals(eL,e,t)}constructor(e){super(),this.id="",this.username="",Q.w.util.initPartial(e,this)}}eL.runtime=Q.w,eL.typeName="yorkie.v1.User",eL.fields=Q.w.util.newFieldList(()=>[{no:1,name:"id",kind:"scalar",T:9},{no:2,name:"username",kind:"scalar",T:9},{no:3,name:"created_at",kind:"message",T:ee.E}]);class e_ extends X.v{static fromBinary(e,t){return new e_().fromBinary(e,t)}static fromJson(e,t){return new e_().fromJson(e,t)}static fromJsonString(e,t){return new e_().fromJsonString(e,t)}static equals(e,t){return Q.w.util.equals(e_,e,t)}constructor(e){super(),this.id="",this.name="",this.publicKey="",this.secretKey="",this.authWebhookUrl="",this.authWebhookMethods=[],this.clientDeactivateThreshold="",Q.w.util.initPartial(e,this)}}e_.runtime=Q.w,e_.typeName="yorkie.v1.Project",e_.fields=Q.w.util.newFieldList(()=>[{no:1,name:"id",kind:"scalar",T:9},{no:2,name:"name",kind:"scalar",T:9},{no:3,name:"public_key",kind:"scalar",T:9},{no:4,name:"secret_key",kind:"scalar",T:9},{no:5,name:"auth_webhook_url",kind:"scalar",T:9},{no:6,name:"auth_webhook_methods",kind:"scalar",T:9,repeated:!0},{no:7,name:"client_deactivate_threshold",kind:"scalar",T:9},{no:8,name:"created_at",kind:"message",T:ee.E},{no:9,name:"updated_at",kind:"message",T:ee.E}]);class eM extends X.v{static fromBinary(e,t){return new eM().fromBinary(e,t)}static fromJson(e,t){return new eM().fromJson(e,t)}static fromJsonString(e,t){return new eM().fromJsonString(e,t)}static equals(e,t){return Q.w.util.equals(eM,e,t)}constructor(e){super(),Q.w.util.initPartial(e,this)}}eM.runtime=Q.w,eM.typeName="yorkie.v1.UpdatableProjectFields",eM.fields=Q.w.util.newFieldList(()=>[{no:1,name:"name",kind:"message",T:et.Gm},{no:2,name:"auth_webhook_url",kind:"message",T:et.Gm},{no:3,name:"auth_webhook_methods",kind:"message",T:eq},{no:4,name:"client_deactivate_threshold",kind:"message",T:et.Gm}]);class eq extends X.v{static fromBinary(e,t){return new eq().fromBinary(e,t)}static fromJson(e,t){return new eq().fromJson(e,t)}static fromJsonString(e,t){return new eq().fromJsonString(e,t)}static equals(e,t){return Q.w.util.equals(eq,e,t)}constructor(e){super(),this.methods=[],Q.w.util.initPartial(e,this)}}eq.runtime=Q.w,eq.typeName="yorkie.v1.UpdatableProjectFields.AuthWebhookMethods",eq.fields=Q.w.util.newFieldList(()=>[{no:1,name:"methods",kind:"scalar",T:9,repeated:!0}]);class ez extends X.v{static fromBinary(e,t){return new ez().fromBinary(e,t)}static fromJson(e,t){return new ez().fromJson(e,t)}static fromJsonString(e,t){return new ez().fromJsonString(e,t)}static equals(e,t){return Q.w.util.equals(ez,e,t)}constructor(e){super(),this.id="",this.key="",this.snapshot="",Q.w.util.initPartial(e,this)}}ez.runtime=Q.w,ez.typeName="yorkie.v1.DocumentSummary",ez.fields=Q.w.util.newFieldList(()=>[{no:1,name:"id",kind:"scalar",T:9},{no:2,name:"key",kind:"scalar",T:9},{no:3,name:"snapshot",kind:"scalar",T:9},{no:4,name:"created_at",kind:"message",T:ee.E},{no:5,name:"accessed_at",kind:"message",T:ee.E},{no:6,name:"updated_at",kind:"message",T:ee.E}]);class eK extends X.v{static fromBinary(e,t){return new eK().fromBinary(e,t)}static fromJson(e,t){return new eK().fromJson(e,t)}static fromJsonString(e,t){return new eK().fromJsonString(e,t)}static equals(e,t){return Q.w.util.equals(eK,e,t)}constructor(e){super(),this.type=0,Q.w.util.initPartial(e,this)}}eK.runtime=Q.w,eK.typeName="yorkie.v1.PresenceChange",eK.fields=Q.w.util.newFieldList(()=>[{no:1,name:"type",kind:"enum",T:Q.w.getEnumType(C)},{no:2,name:"presence",kind:"message",T:eF}]),(s=C||(C={}))[s.UNSPECIFIED=0]="UNSPECIFIED",s[s.PUT=1]="PUT",s[s.DELETE=2]="DELETE",s[s.CLEAR=3]="CLEAR",Q.w.util.setEnumType(C,"yorkie.v1.PresenceChange.ChangeType",[{no:0,name:"CHANGE_TYPE_UNSPECIFIED"},{no:1,name:"CHANGE_TYPE_PUT"},{no:2,name:"CHANGE_TYPE_DELETE"},{no:3,name:"CHANGE_TYPE_CLEAR"}]);class eF extends X.v{static fromBinary(e,t){return new eF().fromBinary(e,t)}static fromJson(e,t){return new eF().fromJson(e,t)}static fromJsonString(e,t){return new eF().fromJsonString(e,t)}static equals(e,t){return Q.w.util.equals(eF,e,t)}constructor(e){super(),this.data={},Q.w.util.initPartial(e,this)}}eF.runtime=Q.w,eF.typeName="yorkie.v1.Presence",eF.fields=Q.w.util.newFieldList(()=>[{no:1,name:"data",kind:"map",K:9,V:{kind:"scalar",T:9}}]);class eV extends X.v{static fromBinary(e,t){return new eV().fromBinary(e,t)}static fromJson(e,t){return new eV().fromJson(e,t)}static fromJsonString(e,t){return new eV().fromJsonString(e,t)}static equals(e,t){return Q.w.util.equals(eV,e,t)}constructor(e){super(),this.serverSeq=$.q.zero,this.clientSeq=0,Q.w.util.initPartial(e,this)}}eV.runtime=Q.w,eV.typeName="yorkie.v1.Checkpoint",eV.fields=Q.w.util.newFieldList(()=>[{no:1,name:"server_seq",kind:"scalar",T:3},{no:2,name:"client_seq",kind:"scalar",T:13}]);class eU extends X.v{static fromBinary(e,t){return new eU().fromBinary(e,t)}static fromJson(e,t){return new eU().fromJson(e,t)}static fromJsonString(e,t){return new eU().fromJsonString(e,t)}static equals(e,t){return Q.w.util.equals(eU,e,t)}constructor(e){super(),this.offset=0,this.relativeOffset=0,Q.w.util.initPartial(e,this)}}eU.runtime=Q.w,eU.typeName="yorkie.v1.TextNodePos",eU.fields=Q.w.util.newFieldList(()=>[{no:1,name:"created_at",kind:"message",T:ej},{no:2,name:"offset",kind:"scalar",T:5},{no:3,name:"relative_offset",kind:"scalar",T:5}]);class ej extends X.v{static fromBinary(e,t){return new ej().fromBinary(e,t)}static fromJson(e,t){return new ej().fromJson(e,t)}static fromJsonString(e,t){return new ej().fromJsonString(e,t)}static equals(e,t){return Q.w.util.equals(ej,e,t)}constructor(e){super(),this.lamport=$.q.zero,this.delimiter=0,this.actorId=new Uint8Array(0),Q.w.util.initPartial(e,this)}}ej.runtime=Q.w,ej.typeName="yorkie.v1.TimeTicket",ej.fields=Q.w.util.newFieldList(()=>[{no:1,name:"lamport",kind:"scalar",T:3},{no:2,name:"delimiter",kind:"scalar",T:13},{no:3,name:"actor_id",kind:"scalar",T:12}]);class eW extends X.v{static fromBinary(e,t){return new eW().fromBinary(e,t)}static fromJson(e,t){return new eW().fromJson(e,t)}static fromJsonString(e,t){return new eW().fromJsonString(e,t)}static equals(e,t){return Q.w.util.equals(eW,e,t)}constructor(e){super(),this.topic="",this.payload=new Uint8Array(0),Q.w.util.initPartial(e,this)}}eW.runtime=Q.w,eW.typeName="yorkie.v1.DocEventBody",eW.fields=Q.w.util.newFieldList(()=>[{no:1,name:"topic",kind:"scalar",T:9},{no:2,name:"payload",kind:"scalar",T:12}]);class eG extends X.v{static fromBinary(e,t){return new eG().fromBinary(e,t)}static fromJson(e,t){return new eG().fromJson(e,t)}static fromJsonString(e,t){return new eG().fromJsonString(e,t)}static equals(e,t){return Q.w.util.equals(eG,e,t)}constructor(e){super(),this.type=0,this.publisher="",Q.w.util.initPartial(e,this)}}eG.runtime=Q.w,eG.typeName="yorkie.v1.DocEvent",eG.fields=Q.w.util.newFieldList(()=>[{no:1,name:"type",kind:"enum",T:Q.w.getEnumType(I)},{no:2,name:"publisher",kind:"scalar",T:9},{no:3,name:"body",kind:"message",T:eW}]);class eH extends X.v{static fromBinary(e,t){return new eH().fromBinary(e,t)}static fromJson(e,t){return new eH().fromJson(e,t)}static fromJsonString(e,t){return new eH().fromJsonString(e,t)}static equals(e,t){return Q.w.util.equals(eH,e,t)}constructor(e){super(),this.clientKey="",Q.w.util.initPartial(e,this)}}eH.runtime=Q.w,eH.typeName="yorkie.v1.ActivateClientRequest",eH.fields=Q.w.util.newFieldList(()=>[{no:1,name:"client_key",kind:"scalar",T:9}]);class eY extends X.v{static fromBinary(e,t){return new eY().fromBinary(e,t)}static fromJson(e,t){return new eY().fromJson(e,t)}static fromJsonString(e,t){return new eY().fromJsonString(e,t)}static equals(e,t){return Q.w.util.equals(eY,e,t)}constructor(e){super(),this.clientId="",Q.w.util.initPartial(e,this)}}eY.runtime=Q.w,eY.typeName="yorkie.v1.ActivateClientResponse",eY.fields=Q.w.util.newFieldList(()=>[{no:1,name:"client_id",kind:"scalar",T:9}]);class eZ extends X.v{static fromBinary(e,t){return new eZ().fromBinary(e,t)}static fromJson(e,t){return new eZ().fromJson(e,t)}static fromJsonString(e,t){return new eZ().fromJsonString(e,t)}static equals(e,t){return Q.w.util.equals(eZ,e,t)}constructor(e){super(),this.clientId="",Q.w.util.initPartial(e,this)}}eZ.runtime=Q.w,eZ.typeName="yorkie.v1.DeactivateClientRequest",eZ.fields=Q.w.util.newFieldList(()=>[{no:1,name:"client_id",kind:"scalar",T:9}]);class eX extends X.v{static fromBinary(e,t){return new eX().fromBinary(e,t)}static fromJson(e,t){return new eX().fromJson(e,t)}static fromJsonString(e,t){return new eX().fromJsonString(e,t)}static equals(e,t){return Q.w.util.equals(eX,e,t)}constructor(e){super(),Q.w.util.initPartial(e,this)}}eX.runtime=Q.w,eX.typeName="yorkie.v1.DeactivateClientResponse",eX.fields=Q.w.util.newFieldList(()=>[]);class eQ extends X.v{static fromBinary(e,t){return new eQ().fromBinary(e,t)}static fromJson(e,t){return new eQ().fromJson(e,t)}static fromJsonString(e,t){return new eQ().fromJsonString(e,t)}static equals(e,t){return Q.w.util.equals(eQ,e,t)}constructor(e){super(),this.clientId="",Q.w.util.initPartial(e,this)}}eQ.runtime=Q.w,eQ.typeName="yorkie.v1.AttachDocumentRequest",eQ.fields=Q.w.util.newFieldList(()=>[{no:1,name:"client_id",kind:"scalar",T:9},{no:2,name:"change_pack",kind:"message",T:en}]);class e$ extends X.v{static fromBinary(e,t){return new e$().fromBinary(e,t)}static fromJson(e,t){return new e$().fromJson(e,t)}static fromJsonString(e,t){return new e$().fromJsonString(e,t)}static equals(e,t){return Q.w.util.equals(e$,e,t)}constructor(e){super(),this.documentId="",Q.w.util.initPartial(e,this)}}e$.runtime=Q.w,e$.typeName="yorkie.v1.AttachDocumentResponse",e$.fields=Q.w.util.newFieldList(()=>[{no:1,name:"document_id",kind:"scalar",T:9},{no:2,name:"change_pack",kind:"message",T:en}]);class e0 extends X.v{static fromBinary(e,t){return new e0().fromBinary(e,t)}static fromJson(e,t){return new e0().fromJson(e,t)}static fromJsonString(e,t){return new e0().fromJsonString(e,t)}static equals(e,t){return Q.w.util.equals(e0,e,t)}constructor(e){super(),this.clientId="",this.documentId="",this.removeIfNotAttached=!1,Q.w.util.initPartial(e,this)}}e0.runtime=Q.w,e0.typeName="yorkie.v1.DetachDocumentRequest",e0.fields=Q.w.util.newFieldList(()=>[{no:1,name:"client_id",kind:"scalar",T:9},{no:2,name:"document_id",kind:"scalar",T:9},{no:3,name:"change_pack",kind:"message",T:en},{no:4,name:"remove_if_not_attached",kind:"scalar",T:8}]);class e1 extends X.v{static fromBinary(e,t){return new e1().fromBinary(e,t)}static fromJson(e,t){return new e1().fromJson(e,t)}static fromJsonString(e,t){return new e1().fromJsonString(e,t)}static equals(e,t){return Q.w.util.equals(e1,e,t)}constructor(e){super(),Q.w.util.initPartial(e,this)}}e1.runtime=Q.w,e1.typeName="yorkie.v1.DetachDocumentResponse",e1.fields=Q.w.util.newFieldList(()=>[{no:2,name:"change_pack",kind:"message",T:en}]);class e2 extends X.v{static fromBinary(e,t){return new e2().fromBinary(e,t)}static fromJson(e,t){return new e2().fromJson(e,t)}static fromJsonString(e,t){return new e2().fromJsonString(e,t)}static equals(e,t){return Q.w.util.equals(e2,e,t)}constructor(e){super(),this.clientId="",this.documentId="",Q.w.util.initPartial(e,this)}}e2.runtime=Q.w,e2.typeName="yorkie.v1.WatchDocumentRequest",e2.fields=Q.w.util.newFieldList(()=>[{no:1,name:"client_id",kind:"scalar",T:9},{no:2,name:"document_id",kind:"scalar",T:9}]);class e3 extends X.v{static fromBinary(e,t){return new e3().fromBinary(e,t)}static fromJson(e,t){return new e3().fromJson(e,t)}static fromJsonString(e,t){return new e3().fromJsonString(e,t)}static equals(e,t){return Q.w.util.equals(e3,e,t)}constructor(e){super(),this.body={case:void 0},Q.w.util.initPartial(e,this)}}e3.runtime=Q.w,e3.typeName="yorkie.v1.WatchDocumentResponse",e3.fields=Q.w.util.newFieldList(()=>[{no:1,name:"initialization",kind:"message",T:e9,oneof:"body"},{no:2,name:"event",kind:"message",T:eG,oneof:"body"}]);class e9 extends X.v{static fromBinary(e,t){return new e9().fromBinary(e,t)}static fromJson(e,t){return new e9().fromJson(e,t)}static fromJsonString(e,t){return new e9().fromJsonString(e,t)}static equals(e,t){return Q.w.util.equals(e9,e,t)}constructor(e){super(),this.clientIds=[],Q.w.util.initPartial(e,this)}}e9.runtime=Q.w,e9.typeName="yorkie.v1.WatchDocumentResponse.Initialization",e9.fields=Q.w.util.newFieldList(()=>[{no:1,name:"client_ids",kind:"scalar",T:9,repeated:!0}]);class e4 extends X.v{static fromBinary(e,t){return new e4().fromBinary(e,t)}static fromJson(e,t){return new e4().fromJson(e,t)}static fromJsonString(e,t){return new e4().fromJsonString(e,t)}static equals(e,t){return Q.w.util.equals(e4,e,t)}constructor(e){super(),this.clientId="",this.documentId="",Q.w.util.initPartial(e,this)}}e4.runtime=Q.w,e4.typeName="yorkie.v1.RemoveDocumentRequest",e4.fields=Q.w.util.newFieldList(()=>[{no:1,name:"client_id",kind:"scalar",T:9},{no:2,name:"document_id",kind:"scalar",T:9},{no:3,name:"change_pack",kind:"message",T:en}]);class e8 extends X.v{static fromBinary(e,t){return new e8().fromBinary(e,t)}static fromJson(e,t){return new e8().fromJson(e,t)}static fromJsonString(e,t){return new e8().fromJsonString(e,t)}static equals(e,t){return Q.w.util.equals(e8,e,t)}constructor(e){super(),Q.w.util.initPartial(e,this)}}e8.runtime=Q.w,e8.typeName="yorkie.v1.RemoveDocumentResponse",e8.fields=Q.w.util.newFieldList(()=>[{no:1,name:"change_pack",kind:"message",T:en}]);class e5 extends X.v{static fromBinary(e,t){return new e5().fromBinary(e,t)}static fromJson(e,t){return new e5().fromJson(e,t)}static fromJsonString(e,t){return new e5().fromJsonString(e,t)}static equals(e,t){return Q.w.util.equals(e5,e,t)}constructor(e){super(),this.clientId="",this.documentId="",this.pushOnly=!1,Q.w.util.initPartial(e,this)}}e5.runtime=Q.w,e5.typeName="yorkie.v1.PushPullChangesRequest",e5.fields=Q.w.util.newFieldList(()=>[{no:1,name:"client_id",kind:"scalar",T:9},{no:2,name:"document_id",kind:"scalar",T:9},{no:3,name:"change_pack",kind:"message",T:en},{no:4,name:"push_only",kind:"scalar",T:8}]);class e6 extends X.v{static fromBinary(e,t){return new e6().fromBinary(e,t)}static fromJson(e,t){return new e6().fromJson(e,t)}static fromJsonString(e,t){return new e6().fromJsonString(e,t)}static equals(e,t){return Q.w.util.equals(e6,e,t)}constructor(e){super(),Q.w.util.initPartial(e,this)}}e6.runtime=Q.w,e6.typeName="yorkie.v1.PushPullChangesResponse",e6.fields=Q.w.util.newFieldList(()=>[{no:1,name:"change_pack",kind:"message",T:en}]);class e7 extends X.v{static fromBinary(e,t){return new e7().fromBinary(e,t)}static fromJson(e,t){return new e7().fromJson(e,t)}static fromJsonString(e,t){return new e7().fromJsonString(e,t)}static equals(e,t){return Q.w.util.equals(e7,e,t)}constructor(e){super(),this.clientId="",this.documentId="",this.topic="",this.payload=new Uint8Array(0),Q.w.util.initPartial(e,this)}}e7.runtime=Q.w,e7.typeName="yorkie.v1.BroadcastRequest",e7.fields=Q.w.util.newFieldList(()=>[{no:1,name:"client_id",kind:"scalar",T:9},{no:2,name:"document_id",kind:"scalar",T:9},{no:3,name:"topic",kind:"scalar",T:9},{no:4,name:"payload",kind:"scalar",T:12}]);class te extends X.v{static fromBinary(e,t){return new te().fromBinary(e,t)}static fromJson(e,t){return new te().fromJson(e,t)}static fromJsonString(e,t){return new te().fromJsonString(e,t)}static equals(e,t){return Q.w.util.equals(te,e,t)}constructor(e){super(),Q.w.util.initPartial(e,this)}}te.runtime=Q.w,te.typeName="yorkie.v1.BroadcastResponse",te.fields=Q.w.util.newFieldList(()=>[]);var tt=r(6438);let tr={typeName:"yorkie.v1.YorkieService",methods:{activateClient:{name:"ActivateClient",I:eH,O:eY,kind:tt.t.Unary},deactivateClient:{name:"DeactivateClient",I:eZ,O:eX,kind:tt.t.Unary},attachDocument:{name:"AttachDocument",I:eQ,O:e$,kind:tt.t.Unary},detachDocument:{name:"DetachDocument",I:e0,O:e1,kind:tt.t.Unary},removeDocument:{name:"RemoveDocument",I:e4,O:e8,kind:tt.t.Unary},pushPullChanges:{name:"PushPullChanges",I:e5,O:e6,kind:tt.t.Unary},watchDocument:{name:"WatchDocument",I:e2,O:e3,kind:tt.t.ServerStreaming},broadcast:{name:"Broadcast",I:e7,O:te,kind:tt.t.Unary}}};var tn=r(624);(o=x||(x={})).Ok="ok",o.ErrClientNotActivated="ErrClientNotActivated",o.ErrClientNotFound="ErrClientNotFound",o.ErrUnimplemented="ErrUnimplemented",o.ErrInvalidType="ErrInvalidType",o.ErrDummy="ErrDummy",o.ErrDocumentNotAttached="ErrDocumentNotAttached",o.ErrDocumentNotDetached="ErrDocumentNotDetached",o.ErrDocumentRemoved="ErrDocumentRemoved",o.ErrInvalidObjectKey="ErrInvalidObjectKey",o.ErrInvalidArgument="ErrInvalidArgument",o.ErrNotInitialized="ErrNotInitialized",o.ErrNotReady="ErrNotReady",o.ErrRefused="ErrRefused",o.ErrContextNotProvided="ErrContextNotProvided";class ti extends Error{constructor(e,t){super(t),this.code=e,this.message=t,this.name="YorkieError",this.toString=()=>"[code=".concat(this.code,"]: ").concat(this.message)}}function ts(e){if(e instanceof Map){let t=Array.from(e);return new Map(JSON.parse(JSON.stringify(t)))}return JSON.parse(JSON.stringify(e))}let to=e=>!e||0===Object.entries(e).length,ta=e=>{let t={};for(let[r,n]of Object.entries(e))t[r]=JSON.stringify(n);return t},tc=e=>{let t={};for(let[r,n]of Object.entries(e))t[r]=JSON.parse(n);return t};(a=P||(P={})).Put="put",a.Clear="clear";class tl{set(e,t){for(let t of Object.keys(e))this.presence[t]=e[t];this.context.setPresenceChange({type:"put",presence:ts(this.presence)}),this.context.setReversePresence(e,t)}get(e){return this.presence[e]}clear(){this.presence={},this.context.setPresenceChange({type:"clear"})}constructor(e,t){this.context=e,this.presence=t}}let th="000000000000000000000000";class td{static of(e,t,r){return new td(e,t,r)}static fromStruct(e){return td.of(BigInt(e.lamport),e.delimiter,e.actorID)}toIDString(){return"".concat(this.lamport.toString(),":").concat(this.actorID,":").concat(this.delimiter)}toStruct(){return{lamport:this.getLamportAsString(),delimiter:this.getDelimiter(),actorID:this.getActorID()}}toTestString(){return"".concat(this.lamport.toString(),":").concat(this.actorID.slice(-2),":").concat(this.delimiter)}setActor(e){return new td(this.lamport,this.delimiter,e)}getLamportAsString(){return this.lamport.toString()}getLamport(){return this.lamport}getDelimiter(){return this.delimiter}getActorID(){return this.actorID}after(e){return this.compare(e)>0}equals(e){return 0===this.compare(e)}compare(e){if(this.lamport>e.lamport)return 1;if(e.lamport>this.lamport)return -1;let t=this.actorID.localeCompare(e.actorID);return 0!==t?t:this.delimiter>e.delimiter?1:e.delimiter>this.delimiter?-1:0}constructor(e,t,r){this.lamport=e,this.delimiter=t,this.actorID=r}}let tu=new td(0n,0,th),tg=new td(0x7fffffffffffffffn,4294967295,"FFFFFFFFFFFFFFFFFFFFFFFF");function tf(e){return e.replace(/["'\\\n\r\f\b\t\u2028\u2029]/g,function(e){switch(e){case'"':case"\\":return"\\"+e;case"\n":return"\\n";case"\r":return"\\r";case"\f":return"\\f";case"\b":return"\\b";case" ":return"\\t";case"\u2028":return"\\u2028";case"\u2029":return"\\u2029";default:return e}})}class tm{getCreatedAt(){return this.createdAt}getID(){return this.createdAt}getMovedAt(){return this.movedAt}getRemovedAt(){return this.removedAt}getPositionedAt(){return this.movedAt?this.movedAt:this.createdAt}setMovedAt(e){return!!(!this.movedAt||e&&e.after(this.movedAt))&&(this.movedAt=e,!0)}setRemovedAt(e){this.removedAt=e}remove(e){return!!(e&&e.after(this.getPositionedAt())&&(!this.removedAt||e.after(this.removedAt)))&&(this.removedAt=e,!0)}isRemoved(){return!!this.removedAt}constructor(e){this.createdAt=e}}class tp extends tm{constructor(e){super(e)}}class ty{static of(e,t){return new ty(e,t)}isRemoved(){return this.value.isRemoved()}getStrKey(){return this.strKey}getValue(){return this.value}remove(e){return this.value.remove(e)}constructor(e,t){this.strKey=e,this.value=t}}class tv{static create(){return new tv}set(e,t,r){let n;let i=this.nodeMapByKey.get(e);null!=i&&!i.isRemoved()&&i.remove(r)&&(n=i.getValue());let s=ty.of(e,t);return this.nodeMapByCreatedAt.set(t.getCreatedAt().toIDString(),s),(null==i||r.after(i.getValue().getPositionedAt()))&&(this.nodeMapByKey.set(e,s),t.setMovedAt(r)),n}delete(e,t){if(!this.nodeMapByCreatedAt.has(e.toIDString()))throw new ti(x.ErrInvalidArgument,"fail to find ".concat(e.toIDString()));let r=this.nodeMapByCreatedAt.get(e.toIDString());return r.remove(t),r.getValue()}subPathOf(e){let t=this.nodeMapByCreatedAt.get(e.toIDString());if(t)return t.getStrKey()}purge(e){let t=this.nodeMapByCreatedAt.get(e.getCreatedAt().toIDString());if(!t)throw new ti(x.ErrInvalidArgument,"fail to find ".concat(e.getCreatedAt().toIDString()));let r=this.nodeMapByKey.get(t.getStrKey());t===r&&this.nodeMapByKey.delete(r.getStrKey()),this.nodeMapByCreatedAt.delete(t.getValue().getCreatedAt().toIDString())}deleteByKey(e,t){let r=this.nodeMapByKey.get(e);if(null!=r&&r.remove(t))return r.getValue()}has(e){let t=this.nodeMapByKey.get(e);return null!=t&&!t.isRemoved()}getByID(e){return this.nodeMapByCreatedAt.get(e.toIDString())}get(e){let t=this.nodeMapByKey.get(e);if(!(!t||t.isRemoved()))return t}*[Symbol.iterator](){for(let[,e]of this.nodeMapByKey)yield e}constructor(){this.nodeMapByKey=new Map,this.nodeMapByCreatedAt=new Map}}class tw extends tp{static create(e,t){if(!t)return new tw(e,tv.create());let r=tv.create();for(let[e,n]of Object.entries(t))r.set(e,n.deepcopy(),n.getCreatedAt());return new tw(e,r)}subPathOf(e){return this.memberNodes.subPathOf(e)}purge(e){this.memberNodes.purge(e)}set(e,t,r){return this.memberNodes.set(e,t,r)}delete(e,t){return this.memberNodes.delete(e,t)}deleteByKey(e,t){return this.memberNodes.deleteByKey(e,t)}get(e){let t=this.memberNodes.get(e);return null==t?void 0:t.getValue()}getByID(e){let t=this.memberNodes.getByID(e);return null==t?void 0:t.getValue()}has(e){return this.memberNodes.has(e)}toJSON(){let e=[];for(let[t,r]of this)e.push('"'.concat(tf(t),'":').concat(r.toJSON()));return"{".concat(e.join(","),"}")}toJS(){return JSON.parse(this.toJSON())}toJSForTest(){let e={};for(let[t,r]of this){let{createdAt:n,value:i,type:s}=r.toJSForTest();e[t]={key:t,createdAt:n,value:i,type:s}}return{createdAt:this.getCreatedAt().toTestString(),value:e,type:"YORKIE_OBJECT"}}getKeys(){let e=[];for(let[t]of this)e.push(t);return e}toSortedJSON(){let e=[];for(let[t]of this)e.push(t);let t=[];for(let n of e.sort()){var r;let e=null===(r=this.memberNodes.get(n))||void 0===r?void 0:r.getValue();t.push('"'.concat(tf(n),'":').concat(e.toSortedJSON()))}return"{".concat(t.join(","),"}")}getRHT(){return this.memberNodes}deepcopy(){let e=tw.create(this.getCreatedAt());for(let t of this.memberNodes)e.memberNodes.set(t.getStrKey(),t.getValue().deepcopy(),this.getPositionedAt());return e.remove(this.getRemovedAt()),e}getDescendants(e){for(let t of this.memberNodes){let r=t.getValue();if(e(r,this))return;r instanceof tp&&r.getDescendants(e)}}*[Symbol.iterator](){let e=new Set;for(let t of this.memberNodes)e.has(t.getStrKey())||(e.add(t.getStrKey()),t.isRemoved()||(yield[t.getStrKey(),t.getValue()]))}constructor(e,t){super(e),this.memberNodes=t}}(c=E||(E={})).Local="local",c.Remote="remote",c.UndoRedo="undoredo";class tA{getParentCreatedAt(){return this.parentCreatedAt}getExecutedAt(){if(!this.executedAt)throw new ti(x.ErrNotReady,"executedAt is not set yet");return this.executedAt}setActor(e){this.executedAt&&(this.executedAt=this.executedAt.setActor(e))}setExecutedAt(e){this.executedAt=e}constructor(e,t){this.parentCreatedAt=e,this.executedAt=t}}class tT{getNodeString(){return"".concat(this.weight).concat(this.value)}getValue(){return this.value}getLeftWeight(){return this.hasLeft()?this.left.getWeight():0}getRightWeight(){return this.hasRight()?this.right.getWeight():0}getWeight(){return this.weight}getLeft(){return this.left}getRight(){return this.right}getParent(){return this.parent}hasLeft(){return!!this.left}hasRight(){return!!this.right}hasParent(){return!!this.parent}setLeft(e){this.left=e}setRight(e){this.right=e}setParent(e){this.parent=e}unlink(){this.parent=void 0,this.right=void 0,this.left=void 0}hasLinks(){return this.hasParent()||this.hasLeft()||this.hasRight()}increaseWeight(e){this.weight+=e}initWeight(){this.weight=this.getLength()}constructor(e){this.value=e,this.initWeight()}}class tS{get length(){return this.root?this.root.getWeight():0}find(e){if(!this.root||e<0)return[void 0,0];let t=this.root;for(;;)if(t.hasLeft()&&e<=t.getLeftWeight())t=t.getLeft();else if(t.hasRight()&&t.getLeftWeight()+t.getLength()t.getLength())throw new ti(x.ErrInvalidArgument,"out of index range: pos: ".concat(e," > node.length: ").concat(t.getLength()));return this.splayNode(t),[t,e]}indexOf(e){return e&&(e===this.root||e.hasLinks())?(this.splayNode(e),this.root.getLeftWeight()):-1}getRoot(){return this.root}insert(e){return this.insertAfter(this.root,e)}insertAfter(e,t){return e?(this.splayNode(e),this.root=t,t.setRight(e.getRight()),e.hasRight()&&e.getRight().setParent(t),t.setLeft(e),e.setParent(t),e.setRight(),this.updateWeight(e),this.updateWeight(t)):this.root=t,t}updateWeight(e){e.initWeight(),e.hasLeft()&&e.increaseWeight(e.getLeftWeight()),e.hasRight()&&e.increaseWeight(e.getRightWeight())}updateTreeWeight(e){for(;e;)this.updateWeight(e),e=e.getParent()}splayNode(e){if(e)for(;;)if(this.isLeftChild(e.getParent())&&this.isRightChild(e))this.rotateLeft(e),this.rotateRight(e);else if(this.isRightChild(e.getParent())&&this.isLeftChild(e))this.rotateRight(e),this.rotateLeft(e);else if(this.isLeftChild(e.getParent())&&this.isLeftChild(e))this.rotateRight(e.getParent()),this.rotateRight(e);else if(this.isRightChild(e.getParent())&&this.isRightChild(e))this.rotateLeft(e.getParent()),this.rotateLeft(e);else{this.isLeftChild(e)?this.rotateRight(e):this.isRightChild(e)&&this.rotateLeft(e),this.updateWeight(e);return}}delete(e){this.splayNode(e);let t=new tS(e.getLeft());t.root&&t.root.setParent();let r=new tS(e.getRight());if(r.root&&r.root.setParent(),t.root){let e=t.getRightmost();t.splayNode(e),t.root.setRight(r.root),r.root&&r.root.setParent(t.root),this.root=t.root}else this.root=r.root;e.unlink(),this.root&&this.updateWeight(this.root)}deleteRange(e,t){if(!t){this.splayNode(e),this.cutOffRight(e);return}this.splayNode(e),this.splayNode(t),t.getLeft()!=e&&this.rotateRight(e),this.cutOffRight(e)}cutOffRight(e){let t=[];for(let r of(this.traversePostorder(e.getRight(),t),t))r.initWeight();this.updateTreeWeight(e)}toTestString(){let e=[];return this.traverseInorder(this.root,e),e.map(e=>"[".concat(e.getWeight(),",").concat(e.getLength(),"]").concat(e.getValue()||"")).join("")}checkWeight(){let e=[];for(let t of(this.traverseInorder(this.root,e),e))if(t.getWeight()!=t.getLength()+t.getLeftWeight()+t.getRightWeight())return!1;return!0}getRightmost(){let e=this.root;for(;e.hasRight();)e=e.getRight();return e}traverseInorder(e,t){e&&(this.traverseInorder(e.getLeft(),t),t.push(e),this.traverseInorder(e.getRight(),t))}traversePostorder(e,t){e&&(this.traversePostorder(e.getLeft(),t),this.traversePostorder(e.getRight(),t),t.push(e))}rotateLeft(e){let t=e.getParent();t.hasParent()?t===t.getParent().getLeft()?t.getParent().setLeft(e):t.getParent().setRight(e):this.root=e,e.setParent(t.getParent()),t.setRight(e.getLeft()),t.hasRight()&&t.getRight().setParent(t),e.setLeft(t),e.getLeft().setParent(e),this.updateWeight(t),this.updateWeight(e)}rotateRight(e){let t=e.getParent();t.hasParent()?t===t.getParent().getLeft()?t.getParent().setLeft(e):t.getParent().setRight(e):this.root=e,e.setParent(t.getParent()),t.setLeft(e.getRight()),t.hasLeft()&&t.getLeft().setParent(t),e.setRight(t),e.getRight().setParent(e),this.updateWeight(t),this.updateWeight(e)}isLeftChild(e){return!!(e&&e.hasParent())&&e.getParent().getLeft()===e}isRightChild(e){return!!(e&&e.hasParent())&&e.getParent().getRight()===e}constructor(e){this.root=e}}var tI=r(7319);(l=b||(b={}))[l.Null=0]="Null",l[l.Boolean=1]="Boolean",l[l.Integer=2]="Integer",l[l.Long=3]="Long",l[l.Double=4]="Double",l[l.String=5]="String",l[l.Bytes=6]="Bytes",l[l.Date=7]="Date";class tC extends tm{static of(e,t){return new tC(e,t)}static valueFromBytes(e,t){switch(e){case 0:return null;case 1:return!!t[0];case 2:return t[0]|t[1]<<8|t[2]<<16|t[3]<<24;case 4:{let e=new DataView(t.buffer);return t.forEach(function(t,r){e.setUint8(r,t)}),e.getFloat64(0,!0)}case 5:return new TextDecoder("utf-8").decode(t);case 3:return tI.Z.fromBytesLE(Array.from(t));case 6:return t;case 7:return new Date(tI.Z.fromBytesLE(Array.from(t),!0).toNumber());default:throw new ti(x.ErrUnimplemented,"unimplemented type: ".concat(e))}}toJSON(){return 5===this.valueType?'"'.concat(tf(this.value),'"'):"".concat(this.value)}toSortedJSON(){return this.toJSON()}toJSForTest(){return{createdAt:this.getCreatedAt().toTestString(),value:this.value,type:"YORKIE_PRIMITIVE"}}deepcopy(){let e=tC.of(this.value,this.getCreatedAt());return e.setMovedAt(this.getMovedAt()),e.setRemovedAt(this.getRemovedAt()),e}getType(){return this.valueType}static getPrimitiveType(e){switch(typeof e){case"undefined":return 0;case"boolean":return 1;case"number":if(this.isInteger(e))return 2;return 4;case"string":return 5;case"object":if(null===e)return 0;if(e instanceof tI.Z)return 3;if(e instanceof Uint8Array)return 6;if(e instanceof Date)return 7}}static isSupport(e){return void 0!==tC.getPrimitiveType(e)}static isInteger(e){return e%1==0}isNumericType(){let e=this.valueType;return 2===e||3===e||4===e}getValue(){return this.value}toBytes(){switch(this.valueType){case 0:return new Uint8Array;case 1:{let e=this.value;return new Uint8Array(e?[1]:[0])}case 2:{let e=this.value;return new Uint8Array([255&e,e>>8&255,e>>16&255,e>>24&255])}case 4:{let e=this.value,t=new Uint8Array(8);return new DataView(t.buffer).setFloat64(0,e,!0),t}case 5:return new TextEncoder().encode(this.value);case 3:{let e=this.value.toBytesLE();return Uint8Array.from(e)}case 6:return this.value;case 7:{let e=this.value,t=tI.Z.fromNumber(e.getTime(),!0).toBytesLE();return Uint8Array.from(t)}default:throw new ti(x.ErrUnimplemented,"unimplemented type: ".concat(this.valueType))}}constructor(e,t){super(t),this.valueType=tC.getPrimitiveType(e),this.value=void 0===e?null:e}}class tx extends tT{static createAfter(e,t){let r=new tx(t),n=e.next;return e.next=r,r.prev=e,r.next=n,n&&(n.prev=r),r}remove(e){return this.value.remove(e)}getCreatedAt(){return this.value.getCreatedAt()}getPositionedAt(){return this.value.getPositionedAt()}release(){this.prev&&(this.prev.next=this.next),this.next&&(this.next.prev=this.prev),this.prev=void 0,this.next=void 0}getLength(){return this.value.isRemoved()?0:1}getPrev(){return this.prev}getNext(){return this.next}getValue(){return this.value}isRemoved(){return this.value.isRemoved()}constructor(e){super(e),this.value=e}}class tP{static create(){return new tP}get length(){return this.nodeMapByIndex.length}findNextBeforeExecutedAt(e,t){let r=this.nodeMapByCreatedAt.get(e.toIDString());if(!r)throw new ti(x.ErrInvalidArgument,"cant find the given node: ".concat(e.toIDString()));for(;r.getNext()&&r.getNext().getPositionedAt().after(t);)r=r.getNext();return r}release(e){this.last===e&&(this.last=e.getPrev()),e.release(),this.nodeMapByIndex.delete(e),this.nodeMapByCreatedAt.delete(e.getValue().getCreatedAt().toIDString())}insertAfter(e,t){let r=arguments.length>2&&void 0!==arguments[2]?arguments[2]:t.getCreatedAt(),n=this.findNextBeforeExecutedAt(e,r),i=tx.createAfter(n,t);n===this.last&&(this.last=i),this.nodeMapByIndex.insertAfter(n,i),this.nodeMapByCreatedAt.set(i.getCreatedAt().toIDString(),i)}moveAfter(e,t,r){let n=this.nodeMapByCreatedAt.get(e.toIDString());if(!n)throw new ti(x.ErrInvalidArgument,"cant find the given node: ".concat(e.toIDString()));let i=this.nodeMapByCreatedAt.get(t.toIDString());if(!i)throw new ti(x.ErrInvalidArgument,"cant find the given node: ".concat(t.toIDString()));n!==i&&(!i.getValue().getMovedAt()||r.after(i.getValue().getMovedAt()))&&(this.release(i),this.insertAfter(n.getCreatedAt(),i.getValue(),r),i.getValue().setMovedAt(r))}insert(e){this.insertAfter(this.last.getCreatedAt(),e)}getByID(e){return this.nodeMapByCreatedAt.get(e.toIDString())}subPathOf(e){let t=this.nodeMapByCreatedAt.get(e.toIDString());if(t)return String(this.nodeMapByIndex.indexOf(t))}purge(e){let t=this.nodeMapByCreatedAt.get(e.getCreatedAt().toIDString());if(!t)throw new ti(x.ErrInvalidArgument,"fail to find the given createdAt: ".concat(e.getCreatedAt().toIDString()));this.release(t)}getByIndex(e){if(e>=this.length)return;let[t,r]=this.nodeMapByIndex.find(e),n=t;if(0===e&&t===this.dummyHead||r>0)do n&&(n=n.getNext());while(n&&n.isRemoved());return n}getPrevCreatedAt(e){let t=this.nodeMapByCreatedAt.get(e.toIDString());do t=t.getPrev();while(this.dummyHead!==t&&t.isRemoved());return t.getValue().getCreatedAt()}delete(e,t){let r=this.nodeMapByCreatedAt.get(e.toIDString()),n=r.isRemoved();return r.remove(t)&&!n&&this.nodeMapByIndex.splayNode(r),r.getValue()}deleteByIndex(e,t){let r=this.getByIndex(e);if(r)return r.remove(t)&&this.nodeMapByIndex.splayNode(r),r.getValue()}getHead(){return this.dummyHead.getValue()}getLast(){return this.last.getValue()}getLastCreatedAt(){return this.last.getCreatedAt()}toTestString(){let e=[];for(let t of this){let r="".concat(t.getCreatedAt().toIDString(),":").concat(t.getValue().toJSON());t.isRemoved()?e.push("{".concat(r,"}")):e.push("[".concat(r,"]"))}return e.join("")}*[Symbol.iterator](){let e=this.dummyHead.getNext();for(;e;)yield e,e=e.getNext()}constructor(){let e=tC.of(0,tu);e.setRemovedAt(tu),this.dummyHead=new tx(e),this.last=this.dummyHead,this.nodeMapByIndex=new tS,this.nodeMapByCreatedAt=new Map,this.nodeMapByIndex.insert(this.dummyHead),this.nodeMapByCreatedAt.set(this.dummyHead.getCreatedAt().toIDString(),this.dummyHead)}}class tE extends tp{static create(e,t){if(!t)return new tE(e,tP.create());let r=tP.create();for(let e of t)r.insertAfter(r.getLastCreatedAt(),e.deepcopy());return new tE(e,r)}subPathOf(e){return this.elements.subPathOf(e)}purge(e){this.elements.purge(e)}insertAfter(e,t){this.elements.insertAfter(e,t)}moveAfter(e,t,r){this.elements.moveAfter(e,t,r)}get(e){let t=this.elements.getByIndex(e);return null==t?void 0:t.getValue()}getByID(e){let t=this.elements.getByID(e);return null==t?void 0:t.getValue()}getHead(){return this.elements.getHead()}getLast(){return this.elements.getLast()}getPrevCreatedAt(e){return this.elements.getPrevCreatedAt(e)}delete(e,t){return this.elements.delete(e,t)}deleteByIndex(e,t){return this.elements.deleteByIndex(e,t)}getLastCreatedAt(){return this.elements.getLastCreatedAt()}get length(){return this.elements.length}*[Symbol.iterator](){for(let e of this.elements)e.isRemoved()||(yield e.getValue())}toTestString(){return this.elements.toTestString()}getDescendants(e){for(let t of this.elements){let r=t.getValue();if(e(r,this))return;r instanceof tp&&r.getDescendants(e)}}toJSON(){let e=[];for(let t of this)e.push(t.toJSON());return"[".concat(e.join(","),"]")}toJS(){return JSON.parse(this.toJSON())}toJSForTest(){let e={};for(let t=0;t({...e,value:e.value?{attributes:tc(e.value.getAttributes()),content:e.value.getContent()}:{attributes:void 0,content:""},type:"content"})),c,[o,o]]}setStyle(e,t,r,n){let[,i]=this.rgaTreeSplit.findNodeWithSplit(e[1],r),[,s]=this.rgaTreeSplit.findNodeWithSplit(e[0],r),o=[],a=this.rgaTreeSplit.findBetween(s,i),c=new Map,l=[];for(let e of a){let t=e.getCreatedAt().getActorID(),i=(null==n?void 0:n.size)?n.has(t)?n.get(t):tu:tg;if(e.canStyle(r,i)){let r=c.get(t),n=e.getCreatedAt();(!r||n.after(r))&&c.set(t,n),l.push(e)}}let h=[];for(let e of l){if(e.isRemoved())continue;let[n,i]=this.rgaTreeSplit.findIndexesFromRange(e.createPosRange());for(let[s,a]of(o.push({type:"style",actor:r.getActorID(),from:n,to:i,value:{attributes:tc(t)}}),Object.entries(t))){let[t]=e.getValue().setAttr(s,a,r);void 0!==t&&h.push({parent:e.getValue(),child:t})}}return[c,h,o]}indexRangeToPosRange(e,t){let r=this.rgaTreeSplit.indexToPos(e);return e===t?[r,r]:[r,this.rgaTreeSplit.indexToPos(t)]}get length(){return this.rgaTreeSplit.length}getTreeByIndex(){return this.rgaTreeSplit.getTreeByIndex()}getTreeByID(){return this.rgaTreeSplit.getTreeByID()}toJSON(){let e=[];for(let t of this.rgaTreeSplit)t.isRemoved()||e.push(t.getValue().toJSON());return"[".concat(e.join(","),"]")}toSortedJSON(){return this.toJSON()}toJSForTest(){return{createdAt:this.getCreatedAt().toTestString(),value:JSON.parse(this.toJSON()),type:"YORKIE_TEXT"}}toString(){return this.rgaTreeSplit.toString()}values(){let e=[];for(let t of this.rgaTreeSplit)if(!t.isRemoved()){let r=t.getValue();e.push({attributes:tc(r.getAttributes()),content:r.getContent()})}return e}getRGATreeSplit(){return this.rgaTreeSplit}toTestString(){return this.rgaTreeSplit.toTestString()}deepcopy(){let e=new tJ(this.rgaTreeSplit.deepcopy(),this.getCreatedAt());return e.remove(this.getRemovedAt()),e}findIndexesFromRange(e){return this.rgaTreeSplit.findIndexesFromRange(e)}getGCPairs(){let e=[];for(let t of this.rgaTreeSplit)for(let r of(t.getRemovedAt()&&e.push({parent:this.rgaTreeSplit,child:t}),t.getValue().getGCPairs()))e.push(r);return e}constructor(e,t){super(t),this.rgaTreeSplit=e}}class tL extends tA{static create(e,t,r,n,i,s,o){return new tL(e,t,r,n,i,s,o)}execute(e){let t=e.findByCreatedAt(this.getParentCreatedAt());if(!t)throw new ti(x.ErrInvalidArgument,"fail to find ".concat(this.getParentCreatedAt()));if(!(t instanceof tJ))throw new ti(x.ErrInvalidArgument,"fail to execute, only Text can execute edit");let[,r,n]=t.edit([this.fromPos,this.toPos],this.content,this.getExecutedAt(),Object.fromEntries(this.attributes),this.maxCreatedAtMapByActor);for(let t of n)e.registerGCPair(t);return{opInfos:r.map(t=>{let{from:r,to:n,value:i}=t;return{type:"edit",from:r,to:n,value:i,path:e.createPath(this.getParentCreatedAt())}})}}getEffectedCreatedAt(){return this.getParentCreatedAt()}toTestString(){let e=this.getParentCreatedAt().toTestString(),t=this.fromPos.toTestString(),r=this.toPos.toTestString(),n=this.content;return"".concat(e,".EDIT(").concat(t,",").concat(r,",").concat(n,")")}getFromPos(){return this.fromPos}getToPos(){return this.toPos}getContent(){return this.content}getAttributes(){return this.attributes||new Map}getMaxCreatedAtMapByActor(){return this.maxCreatedAtMapByActor}constructor(e,t,r,n,i,s,o){super(e,o),this.fromPos=t,this.toPos=r,this.maxCreatedAtMapByActor=n,this.content=i,this.attributes=s}}class t_ extends tA{static create(e,t,r,n,i,s){return new t_(e,t,r,n,i,s)}execute(e){let t=e.findByCreatedAt(this.getParentCreatedAt());if(!t)throw new ti(x.ErrInvalidArgument,"fail to find ".concat(this.getParentCreatedAt()));if(!(t instanceof tJ))throw new ti(x.ErrInvalidArgument,"fail to execute, only Text can execute edit");let[,r,n]=t.setStyle([this.fromPos,this.toPos],this.attributes?Object.fromEntries(this.attributes):{},this.getExecutedAt(),this.maxCreatedAtMapByActor);for(let t of r)e.registerGCPair(t);return{opInfos:n.map(t=>{let{from:r,to:n,value:i}=t;return{type:"style",from:r,to:n,value:i,path:e.createPath(this.getParentCreatedAt())}})}}getEffectedCreatedAt(){return this.getParentCreatedAt()}toTestString(){let e=this.getParentCreatedAt().toTestString(),t=this.fromPos.toTestString(),r=this.toPos.toTestString(),n=this.attributes;return"".concat(e,".STYL(").concat(t,",").concat(r,",").concat(JSON.stringify(n),")")}getFromPos(){return this.fromPos}getToPos(){return this.toPos}getAttributes(){return this.attributes}getMaxCreatedAtMapByActor(){return this.maxCreatedAtMapByActor}constructor(e,t,r,n,i,s){super(e,s),this.fromPos=t,this.toPos=r,this.maxCreatedAtMapByActor=n,this.attributes=i}}let tM="text";function tq(e,t){let r=0,n=e.children;for(let e=0;e!e.isRemoved)}get allChildren(){return[...this._children]}hasTextChild(){return this.children.length>0&&this.children.every(e=>e.isText)}append(){for(var e=arguments.length,t=Array(e),r=0;re+t.paddedSize,0),r.size=r._children.reduce((e,t)=>e+t.paddedSize,0),r._children))e.parent=r;return r}insertAfterInternal(e,t){if(this.isText)throw new ti(x.ErrRefused,"Text node cannot have children");let r=this._children.indexOf(t);if(-1===r)throw new ti(x.ErrInvalidArgument,"child not found");this.insertAtInternal(e,r+1)}insertAtInternal(e,t){if(this.isText)throw new ti(x.ErrRefused,"Text node cannot have children");this._children.splice(t,0,e),e.parent=this}findOffset(e){if(this.isText)throw new ti(x.ErrRefused,"Text node cannot have children");if(e.isRemoved){let t=this._children.indexOf(e);return this.allChildren.splice(0,t).filter(e=>!e.isRemoved).length}return this.children.indexOf(e)}findBranchOffset(e){if(this.isText)throw new ti(x.ErrRefused,"Text node cannot have children");let t=e;for(;t;){let e=this._children.indexOf(t);if(-1!==e)return e;t=t.parent}return -1}constructor(e,t=[]){if(this.type=e,this.size=0,this._children=t,this.isText&&this._children.length>0)throw new ti(x.ErrRefused,"Text node cannot have children")}}function tK(e,t){let r=arguments.length>2&&void 0!==arguments[2]?arguments[2]:0;for(let n of e._children)tK(n,t,r+1);t(e,r)}(d=D||(D={})).Start="Start",d.End="End",d.Text="Text";class tF{tokensBetween(e,t,r){!function e(t,r,n,i){if(r>n)throw new ti(x.ErrInvalidArgument,"from is greater than to: ".concat(r," > ").concat(n));if(r>t.size)throw new ti(x.ErrInvalidArgument,"from is out of range: ".concat(r," > ").concat(t.size));if(n>t.size)throw new ti(x.ErrInvalidArgument,"to is out of range: ".concat(n," > ").concat(t.size));if(r===n)return;let s=0;for(let o of t.children){if(r-o.paddedSizeo.size;(o.isText||c)&&i([o,o.isText?"Text":"Start"],l),e(o,Math.max(0,t),Math.min(a,o.size),i),l&&i([o,"End"],l)}s+=o.paddedSize}}(this.root,e,t,r)}traverse(e){!function e(t,r){let n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:0;for(let i of t.children)e(i,r,n+1);r(t,n)}(this.root,e,0)}traverseAll(e){tK(this.root,e,0)}findTreePos(e){let t=!(arguments.length>1)||void 0===arguments[1]||arguments[1];return function e(t,r){let n=!(arguments.length>2)||void 0===arguments[2]||arguments[2];if(r>t.size)throw new ti(x.ErrInvalidArgument,"index is out of range: ".concat(r," > ").concat(t.size));if(t.isText)return{node:t,offset:r};let i=0,s=0;for(let o of t.children){if(n&&o.isText&&o.size>=r-s)return e(o,r-s,n);if(r===s)break;if(!n&&o.paddedSize===r-s)return{node:t,offset:i+1};if(o.paddedSize>r-s)return e(o,r-s-1,n);s+=o.paddedSize,i+=1}return{node:t,offset:i}}(this.root,e,t)}treePosToPath(e){let t=[],r=e.node;if(r.isText){let n=r.parent.findOffset(r);if(-1===n)throw new ti(x.ErrInvalidArgument,"invalid treePos");let i=tq(r.parent,n);t.push(i+e.offset),r=r.parent}else if(r.hasTextChild()){let n=tq(r,e.offset);t.push(n)}else t.push(e.offset);for(;r.parent;){let e=r.parent.findOffset(r);if(-1===e)throw new ti(x.ErrInvalidArgument,"invalid treePos");t.push(e),r=r.parent}return t.reverse()}pathToIndex(e){let t=this.pathToTreePos(e);return this.indexOf(t)}pathToTreePos(e){if(!e.length)throw new ti(x.ErrInvalidArgument,"unacceptable path");let t=this.root;for(let r=0;re===t?0:e0){if(!t.right)return t;t.right.parent=t,t=t.right}else if(!(r<0))return t;else if(t.left)t.left.parent=t,t=t.left;else{let e=t.parent,r=t;for(;e&&r===e.left;)r=e,e=e.parent;return e}}}lastEntry(){if(!this.root)return this.root;let e=this.root;for(;e.right;)e=e.right;return e}size(){return this.counter}isEmpty(){return 0===this.counter}getInternal(e,t){for(;t;){let r=this.comparator(e,t.key);if(0===r)return t;r<0?t=t.left:r>0&&(t=t.right)}}putInternal(e,t,r){if(!r)return this.counter+=1,new tU(e,t,!0);let n=this.comparator(e,r.key);return n<0?r.left=this.putInternal(e,t,r.left):n>0?r.right=this.putInternal(e,t,r.right):r.value=t,this.isRed(r.right)&&!this.isRed(r.left)&&(r=this.rotateLeft(r)),this.isRed(r.left)&&this.isRed(r.left.left)&&(r=this.rotateRight(r)),this.isRed(r.left)&&this.isRed(r.right)&&this.flipColors(r),r}removeInternal(e,t){if(0>this.comparator(t,e.key))this.isRed(e.left)||this.isRed(e.left.left)||(e=this.moveRedLeft(e)),e.left=this.removeInternal(e.left,t);else{if(this.isRed(e.left)&&(e=this.rotateRight(e)),0===this.comparator(t,e.key)&&!e.right){this.counter-=1;return}if(this.isRed(e.right)||this.isRed(e.right.left)||(e=this.moveRedRight(e)),0===this.comparator(t,e.key)){this.counter-=1;let t=this.min(e.right);e.value=t.value,e.key=t.key,e.right=this.removeMin(e.right)}else e.right=this.removeInternal(e.right,t)}return this.fixUp(e)}min(e){return e.left?this.min(e.left):e}removeMin(e){if(e.left)return this.isRed(e.left)||this.isRed(e.left.left)||(e=this.moveRedLeft(e)),e.left=this.removeMin(e.left),this.fixUp(e)}fixUp(e){return this.isRed(e.right)&&(e=this.rotateLeft(e)),this.isRed(e.left)&&this.isRed(e.left.left)&&(e=this.rotateRight(e)),this.isRed(e.left)&&this.isRed(e.right)&&this.flipColors(e),e}moveRedLeft(e){return this.flipColors(e),this.isRed(e.right.left)&&(e.right=this.rotateRight(e.right),e=this.rotateLeft(e),this.flipColors(e)),e}moveRedRight(e){return this.flipColors(e),this.isRed(e.left.left)&&(e=this.rotateRight(e),this.flipColors(e)),e}isRed(e){return e&&e.isRed}rotateLeft(e){let t=e.right;return e.right=t.left,t.left=e,t.isRed=t.left.isRed,t.left.isRed=!0,t}rotateRight(e){let t=e.left;return e.left=t.right,t.right=e,t.isRed=t.right.isRed,t.right.isRed=!0,t}flipColors(e){e.isRed=!e.isRed,e.left.isRed=!e.left.isRed,e.right.isRed=!e.right.isRed}constructor(e){this.comparator=void 0!==e?e:tV,this.counter=0}}(u=R||(R={})).Content="content",u.Style="style",u.RemoveStyle="removeStyle";class tG{static of(e,t){return new tG(e,t)}static fromTreePos(e){let t;let{offset:r}=e,{node:n}=e;return n.isText?(t=n.parent.children[0]===n&&0===r?n.parent:n,n=n.parent):t=0===r?n:n.children[r-1],tG.of(n.id,tH.of(t.getCreatedAt(),t.getOffset()+r))}getParentID(){return this.parentID}static fromStruct(e){return tG.of(tH.of(td.fromStruct(e.parentID.createdAt),e.parentID.offset),tH.of(td.fromStruct(e.leftSiblingID.createdAt),e.leftSiblingID.offset))}toStruct(){return{parentID:{createdAt:this.getParentID().getCreatedAt().toStruct(),offset:this.getParentID().getOffset()},leftSiblingID:{createdAt:this.getLeftSiblingID().getCreatedAt().toStruct(),offset:this.getLeftSiblingID().getOffset()}}}toTreeNodePair(e){let t=this.getParentID(),r=this.getLeftSiblingID(),n=e.findFloorNode(t),i=e.findFloorNode(r);if(!n||!i)throw new ti(x.ErrRefused,"cannot find node of CRDTTreePos(".concat(t.toTestString(),", ").concat(r.toTestString(),")"));return!r.equals(t)&&r.getOffset()>0&&r.getOffset()===i.id.getOffset()&&i.insPrevID&&(i=e.findFloorNode(i.insPrevID)),[n,i]}getLeftSiblingID(){return this.leftSiblingID}equals(e){return this.getParentID().getCreatedAt().equals(e.getParentID().getCreatedAt())&&this.getParentID().getOffset()===e.getParentID().getOffset()&&this.getLeftSiblingID().getCreatedAt().equals(e.getLeftSiblingID().getCreatedAt())&&this.getLeftSiblingID().getOffset()===e.getLeftSiblingID().getOffset()}constructor(e,t){this.parentID=e,this.leftSiblingID=t}}class tH{static of(e,t){return new tH(e,t)}static fromStruct(e){return tH.of(td.fromStruct(e.createdAt),e.offset)}static createComparator(){return(e,t)=>{let r=e.getCreatedAt().compare(t.getCreatedAt());return 0!==r?r:e.getOffset()>t.getOffset()?1:e.getOffset(){let r=e.deepcopy();return r.parent=t,r}),t.insPrevID=this.insPrevID,t.insNextID=this.insNextID,t}get value(){if(!this.isText)throw new ti(x.ErrInvalidType,"cannot get value of element node: ".concat(this.type));return this._value}set value(e){if(!this.isText)throw new ti(x.ErrInvalidType,"cannot set value of element node: ".concat(this.type));this._value=e,this.size=e.length}get isRemoved(){return!!this.removedAt}remove(e){let t=!this.removedAt;(!this.removedAt||this.removedAt.compare(e)>0)&&(this.removedAt=e),t&&this.updateAncestorsSize()}cloneText(e){return new tY(tH.of(this.id.getCreatedAt(),e),this.type,void 0,void 0,this.removedAt)}cloneElement(e){return new tY(tH.of(e(),0),this.type,void 0,void 0,this.removedAt)}split(e,t,r){let n=this.isText?this.splitText(t,this.id.getOffset()):this.splitElement(t,r);return n&&(n.insPrevID=this.id,this.insNextID&&(e.findFloorNode(this.insNextID).insPrevID=n.id,n.insNextID=this.insNextID),this.insNextID=n.id,e.registerNode(n)),n}getCreatedAt(){return this.id.getCreatedAt()}getOffset(){return this.id.getOffset()}canDelete(e,t){return!this.getCreatedAt().after(t)&&(!this.removedAt||e.after(this.removedAt))}canStyle(e,t){return!this.isText&&!this.getCreatedAt().after(t)&&(!this.removedAt||e.after(this.removedAt))}setAttrs(e,t){this.attrs||(this.attrs=new tO);let r=[];for(let[n,i]of Object.entries(e))r.push(this.attrs.set(n,i,t));return r}purge(e){this.attrs&&this.attrs.purge(e)}getGCPairs(){let e=[];if(!this.attrs)return e;for(let t of this.attrs)t.getRemovedAt()&&e.push({parent:this,child:t});return e}constructor(e,t,r,n,i){super(t),this._value="",this.id=e,this.removedAt=i,n&&(this.attrs=n),"string"==typeof r?this.value=r:Array.isArray(r)&&(this._children=r)}}function tZ(e){if(e.isText)return{type:e.type,value:e.value};let t={type:e.type,children:e.children.map(tZ)};if(e.attrs){var r;t.attributes=tc(null===(r=e.attrs)||void 0===r?void 0:r.toObject())}return t}function tX(e){if(e.isText)return e.value;let t="";return e.attrs&&e.attrs.size()&&(t=" "+Array.from(e.attrs).filter(e=>!e.isRemoved()).sort((e,t)=>e.getKey().localeCompare(t.getKey())).map(e=>{let t=JSON.parse(e.getValue());return"string"==typeof t?"".concat(e.getKey(),'="').concat(t,'"'):"".concat(e.getKey(),'="').concat(tf(e.getValue()),'"')}).join(" ")),"<".concat(e.type).concat(t,">").concat(e.children.map(e=>tX(e)).join(""),"")}class tQ extends tm{static create(e,t){return new tQ(e,t)}findFloorNode(e){let t=this.nodeMapByID.floorEntry(e);if(t&&t.key.getCreatedAt().equals(e.getCreatedAt()))return t.value}registerNode(e){this.nodeMapByID.put(e.id,e)}findNodesAndSplitText(e,t){let[r,n]=e.toTreeNodePair(this),i=n,s=r===i,o=i.parent&&!s?i.parent:r;if(i.isText&&i.split(this,e.getLeftSiblingID().getOffset()-i.id.getOffset()),t){let e=o.allChildren,r=s?0:e.indexOf(i)+1;for(let n=r;n{let[i]=e,s=i.getCreatedAt().getActorID(),o=n?n.has(s)?n.get(s):tu:tg;if(i.canStyle(r,o)&&t){let e=h.get(s),n=i.getCreatedAt();(!e||n.after(e))&&h.set(s,n);let o=i.setAttrs(t,r),a=o.reduce((e,t)=>{let[,r]=t;return r&&(e[r.getKey()]=l[r.getKey()]),e},{}),u=i.parent,g=i.prevSibling||i.parent;for(let[e]of(Object.keys(a).length>0&&c.push({type:"style",from:this.toIndex(u,g),to:this.toIndex(i,i),fromPath:this.toPath(u,g),toPath:this.toPath(i,i),actor:r.getActorID(),value:a}),o))e&&d.push({parent:i,child:e})}}),[h,d,c]}removeStyle(e,t,r,n){let[i,s]=this.findNodesAndSplitText(e[0],r),[o,a]=this.findNodesAndSplitText(e[1],r),c=[],l=new Map,h=[];return this.traverseInPosRange(i,s,o,a,e=>{let[i]=e,s=i.getCreatedAt().getActorID(),o=n?n.has(s)?n.get(s):tu:tg;if(i.canStyle(r,o)&&t){let e=l.get(s),n=i.getCreatedAt();for(let o of((!e||n.after(e))&&l.set(s,n),i.attrs||(i.attrs=new tO),t))for(let e of i.attrs.remove(o,r))h.push({parent:i,child:e});let o=i.parent,a=i.prevSibling||i.parent;c.push({actor:r.getActorID(),type:"removeStyle",from:this.toIndex(o,a),to:this.toIndex(i,i),fromPath:this.toPath(o,a),toPath:this.toPath(i,i),value:t})}}),[l,h,c]}edit(e,t,r,n,i,s){let[o,a]=this.findNodesAndSplitText(e[0],n),[c,l]=this.findNodesAndSplitText(e[1],n),h=this.toIndex(o,a),d=this.toPath(o,a),u=[],g=[],f=[],m=new Map;this.traverseInPosRange(o,a,c,l,(e,t)=>{let[r,i]=e;if(i===D.Start&&!t)for(let e of r.children)f.push(e);let o=r.getCreatedAt().getActorID(),a=s?s.has(o)?s.get(o):tu:tg;if(r.canDelete(n,a)||u.includes(r.parent)){let e=m.get(o),t=r.getCreatedAt();(!e||t.after(e))&&m.set(o,t),(i===D.Text||i===D.Start)&&u.push(r),g.push([r,i])}});let p=this.makeDeletionChanges(g,n),y=[];for(let e of u)e.remove(n),e.isRemoved&&y.push({parent:this,child:e});for(let e of f)e.removedAt||o.append(e);if(r>0){let e=0,t=o,s=a;for(;e{o.isRemoved&&(e.remove(n),y.push({parent:this,child:e})),this.nodeMapByID.put(e.id,e)}),i.isRemoved||e.push(i);if(e.length){let t=e.map(e=>tZ(e));p.length&&p[p.length-1].from===h?p[p.length-1].value=t:p.push({type:"content",from:h,to:h,fromPath:d,toPath:d,actor:n.getActorID(),value:t})}}return[p,y,m]}editT(e,t,r,n,i){let s=this.findPos(e[0]),o=this.findPos(e[1]);this.edit([s,o],t,r,n,i)}move(e,t,r){throw new ti(x.ErrUnimplemented,"not implemented: ".concat(e,", ").concat(t,", ").concat(r))}purge(e){var t;null===(t=e.parent)||void 0===t||t.removeChild(e),this.nodeMapByID.remove(e.id);let r=e.insPrevID,n=e.insNextID;r&&(this.findFloorNode(r).insNextID=n),n&&(this.findFloorNode(n).insPrevID=r),e.insPrevID=void 0,e.insNextID=void 0}getGCPairs(){let e=[];return this.indexTree.traverse(t=>{for(let r of(t.getRemovedAt()&&e.push({parent:this,child:t}),t.getGCPairs()))e.push(r)}),e}findPos(e){let t=!(arguments.length>1)||void 0===arguments[1]||arguments[1],r=this.indexTree.findTreePos(e,t);return tG.fromTreePos(r)}pathToPosRange(e){let t=this.pathToIndex(e);return[this.findPos(t),this.findPos(t+1)]}pathToPos(e){let t=this.indexTree.pathToIndex(e);return this.findPos(t)}getRoot(){return this.indexTree.getRoot()}getSize(){return this.indexTree.size}getNodeSize(){return this.nodeMapByID.size()}getIndexTree(){return this.indexTree}toXML(){return tX(this.indexTree.getRoot())}toJSON(){return JSON.stringify(this.getRootTreeNode())}toJSForTest(){return{createdAt:this.getCreatedAt().toTestString(),value:JSON.parse(this.toJSON()),type:"YORKIE_TREE"}}toJSInfoForTest(){var e=this;let t=this.indexTree.getRoot(),r=function(t){var n,i,s,o;let a,c,l,h=arguments.length>1&&void 0!==arguments[1]?arguments[1]:void 0,d=arguments.length>2&&void 0!==arguments[2]?arguments[2]:void 0,u=arguments.length>3&&void 0!==arguments[3]?arguments[3]:0,g=t.isText?{node:t,offset:0}:h&&d?e.toTreePos(h,d):null;g&&(a=e.indexTree.indexOf(g),c=e.indexTree.treePosToPath(g),l=tG.fromTreePos(g).toStruct());let f={type:t.type,parent:null==h?void 0:h.id.toTestString(),size:t.size,id:t.id.toTestString(),removedAt:null===(n=t.removedAt)||void 0===n?void 0:n.toTestString(),insPrev:null===(i=t.insPrevID)||void 0===i?void 0:i.toTestString(),insNext:null===(s=t.insNextID)||void 0===s?void 0:s.toTestString(),value:t.isText?t.value:void 0,isRemoved:t.isRemoved,children:[],depth:u,attributes:t.attrs?tc(null===(o=t.attrs)||void 0===o?void 0:o.toObject()):void 0,index:a,path:c,pos:l};for(let e=0;e0&&d===r[r.length-1].to?(r[r.length-1].to=u,r[r.length-1].toPath=this.toPath(h,a)):r.push({type:"content",from:d,to:u,fromPath:this.toPath(l,s),toPath:this.toPath(h,a),actor:t.getActorID()}))}return r.reverse()}findRightToken(e){let[t,r]=e;if(r===D.Start){let e=t.allChildren;return e.length>0?[e[0],e[0].isText?D.Text:D.Start]:[t,D.End]}let n=t.parent,i=n.allChildren,s=i.indexOf(t);if(n&&s===i.length-1)return[n,D.End];let o=i[s+1];return[o,o.isText?D.Text:D.Start]}findLeftToken(e){let[t,r]=e;if(r===D.End){let e=t.allChildren;if(e.length>0){let t=e[e.length-1];return[t,t.isText?D.Text:D.End]}return[t,D.Start]}let n=t.parent,i=n.allChildren,s=i.indexOf(t);if(n&&0===s)return[n,D.Start];let o=i[s-1];return[o,o.isText?D.Text:D.End]}constructor(e,t){super(t),this.indexTree=new tF(e),this.nodeMapByID=new tW(tH.createComparator()),this.indexTree.traverseAll(e=>{this.nodeMapByID.put(e.id,e)})}}class t$ extends tA{static create(e,t,r,n,i,s,o){return new t$(e,t,r,n,i,s,o)}execute(e){var t;let r=e.findByCreatedAt(this.getParentCreatedAt());if(!r)throw new ti(x.ErrInvalidArgument,"fail to find ".concat(this.getParentCreatedAt()));if(!(r instanceof tQ))throw new ti(x.ErrInvalidArgument,"fail to execute, only Tree can execute edit");let n=this.getExecutedAt(),[i,s]=r.edit([this.fromPos,this.toPos],null===(t=this.contents)||void 0===t?void 0:t.map(e=>e.deepcopy()),this.splitLevel,n,(()=>{let e=n.getDelimiter();return void 0!==this.contents&&(e+=this.contents.length),()=>td.of(n.getLamport(),++e,n.getActorID())})(),this.maxCreatedAtMapByActor);for(let t of s)e.registerGCPair(t);return{opInfos:i.map(t=>{let{from:r,to:n,value:i,splitLevel:s,fromPath:o,toPath:a}=t;return{type:"tree-edit",path:e.createPath(this.getParentCreatedAt()),from:r,to:n,value:i,splitLevel:s,fromPath:o,toPath:a}})}}getEffectedCreatedAt(){return this.getParentCreatedAt()}toTestString(){let e=this.getParentCreatedAt().toTestString(),t="".concat(this.fromPos.getLeftSiblingID().getCreatedAt().toTestString(),"/").concat(this.fromPos.getLeftSiblingID().getOffset()),r="".concat(this.toPos.getLeftSiblingID().getCreatedAt().toTestString(),"/").concat(this.toPos.getLeftSiblingID().getOffset()),n=this.contents||[];return"".concat(e,".EDIT(").concat(t,",").concat(r,",").concat(n.map(e=>tX(e)).join(""),")")}getFromPos(){return this.fromPos}getToPos(){return this.toPos}getContents(){return this.contents}getSplitLevel(){return this.splitLevel}getMaxCreatedAtMapByActor(){return this.maxCreatedAtMapByActor}constructor(e,t,r,n,i,s,o){super(e,o),this.fromPos=t,this.toPos=r,this.contents=n,this.splitLevel=i,this.maxCreatedAtMapByActor=s}}class t0{set(e,t){this.vector.set(e,t)}get(e){return this.vector.get(e)}maxLamport(){let e=BigInt(0);for(let[,t]of this)t>e&&(e=t);return e}max(e){let t=new Map;for(let[r,n]of e){let e=this.vector.get(r),i=e&&e>n?e:n;t.set(r,i)}for(let[r,n]of this){let i=e.get(r),s=i&&i>n?i:n;t.set(r,s)}return new t0(t)}afterOrEqual(e){let t=this.vector.get(e.getActorID());return void 0!==t&&t>=e.getLamport()}deepcopy(){let e=new Map;for(let[t,r]of this.vector)e.set(t,r);return new t0(e)}filter(e){let t=new Map;for(let[r]of e){let e=this.vector.get(r);void 0!==e&&t.set(r,e)}return new t0(t)}size(){return this.vector.size}*[Symbol.iterator](){for(let[e,t]of this.vector)yield[e,t]}constructor(e){this.vector=e||new Map}}let t1=new t0(new Map);class t2{static of(e,t,r,n,i){return new t2(e,t,r,n,i)}next(){let e=this.versionVector.deepcopy();return e.set(this.actor,this.lamport+1n),new t2(this.clientSeq+1,this.lamport+1n,this.actor,e)}syncClocks(e){let t=e.lamport>this.lamport?e.lamport+1n:this.lamport+1n,r=this.versionVector.max(e.versionVector),n=new t2(this.clientSeq,t,this.actor,r);return n.versionVector.set(this.actor,t),n}setClocks(e,t){let r=e>this.lamport?e:this.lamport+1n,n=this.versionVector.max(t);return n.set(this.actor,r),t2.of(this.clientSeq,r,this.actor,n)}createTimeTicket(e){return td.of(this.lamport,e,this.actor)}setActor(e){return new t2(this.clientSeq,this.lamport,e,this.versionVector,this.serverSeq)}setVersionVector(e){return new t2(this.clientSeq,this.lamport,this.actor,e,this.serverSeq)}getClientSeq(){return this.clientSeq}getServerSeq(){return this.serverSeq?this.serverSeq.toString():""}getLamport(){return this.lamport}getLamportAsString(){return this.lamport.toString()}getActorID(){return this.actor}getVersionVector(){return this.versionVector}toTestString(){return"".concat(this.lamport.toString(),":").concat(this.actor.slice(-2),":").concat(this.clientSeq)}constructor(e,t,r,n,i){this.clientSeq=e,this.serverSeq=i,this.lamport=t,this.versionVector=n,this.actor=r}}let t3=new t2(0,0n,th,t1);class t9{static create(e){let{id:t,operations:r,presenceChange:n,message:i}=e;return new t9({id:t,operations:r,presenceChange:n,message:i})}getID(){return this.id}getMessage(){return this.message}hasOperations(){return this.operations.length>0}getOperations(){return this.operations}setActor(e){for(let t of this.operations)t.setActor(e);this.id=this.id.setActor(e)}hasPresenceChange(){return void 0!==this.presenceChange}getPresenceChange(){return this.presenceChange}execute(e,t,r){let n=[],i=[];for(let t of this.operations){let s=t.execute(e,r);if(!s)continue;let{opInfos:o,reverseOp:a}=s;n.push(...o),a&&i.unshift(a)}return this.presenceChange&&(this.presenceChange.type===P.Put?t.set(this.id.getActorID(),ts(this.presenceChange.presence)):t.delete(this.id.getActorID())),{opInfos:n,reverseOps:i}}toTestString(){return"".concat(this.operations.map(e=>e.toTestString()).join(","))}toStruct(){return{changeID:rU.bytesToHex(rU.toChangeID(this.getID()).toBinary()),message:this.getMessage(),operations:this.getOperations().map(e=>rU.bytesToHex(rU.toOperation(e).toBinary())),presenceChange:this.getPresenceChange()}}static fromStruct(e){let{changeID:t,operations:r,presenceChange:n,message:i}=e;return t9.create({id:rU.bytesToChangeID(rU.hexToBytes(t)),operations:null==r?void 0:r.map(e=>rU.bytesToOperation(rU.hexToBytes(e))),presenceChange:n,message:i})}constructor({id:e,operations:t,presenceChange:r,message:n}){this.id=e,this.operations=t||[],this.presenceChange=r,this.message=n}}class t4{static create(e,t,r,n,i,s,o){return new t4(e,t,r,n,i,s,o)}getDocumentKey(){return this.documentKey}getCheckpoint(){return this.checkpoint}getIsRemoved(){return this.isRemoved}getChanges(){return this.changes}hasChanges(){return this.changes.length>0}getChangeSize(){return this.changes.length}hasSnapshot(){return!!this.snapshot&&!!this.snapshot.length}getSnapshot(){return this.snapshot}getMinSyncedTicket(){return this.minSyncedTicket}getVersionVector(){return this.versionVector}constructor(e,t,r,n,i,s,o){this.documentKey=e,this.checkpoint=t,this.isRemoved=r,this.changes=n,this.snapshot=s,this.minSyncedTicket=o,this.versionVector=i}}class t8{static of(e,t){return new t8(e,t)}increaseClientSeq(e){return 0===e?this:new t8(this.serverSeq,this.clientSeq+e)}forward(e){if(this.equals(e))return this;let t=this.serverSeq>e.serverSeq?this.serverSeq:e.serverSeq,r=Math.max(this.clientSeq,e.clientSeq);return t8.of(t,r)}getServerSeqAsString(){return this.serverSeq.toString()}getClientSeq(){return this.clientSeq}getServerSeq(){return this.serverSeq}equals(e){return this.clientSeq===e.clientSeq&&this.serverSeq==e.serverSeq}toTestString(){return"serverSeq=".concat(this.serverSeq,", clientSeq=").concat(this.clientSeq)}constructor(e,t){this.serverSeq=e,this.clientSeq=t}}let t5=new t8(0n,0);class t6{static of(e,t){return new t6(e,t)}static fromStruct(e){return t6.of(td.fromStruct(e.createdAt),e.offset)}getCreatedAt(){return this.createdAt}getOffset(){return this.offset}equals(e){return 0===this.createdAt.compare(e.createdAt)&&this.offset===e.offset}hasSameCreatedAt(e){return 0===this.createdAt.compare(e.createdAt)}split(e){return new t6(this.createdAt,this.offset+e)}toStruct(){return{createdAt:this.createdAt.toStruct(),offset:this.offset}}toTestString(){return"".concat(this.createdAt.toTestString(),":").concat(this.offset)}toIDString(){return"".concat(this.createdAt.toIDString(),":").concat(this.offset)}constructor(e,t){this.createdAt=e,this.offset=t}}let t7=t6.of(tu,0);class re{static of(e,t){return new re(e,t)}static fromStruct(e){let t=t6.fromStruct(e.id);return re.of(t,e.relativeOffset)}getID(){return this.id}getRelativeOffset(){return this.relativeOffset}getAbsoluteID(){return t6.of(this.id.getCreatedAt(),this.id.getOffset()+this.relativeOffset)}toTestString(){return"".concat(this.id.toTestString(),":").concat(this.relativeOffset)}toStruct(){return{id:this.id.toStruct(),relativeOffset:this.relativeOffset}}equals(e){return!!this.id.equals(e.id)&&this.relativeOffset===e.relativeOffset}constructor(e,t){this.id=e,this.relativeOffset=t}}class rt extends tT{static create(e,t){return new rt(e,t)}static createComparator(){return(e,t)=>{let r=e.getCreatedAt().compare(t.getCreatedAt());return 0!==r?r:e.getOffset()>t.getOffset()?1:e.getOffset()0&&t.getID().getOffset()==e.getOffset()){if(!t.hasInsPrev())return t;t=t.getInsPrev()}return t}findFloorNode(e){let t=this.treeByID.floorEntry(e);if(t&&(t.key.equals(e)||t.key.hasSameCreatedAt(e)))return t.value}findBetween(e,t){let r=[],n=e;for(;n&&n!==t;)r.push(n),n=n.getNext();return r}splitNode(e,t){if(t>e.getContentLength())throw new ti(x.ErrInvalidArgument,"offset should be less than or equal to length");if(0===t)return e;if(t===e.getContentLength())return e.getNext();let r=e.split(t);this.treeByIndex.updateWeight(r),this.insertAfter(e,r);let n=e.getInsNext();return n&&n.setInsPrev(r),r.setInsPrev(e),r}deleteNodes(e,t,r){if(!e.length)return[[],new Map,new Map];let[n,i]=this.filterNodes(e,t,r),s=new Map,o=new Map,a=this.makeChanges(i,t);for(let e of n){let r=e.getCreatedAt().getActorID();(!s.has(r)||e.getID().getCreatedAt().after(s.get(r)))&&s.set(r,e.getID().getCreatedAt()),o.set(e.getID().toIDString(),e),e.remove(t)}return this.deleteIndexNodes(i),[a,s,o]}filterNodes(e,t,r){let n=!!r,i=[],s=[],[o,a]=this.findEdgesOfCandidates(e);for(let a of(s.push(o),e)){let e=a.getCreatedAt().getActorID(),o=n?r.has(e)?r.get(e):tu:tg;a.canDelete(t,o)?i.push(a):s.push(a)}return s.push(a),[i,s]}findEdgesOfCandidates(e){return[e[0].getPrev(),e[e.length-1].getNext()]}makeChanges(e,t){let r,n;let i=[];for(let s=0;se<0?Math.ceil(e):Math.floor(e);(g=N||(N={}))[g.IntegerCnt=0]="IntegerCnt",g[g.LongCnt=1]="LongCnt";class ri extends tm{static create(e,t,r){return new ri(e,t,r)}static valueFromBytes(e,t){switch(e){case 0:return t[0]|t[1]<<8|t[2]<<16|t[3]<<24;case 1:return tI.Z.fromBytesLE(Array.from(t));default:throw new ti(x.ErrUnimplemented,"unimplemented type: ".concat(e))}}toJSON(){return"".concat(this.value)}toSortedJSON(){return this.toJSON()}toJSForTest(){return{createdAt:this.getCreatedAt().toTestString(),value:this.value,type:"YORKIE_COUNTER"}}deepcopy(){let e=ri.create(this.valueType,this.value,this.getCreatedAt());return e.setMovedAt(this.getMovedAt()),e}getType(){return this.valueType}static getCounterType(e){switch(typeof e){case"object":if(e instanceof tI.Z)return 1;return;case"number":if(e>2147483647||e<-2147483648)return 1;return 0;default:return}}static isSupport(e){return!!ri.getCounterType(e)}static isInteger(e){return e%1==0}isNumericType(){let e=this.valueType;return 0===e||1===e}getValueType(){return this.valueType}getValue(){return this.value}toBytes(){switch(this.valueType){case 0:{let e=this.value;return new Uint8Array([255&e,e>>8&255,e>>16&255,e>>24&255])}case 1:{let e=this.value.toBytesLE();return Uint8Array.from(e)}default:throw new ti(x.ErrUnimplemented,"unimplemented type: ".concat(this.valueType))}}increase(e){function t(e){if(!e.isNumericType())throw TypeError("Unsupported type of value: ".concat(typeof e.getValue()))}return t(this),t(e),1===this.valueType?this.value=this.value.add(e.getValue()):e.getType()===b.Long?this.value=this.value+e.getValue().toInt():this.value=tI.Z.fromNumber(this.value+rn(e.getValue())).toInt(),this}constructor(e,t,r){switch(super(r),this.valueType=e,e){case 0:"number"==typeof t?t>2147483647||t<-2147483648?this.value=tI.Z.fromNumber(t).toInt():this.value=rn(t):this.value=t.toInt();break;case 1:"number"==typeof t?this.value=tI.Z.fromNumber(t):this.value=t;break;default:throw new ti(x.ErrUnimplemented,"unimplemented type: ".concat(e))}}}class rs extends tA{static create(e,t,r){return new rs(e,t,r)}execute(e){let t=e.findByCreatedAt(this.getParentCreatedAt());if(!t)throw new ti(x.ErrInvalidArgument,"fail to find ".concat(this.getParentCreatedAt()));if(!(t instanceof ri))throw new ti(x.ErrInvalidArgument,"fail to execute, only Counter can execute increase");let r=this.value.deepcopy();return t.increase(r),{opInfos:[{type:"increase",path:e.createPath(this.getParentCreatedAt()),value:r.getValue()}],reverseOp:this.toReverseOperation()}}toReverseOperation(){let e=this.value.deepcopy(),t=e.getType()===b.Long?e.getValue().multiply(-1):-1*e.getValue();return rs.create(this.getParentCreatedAt(),tC.of(t,e.getCreatedAt()))}getEffectedCreatedAt(){return this.getParentCreatedAt()}toTestString(){return"".concat(this.getParentCreatedAt().toTestString(),".INCREASE.").concat(this.value.toJSON())}getValue(){return this.value}constructor(e,t,r){super(e,r),this.value=t}}class ro extends tA{static create(e,t,r,n,i,s){return new ro(e,t,r,n,i,[],s)}static createTreeRemoveStyleOperation(e,t,r,n,i,s){return new ro(e,t,r,n,new Map,i,s)}execute(e){let t,r;let n=e.findByCreatedAt(this.getParentCreatedAt());if(!n)throw new ti(x.ErrInvalidArgument,"fail to find ".concat(this.getParentCreatedAt()));if(!(n instanceof tQ))throw new ti(x.ErrInvalidArgument,"fail to execute, only Tree can execute edit");if(this.attributes.size){let e={};[...this.attributes].forEach(t=>{let[r,n]=t;return e[r]=n}),[,r,t]=n.style([this.fromPos,this.toPos],e,this.getExecutedAt(),this.maxCreatedAtMapByActor)}else{let e=this.attributesToRemove;[,r,t]=n.removeStyle([this.fromPos,this.toPos],e,this.getExecutedAt(),this.maxCreatedAtMapByActor)}for(let t of r)e.registerGCPair(t);return{opInfos:t.map(t=>{let{from:r,to:n,value:i,fromPath:s,toPath:o}=t;return{type:"tree-style",from:r,to:n,value:this.attributes.size?{attributes:i}:{attributesToRemove:i},fromPath:s,toPath:o,path:e.createPath(this.getParentCreatedAt())}})}}getEffectedCreatedAt(){return this.getParentCreatedAt()}toTestString(){let e=this.getParentCreatedAt().toTestString(),t="".concat(this.fromPos.getLeftSiblingID().getCreatedAt().toTestString(),":").concat(this.fromPos.getLeftSiblingID().getOffset()),r="".concat(this.toPos.getLeftSiblingID().getCreatedAt().toTestString(),":").concat(this.toPos.getLeftSiblingID().getOffset());return"".concat(e,".STYLE(").concat(t,",").concat(r,",").concat(Object.entries(this.attributes||{}).map(e=>{let[t,r]=e;return"".concat(t,':"').concat(r,'"')}).join(" "),")")}getFromPos(){return this.fromPos}getToPos(){return this.toPos}getAttributes(){return this.attributes}getAttributesToRemove(){return this.attributesToRemove}getMaxCreatedAtMapByActor(){return this.maxCreatedAtMapByActor}constructor(e,t,r,n,i,s,o){super(e,o),this.fromPos=t,this.toPos=r,this.maxCreatedAtMapByActor=n,this.attributes=i,this.attributesToRemove=s}}function ra(e){return new es({clientSeq:e.getClientSeq(),lamport:e.getLamport(),actorId:rV(e.getActorID()),versionVector:rl(e.getVersionVector())})}function rc(e){if(e)return new ej({lamport:e.getLamport(),delimiter:e.getDelimiter(),actorId:rV(e.getActorID())})}function rl(e){if(!e)return;let t=new eo;for(let[r,n]of e)t.vector[r]=BigInt(n.toString());return t}function rh(e){switch(e){case b.Null:return S.NULL;case b.Boolean:return S.BOOLEAN;case b.Integer:return S.INTEGER;case b.Long:return S.LONG;case b.Double:return S.DOUBLE;case b.String:return S.STRING;case b.Bytes:return S.BYTES;case b.Date:return S.DATE;default:throw new ti(x.ErrInvalidType,"unsupported type: ".concat(e))}}function rd(e){switch(e){case N.IntegerCnt:return S.INTEGER_CNT;case N.LongCnt:return S.LONG_CNT;default:throw new ti(x.ErrInvalidType,"unsupported type: ".concat(e))}}function ru(e){if(e instanceof tw)return new ew({type:S.JSON_OBJECT,createdAt:rc(e.getCreatedAt()),value:rK(e)});if(e instanceof tE)return new ew({type:S.JSON_ARRAY,createdAt:rc(e.getCreatedAt()),value:rv(e).toBinary()});if(e instanceof tJ)return new ew({type:S.TEXT,createdAt:rc(e.getCreatedAt())});if(e instanceof tC)return new ew({type:rh(e.getType()),createdAt:rc(e.getCreatedAt()),value:e.toBytes()});if(e instanceof ri)return new ew({type:rd(e.getType()),createdAt:rc(e.getCreatedAt()),value:e.toBytes()});if(e instanceof tQ)return new ew({type:S.TREE,createdAt:rc(e.getCreatedAt()),value:rw(e).toBinary()});throw new ti(x.ErrUnimplemented,"unimplemented element")}function rg(e){return new eU({createdAt:rc(e.getID().getCreatedAt()),offset:e.getID().getOffset(),relativeOffset:e.getRelativeOffset()})}function rf(e){return new eJ({parentId:rm(e.getParentID()),leftSiblingId:rm(e.getLeftSiblingID())})}function rm(e){return new eB({createdAt:rc(e.getCreatedAt()),offset:e.getOffset()})}function rp(e){let t=new ea;if(e instanceof tk){let r=new ec;r.parentCreatedAt=rc(e.getParentCreatedAt()),r.key=e.getKey(),r.value=ru(e.getValue()),r.executedAt=rc(e.getExecutedAt()),t.body.case="set",t.body.value=r}else if(e instanceof tD){let r=new el;r.parentCreatedAt=rc(e.getParentCreatedAt()),r.prevCreatedAt=rc(e.getPrevCreatedAt()),r.value=ru(e.getValue()),r.executedAt=rc(e.getExecutedAt()),t.body.case="add",t.body.value=r}else if(e instanceof tR){let r=new eh;r.parentCreatedAt=rc(e.getParentCreatedAt()),r.prevCreatedAt=rc(e.getPrevCreatedAt()),r.createdAt=rc(e.getCreatedAt()),r.executedAt=rc(e.getExecutedAt()),t.body.case="move",t.body.value=r}else if(e instanceof tb){let r=new ed;r.parentCreatedAt=rc(e.getParentCreatedAt()),r.createdAt=rc(e.getCreatedAt()),r.executedAt=rc(e.getExecutedAt()),t.body.case="remove",t.body.value=r}else if(e instanceof tL){let r=new eu;r.parentCreatedAt=rc(e.getParentCreatedAt()),r.from=rg(e.getFromPos()),r.to=rg(e.getToPos());let n=r.createdAtMapByActor;for(let[t,r]of e.getMaxCreatedAtMapByActor())n[t]=rc(r);r.content=e.getContent();let i=r.attributes;for(let[t,r]of e.getAttributes())i[t]=r;r.executedAt=rc(e.getExecutedAt()),t.body.case="edit",t.body.value=r}else if(e instanceof t_){let r=new ef;r.parentCreatedAt=rc(e.getParentCreatedAt()),r.from=rg(e.getFromPos()),r.to=rg(e.getToPos());let n=r.createdAtMapByActor;for(let[t,r]of e.getMaxCreatedAtMapByActor())n[t]=rc(r);let i=r.attributes;for(let[t,r]of e.getAttributes())i[t]=r;r.executedAt=rc(e.getExecutedAt()),t.body.case="style",t.body.value=r}else if(e instanceof rs){let r=new em;r.parentCreatedAt=rc(e.getParentCreatedAt()),r.value=ru(e.getValue()),r.executedAt=rc(e.getExecutedAt()),t.body.case="increase",t.body.value=r}else if(e instanceof t$){let r=new ep,n=r.createdAtMapByActor;for(let[t,r]of e.getMaxCreatedAtMapByActor())n[t]=rc(r);r.parentCreatedAt=rc(e.getParentCreatedAt()),r.from=rf(e.getFromPos()),r.to=rf(e.getToPos()),r.contents=function(e){let t=[];if(!e||!e.length)return t;for(let r of e)t.push(new eO({content:ry(r)}));return t}(e.getContents()),r.splitLevel=e.getSplitLevel(),r.executedAt=rc(e.getExecutedAt()),t.body.case="treeEdit",t.body.value=r}else if(e instanceof ro){let r=new ey;r.parentCreatedAt=rc(e.getParentCreatedAt()),r.from=rf(e.getFromPos()),r.to=rf(e.getToPos());let n=r.createdAtMapByActor;for(let[t,r]of e.getMaxCreatedAtMapByActor())n[t]=rc(r);let i=e.getAttributesToRemove();if(i.length>0)r.attributesToRemove=i;else{let t=r.attributes;for(let[r,n]of e.getAttributes())t[r]=n}r.executedAt=rc(e.getExecutedAt()),t.body.case="treeStyle",t.body.value=r}else throw new ti(x.ErrUnimplemented,"unimplemented operation");return t}function ry(e){if(!e)return[];let t=[];return tK(e,(e,r)=>{let n=new eN({id:rm(e.id),type:e.type,removedAt:rc(e.removedAt),depth:r});e.isText&&(n.value=e.value),e.insPrevID&&(n.insPrevId=rm(e.insPrevID)),e.insNextID&&(n.insNextId=rm(e.insNextID)),e.attrs&&(n.attributes=function(e){let t={};for(let r of e)t[r.getKey()]=new ek({value:r.getValue(),updatedAt:rc(r.getUpdatedAt()),isRemoved:r.isRemoved()});return t}(e.attrs)),t.push(n)}),t}function rv(e){let t=new eA;return t.body.case="jsonArray",t.body.value=new eS({nodes:function(e){let t=[];for(let r of e)t.push(new eb({element:rA(r.getValue())}));return t}(e.getElements()),createdAt:rc(e.getCreatedAt()),movedAt:rc(e.getMovedAt()),removedAt:rc(e.getRemovedAt())}),t}function rw(e){let t=new eA;return t.body.case="tree",t.body.value=new eP({nodes:ry(e.getRoot()),createdAt:rc(e.getCreatedAt()),movedAt:rc(e.getMovedAt()),removedAt:rc(e.getRemovedAt())}),t}function rA(e){if(e instanceof tw)return function(e){let t=new eA;return t.body.case="jsonObject",t.body.value=new eT({nodes:function(e){let t=[];for(let r of e)t.push(new eE({key:r.getStrKey(),element:rA(r.getValue())}));return t}(e.getRHT()),createdAt:rc(e.getCreatedAt()),movedAt:rc(e.getMovedAt()),removedAt:rc(e.getRemovedAt())}),t}(e);if(e instanceof tE)return rv(e);if(e instanceof tC)return function(e){let t=new eA;return t.body.case="primitive",t.body.value=new eI({type:rh(e.getType()),value:e.toBytes(),createdAt:rc(e.getCreatedAt()),movedAt:rc(e.getMovedAt()),removedAt:rc(e.getRemovedAt())}),t}(e);if(e instanceof tJ)return function(e){let t=new eA;return t.body.case="text",t.body.value=new eC({nodes:function(e){let t=[];for(let n of e){var r;let e=new eD;e.id=new eR({createdAt:rc((r=n.getID()).getCreatedAt()),offset:r.getOffset()}),e.value=n.getValue().getContent(),e.removedAt=rc(n.getRemovedAt());let i=e.attributes;for(let e of n.getValue().getAttrs()){let t=new ek;t.value=e.getValue(),t.updatedAt=rc(e.getUpdatedAt()),i[e.getKey()]=t}t.push(e)}return t}(e.getRGATreeSplit()),createdAt:rc(e.getCreatedAt()),movedAt:rc(e.getMovedAt()),removedAt:rc(e.getRemovedAt())}),t}(e);if(e instanceof ri)return function(e){let t=new eA;return t.body.case="counter",t.body.value=new ex({type:rd(e.getType()),value:e.toBytes(),createdAt:rc(e.getCreatedAt()),movedAt:rc(e.getMovedAt()),removedAt:rc(e.getRemovedAt())}),t}(e);if(e instanceof tQ)return rw(e);throw new ti(x.ErrUnimplemented,"unimplemented element")}function rT(e){for(let t of e.findDetails(tn.Qf))if(t.metadata.code)return t.metadata.code;return""}function rS(e){return t2.of(e.clientSeq,BigInt(e.lamport),rF(e.actorId),rI(e.versionVector),BigInt(e.serverSeq))}function rI(e){if(!e)return;let t=new t0;return Object.entries(e.vector).forEach(e=>{let[r,n]=e;t.set(r,BigInt(n.toString()))}),t}function rC(e){if(e)return td.of(BigInt(e.lamport),e.delimiter,rF(e.actorId))}function rx(e){let t={};return Object.entries(e.data).forEach(e=>{let[r,n]=e;t[r]=JSON.parse(n)}),t}function rP(e){switch(e){case S.NULL:return b.Null;case S.BOOLEAN:return b.Boolean;case S.INTEGER:return b.Integer;case S.LONG:return b.Long;case S.DOUBLE:return b.Double;case S.STRING:return b.String;case S.BYTES:return b.Bytes;case S.DATE:return b.Date}throw new ti(x.ErrUnimplemented,"unimplemented value type: ".concat(e))}function rE(e){switch(e){case S.INTEGER_CNT:return N.IntegerCnt;case S.LONG_CNT:return N.LongCnt}throw new ti(x.ErrUnimplemented,"unimplemented value type: ".concat(e))}function rb(e){switch(e.type){case S.JSON_OBJECT:if(!e.value)return tw.create(rC(e.createdAt));return rz(e.value);case S.JSON_ARRAY:if(!e.value)return tE.create(rC(e.createdAt));return function(e){if(!e)throw new ti(x.ErrInvalidArgument,"bytes is empty");return r_(eA.fromBinary(e).body.value)}(e.value);case S.TEXT:return tJ.create(rr.create(),rC(e.createdAt));case S.TREE:return function(e){if(!e)throw new ti(x.ErrInvalidArgument,"bytes is empty");return rM(eA.fromBinary(e).body.value)}(e.value);case S.NULL:case S.BOOLEAN:case S.INTEGER:case S.LONG:case S.DOUBLE:case S.STRING:case S.BYTES:case S.DATE:return tC.of(tC.valueFromBytes(rP(e.type),e.value),rC(e.createdAt));case S.INTEGER_CNT:case S.LONG_CNT:return ri.create(rE(e.type),ri.valueFromBytes(rE(e.type),e.value),rC(e.createdAt))}}function rk(e){return re.of(t6.of(rC(e.createdAt),e.offset),e.relativeOffset)}function rD(e){return t6.of(rC(e.createdAt),e.offset)}function rR(e){return tG.of(rN(e.parentId),rN(e.leftSiblingId))}function rN(e){return tH.of(rC(e.createdAt),e.offset)}function rO(e){if(0===e.length)return;let t=[];for(let r of e)t.push(function(e){let t=rN(e.id),r=tY.create(t,e.type),n=Object.entries(e.attributes);return r.isText?r.value=e.value:n.length&&(r.attrs=function(e){let t=tO.create();for(let[r,n]of Object.entries(e))t.setInternal(r,n.value,rC(n.updatedAt),n.isRemoved);return t}(e.attributes)),e.insPrevId&&(r.insPrevID=rN(e.insPrevId)),e.insNextId&&(r.insNextID=rN(e.insNextId)),r.removedAt=rC(e.removedAt),r}(r));let r=t[t.length-1],n=new Map;n.set(e[t.length-1].depth,t[t.length-1]);for(let r=t.length-2;r>=0;r--)n.get(e[r].depth-1).prepend(t[r]),n.set(e[r].depth,t[r]);return r.updateDescendantsSize(),tQ.create(r,tu).getRoot()}function rB(e){if("set"===e.body.case){let t=e.body.value;return tk.create(t.key,rb(t.value),rC(t.parentCreatedAt),rC(t.executedAt))}if("add"===e.body.case){let t=e.body.value;return tD.create(rC(t.parentCreatedAt),rC(t.prevCreatedAt),rb(t.value),rC(t.executedAt))}if("move"===e.body.case){let t=e.body.value;return tR.create(rC(t.parentCreatedAt),rC(t.prevCreatedAt),rC(t.createdAt),rC(t.executedAt))}if("remove"===e.body.case){let t=e.body.value;return tb.create(rC(t.parentCreatedAt),rC(t.createdAt),rC(t.executedAt))}if("edit"===e.body.case){let t=e.body.value,r=new Map;Object.entries(t.createdAtMapByActor).forEach(e=>{let[t,n]=e;r.set(t,rC(n))});let n=new Map;return Object.entries(t.attributes).forEach(e=>{let[t,r]=e;n.set(t,r)}),tL.create(rC(t.parentCreatedAt),rk(t.from),rk(t.to),r,t.content,n,rC(t.executedAt))}if("style"===e.body.case){let t=e.body.value,r=new Map;Object.entries(t.createdAtMapByActor).forEach(e=>{let[t,n]=e;r.set(t,rC(n))});let n=new Map;return Object.entries(t.attributes).forEach(e=>{let[t,r]=e;n.set(t,r)}),t_.create(rC(t.parentCreatedAt),rk(t.from),rk(t.to),r,n,rC(t.executedAt))}if("select"===e.body.case)return;else if("increase"===e.body.case){let t=e.body.value;return rs.create(rC(t.parentCreatedAt),rb(t.value),rC(t.executedAt))}else if("treeEdit"===e.body.case){let t=e.body.value,r=new Map;return Object.entries(t.createdAtMapByActor).forEach(e=>{let[t,n]=e;r.set(t,rC(n))}),t$.create(rC(t.parentCreatedAt),rR(t.from),rR(t.to),function(e){if(!e.length)return;let t=[];return e.forEach(e=>{let r=rO(e.content);t.push(r)}),t}(t.contents),t.splitLevel,r,rC(t.executedAt))}else if("treeStyle"===e.body.case){let t=e.body.value,r=new Map,n=t.attributesToRemove,i=new Map;return((null==t?void 0:t.createdAtMapByActor)&&Object.entries(t.createdAtMapByActor).forEach(e=>{let[t,r]=e;i.set(t,rC(r))}),(null==n?void 0:n.length)>0)?ro.createTreeRemoveStyleOperation(rC(t.parentCreatedAt),rR(t.from),rR(t.to),i,n,rC(t.executedAt)):(Object.entries(t.attributes).forEach(e=>{let[t,n]=e;r.set(t,n)}),ro.create(rC(t.parentCreatedAt),rR(t.from),rR(t.to),i,r,rC(t.executedAt)))}else throw new ti(x.ErrUnimplemented,"unimplemented operation")}function rJ(e){let t=[];for(let r of e)t.push(t9.create({id:rS(r.id),operations:function(e){let t=[];for(let r of e){let e=rB(r);e&&t.push(e)}return t}(r.operations),presenceChange:r.presenceChange?function(e){let t=e.type;if(t===C.PUT){let t=rx(e.presence);return{type:P.Put,presence:t}}if(t===C.CLEAR)return{type:P.Clear};throw new ti(x.ErrInvalidType,"unsupported type: ".concat(t))}(r.presenceChange):void 0,message:r.message}));return t}function rL(e){let t=new tv;for(let r of e.nodes){let e=rq(r.element);t.set(r.key,e,e.getPositionedAt())}let r=new tw(rC(e.createdAt),t);return r.setMovedAt(rC(e.movedAt)),r.setRemovedAt(rC(e.removedAt)),r}function r_(e){let t=new tP;for(let r of e.nodes)t.insert(rq(r.element));let r=new tE(rC(e.createdAt),t);return r.setMovedAt(rC(e.movedAt)),r.setRemovedAt(rC(e.removedAt)),r}function rM(e){let t=rO(e.nodes);return tQ.create(t,rC(e.createdAt))}function rq(e){if("jsonObject"===e.body.case)return rL(e.body.value);if("jsonArray"===e.body.case)return r_(e.body.value);if("primitive"===e.body.case)return function(e){let t=tC.of(tC.valueFromBytes(rP(e.type),e.value),rC(e.createdAt));return t.setMovedAt(rC(e.movedAt)),t.setRemovedAt(rC(e.removedAt)),t}(e.body.value);if("text"===e.body.case)return function(e){let t=new rr,r=t.getHead();for(let n of e.nodes){let e=t.insertAfter(r,function(e){let t=tB.create(e.value);Object.entries(e.attributes).forEach(e=>{let[r,n]=e;t.setAttr(r,n.value,rC(n.updatedAt))});let r=rt.create(rD(e.id),t);return r.remove(rC(e.removedAt)),r}(n));n.insPrevId&&e.setInsPrev(t.findNode(rD(n.insPrevId))),r=e}let n=new tJ(t,rC(e.createdAt));return n.setMovedAt(rC(e.movedAt)),n.setRemovedAt(rC(e.removedAt)),n}(e.body.value);if("counter"===e.body.case)return function(e){let t=ri.create(rE(e.type),ri.valueFromBytes(rE(e.type),e.value),rC(e.createdAt));return t.setMovedAt(rC(e.movedAt)),t.setRemovedAt(rC(e.removedAt)),t}(e.body.value);if("tree"===e.body.case)return rM(e.body.value);throw new ti(x.ErrUnimplemented,"unimplemented element")}function rz(e){if(!e)throw new ti(x.ErrInvalidArgument,"bytes is empty");return rL(eA.fromBinary(e).body.value)}function rK(e){return rA(e).toBinary()}function rF(e){return e?Array.from(e).map(e=>e.toString(16).padStart(2,"0")).join(""):""}function rV(e){return new Uint8Array(e.match(/.{1,2}/g).map(e=>parseInt(e,16)))}let rU={fromPresence:rx,toChangePack:function(e){var t;return new en({documentKey:e.getDocumentKey(),checkpoint:new eV({serverSeq:(t=e.getCheckpoint()).getServerSeq(),clientSeq:t.getClientSeq()}),isRemoved:e.getIsRemoved(),changes:function(e){let t=[];for(let r of e)t.push(function(e){let t=new ei({id:ra(e.getID()),message:e.getMessage()});return e.hasOperations()&&(t.operations=function(e){let t=[];for(let r of e)t.push(rp(r));return t}(e.getOperations())),e.hasPresenceChange()&&(t.presenceChange=function(e){if(e.type===P.Put)return new eK({type:C.PUT,presence:function(e){let t=new eF,r=t.data;for(let[t,n]of Object.entries(e))r[t]=JSON.stringify(n);return t}(e.presence)});if(e.type===P.Clear)return new eK({type:C.CLEAR});throw new ti(x.ErrUnimplemented,"unimplemented type")}(e.getPresenceChange())),t}(r));return t}(e.getChanges()),snapshot:e.getSnapshot(),versionVector:rl(e.getVersionVector()),minSyncedTicket:rc(e.getMinSyncedTicket())})},fromChangePack:function(e){var t;return t4.create(e.documentKey,(t=e.checkpoint,t8.of(BigInt(t.serverSeq),t.clientSeq)),e.isRemoved,rJ(e.changes),rI(e.versionVector),e.snapshot,rC(e.minSyncedTicket))},fromChanges:rJ,toTreeNodes:ry,fromTreeNodes:rO,objectToBytes:rK,bytesToObject:rz,bytesToSnapshot:function(e){if(!e)return{root:tw.create(tu),presences:new Map};let t=er.fromBinary(e);return{root:rq(t.root),presences:function(e){let t=new Map;return Object.entries(e).forEach(e=>{let[r,n]=e;t.set(r,rx(n))}),t}(t.presences)}},bytesToHex:rF,hexToBytes:rV,toHexString:function(e){return rF(e)},toUint8Array:function(e){return rV(e)},toOperation:rp,toChangeID:ra,PbChangeID:es,bytesToChangeID:function(e){return rS(es.fromBinary(e))},bytesToOperation:function(e){return rB(ea.fromBinary(e))},versionVectorToHex:function(e){return rF(rl(e).toBinary())},hexToVersionVector:function(e){let t=rV(e);return rI(eo.fromBinary(t))}};(f=O||(O={}))[f.Trivial=0]="Trivial",f[f.Debug=1]="Debug",f[f.Info=2]="Info",f[f.Warn=3]="Warn",f[f.Error=4]="Error",f[f.Fatal=5]="Fatal";let rj=3;function rW(e){rj=e}let rG={trivial:function(){for(var e=arguments.length,t=Array(e),r=0;r0||"undefined"==typeof console||console.log("YORKIE T:",...t)},debug:function(){for(var e=arguments.length,t=Array(e),r=0;r1||"undefined"==typeof console||console.log("YORKIE D:",...t)},info:function(){for(var e=arguments.length,t=Array(e),r=0;r2||"undefined"==typeof console||console.log("YORKIE I:",...t)},warn:function(){for(var e=arguments.length,t=Array(e),r=0;r3||"undefined"==typeof console||(void 0!==console.warn?console.warn("YORKIE W:",...t):console.log("YORKIE W:",...t))},error:function(){for(var e=arguments.length,t=Array(e),r=0;r4||"undefined"==typeof console||(void 0!==console.error?console.error("YORKIE E:",...t):console.log("YORKIE E:",...t))},fatal:function(){for(var e=arguments.length,t=Array(e),r=0;rrj<=e};function rH(){return"xxxxxxxx-xxxx-4xxxy-xxxx-xxxxxxxxxxx".replace(/[xy]/g,e=>{let t=16*Math.random()|0;return("x"===e?t:3&t|8).toString(16)})}class rY{changeSyncMode(e){this.syncMode=e}needRealtimeSync(){return this.syncMode!==M.RealtimeSyncOff&&(this.syncMode===M.RealtimePushOnly?this.doc.hasLocalChanges():this.syncMode!==M.Manual&&(this.doc.hasLocalChanges()||this.remoteChangeEventReceived))}async runWatchLoop(e){let t=async()=>{if(this.watchStream)return Promise.resolve();this.watchLoopTimerID&&(clearTimeout(this.watchLoopTimerID),this.watchLoopTimerID=void 0);try{[this.watchStream,this.watchAbortController]=await e(()=>{this.watchStream=void 0,this.watchAbortController=void 0,this.watchLoopTimerID=setTimeout(t,this.reconnectStreamDelay)})}catch(e){}};await t()}cancelWatchStream(){this.watchStream&&this.watchAbortController&&(this.watchAbortController.abort(),this.watchStream=void 0,this.watchAbortController=void 0),clearTimeout(this.watchLoopTimerID),this.watchLoopTimerID=void 0}constructor(e,t,r,n,i){this.reconnectStreamDelay=e,this.doc=t,this.docID=r,this.syncMode=n,this.remoteChangeEventReceived=!1,this.unsubscribeBroadcastEvent=i}}let rZ=()=>{};class rX{next(e){this.forEachObserver(t=>{t.next(e)})}error(e){this.forEachObserver(t=>{t.error(e)}),this.close(e)}complete(){this.forEachObserver(e=>{e.complete()}),this.close()}subscribe(e,t,r){let n;if(!e)throw new ti(x.ErrInvalidArgument,"missing observer");if(this.finalized)throw new ti(x.ErrRefused,"observable is finalized due to previous error");void 0===(n="object"==typeof e?e:{next:e,error:t,complete:r}).next&&(n.next=rZ),void 0===n.error&&(n.error=rZ),void 0===n.complete&&(n.complete=rZ);let i=rH(),s=this.unsubscribeOne.bind(this,i);if(this.observers.push({subscriptionID:i,observer:n}),this.finalized)try{this.finalError?n.error(this.finalError):n.complete()}catch(e){rG.warn(e)}return s}unsubscribeOne(e){var t;this.observers=null===(t=this.observers)||void 0===t?void 0:t.filter(t=>t.subscriptionID!==e)}forEachObserver(e){if(!this.finalized)for(let t=0;t0||void 0!==this.presenceChange}setPresenceChange(e){this.presenceChange=e}setReversePresence(e,t){for(let r of Object.keys(e))(null==t?void 0:t.addToHistory)?this.reversePresenceKeys.add(r):this.reversePresenceKeys.delete(r)}getReversePresence(){if(0===this.reversePresenceKeys.size)return;let e={};for(let t of this.reversePresenceKeys)e[t]=this.previousPresence[t];return e}issueTimeTicket(){return this.delimiter+=1,this.id.createTimeTicket(this.delimiter)}getLastTimeTicket(){return this.id.createTimeTicket(this.delimiter)}constructor(e,t,r,n){this.id=e,this.delimiter=0,this.root=t,this.operations=[],this.previousPresence=ts(r),this.presenceChange=void 0,this.reversePresenceKeys=new Set,this.message=n}}class r${static create(){return new r$(tw.create(tu))}findByCreatedAt(e){let t=this.elementPairMapByCreatedAt.get(e.toIDString());if(t)return t.element}findElementPairByCreatedAt(e){return this.elementPairMapByCreatedAt.get(e.toIDString())}createSubPaths(e){let t=this.elementPairMapByCreatedAt.get(e.toIDString());if(!t)return[];let r=[];for(;t.parent;){let e=t.element.getCreatedAt(),n=t.parent.subPathOf(e);if(void 0===n)throw new ti(x.ErrInvalidArgument,"cant find the given element: ".concat(e.toIDString()));r.unshift(n),t=this.elementPairMapByCreatedAt.get(t.parent.getCreatedAt().toIDString())}return r.unshift("$"),r}createPath(e){return this.createSubPaths(e).join(".")}registerElement(e,t){this.elementPairMapByCreatedAt.set(e.getCreatedAt().toIDString(),{parent:t,element:e}),e instanceof tp&&e.getDescendants((e,t)=>(this.registerElement(e,t),!1))}deregisterElement(e){let t=0,r=e=>{let r=e.getCreatedAt().toIDString();this.elementPairMapByCreatedAt.delete(r),this.gcElementSetByCreatedAt.delete(r),t++};return r(e),e instanceof tp&&e.getDescendants(e=>(r(e),!1)),t}registerRemovedElement(e){this.gcElementSetByCreatedAt.add(e.getCreatedAt().toIDString())}registerGCPair(e){if(this.gcPairMap.get(e.child.toIDString())){this.gcPairMap.delete(e.child.toIDString());return}this.gcPairMap.set(e.child.toIDString(),e)}getElementMapSize(){return this.elementPairMapByCreatedAt.size}getGarbageElementSetSize(){let e=new Set;for(let t of this.gcElementSetByCreatedAt){e.add(t);let r=this.elementPairMapByCreatedAt.get(t);r.element instanceof tp&&r.element.getDescendants(t=>(e.add(t.getCreatedAt().toIDString()),!1))}return e.size}getObject(){return this.rootObject}getGarbageLen(){return this.getGarbageElementSetSize()+this.gcPairMap.size}deepcopy(){return new r$(this.rootObject.deepcopy())}garbageCollect(e){let t=0;for(let r of this.gcElementSetByCreatedAt){let n=this.elementPairMapByCreatedAt.get(r),i=n.element.getRemovedAt();i&&(null==e?void 0:e.afterOrEqual(i))&&(n.parent.purge(n.element),t+=this.deregisterElement(n.element))}for(let[,r]of this.gcPairMap){let n=r.child.getRemovedAt();n&&(null==e?void 0:e.afterOrEqual(n))&&(r.parent.purge(r.child),this.gcPairMap.delete(r.child.toIDString()),t+=1)}return t}toJSON(){return this.rootObject.toJSON()}toSortedJSON(){return this.rootObject.toSortedJSON()}getStats(){return{elements:this.getElementMapSize(),gcPairs:this.gcPairMap.size,gcElements:this.getGarbageElementSetSize()}}constructor(e){this.rootObject=e,this.elementPairMapByCreatedAt=new Map,this.gcElementSetByCreatedAt=new Set,this.gcPairMap=new Map,this.registerElement(e,void 0),e.getDescendants(e=>{if(e.getRemovedAt()&&this.registerRemovedElement(e),e instanceof tJ||e instanceof tQ)for(let t of e.getGCPairs())this.registerGCPair(t);return!1})}}function r0(e,t){let r=new r1(e);return new Proxy(t,r.getHandlers())}class r1{static setInternal(e,t,r,n){if(r.includes("."))throw new ti(x.ErrInvalidObjectKey,"key must not contain the '.'.");let i=e.issueTimeTicket(),s=nt(e,n,i),o=t.set(r,s,i);e.registerElement(s,t),o&&e.registerRemovedElement(o),e.push(tk.create(r,s.deepcopy(),t.getCreatedAt(),i))}static buildObjectMembers(e,t){let r={};for(let[n,i]of Object.entries(t)){if(n.includes("."))throw new ti(x.ErrInvalidObjectKey,"key must not contain the '.'.");let t=e.issueTimeTicket(),s=nt(e,i,t);r[n]=s}return r}static deleteInternal(e,t,r){let n=e.issueTimeTicket(),i=t.deleteByKey(r,n);i&&(e.push(tb.create(t.getCreatedAt(),i.getCreatedAt(),n)),e.registerRemovedElement(i))}getHandlers(){return this.handlers}constructor(e){this.context=e,this.handlers={set:(t,r,n)=>(rG.isEnabled(O.Trivial)&&rG.trivial("obj[".concat(r,"]=").concat(JSON.stringify(n))),r1.setInternal(e,t,r,n),!0),get:(t,r)=>(rG.isEnabled(O.Trivial)&&rG.trivial("obj[".concat(r,"]")),"getID"===r)?()=>t.getCreatedAt():"toJSON"===r||"toString"===r?()=>t.toJSON():"toJS"===r?()=>t.toJS():"toJSForTest"===r?()=>t.toJSForTest():ne(e,t.get(r)),ownKeys:e=>e.getKeys(),getOwnPropertyDescriptor:()=>({enumerable:!0,configurable:!0}),deleteProperty:(t,r)=>(rG.isEnabled(O.Trivial)&&rG.trivial("obj[".concat(r,"]")),r1.deleteInternal(e,t,r),!0)}}}class r2{static*iteratorInternal(e,t){for(let r of t)yield r7(e,r)}static buildArrayElements(e,t){let r=[];for(let n of t){let t=e.issueTimeTicket(),i=nt(e,n,t);r.push(i)}return r}static pushInternal(e,t,r){return r2.insertAfterInternal(e,t,t.getLastCreatedAt(),r),t.length}static moveBeforeInternal(e,t,r,n){let i=e.issueTimeTicket(),s=t.getPrevCreatedAt(r);t.moveAfter(s,n,i),e.push(tR.create(t.getCreatedAt(),s,n,i))}static moveAfterInternal(e,t,r,n){let i=e.issueTimeTicket();t.moveAfter(r,n,i),e.push(tR.create(t.getCreatedAt(),r,n,i))}static moveFrontInternal(e,t,r){let n=e.issueTimeTicket(),i=t.getHead();t.moveAfter(i.getCreatedAt(),r,n),e.push(tR.create(t.getCreatedAt(),i.getCreatedAt(),r,n))}static moveLastInternal(e,t,r){let n=e.issueTimeTicket(),i=t.getLastCreatedAt();t.moveAfter(i,r,n),e.push(tR.create(t.getCreatedAt(),i,r,n))}static insertAfterInternal(e,t,r,n){let i=e.issueTimeTicket(),s=nt(e,n,i);return t.insertAfter(r,s),e.registerElement(s,t),e.push(tD.create(t.getCreatedAt(),r,s.deepcopy(),i)),s}static insertBeforeInternal(e,t,r,n){return r2.insertAfterInternal(e,t,t.getPrevCreatedAt(r),n)}static deleteInternalByIndex(e,t,r){let n=e.issueTimeTicket(),i=t.deleteByIndex(r,n);if(i)return e.push(tb.create(t.getCreatedAt(),i.getCreatedAt(),n)),e.registerRemovedElement(i),i}static deleteInternalByID(e,t,r){let n=e.issueTimeTicket(),i=t.delete(r,n);return e.push(tb.create(t.getCreatedAt(),i.getCreatedAt(),n)),e.registerRemovedElement(i),i}static splice(e,t,r,n){for(var i=arguments.length,s=Array(i>4?i-4:0),o=4;o=0?Math.min(r,a):Math.max(a+r,0),l=void 0===n?a:n<0?c:Math.min(c+n,a),h=[];for(let r=c;r=i)return!1;if(tC.isSupport(r))return Array.from(t).map(t=>ne(e,t)).includes(r,s);for(let e=s;e=i)return -1;if(tC.isSupport(r))return Array.from(t).map(t=>ne(e,t)).indexOf(r,s);for(let e=s;e=i?i-1:n<0?n+i:n;if(s<0)return -1;if(tC.isSupport(r))return Array.from(t).map(t=>ne(e,t)).lastIndexOf(r,s);for(let e=s;e>0;e--){var o;if((null===(o=t.get(e))||void 0===o?void 0:o.getID())===r.getID())return e}return -1}static toTestString(e){return e.toTestString()}getHandlers(){return this.handlers}constructor(e,t){this.context=e,this.array=t,this.handlers={get:(t,r,n)=>"getID"===r?()=>t.getCreatedAt():"getElementByID"===r?r=>{let n=t.getByID(r);if(!(!n||n.isRemoved()))return r7(e,n)}:"getElementByIndex"===r?r=>r7(e,t.get(r)):"getLast"===r?()=>r7(e,t.getLast()):"deleteByID"===r?r=>{let n=r2.deleteInternalByID(e,t,r);return r7(e,n)}:"insertAfter"===r?(r,n)=>{let i=r2.insertAfterInternal(e,t,r,n);return r7(e,i)}:"insertBefore"===r?(r,n)=>{let i=r2.insertBeforeInternal(e,t,r,n);return r7(e,i)}:"moveBefore"===r?(r,n)=>{r2.moveBeforeInternal(e,t,r,n)}:"moveAfter"===r?(r,n)=>{r2.moveAfterInternal(e,t,r,n)}:"moveFront"===r?r=>{r2.moveFrontInternal(e,t,r)}:"moveLast"===r?r=>{r2.moveLastInternal(e,t,r)}:("string"==typeof r||r instanceof String)&&!isNaN(r)?ne(e,t.get(Number(r))):"push"===r?r=>r2.pushInternal(e,t,r):"splice"===r?function(r,n){for(var i=arguments.length,s=Array(i>2?i-2:0),o=2;or2.includes(e,t,r,n):"indexOf"===r?(r,n)=>r2.indexOf(e,t,r,n):"lastIndexOf"===r?(r,n)=>r2.lastIndexOf(e,t,r,n):"toJSForTest"===r?()=>t.toJSForTest():"toTestString"===r?()=>r2.toTestString(t):"string"==typeof r&&["concat","entries","every","filter","find","findIndex","forEach","join","keys","map","reduce","reduceRight","slice","some","toLocaleString","toString","values"].includes(r)?function(){for(var n=arguments.length,i=Array(n),s=0;sne(e,t));return Array.prototype[r].apply(o,i)}:Reflect.get(t,r,n),deleteProperty:(t,r)=>(rG.isEnabled(O.Trivial)&&rG.trivial("array[".concat(r,"]")),r2.deleteInternalByIndex(e,t,Number.parseInt(r)),!0)}}}class r3{initialize(e,t){this.context=e,this.text=t}getID(){return this.text.getID()}edit(e,t,r,n){if(!this.context||!this.text)throw new ti(x.ErrNotInitialized,"Text is not initialized yet");if(e>t)throw new ti(x.ErrInvalidArgument,"from should be less than or equal to to");let i=this.text.indexRangeToPosRange(e,t);rG.isEnabled(O.Debug)&&rG.debug("EDIT: f:".concat(e,"->").concat(i[0].toTestString(),", t:").concat(t,"->").concat(i[1].toTestString()," c:").concat(r));let s=n?ta(n):void 0,o=this.context.issueTimeTicket(),[a,,c,l]=this.text.edit(i,r,o,s);for(let e of c)this.context.registerGCPair(e);return this.context.push(new tL(this.text.getCreatedAt(),i[0],i[1],a,r,s?new Map(Object.entries(s)):new Map,o)),this.text.findIndexesFromRange(l)}delete(e,t){return this.edit(e,t,"")}empty(){return this.edit(0,this.length,"")}setStyle(e,t,r){if(!this.context||!this.text)throw new ti(x.ErrNotInitialized,"Text is not initialized yet");if(e>t)throw new ti(x.ErrInvalidArgument,"from should be less than or equal to to");let n=this.text.indexRangeToPosRange(e,t);rG.isEnabled(O.Debug)&&rG.debug("STYL: f:".concat(e,"->").concat(n[0].toTestString(),", t:").concat(t,"->").concat(n[1].toTestString()," a:").concat(JSON.stringify(r)));let i=ta(r),s=this.context.issueTimeTicket(),[o,a]=this.text.setStyle(n,i,s);for(let e of a)this.context.registerGCPair(e);return this.context.push(new t_(this.text.getCreatedAt(),n[0],n[1],o,new Map(Object.entries(i)),s)),!0}indexRangeToPosRange(e){if(!this.context||!this.text)throw new ti(x.ErrNotInitialized,"Text is not initialized yet");let t=this.text.indexRangeToPosRange(e[0],e[1]);return[t[0].toStruct(),t[1].toStruct()]}posRangeToIndexRange(e){if(!this.context||!this.text)throw new ti(x.ErrNotInitialized,"Text is not initialized yet");let t=this.text.findIndexesFromRange([re.fromStruct(e[0]),re.fromStruct(e[1])]);return[t[0],t[1]]}toTestString(){if(!this.context||!this.text)throw new ti(x.ErrNotInitialized,"Text is not initialized yet");return this.text.toTestString()}values(){if(!this.context||!this.text)throw new ti(x.ErrNotInitialized,"Text is not initialized yet");return this.text.values()}get length(){return this.text.length}getTreeByIndex(){return this.text.getTreeByIndex()}getTreeByID(){return this.text.getTreeByID()}toString(){if(!this.context||!this.text)throw new ti(x.ErrNotInitialized,"Text is not initialized yet");return this.text.toString()}toJSON(){if(!this.context||!this.text)throw new ti(x.ErrNotInitialized,"Text is not initialized yet");return this.text.toJSON()}toJSForTest(){if(!this.context||!this.text)throw new ti(x.ErrNotInitialized,"Text is not initialized yet");return this.text.toJSForTest()}createRangeForTest(e,t){if(!this.context||!this.text)throw new ti(x.ErrNotInitialized,"Text is not initialized yet");return this.text.indexRangeToPosRange(e,t)}constructor(e,t){this.context=e,this.text=t}}class r9{initialize(e,t){this.valueType=t.getValueType(),this.context=e,this.counter=t,this.value=t.getValue()}getID(){return this.counter.getID()}getValue(){return this.value}getValueType(){return this.valueType}increase(e){if(!this.context||!this.counter)throw new ti(x.ErrNotInitialized,"Counter is not initialized yet");let t=this.context.issueTimeTicket(),r=tC.of(e,t);if(!r.isNumericType())throw TypeError("Unsupported type of value: ".concat(typeof r.getValue()));return this.counter.increase(r),this.context.push(rs.create(this.counter.getCreatedAt(),r,t)),this}toJSForTest(){if(!this.context||!this.counter)throw new ti(x.ErrNotInitialized,"Counter is not initialized yet");return this.counter.toJSForTest()}constructor(e,t){this.valueType=e,this.value=t}}function r4(e,t,r){let{type:n}=e,i=r.issueTimeTicket();if(n===tM){r8(e);let{value:r}=e,s=tY.create(tH.of(i,0),n,r);t.append(s)}else{let s;let{children:o=[]}=e,{attributes:a}=e;if("object"==typeof a&&!to(a)){let e=ta(a);for(let[t,r]of(s=new tO,Object.entries(e)))s.set(t,r,i)}let c=tY.create(tH.of(i,0),n,void 0,s);for(let e of(t.append(c),o))r4(e,c,r)}}function r8(e){if(!e.value.length)throw new ti(x.ErrInvalidArgument,"text node cannot have empty value");return!0}function r5(e){if(!e.length)return!0;if(e[0].type===tM)for(let t of e){let{type:e}=t;if(e!==tM)throw new ti(x.ErrInvalidArgument,"element node and text node cannot be passed together");r8(t)}else for(let t of e){let{type:e}=t;if(e===tM)throw new ti(x.ErrInvalidArgument,"element node and text node cannot be passed together")}return!0}class r6{initialize(e,t){this.context=e,this.tree=t}getID(){return this.tree.getID()}buildRoot(e){if(!this.initialRoot)return tY.create(tH.of(e.issueTimeTicket(),0),"root");let t=tY.create(tH.of(e.issueTimeTicket(),0),this.initialRoot.type);for(let r of this.initialRoot.children)r4(r,t,e);return t}getSize(){if(!this.context||!this.tree)throw new ti(x.ErrNotInitialized,"Tree is not initialized yet");return this.tree.getSize()}getNodeSize(){if(!this.context||!this.tree)throw new ti(x.ErrNotInitialized,"Tree is not initialized yet");return this.tree.getNodeSize()}getIndexTree(){if(!this.context||!this.tree)throw new ti(x.ErrNotInitialized,"Tree is not initialized yet");return this.tree.getIndexTree()}styleByPath(e,t){if(!this.context||!this.tree)throw new ti(x.ErrNotInitialized,"Tree is not initialized yet");if(!e.length)throw new ti(x.ErrInvalidArgument,"path should not be empty");let[r,n]=this.tree.pathToPosRange(e),i=this.context.issueTimeTicket(),s=t?ta(t):void 0,[o]=this.tree.style([r,n],s,i);this.context.push(ro.create(this.tree.getCreatedAt(),r,n,o,s?new Map(Object.entries(s)):new Map,i))}style(e,t,r){if(!this.context||!this.tree)throw new ti(x.ErrNotInitialized,"Tree is not initialized yet");if(e>t)throw new ti(x.ErrInvalidArgument,"from should be less than or equal to to");let n=this.tree.findPos(e),i=this.tree.findPos(t),s=this.context.issueTimeTicket(),o=r?ta(r):void 0,[a,c]=this.tree.style([n,i],o,s);for(let e of c)this.context.registerGCPair(e);this.context.push(ro.create(this.tree.getCreatedAt(),n,i,a,o?new Map(Object.entries(o)):new Map,s))}removeStyle(e,t,r){if(!this.context||!this.tree)throw new ti(x.ErrNotInitialized,"Tree is not initialized yet");if(e>t)throw new ti(x.ErrInvalidArgument,"from should be less than or equal to to");let n=this.tree.findPos(e),i=this.tree.findPos(t),s=this.context.issueTimeTicket(),[o,a]=this.tree.removeStyle([n,i],r,s);for(let e of a)this.context.registerGCPair(e);this.context.push(ro.createTreeRemoveStyleOperation(this.tree.getCreatedAt(),n,i,o,r,s))}editInternal(e,t,r){var n;let i=arguments.length>3&&void 0!==arguments[3]?arguments[3]:0;if(0!==r.length&&r[0]&&(r5(r),r[0].type!==tM))for(let e of r){let{children:t=[]}=e;r5(t)}let s=this.context.getLastTimeTicket(),o=[];if((null===(n=r[0])||void 0===n?void 0:n.type)===tM){let e="";for(let t of r){let{value:r}=t;e+=r}o.push(tY.create(tH.of(this.context.issueTimeTicket(),0),tM,e))}else o=r.map(e=>e&&function(e,t){let r;let{type:n}=t,i=e.issueTimeTicket();if(t.type===tM){let{value:e}=t;r=tY.create(tH.of(i,0),n,e)}else if(t){let s;let{children:o=[]}=t,{attributes:a}=t;if("object"==typeof a&&!to(a)){let e=ta(a);for(let[t,r]of(s=new tO,Object.entries(e)))s.set(t,r,i)}for(let t of(r=tY.create(tH.of(e.issueTimeTicket(),0),n,void 0,s),o))r4(t,r,e)}return r}(this.context,e)).filter(e=>e);let[,a,c]=this.tree.edit([e,t],o.length?o.map(e=>null==e?void 0:e.deepcopy()):void 0,i,s,()=>this.context.issueTimeTicket());for(let e of a)this.context.registerGCPair(e);return this.context.push(t$.create(this.tree.getCreatedAt(),e,t,o.length?o:void 0,i,c,s)),!0}editByPath(e,t,r){let n=arguments.length>3&&void 0!==arguments[3]?arguments[3]:0;if(!this.context||!this.tree)throw new ti(x.ErrNotInitialized,"Tree is not initialized yet");if(e.length!==t.length)throw new ti(x.ErrInvalidArgument,"path length should be equal");if(!e.length||!t.length)throw new ti(x.ErrInvalidArgument,"path should not be empty");let i=this.tree.pathToPos(e),s=this.tree.pathToPos(t);return this.editInternal(i,s,r?[r]:[],n)}editBulkByPath(e,t,r){let n=arguments.length>3&&void 0!==arguments[3]?arguments[3]:0;if(!this.context||!this.tree)throw new ti(x.ErrNotInitialized,"Tree is not initialized yet");if(e.length!==t.length)throw new ti(x.ErrInvalidArgument,"path length should be equal");if(!e.length||!t.length)throw new ti(x.ErrInvalidArgument,"path should not be empty");let i=this.tree.pathToPos(e),s=this.tree.pathToPos(t);return this.editInternal(i,s,r,n)}edit(e,t,r){let n=arguments.length>3&&void 0!==arguments[3]?arguments[3]:0;if(!this.context||!this.tree)throw new ti(x.ErrNotInitialized,"Tree is not initialized yet");if(e>t)throw new ti(x.ErrInvalidArgument,"from should be less than or equal to to");let i=this.tree.findPos(e),s=this.tree.findPos(t);return this.editInternal(i,s,r?[r]:[],n)}editBulk(e,t,r){let n=arguments.length>3&&void 0!==arguments[3]?arguments[3]:0;if(!this.context||!this.tree)throw new ti(x.ErrNotInitialized,"Tree is not initialized yet");if(e>t)throw new ti(x.ErrInvalidArgument,"from should be less than or equal to to");let i=this.tree.findPos(e),s=this.tree.findPos(t);return this.editInternal(i,s,r,n)}toXML(){if(!this.context||!this.tree)throw new ti(x.ErrNotInitialized,"Tree is not initialized yet");return this.tree.toXML()}toJSON(){if(!this.context||!this.tree)throw new ti(x.ErrNotInitialized,"Tree is not initialized yet");return this.tree.toJSON()}toJSForTest(){if(!this.context||!this.tree)throw new ti(x.ErrNotInitialized,"Tree is not initialized yet");return this.tree.toJSForTest()}toJSInfoForTest(){if(!this.context||!this.tree)throw new ti(x.ErrNotInitialized,"Tree is not initialized yet");return this.tree.toJSInfoForTest()}getRootTreeNode(){if(!this.context||!this.tree)throw new ti(x.ErrNotInitialized,"Tree is not initialized yet");return this.tree.getRootTreeNode()}indexToPath(e){if(!this.context||!this.tree)throw new ti(x.ErrNotInitialized,"Tree is not initialized yet");return this.tree.indexToPath(e)}pathToIndex(e){if(!this.context||!this.tree)throw new ti(x.ErrNotInitialized,"Tree is not initialized yet");return this.tree.pathToIndex(e)}pathRangeToPosRange(e){if(!this.context||!this.tree)throw new ti(x.ErrNotInitialized,"Tree is not initialized yet");let t=[this.tree.pathToIndex(e[0]),this.tree.pathToIndex(e[1])],r=this.tree.indexRangeToPosRange(t);return[r[0].toStruct(),r[1].toStruct()]}indexRangeToPosRange(e){if(!this.context||!this.tree)throw new ti(x.ErrNotInitialized,"Tree is not initialized yet");return this.tree.indexRangeToPosStructRange(e)}posRangeToIndexRange(e){if(!this.context||!this.tree)throw new ti(x.ErrNotInitialized,"Tree is not initialized yet");let t=[tG.fromStruct(e[0]),tG.fromStruct(e[1])];return this.tree.posRangeToIndexRange(t)}posRangeToPathRange(e){if(!this.context||!this.tree)throw new ti(x.ErrNotInitialized,"Tree is not initialized yet");let t=[tG.fromStruct(e[0]),tG.fromStruct(e[1])];return this.tree.posRangeToPathRange(t)}constructor(e){this.initialRoot=e}}function r7(e,t){if(t){if(t instanceof tC)return t;if(t instanceof tw)return r0(e,t);if(t instanceof tE)return function(e,t){let r=new r2(e,t);return new Proxy(t,r.getHandlers())}(e,t);if(t instanceof tJ)return new r3(e,t);else if(t instanceof ri){let r=new r9(N.IntegerCnt,0);return r.initialize(e,t),r}else if(t instanceof tQ){let r=new r6;return r.initialize(e,t),r}throw TypeError("Unsupported type of element: ".concat(typeof t))}}function ne(e,t){let r=r7(e,t);return r instanceof tC?r.getValue():r}function nt(e,t,r){let n;if(tC.isSupport(t))n=tC.of(t,r);else if(Array.isArray(t))n=tE.create(r,r2.buildArrayElements(e,t));else if("object"==typeof t)t instanceof r3?(n=tJ.create(rr.create(),r),t.initialize(e,n)):t instanceof r9?(n=ri.create(t.getValueType(),t.getValue(),r),t.initialize(e,n)):t instanceof r6?(n=tQ.create(t.buildRoot(e),r),t.initialize(e,n)):n=tw.create(r,r1.buildObjectMembers(e,t));else throw TypeError("Unsupported type of value: ".concat(typeof t));return n}class nr{hasUndo(){return this.undoStack.length>0}hasRedo(){return this.redoStack.length>0}pushUndo(e){this.undoStack.length>=50&&this.undoStack.shift(),this.undoStack.push(e)}popUndo(){return this.undoStack.pop()}pushRedo(e){this.redoStack.length>=50&&this.redoStack.shift(),this.redoStack.push(e)}popRedo(){return this.redoStack.pop()}clearRedo(){this.redoStack=[]}getUndoStackForTest(){return this.undoStack}getRedoStackForTest(){return this.redoStack}constructor(){this.undoStack=[],this.redoStack=[]}}let nn="disconnected",ni=new Map,ns=new Map;function no(e,t){((null==t?void 0:t.force)||"disconnected"!==nn)&&window.postMessage({source:"yorkie-devtools-sdk",...e},"*")}window.transactionEventsByDocKey=ns,(m=B||(B={})).Detached="detached",m.Attached="attached",m.Removed="removed",(p=J||(J={})).StatusChanged="status-changed",p.ConnectionChanged="connection-changed",p.SyncStatusChanged="sync-status-changed",p.Snapshot="snapshot",p.LocalChange="local-change",p.RemoteChange="remote-change",p.Initialized="initialized",p.Watched="watched",p.Unwatched="unwatched",p.PresenceChanged="presence-changed",p.Broadcast="broadcast",p.LocalBroadcast="local-broadcast",(y=L||(L={})).Connected="connected",y.Disconnected="disconnected",(v=_||(_={})).Synced="synced",v.SyncFailed="sync-failed";class na{update(e,t){if("removed"===this.getStatus())throw new ti(x.ErrDocumentRemoved,"".concat(this.key," is removed"));this.ensureClone();let r=this.changeID.getActorID(),n=rQ.create(this.changeID.next(),this.clone.root,this.clone.presences.get(r)||{},t);try{var i;let t=(i=this.clone.root.getObject(),r0(n,i));this.presences.has(r)||this.clone.presences.set(r,{}),this.isUpdating=!0,e(t,new tl(n,this.clone.presences.get(r)))}catch(e){throw this.clone=void 0,e}finally{this.isUpdating=!1}if(n.hasChange()){rG.isEnabled(O.Trivial)&&rG.trivial("trying to update a local change: ".concat(this.toJSON()));let e=n.getChange(),{opInfos:t,reverseOps:i}=e.execute(this.root,this.presences,E.Local),s=n.getReversePresence();s&&i.push({type:"presence",value:s}),this.localChanges.push(e),i.length>0&&this.internalHistory.pushUndo(i),t.length>0&&this.internalHistory.clearRedo(),this.changeID=e.getID();let o=[];t.length>0&&o.push({type:"local-change",source:E.Local,value:{message:e.getMessage()||"",operations:t,actor:r,clientSeq:e.getID().getClientSeq(),serverSeq:e.getID().getServerSeq()},rawChange:this.isEnableDevtools()?e.toStruct():void 0}),e.hasPresenceChange()&&o.push({type:"presence-changed",source:E.Local,value:{clientID:r,presence:this.getPresence(r)}}),this.publish(o),rG.isEnabled(O.Trivial)&&rG.trivial("after update a local change: ".concat(this.toJSON()))}}subscribe(e,t,r,n){if("string"==typeof e){if("function"!=typeof t)throw new ti(x.ErrInvalidArgument,"Second argument must be a callback function");return"presence"===e?this.eventStream.subscribe(e=>{for(let r of e)("initialized"===r.type||"watched"===r.type||"unwatched"===r.type||"presence-changed"===r.type)&&t(r)},r,n):"my-presence"===e?this.eventStream.subscribe(e=>{for(let r of e)("initialized"===r.type||"presence-changed"===r.type)&&("presence-changed"!==r.type||r.value.clientID===this.changeID.getActorID())&&t(r)},r,n):"others"===e?this.eventStream.subscribe(e=>{for(let r of e)("watched"===r.type||"unwatched"===r.type||"presence-changed"===r.type)&&r.value.clientID!==this.changeID.getActorID()&&t(r)},r,n):"connection"===e?this.eventStream.subscribe(e=>{for(let r of e)"connection-changed"===r.type&&t(r)},r,n):"status"===e?this.eventStream.subscribe(e=>{for(let r of e)"status-changed"===r.type&&t(r)},r,n):"sync"===e?this.eventStream.subscribe(e=>{for(let r of e)"sync-status-changed"===r.type&&t(r)},r,n):"local-broadcast"===e?this.eventStream.subscribe(e=>{for(let r of e)"local-broadcast"===r.type&&t(r)},r):"broadcast"===e?this.eventStream.subscribe(e=>{for(let r of e)"broadcast"===r.type&&t(r)},r):"all"===e?this.eventStream.subscribe(t,r,n):this.eventStream.subscribe(r=>{for(let n of r){if("local-change"!==n.type&&"remote-change"!==n.type)continue;let r=[];for(let t of n.value.operations)this.isSameElementOrChildOf(t.path,e)&&r.push(t);r.length&&t({...n,value:{...n.value,operations:r}})}},r,n)}if("function"==typeof e)return this.eventStream.subscribe(t=>{for(let r of t)("snapshot"===r.type||"local-change"===r.type||"remote-change"===r.type)&&e(r)},t,r);throw new ti(x.ErrInvalidArgument,'"'.concat(e,'" is not a valid'))}publish(e){this.eventStreamObserver&&this.eventStreamObserver.next(e)}isSameElementOrChildOf(e,t){if(t===e)return!0;let r=e.split(".");return t.split(".").every((e,t)=>e===r[t])}removePushedLocalChanges(e){for(;this.localChanges.length&&!(this.localChanges[0].getID().getClientSeq()>e);)this.localChanges.shift()}applyChangePack(e){let t=e.hasSnapshot();t?this.applySnapshot(e.getCheckpoint().getServerSeq(),e.getVersionVector(),e.getSnapshot(),e.getCheckpoint().getClientSeq()):(this.applyChanges(e.getChanges(),E.Remote),this.removePushedLocalChanges(e.getCheckpoint().getClientSeq())),this.checkpoint=this.checkpoint.forward(e.getCheckpoint()),t||this.garbageCollect(e.getVersionVector()),t||this.filterVersionVector(e.getVersionVector()),e.getIsRemoved()&&this.applyStatus("removed"),rG.isEnabled(O.Trivial)&&rG.trivial("".concat(this.root.toJSON()))}getCheckpoint(){return this.checkpoint}getChangeID(){return this.changeID}hasLocalChanges(){return this.localChanges.length>0}ensureClone(){this.clone||(this.clone={root:this.root.deepcopy(),presences:ts(this.presences)})}createChangePack(){let e=Array.from(this.localChanges),t=this.checkpoint.increaseClientSeq(e.length);return t4.create(this.key,t,!1,e,this.getVersionVector())}setActor(e){for(let t of this.localChanges)t.setActor(e);this.changeID=this.changeID.setActor(e)}isEnableDevtools(){return!!this.opts.enableDevtools}getKey(){return this.key}getStatus(){return this.status}getCloneRoot(){if(this.clone)return this.clone.root.getObject()}getRoot(){return this.ensureClone(),r0(rQ.create(this.changeID.next(),this.clone.root,this.clone.presences.get(this.changeID.getActorID())||{}),this.clone.root.getObject())}garbageCollect(e){return this.opts.disableGC?0:(this.clone&&this.clone.root.garbageCollect(e),this.root.garbageCollect(e))}getRootObject(){return this.root.getObject()}getGarbageLen(){return this.root.getGarbageLen()}getGarbageLenFromClone(){return this.clone.root.getGarbageLen()}toJSON(){return this.root.toJSON()}toSortedJSON(){return this.root.toSortedJSON()}getStats(){return this.root.getStats()}toJSForTest(){return{...this.getRoot().toJSForTest(),key:"root"}}applySnapshot(e,t,r){let n=arguments.length>3&&void 0!==arguments[3]?arguments[3]:-1,{root:i,presences:s}=rU.bytesToSnapshot(r);this.root=new r$(i),this.presences=s,this.changeID=this.changeID.setClocks(e,t),this.clone=void 0,this.removePushedLocalChanges(n),this.applyChanges(this.localChanges,E.Local),this.publish([{type:"snapshot",source:E.Remote,value:{serverSeq:e.toString(),snapshot:this.isEnableDevtools()?rU.bytesToHex(r):void 0,snapshotVector:rU.versionVectorToHex(t)}}])}applyChanges(e,t){for(let r of(rG.isEnabled(O.Debug)&&rG.debug("trying to apply ".concat(e.length," remote changes.")+"elements:".concat(this.root.getElementMapSize(),", ")+"removeds:".concat(this.root.getGarbageElementSetSize())),rG.isEnabled(O.Trivial)&&rG.trivial(e.map(e=>"".concat(e.getID().toTestString()," ").concat(e.toTestString())).join("\n")),e))this.applyChange(r,t);rG.isEnabled(O.Debug)&&rG.debug("after appling ".concat(e.length," remote changes.")+"elements:".concat(this.root.getElementMapSize(),", ")+" removeds:".concat(this.root.getGarbageElementSetSize()))}applyChange(e,t){this.ensureClone(),e.execute(this.clone.root,this.clone.presences,t);let r=[],n=e.getID().getActorID();if(e.hasPresenceChange()&&this.onlineClients.has(n)){let i=e.getPresenceChange();switch(i.type){case P.Put:r.push(this.presences.has(n)?{type:"presence-changed",source:t,value:{clientID:n,presence:i.presence}}:{type:"watched",source:E.Remote,value:{clientID:n,presence:i.presence}});break;case P.Clear:r.push({type:"unwatched",source:E.Remote,value:{clientID:n,presence:this.getPresence(n)}}),this.removeOnlineClient(n)}}let{opInfos:i}=e.execute(this.root,this.presences,t);if(this.changeID=this.changeID.syncClocks(e.getID()),i.length>0){let s=this.isEnableDevtools()?e.toStruct():void 0;r.push(t===E.Remote?{type:"remote-change",source:t,value:{actor:n,clientSeq:e.getID().getClientSeq(),serverSeq:e.getID().getServerSeq(),message:e.getMessage()||"",operations:i},rawChange:s}:{type:"local-change",source:t,value:{actor:n,clientSeq:e.getID().getClientSeq(),serverSeq:e.getID().getServerSeq(),message:e.getMessage()||"",operations:i},rawChange:s})}r.length>0&&this.publish(r)}applyWatchStream(e){if("initialization"===e.body.case){let t=e.body.value.clientIds,r=new Set;for(let e of t)e!==this.changeID.getActorID()&&r.add(e);this.setOnlineClients(r),this.publish([{type:"initialized",source:E.Local,value:this.getPresences()}]);return}if("event"===e.body.case){let{type:t,publisher:r}=e.body.value,n=[];if(t===I.DOCUMENT_WATCHED){if(this.onlineClients.has(r)&&this.hasPresence(r))return;this.addOnlineClient(r),this.hasPresence(r)&&n.push({type:"watched",source:E.Remote,value:{clientID:r,presence:this.getPresence(r)}})}else if(t===I.DOCUMENT_UNWATCHED){let e=this.getPresence(r);this.removeOnlineClient(r),e&&n.push({type:"unwatched",source:E.Remote,value:{clientID:r,presence:e}})}else if(t===I.DOCUMENT_BROADCAST&&e.body.value.body){let{topic:t,payload:i}=e.body.value.body,s=new TextDecoder;n.push({type:"broadcast",value:{clientID:r,topic:t,payload:JSON.parse(s.decode(i))}})}n.length>0&&this.publish(n)}}applyStatus(e){this.status=e,"detached"===e&&this.setActor(th),this.publish([{source:"removed"===e?E.Remote:E.Local,type:"status-changed",value:"attached"===e?{status:e,actorID:this.changeID.getActorID()}:{status:e}}])}applyDocEvent(e){if("status-changed"===e.type){this.applyStatus(e.value.status),"attached"===e.value.status&&this.setActor(e.value.actorID);return}if("snapshot"===e.type){let{snapshot:t,serverSeq:r,snapshotVector:n}=e.value;if(!t)return;this.applySnapshot(BigInt(r),rU.hexToVersionVector(n),rU.hexToBytes(t));return}if("local-change"===e.type||"remote-change"===e.type){if(!e.rawChange)return;let t=t9.fromStruct(e.rawChange);this.applyChange(t,e.source)}if("initialized"===e.type){let t=new Set;for(let{clientID:r,presence:n}of e.value)t.add(r),this.presences.set(r,n);this.setOnlineClients(t);return}if("watched"===e.type){let{clientID:t,presence:r}=e.value;this.addOnlineClient(t),this.presences.set(t,r);return}if("unwatched"===e.type){let{clientID:t}=e.value;this.removeOnlineClient(t),this.presences.delete(t)}if("presence-changed"===e.type){let{clientID:t,presence:r}=e.value;this.presences.set(t,r)}}applyTransactionEvent(e){for(let t of e)this.applyDocEvent(t)}getValueByPath(e){if(!e.startsWith("$"))throw new ti(x.ErrInvalidArgument,'path must start with "$"');let t=e.split(".");t.shift();let r=this.getRoot();for(let e of t)if(void 0===(r=r[e]))return;return r}setOnlineClients(e){this.onlineClients=e}resetOnlineClients(){this.onlineClients=new Set}addOnlineClient(e){this.onlineClients.add(e)}removeOnlineClient(e){this.onlineClients.delete(e)}hasPresence(e){return this.presences.has(e)}getMyPresence(){if("attached"!==this.status)return{};let e=this.presences.get(this.changeID.getActorID());return e?ts(e):{}}getPresence(e){if(e===this.changeID.getActorID())return this.getMyPresence();if(!this.onlineClients.has(e))return;let t=this.presences.get(e);return t?ts(t):void 0}getPresenceForTest(e){let t=this.presences.get(e);return t?ts(t):void 0}getPresences(){let e=[];for(let t of(e.push({clientID:this.changeID.getActorID(),presence:ts(this.getMyPresence())}),this.onlineClients))this.presences.has(t)&&e.push({clientID:t,presence:ts(this.presences.get(t))});return e}getSelfForTest(){return{clientID:this.getChangeID().getActorID(),presence:this.getMyPresence()}}getOthersForTest(){let e=this.getChangeID().getActorID();return this.getPresences().filter(t=>t.clientID!==e).sort((e,t)=>e.clientID>t.clientID?1:-1)}canUndo(){return this.internalHistory.hasUndo()&&!this.isUpdating}filterVersionVector(e){let t=this.changeID.getVersionVector().filter(e);this.changeID=this.changeID.setVersionVector(t)}canRedo(){return this.internalHistory.hasRedo()&&!this.isUpdating}undo(){if(this.isUpdating)throw new ti(x.ErrRefused,"Undo is not allowed during an update");let e=this.internalHistory.popUndo();if(void 0===e)throw new ti(x.ErrRefused,"There is no operation to be undone");this.ensureClone();let t=rQ.create(this.changeID.next(),this.clone.root,this.clone.presences.get(this.changeID.getActorID())||{});for(let r of e){if(!(r instanceof tA)){new tl(t,ts(this.clone.presences.get(this.changeID.getActorID()))).set(r.value,{addToHistory:!0});continue}let e=t.issueTimeTicket();r.setExecutedAt(e),t.push(r)}let r=t.getChange();r.execute(this.clone.root,this.clone.presences,E.UndoRedo);let{opInfos:n,reverseOps:i}=r.execute(this.root,this.presences,E.UndoRedo),s=t.getReversePresence();if(s&&i.push({type:"presence",value:s}),i.length>0&&this.internalHistory.pushRedo(i),!r.hasPresenceChange()&&0===n.length)return;this.localChanges.push(r),this.changeID=r.getID();let o=this.changeID.getActorID(),a=[];n.length>0&&a.push({type:"local-change",source:E.UndoRedo,value:{message:r.getMessage()||"",operations:n,actor:o,clientSeq:r.getID().getClientSeq(),serverSeq:r.getID().getServerSeq()},rawChange:this.isEnableDevtools()?r.toStruct():void 0}),r.hasPresenceChange()&&a.push({type:"presence-changed",source:E.UndoRedo,value:{clientID:o,presence:this.getPresence(o)}}),this.publish(a)}redo(){if(this.isUpdating)throw new ti(x.ErrRefused,"Redo is not allowed during an update");let e=this.internalHistory.popRedo();if(void 0===e)throw new ti(x.ErrRefused,"There is no operation to be redone");this.ensureClone();let t=rQ.create(this.changeID.next(),this.clone.root,this.clone.presences.get(this.changeID.getActorID())||{});for(let r of e){if(!(r instanceof tA)){new tl(t,ts(this.clone.presences.get(this.changeID.getActorID()))).set(r.value,{addToHistory:!0});continue}let e=t.issueTimeTicket();r.setExecutedAt(e),t.push(r)}let r=t.getChange();r.execute(this.clone.root,this.clone.presences,E.UndoRedo);let{opInfos:n,reverseOps:i}=r.execute(this.root,this.presences,E.UndoRedo),s=t.getReversePresence();if(s&&i.push({type:"presence",value:s}),i.length>0&&this.internalHistory.pushUndo(i),!r.hasPresenceChange()&&0===n.length)return;this.localChanges.push(r),this.changeID=r.getID();let o=this.changeID.getActorID(),a=[];n.length>0&&a.push({type:"local-change",source:E.UndoRedo,value:{message:r.getMessage()||"",operations:n,actor:o,clientSeq:r.getID().getClientSeq(),serverSeq:r.getID().getServerSeq()},rawChange:this.isEnableDevtools()?r.toStruct():void 0}),r.hasPresenceChange()&&a.push({type:"presence-changed",source:E.UndoRedo,value:{clientID:o,presence:this.getPresence(o)}}),this.publish(a)}getUndoStackForTest(){return this.internalHistory.getUndoStackForTest()}getRedoStackForTest(){return this.internalHistory.getRedoStackForTest()}broadcast(e,t,r){this.publish([{type:"local-broadcast",value:{topic:e,payload:t},options:r}])}getVersionVector(){return this.changeID.getVersionVector()}constructor(e,t){this.opts=t||{},this.key=e,this.status="detached",this.root=r$.create(),this.changeID=t3,this.checkpoint=t5,this.localChanges=[],this.eventStream=function(e){let t=new rX(e);return{subscribe:t.subscribe.bind(t),getProxy:()=>t}}(e=>{this.eventStreamObserver=e}),this.onlineClients=new Set,this.presences=new Map,this.isUpdating=!1,this.internalHistory=new nr,this.history={canUndo:this.canUndo.bind(this),canRedo:this.canRedo.bind(this),undo:this.undo.bind(this),redo:this.redo.bind(this)},function(e){if(!e.isEnableDevtools()||ni.has(e.getKey()))return;ns.set(e.getKey(),[]);let t=e.subscribe("all",t=>{t.some(e=>e.type!==J.StatusChanged&&e.type!==J.Snapshot&&e.type!==J.LocalChange&&e.type!==J.RemoteChange&&e.type!==J.Initialized&&e.type!==J.Watched&&e.type!==J.Unwatched&&e.type!==J.PresenceChanged)||(ns.get(e.getKey()).push(t),"synced"===nn&&no({msg:"doc::sync::partial",docKey:e.getKey(),event:t}))});ni.set(e.getKey(),[t]),no({msg:"refresh-devtools"},{force:!0}),window.addEventListener("message",t=>{var r;if((null===(r=t.data)||void 0===r?void 0:r.source)==="yorkie-devtools-panel")switch(t.data.msg){case"devtools::connect":if("disconnected"!==nn)break;nn="connected",no({msg:"doc::available",docKey:e.getKey()}),rG.info("[YD] Devtools connected. Doc: ".concat(e.getKey()));break;case"devtools::disconnect":nn="disconnected",rG.info("[YD] Devtools disconnected. Doc: ".concat(e.getKey()));break;case"devtools::subscribe":nn="synced",no({msg:"doc::sync::full",docKey:e.getKey(),events:ns.get(e.getKey())}),rG.info("[YD] Devtools subscribed. Doc: ".concat(e.getKey()))}})}(this)}}var nc=JSON.parse('{"u2":"yorkie-js-sdk","i8":"0.5.4"}');let nl=e=>{try{let t=JSON.stringify(e);if(void 0===t)return!1}catch(e){return!1}return!0};(w=M||(M={})).Manual="manual",w.Realtime="realtime",w.RealtimePushOnly="realtime-pushonly",w.RealtimeSyncOff="realtime-syncoff",(A=q||(q={})).Deactivated="deactivated",A.Activated="activated",(T=z||(z={})).SyncLoop="SyncLoop",T.WatchLoop="WatchLoop";let nh={syncLoopDuration:50,retrySyncLoopDelay:1e3,reconnectStreamDelay:1e3},nd={maxRetries:1/0,initialRetryInterval:1e3,maxBackoff:2e4};class nu{activate(){return this.isActive()?Promise.resolve():this.enqueueTask(async()=>this.rpcClient.activateClient({clientKey:this.key},{headers:{"x-shard-key":this.apiKey}}).then(e=>{this.id=e.clientId,this.status="activated",this.runSyncLoop(),rG.info('[AC] c:"'.concat(this.getKey(),'" activated, id:"').concat(this.id,'"'))}).catch(e=>{throw rG.error('[AC] c:"'.concat(this.getKey(),'" err :'),e),this.handleConnectError(e),e}))}deactivate(){return"deactivated"===this.status?Promise.resolve():this.enqueueTask(async()=>this.rpcClient.deactivateClient({clientId:this.id},{headers:{"x-shard-key":this.apiKey}}).then(()=>{this.deactivateInternal(),rG.info('[DC] c"'.concat(this.getKey(),'" deactivated'))}).catch(e=>{throw rG.error('[DC] c:"'.concat(this.getKey(),'" err :'),e),this.handleConnectError(e),e}))}attach(e){var t;let r=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};if(!this.isActive())throw new ti(x.ErrClientNotActivated,"".concat(this.key," is not active"));if(e.getStatus()!==B.Detached)throw new ti(x.ErrDocumentNotDetached,"".concat(e.getKey()," is not detached"));e.setActor(this.id),e.update((e,t)=>t.set(r.initialPresence||{}));let n=e.subscribe("local-broadcast",async t=>{var r;let{topic:n,payload:i}=t.value,s=null===(r=t.options)||void 0===r?void 0:r.error,o=t.options;try{await this.broadcast(e.getKey(),n,i,o)}catch(e){e instanceof Error&&(null==s||s(e))}}),i=null!==(t=r.syncMode)&&void 0!==t?t:"realtime";return this.enqueueTask(async()=>this.rpcClient.attachDocument({clientId:this.id,changePack:rU.toChangePack(e.createChangePack())},{headers:{"x-shard-key":"".concat(this.apiKey,"/").concat(e.getKey())}}).then(async t=>{let s=rU.fromChangePack(t.changePack);if(e.applyChangePack(s),e.getStatus()===B.Removed)return e;e.applyStatus(B.Attached),this.attachmentMap.set(e.getKey(),new rY(this.reconnectStreamDelay,e,t.documentId,i,n)),"manual"!==i&&await this.runWatchLoop(e.getKey()),rG.info('[AD] c:"'.concat(this.getKey(),'" attaches d:"').concat(e.getKey(),'"'));let o=e.getRootObject();if(r.initialRoot){let t=r.initialRoot;e.update(e=>{for(let[r,n]of Object.entries(t))o.has(r)||(e[r]=n)})}return e}).catch(e=>{throw rG.error('[AD] c:"'.concat(this.getKey(),'" err :'),e),this.handleConnectError(e),e}))}detach(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};if(!this.isActive())throw new ti(x.ErrClientNotActivated,"".concat(this.key," is not active"));let r=this.attachmentMap.get(e.getKey());if(!r)throw new ti(x.ErrDocumentNotAttached,"".concat(e.getKey()," is not attached"));return e.update((e,t)=>t.clear()),this.enqueueTask(async()=>{var n;return this.rpcClient.detachDocument({clientId:this.id,documentId:r.docID,changePack:rU.toChangePack(e.createChangePack()),removeIfNotAttached:null!==(n=t.removeIfNotAttached)&&void 0!==n&&n},{headers:{"x-shard-key":"".concat(this.apiKey,"/").concat(e.getKey())}}).then(t=>{let r=rU.fromChangePack(t.changePack);return e.applyChangePack(r),e.getStatus()!==B.Removed&&e.applyStatus(B.Detached),this.detachInternal(e.getKey()),rG.info('[DD] c:"'.concat(this.getKey(),'" detaches d:"').concat(e.getKey(),'"')),e}).catch(e=>{throw rG.error('[DD] c:"'.concat(this.getKey(),'" err :'),e),this.handleConnectError(e),e})})}async changeSyncMode(e,t){if(!this.isActive())throw new ti(x.ErrClientNotActivated,"".concat(this.key," is not active"));let r=this.attachmentMap.get(e.getKey());if(!r)throw new ti(x.ErrDocumentNotAttached,"".concat(e.getKey()," is not attached"));let n=r.syncMode;return n===t||((r.changeSyncMode(t),"manual"===t)?r.cancelWatchStream():("realtime"===t&&(r.remoteChangeEventReceived=!0),"manual"===n&&await this.runWatchLoop(e.getKey()))),e}sync(e){if(!this.isActive())throw new ti(x.ErrClientNotActivated,"".concat(this.key," is not active"));if(e){let t=this.attachmentMap.get(e.getKey());if(!t)throw new ti(x.ErrDocumentNotAttached,"".concat(e.getKey()," is not attached"));return this.enqueueTask(async()=>this.syncInternal(t,"realtime").catch(e=>{throw rG.error('[SY] c:"'.concat(this.getKey(),'" err :'),e),this.handleConnectError(e),e}))}return this.enqueueTask(async()=>{let e=[];for(let[,t]of this.attachmentMap)e.push(this.syncInternal(t,t.syncMode));return Promise.all(e).catch(e=>{throw rG.error('[SY] c:"'.concat(this.getKey(),'" err :'),e),this.handleConnectError(e),e})})}remove(e){if(!this.isActive())throw new ti(x.ErrClientNotActivated,"".concat(this.key," is not active"));let t=this.attachmentMap.get(e.getKey());if(!t)throw new ti(x.ErrDocumentNotAttached,"".concat(e.getKey()," is not attached"));e.setActor(this.id);let r=rU.toChangePack(e.createChangePack());return r.isRemoved=!0,this.enqueueTask(async()=>this.rpcClient.removeDocument({clientId:this.id,documentId:t.docID,changePack:r},{headers:{"x-shard-key":"".concat(this.apiKey,"/").concat(e.getKey())}}).then(t=>{let r=rU.fromChangePack(t.changePack);e.applyChangePack(r),this.detachInternal(e.getKey()),rG.info('[RD] c:"'.concat(this.getKey(),'" removes d:"').concat(e.getKey(),'"'))}).catch(e=>{throw rG.error('[RD] c:"'.concat(this.getKey(),'" err :'),e),this.handleConnectError(e),e}))}getID(){return this.id}getKey(){return this.key}isActive(){return"activated"===this.status}getStatus(){return this.status}getCondition(e){return this.conditions[e]}broadcast(e,t,r,n){var i;if(!this.isActive())throw new ti(x.ErrClientNotActivated,"".concat(this.key," is not active"));let s=this.attachmentMap.get(e);if(!s)throw new ti(x.ErrDocumentNotAttached,"".concat(e," is not attached"));if(!nl(r))throw new ti(x.ErrInvalidArgument,"payload is not serializable");let o=null!==(i=null==n?void 0:n.maxRetries)&&void 0!==i?i:nd.maxRetries,a=nd.maxBackoff,c=0,l=e=>Math.min(nd.initialRetryInterval*2**e,a),h=async()=>this.enqueueTask(async()=>this.rpcClient.broadcast({clientId:this.id,documentId:s.docID,topic:t,payload:new TextEncoder().encode(JSON.stringify(r))},{headers:{"x-shard-key":"".concat(this.apiKey,"/").concat(e)}}).then(()=>{rG.info('[BC] c:"'.concat(this.getKey(),'" broadcasts d:"').concat(e,'" t:"').concat(t,'"'))}).catch(e=>{if(rG.error('[BC] c:"'.concat(this.getKey(),'" err:'),e),this.handleConnectError(e)){if(ch(),l(++c-1)),rG.info('[BC] c:"'.concat(this.getKey(),'" retry attempt ').concat(c,"/").concat(o));else throw rG.error('[BC] c:"'.concat(this.getKey(),'" exceeded maximum retry attempts')),e}else throw e}));return h()}runSyncLoop(){let e=()=>{if(!this.isActive()){rG.debug('[SL] c:"'.concat(this.getKey(),'" exit sync loop')),this.conditions.SyncLoop=!1;return}let t=[];for(let[,e]of this.attachmentMap)e.needRealtimeSync()&&(e.remoteChangeEventReceived=!1,t.push(this.syncInternal(e,e.syncMode)));Promise.all(t).then(()=>setTimeout(e,this.syncLoopDuration)).catch(t=>{rG.error('[SL] c:"'.concat(this.getKey(),'" sync failed:'),t),this.handleConnectError(t)?setTimeout(e,this.retrySyncLoopDelay):this.conditions.SyncLoop=!1})};rG.debug('[SL] c:"'.concat(this.getKey(),'" run sync loop')),this.conditions.SyncLoop=!0,e()}async runWatchLoop(e){let t=this.attachmentMap.get(e);if(!t)throw new ti(x.ErrDocumentNotAttached,"".concat(e," is not attached"));return this.conditions.WatchLoop=!0,t.runWatchLoop(r=>{if(!this.isActive())return this.conditions.WatchLoop=!1,Promise.reject(new ti(x.ErrClientNotActivated,"".concat(this.key," is not active")));let n=new AbortController,i=this.rpcClient.watchDocument({clientId:this.id,documentId:t.docID},{headers:{"x-shard-key":"".concat(this.apiKey,"/").concat(e)},signal:n.signal});return t.doc.publish([{type:J.ConnectionChanged,value:L.Connected}]),rG.info('[WD] c:"'.concat(this.getKey(),'" watches d:"').concat(e,'"')),new Promise((e,s)=>{(async()=>{try{for await(let r of i)this.handleWatchDocumentsResponse(t,r),"initialization"===r.body.case&&e([i,n])}catch(e){t.doc.resetOnlineClients(),t.doc.publish([{type:J.Initialized,source:E.Local,value:t.doc.getPresences()}]),t.doc.publish([{type:J.ConnectionChanged,value:L.Disconnected}]),rG.debug('[WD] c:"'.concat(this.getKey(),'" unwatches')),this.handleConnectError(e)?r():this.conditions.WatchLoop=!1,s(e)}})()})})}handleWatchDocumentsResponse(e,t){if("event"===t.body.case&&t.body.value.type===I.DOCUMENT_CHANGED){e.remoteChangeEventReceived=!0;return}e.doc.applyWatchStream(t)}deactivateInternal(){for(let[e,t]of(this.status="deactivated",this.attachmentMap))this.detachInternal(e),t.doc.applyStatus(B.Detached)}detachInternal(e){let t=this.attachmentMap.get(e);t&&(t.cancelWatchStream(),t.unsubscribeBroadcastEvent(),this.attachmentMap.delete(e))}syncInternal(e,t){let{doc:r,docID:n}=e,i=r.createChangePack();return this.rpcClient.pushPullChanges({clientId:this.id,documentId:n,changePack:rU.toChangePack(i),pushOnly:"realtime-pushonly"===t},{headers:{"x-shard-key":"".concat(this.apiKey,"/").concat(r.getKey())}}).then(t=>{let n=rU.fromChangePack(t.changePack);if(n.hasChanges()&&("realtime-pushonly"===e.syncMode||"realtime-syncoff"===e.syncMode))return r;r.applyChangePack(n),e.doc.publish([{type:J.SyncStatusChanged,value:_.Synced}]),r.getStatus()===B.Removed&&this.detachInternal(r.getKey());let s=r.getKey(),o=n.getChangeSize();return rG.info('[PP] c:"'.concat(this.getKey(),'" sync d:"').concat(s,'", push:').concat(i.getChangeSize()," pull:").concat(o," cp:").concat(n.getCheckpoint().toTestString())),r}).catch(e=>{throw r.publish([{type:J.SyncStatusChanged,value:_.SyncFailed}]),rG.error('[PP] c:"'.concat(this.getKey(),'" err :'),e),e})}handleConnectError(e){return e instanceof G.K&&(e.code===H.E.Canceled||e.code===H.E.Unknown||e.code===H.E.ResourceExhausted||e.code===H.E.Unavailable||((rT(e)===x.ErrClientNotActivated||rT(e)===x.ErrClientNotFound)&&this.deactivateInternal(),!1))}enqueueTask(e){return new Promise((t,r)=>{this.taskQueue.push(()=>e().then(t).catch(r)),this.processing||this.processNext()})}async processNext(){if(0===this.taskQueue.length){this.processing=!1;return}try{this.processing=!0;let e=this.taskQueue.shift();await e()}catch(e){rG.error('[TQ] c:"'.concat(this.getKey(),'" process failed, id:"').concat(this.id,'"'))}this.processNext()}constructor(e,t){var r,n;this.processing=!1,t=t||nh,this.key=t.key?t.key:rH(),this.status="deactivated",this.attachmentMap=new Map,this.apiKey=t.apiKey||"",this.conditions={SyncLoop:!1,WatchLoop:!1},this.syncLoopDuration=t.syncLoopDuration||nh.syncLoopDuration,this.reconnectStreamDelay=t.reconnectStreamDelay||nh.reconnectStreamDelay,this.retrySyncLoopDelay=t.retrySyncLoopDelay||nh.retrySyncLoopDelay,this.rpcClient=(0,Y.Hb)(tr,(0,Z.u)({baseUrl:e,interceptors:[(r=t.apiKey,n=t.token,e=>async t=>(r&&t.header.set("x-api-key",r),n&&t.header.set("authorization",n),await e(t))),e=>async t=>(t.header.set("x-yorkie-user-agent",nc.u2+"/"+nc.i8),await e(t))]})),this.taskQueue=[]}}var ng={Client:nu,Document:na,Primitive:tC,Text:r3,Counter:r9,Tree:r6,LogLevel:O,setLogLevel:rW,IntType:N.IntegerCnt,LongType:N.LongCnt};"undefined"!=typeof globalThis&&(globalThis.yorkie={Client:nu,Document:na,Primitive:tC,Text:r3,Counter:r9,Tree:r6,LogLevel:O,setLogLevel:rW,IntType:N.IntegerCnt,LongType:N.LongCnt}),r(109);var nf=r(6182);function nm(e){let{content:t,actions:r}=e,[n,i]=(0,U.useState)(new Date),[s,o]=(0,U.useState)("Enter text here!"),a=n?W(new Date(n.toString())):"",c=e=>{let n=!1;switch(e){case"PUSH":n=!1,t.forEach(e=>{if(e.date===a)return n=!n,0}),n?r.updateContent(a,s):r.addContent(a,s),o("Enter text here!");break;case"DELETE":r.deleteContent(a)}};return(0,K.jsx)("article",{children:(0,K.jsxs)("div",{children:[(0,K.jsx)(nf.ZP,{onChange:i,value:n,locale:"en-EN",showNeighboringMonth:!1,formatDay:(e,t)=>t.toLocaleString("en",{day:"numeric"}),tileClassName:e=>{let{date:r}=e;return t.find(e=>e.date===W(r))?"highlight":""}}),(0,K.jsxs)("p",{children:["selected day : ",a]}),(0,K.jsx)("div",{className:V().memo,children:t.map((e,t)=>{if(e.date===a)return(0,K.jsx)("p",{children:e.text},t)})}),(0,K.jsxs)("div",{className:V().inputForm_editor,children:[(0,K.jsx)("h3",{children:"input form"}),(0,K.jsx)("textarea",{className:V().textArea,value:s,onChange:e=>o(e.target.value)})]}),(0,K.jsx)("button",{className:"button",onClick:()=>c("PUSH"),children:"push"}),(0,K.jsx)("button",{className:"button",onClick:()=>c("DELETE"),children:"pop"})]})})}let np=[{date:W(new Date).replace(/^\d{2}/,"01"),text:"payday"},{date:W(new Date).replace(/^\d{2}/,"17"),text:"Garry's birthday"}],ny="next.js-Scheduler-".concat(W(new Date));function nv(){let[e,t]=(0,U.useState)([]),[r,n]=(0,U.useState)(np),[i]=(0,U.useState)(()=>new ng.Document(ny));return(0,U.useEffect)(()=>{let e=new ng.Client("https://api.yorkie.dev",{apiKey:"cedaovjuioqlk4pjqn6g"});i.subscribe("presence",e=>{e.type!==J.PresenceChanged&&t(function(e){let t=[];for(let{presence:r}of e)t.push(r.userName);return t}(i.getPresences()))}),async function(t,r){await e.activate(),await e.attach(t,{initialPresence:{userName:function(){let e=Math.floor(Math.random()*j.length);return j[e]}()}}),t.update(e=>{e.content||(e.content=np)},"create default content if not exists"),t.subscribe(()=>{r(t.getRoot().content)}),r(t.getRoot().content)}(i,e=>n(e))},[]),(0,K.jsxs)("main",{className:V().main,children:[(0,K.jsxs)("p",{children:["peers : [",e.map((e,t)=>(0,K.jsxs)("span",{children:[" ",e,", "]},t))," ","]"]}),(0,K.jsx)(nm,{content:r,actions:{addContent(e,t){i.update(r=>{r.content.push({date:e,text:t})})},deleteContent(e){i.update(t=>{let r;for(let n of t.content)if(n.date===e){r=n;break}r&&t.content.deleteByID(r.getID())})},updateContent(e,t){i.update(r=>{let n;for(let t of r.content)if(t.date===e){n=t;break}n&&(n.text=t)})}}})]})}},109:function(){},7397:function(e){e.exports={main:"page_main__s_E_L",textArea:"page_textArea__sVKfA",memo:"page_memo__V0Ipn",inputForm_editor:"page_inputForm_editor__Tk7dD"}}},function(e){e.O(0,[662,828,852,744],function(){return e(e.s=4629)}),_N_E=e.O()}]); \ No newline at end of file diff --git a/examples/nextjs-scheduler/_next/static/6_IyhgbJWQCmw1jrIomT-/_buildManifest.js b/examples/nextjs-scheduler/_next/static/iUxV02k8f3BmWC_fcwSG3/_buildManifest.js similarity index 100% rename from examples/nextjs-scheduler/_next/static/6_IyhgbJWQCmw1jrIomT-/_buildManifest.js rename to examples/nextjs-scheduler/_next/static/iUxV02k8f3BmWC_fcwSG3/_buildManifest.js diff --git a/examples/nextjs-scheduler/_next/static/6_IyhgbJWQCmw1jrIomT-/_ssgManifest.js b/examples/nextjs-scheduler/_next/static/iUxV02k8f3BmWC_fcwSG3/_ssgManifest.js similarity index 100% rename from examples/nextjs-scheduler/_next/static/6_IyhgbJWQCmw1jrIomT-/_ssgManifest.js rename to examples/nextjs-scheduler/_next/static/iUxV02k8f3BmWC_fcwSG3/_ssgManifest.js diff --git a/examples/nextjs-scheduler/index.html b/examples/nextjs-scheduler/index.html index 44612c273..ea79faa2c 100644 --- a/examples/nextjs-scheduler/index.html +++ b/examples/nextjs-scheduler/index.html @@ -1 +1 @@ -Next.js react-calendar example

    peers : [ ]

    Mon
    Tue
    Wed
    Thu
    Fri
    Sat
    Sun

    selected day : 04-11-24

    input form

    \ No newline at end of file +Next.js react-calendar example

    peers : [ ]

    Mon
    Tue
    Wed
    Thu
    Fri
    Sat
    Sun

    selected day : 07-11-24

    input form

    \ No newline at end of file diff --git a/examples/nextjs-scheduler/index.txt b/examples/nextjs-scheduler/index.txt index 0710c3562..e0370b0c1 100644 --- a/examples/nextjs-scheduler/index.txt +++ b/examples/nextjs-scheduler/index.txt @@ -1,7 +1,7 @@ 2:I[9974,[],""] -3:I[1802,["662","static/chunks/662-2ca4b8930a4bf5cf.js","931","static/chunks/app/page-a4871ed0264d2385.js"],""] +3:I[1802,["662","static/chunks/662-2ca4b8930a4bf5cf.js","931","static/chunks/app/page-ae882aa4f8b3039b.js"],""] 4:I[4926,[],""] 5:I[4582,[],""] -0:["6_IyhgbJWQCmw1jrIomT-",[[["",{"children":["__PAGE__",{}]},"$undefined","$undefined",true],["",{"children":["__PAGE__",{},["$L1",["$","$L2",null,{"propsForComponent":{"params":{}},"Component":"$3","isStaticGeneration":true}],null]]},[null,["$","html",null,{"lang":"en","children":["$","body",null,{"children":["$","$L4",null,{"parallelRouterKey":"children","segmentPath":["children"],"loading":"$undefined","loadingStyles":"$undefined","loadingScripts":"$undefined","hasLoading":false,"error":"$undefined","errorStyles":"$undefined","errorScripts":"$undefined","template":["$","$L5",null,{}],"templateStyles":"$undefined","templateScripts":"$undefined","notFound":["$","h1",null,{"children":"404 not found"}],"notFoundStyles":[],"styles":[["$","link","0",{"rel":"stylesheet","href":"/yorkie-js-sdk/examples/nextjs-scheduler/_next/static/css/0b8518b4fc95b726.css","precedence":"next","crossOrigin":""}]]}]}]}],null]],[[["$","link","0",{"rel":"stylesheet","href":"/yorkie-js-sdk/examples/nextjs-scheduler/_next/static/css/55c28824c4a39011.css","precedence":"next","crossOrigin":""}]],"$L6"]]]] +0:["iUxV02k8f3BmWC_fcwSG3",[[["",{"children":["__PAGE__",{}]},"$undefined","$undefined",true],["",{"children":["__PAGE__",{},["$L1",["$","$L2",null,{"propsForComponent":{"params":{}},"Component":"$3","isStaticGeneration":true}],null]]},[null,["$","html",null,{"lang":"en","children":["$","body",null,{"children":["$","$L4",null,{"parallelRouterKey":"children","segmentPath":["children"],"loading":"$undefined","loadingStyles":"$undefined","loadingScripts":"$undefined","hasLoading":false,"error":"$undefined","errorStyles":"$undefined","errorScripts":"$undefined","template":["$","$L5",null,{}],"templateStyles":"$undefined","templateScripts":"$undefined","notFound":["$","h1",null,{"children":"404 not found"}],"notFoundStyles":[],"styles":[["$","link","0",{"rel":"stylesheet","href":"/yorkie-js-sdk/examples/nextjs-scheduler/_next/static/css/0b8518b4fc95b726.css","precedence":"next","crossOrigin":""}]]}]}]}],null]],[[["$","link","0",{"rel":"stylesheet","href":"/yorkie-js-sdk/examples/nextjs-scheduler/_next/static/css/55c28824c4a39011.css","precedence":"next","crossOrigin":""}]],"$L6"]]]] 6:[["$","meta","0",{"name":"viewport","content":"width=device-width, initial-scale=1"}],["$","meta","1",{"charSet":"utf-8"}],["$","title","2",{"children":"Next.js react-calendar example"}],["$","meta","3",{"name":"description","content":"example of yorkie-js-sdk with next.js & react-calendar"}],["$","link","4",{"rel":"icon","href":"/yorkie-js-sdk/examples/nextjs-scheduler/favicon.ico","type":"image/x-icon","sizes":"64x64"}]] 1:null diff --git a/examples/profile-stack/assets/index-DCwEJGaT.js b/examples/profile-stack/assets/index-D7a58tRm.js similarity index 98% rename from examples/profile-stack/assets/index-DCwEJGaT.js rename to examples/profile-stack/assets/index-D7a58tRm.js index 71de13e9d..1b2f02633 100644 --- a/examples/profile-stack/assets/index-DCwEJGaT.js +++ b/examples/profile-stack/assets/index-D7a58tRm.js @@ -19,7 +19,7 @@ var ca=Object.defineProperty;var ua=(n,t,e)=>t in n?ca(n,t,{enumerable:!0,config * limitations under the License. * * SPDX-License-Identifier: Apache-2.0 - */var we=null;try{we=new WebAssembly.Instance(new WebAssembly.Module(new Uint8Array([0,97,115,109,1,0,0,0,1,13,2,96,0,1,127,96,4,127,127,127,127,1,127,3,7,6,0,1,1,1,1,1,6,6,1,127,1,65,0,11,7,50,6,3,109,117,108,0,1,5,100,105,118,95,115,0,2,5,100,105,118,95,117,0,3,5,114,101,109,95,115,0,4,5,114,101,109,95,117,0,5,8,103,101,116,95,104,105,103,104,0,0,10,191,1,6,4,0,35,0,11,36,1,1,126,32,0,173,32,1,173,66,32,134,132,32,2,173,32,3,173,66,32,134,132,126,34,4,66,32,135,167,36,0,32,4,167,11,36,1,1,126,32,0,173,32,1,173,66,32,134,132,32,2,173,32,3,173,66,32,134,132,127,34,4,66,32,135,167,36,0,32,4,167,11,36,1,1,126,32,0,173,32,1,173,66,32,134,132,32,2,173,32,3,173,66,32,134,132,128,34,4,66,32,135,167,36,0,32,4,167,11,36,1,1,126,32,0,173,32,1,173,66,32,134,132,32,2,173,32,3,173,66,32,134,132,129,34,4,66,32,135,167,36,0,32,4,167,11,36,1,1,126,32,0,173,32,1,173,66,32,134,132,32,2,173,32,3,173,66,32,134,132,130,34,4,66,32,135,167,36,0,32,4,167,11])),{}).exports}catch{}function O(n,t,e){this.low=n|0,this.high=t|0,this.unsigned=!!e}O.prototype.__isLong__;Object.defineProperty(O.prototype,"__isLong__",{value:!0});function Z(n){return(n&&n.__isLong__)===!0}function Li(n){var t=Math.clz32(n&-n);return n?31-t:t}O.isLong=Z;var Ji={},Fi={};function Tr(n,t){var e,r,s;return t?(n>>>=0,(s=0<=n&&n<256)&&(r=Fi[n],r)?r:(e=B(n,0,!0),s&&(Fi[n]=e),e)):(n|=0,(s=-128<=n&&n<128)&&(r=Ji[n],r)?r:(e=B(n,n<0?-1:0,!1),s&&(Ji[n]=e),e))}O.fromInt=Tr;function Te(n,t){if(isNaN(n))return t?Wt:Se;if(t){if(n<0)return Wt;if(n>=Po)return Bo}else{if(n<=-$i)return te;if(n+1>=$i)return Oo}return n<0?Te(-n,t).neg():B(n%Br|0,n/Br|0,t)}O.fromNumber=Te;function B(n,t,e){return new O(n,t,e)}O.fromBits=B;var Un=Math.pow;function Ks(n,t,e){if(n.length===0)throw Error("empty string");if(typeof t=="number"?(e=t,t=!1):t=!!t,n==="NaN"||n==="Infinity"||n==="+Infinity"||n==="-Infinity")return t?Wt:Se;if(e=e||10,e<2||360)throw Error("interior hyphen");if(r===0)return Ks(n.substring(1),t,e).neg();for(var s=Te(Un(e,8)),i=Se,o=0;o>>0:this.low};T.toNumber=function(){return this.unsigned?(this.high>>>0)*Br+(this.low>>>0):this.high*Br+(this.low>>>0)};T.toString=function(t){if(t=t||10,t<2||36>>0,f=h.toString(t);if(o=l,o.isZero())return f+c;for(;f.length<6;)f="0"+f;c=""+f+c}};T.getHighBits=function(){return this.high};T.getHighBitsUnsigned=function(){return this.high>>>0};T.getLowBits=function(){return this.low};T.getLowBitsUnsigned=function(){return this.low>>>0};T.getNumBitsAbs=function(){if(this.isNegative())return this.eq(te)?64:this.neg().getNumBitsAbs();for(var t=this.high!=0?this.high:this.low,e=31;e>0&&!(t&1<=0};T.isOdd=function(){return(this.low&1)===1};T.isEven=function(){return(this.low&1)===0};T.equals=function(t){return Z(t)||(t=Ce(t)),this.unsigned!==t.unsigned&&this.high>>>31===1&&t.high>>>31===1?!1:this.high===t.high&&this.low===t.low};T.eq=T.equals;T.notEquals=function(t){return!this.eq(t)};T.neq=T.notEquals;T.ne=T.notEquals;T.lessThan=function(t){return this.comp(t)<0};T.lt=T.lessThan;T.lessThanOrEqual=function(t){return this.comp(t)<=0};T.lte=T.lessThanOrEqual;T.le=T.lessThanOrEqual;T.greaterThan=function(t){return this.comp(t)>0};T.gt=T.greaterThan;T.greaterThanOrEqual=function(t){return this.comp(t)>=0};T.gte=T.greaterThanOrEqual;T.ge=T.greaterThanOrEqual;T.compare=function(t){if(Z(t)||(t=Ce(t)),this.eq(t))return 0;var e=this.isNegative(),r=t.isNegative();return e&&!r?-1:!e&&r?1:this.unsigned?t.high>>>0>this.high>>>0||t.high===this.high&&t.low>>>0>this.low>>>0?-1:1:this.sub(t).isNegative()?-1:1};T.comp=T.compare;T.negate=function(){return!this.unsigned&&this.eq(te)?te:this.not().add(Sr)};T.neg=T.negate;T.add=function(t){Z(t)||(t=Ce(t));var e=this.high>>>16,r=this.high&65535,s=this.low>>>16,i=this.low&65535,o=t.high>>>16,c=t.high&65535,l=t.low>>>16,h=t.low&65535,f=0,p=0,v=0,m=0;return m+=i+h,v+=m>>>16,m&=65535,v+=s+l,p+=v>>>16,v&=65535,p+=r+c,f+=p>>>16,p&=65535,f+=e+o,f&=65535,B(v<<16|m,f<<16|p,this.unsigned)};T.subtract=function(t){return Z(t)||(t=Ce(t)),this.add(t.neg())};T.sub=T.subtract;T.multiply=function(t){if(this.isZero())return this;if(Z(t)||(t=Ce(t)),we){var e=we.mul(this.low,this.high,t.low,t.high);return B(e,we.get_high(),this.unsigned)}if(t.isZero())return this.unsigned?Wt:Se;if(this.eq(te))return t.isOdd()?te:Se;if(t.eq(te))return this.isOdd()?te:Se;if(this.isNegative())return t.isNegative()?this.neg().mul(t.neg()):this.neg().mul(t).neg();if(t.isNegative())return this.mul(t.neg()).neg();if(this.lt(Ui)&&t.lt(Ui))return Te(this.toNumber()*t.toNumber(),this.unsigned);var r=this.high>>>16,s=this.high&65535,i=this.low>>>16,o=this.low&65535,c=t.high>>>16,l=t.high&65535,h=t.low>>>16,f=t.low&65535,p=0,v=0,m=0,w=0;return w+=o*f,m+=w>>>16,w&=65535,m+=i*f,v+=m>>>16,m&=65535,m+=o*h,v+=m>>>16,m&=65535,v+=s*f,p+=v>>>16,v&=65535,v+=i*h,p+=v>>>16,v&=65535,v+=o*l,p+=v>>>16,v&=65535,p+=r*f+s*h+i*l+o*c,p&=65535,B(m<<16|w,p<<16|v,this.unsigned)};T.mul=T.multiply;T.divide=function(t){if(Z(t)||(t=Ce(t)),t.isZero())throw Error("division by zero");if(we){if(!this.unsigned&&this.high===-2147483648&&t.low===-1&&t.high===-1)return this;var e=(this.unsigned?we.div_u:we.div_s)(this.low,this.high,t.low,t.high);return B(e,we.get_high(),this.unsigned)}if(this.isZero())return this.unsigned?Wt:Se;var r,s,i;if(this.unsigned){if(t.unsigned||(t=t.toUnsigned()),t.gt(this))return Wt;if(t.gt(this.shru(1)))return Do;i=Wt}else{if(this.eq(te)){if(t.eq(Sr)||t.eq(Bs))return te;if(t.eq(te))return Sr;var o=this.shr(1);return r=o.div(t).shl(1),r.eq(Se)?t.isNegative()?Sr:Bs:(s=this.sub(t.mul(r)),i=r.add(s.div(t)),i)}else if(t.eq(te))return this.unsigned?Wt:Se;if(this.isNegative())return t.isNegative()?this.neg().div(t.neg()):this.neg().div(t).neg();if(t.isNegative())return this.div(t.neg()).neg();i=Se}for(s=this;s.gte(t);){r=Math.max(1,Math.floor(s.toNumber()/t.toNumber()));for(var c=Math.ceil(Math.log(r)/Math.LN2),l=c<=48?1:Un(2,c-48),h=Te(r),f=h.mul(t);f.isNegative()||f.gt(s);)r-=l,h=Te(r,this.unsigned),f=h.mul(t);h.isZero()&&(h=Sr),i=i.add(h),s=s.sub(f)}return i};T.div=T.divide;T.modulo=function(t){if(Z(t)||(t=Ce(t)),we){var e=(this.unsigned?we.rem_u:we.rem_s)(this.low,this.high,t.low,t.high);return B(e,we.get_high(),this.unsigned)}return this.sub(this.div(t).mul(t))};T.mod=T.modulo;T.rem=T.modulo;T.not=function(){return B(~this.low,~this.high,this.unsigned)};T.countLeadingZeros=function(){return this.high?Math.clz32(this.high):Math.clz32(this.low)+32};T.clz=T.countLeadingZeros;T.countTrailingZeros=function(){return this.low?Li(this.low):Li(this.high)+32};T.ctz=T.countTrailingZeros;T.and=function(t){return Z(t)||(t=Ce(t)),B(this.low&t.low,this.high&t.high,this.unsigned)};T.or=function(t){return Z(t)||(t=Ce(t)),B(this.low|t.low,this.high|t.high,this.unsigned)};T.xor=function(t){return Z(t)||(t=Ce(t)),B(this.low^t.low,this.high^t.high,this.unsigned)};T.shiftLeft=function(t){return Z(t)&&(t=t.toInt()),(t&=63)===0?this:t<32?B(this.low<>>32-t,this.unsigned):B(0,this.low<>>t|this.high<<32-t,this.high>>t,this.unsigned):B(this.high>>t-32,this.high>=0?0:-1,this.unsigned)};T.shr=T.shiftRight;T.shiftRightUnsigned=function(t){return Z(t)&&(t=t.toInt()),(t&=63)===0?this:t<32?B(this.low>>>t|this.high<<32-t,this.high>>>t,this.unsigned):t===32?B(this.high,0,this.unsigned):B(this.high>>>t-32,0,this.unsigned)};T.shru=T.shiftRightUnsigned;T.shr_u=T.shiftRightUnsigned;T.rotateLeft=function(t){var e;return Z(t)&&(t=t.toInt()),(t&=63)===0?this:t===32?B(this.high,this.low,this.unsigned):t<32?(e=32-t,B(this.low<>>e,this.high<>>e,this.unsigned)):(t-=32,e=32-t,B(this.high<>>e,this.low<>>e,this.unsigned))};T.rotl=T.rotateLeft;T.rotateRight=function(t){var e;return Z(t)&&(t=t.toInt()),(t&=63)===0?this:t===32?B(this.high,this.low,this.unsigned):t<32?(e=32-t,B(this.high<>>t,this.low<>>t,this.unsigned)):(t-=32,e=32-t,B(this.low<>>t,this.high<>>t,this.unsigned))};T.rotr=T.rotateRight;T.toSigned=function(){return this.unsigned?B(this.low,this.high,!1):this};T.toUnsigned=function(){return this.unsigned?this:B(this.low,this.high,!0)};T.toBytes=function(t){return t?this.toBytesLE():this.toBytesBE()};T.toBytesLE=function(){var t=this.high,e=this.low;return[e&255,e>>>8&255,e>>>16&255,e>>>24,t&255,t>>>8&255,t>>>16&255,t>>>24]};T.toBytesBE=function(){var t=this.high,e=this.low;return[t>>>24,t>>>16&255,t>>>8&255,t&255,e>>>24,e>>>16&255,e>>>8&255,e&255]};O.fromBytes=function(t,e,r){return r?O.fromBytesLE(t,e):O.fromBytesBE(t,e)};O.fromBytesLE=function(t,e){return new O(t[0]|t[1]<<8|t[2]<<16|t[3]<<24,t[4]|t[5]<<8|t[6]<<16|t[7]<<24,e)};O.fromBytesBE=function(t,e){return new O(t[4]<<24|t[5]<<16|t[6]<<8|t[7],t[0]<<24|t[1]<<16|t[2]<<8|t[3],e)};var W=(n=>(n[n.Null=0]="Null",n[n.Boolean=1]="Boolean",n[n.Integer=2]="Integer",n[n.Long=3]="Long",n[n.Double=4]="Double",n[n.String=5]="String",n[n.Bytes=6]="Bytes",n[n.Date=7]="Date",n))(W||{});class $ extends en{constructor(e,r){super(r);a(this,"valueType");a(this,"value");this.valueType=$.getPrimitiveType(e),this.value=e===void 0?null:e}static of(e,r){return new $(e,r)}static valueFromBytes(e,r){switch(e){case 0:return null;case 1:return!!r[0];case 2:return r[0]|r[1]<<8|r[2]<<16|r[3]<<24;case 4:{const s=new DataView(r.buffer);return r.forEach(function(i,o){s.setUint8(o,i)}),s.getFloat64(0,!0)}case 5:return new TextDecoder("utf-8").decode(r);case 3:return O.fromBytesLE(Array.from(r));case 6:return r;case 7:return new Date(O.fromBytesLE(Array.from(r),!0).toNumber());default:throw new g(d.ErrUnimplemented,`unimplemented type: ${e}`)}}toJSON(){return this.valueType===5?`"${qe(this.value)}"`:`${this.value}`}toSortedJSON(){return this.toJSON()}toJSForTest(){return{createdAt:this.getCreatedAt().toTestString(),value:this.value,type:"YORKIE_PRIMITIVE"}}deepcopy(){const e=$.of(this.value,this.getCreatedAt());return e.setMovedAt(this.getMovedAt()),e.setRemovedAt(this.getRemovedAt()),e}getType(){return this.valueType}static getPrimitiveType(e){switch(typeof e){case"undefined":return 0;case"boolean":return 1;case"number":return this.isInteger(e)?2:4;case"string":return 5;case"object":if(e===null)return 0;if(e instanceof O)return 3;if(e instanceof Uint8Array)return 6;if(e instanceof Date)return 7}}static isSupport(e){return $.getPrimitiveType(e)!==void 0}static isInteger(e){return e%1===0}isNumericType(){const e=this.valueType;return e===2||e===3||e===4}getValue(){return this.value}toBytes(){switch(this.valueType){case 0:return new Uint8Array;case 1:return this.value?new Uint8Array([1]):new Uint8Array([0]);case 2:{const e=this.value;return new Uint8Array([e&255,e>>8&255,e>>16&255,e>>24&255])}case 4:{const e=this.value,r=new Uint8Array(8);return new DataView(r.buffer).setFloat64(0,e,!0),r}case 5:return new TextEncoder().encode(this.value);case 3:{const r=this.value.toBytesLE();return Uint8Array.from(r)}case 6:return this.value;case 7:{const e=this.value,r=O.fromNumber(e.getTime(),!0).toBytesLE();return Uint8Array.from(r)}default:throw new g(d.ErrUnimplemented,`unimplemented type: ${this.valueType}`)}}}class qn extends Co{constructor(e){super(e);a(this,"prev");a(this,"next");this.value=e}static createAfter(e,r){const s=new qn(r),i=e.next;return e.next=s,s.prev=e,s.next=i,i&&(i.prev=s),s}remove(e){return this.value.remove(e)}getCreatedAt(){return this.value.getCreatedAt()}getPositionedAt(){return this.value.getPositionedAt()}release(){this.prev&&(this.prev.next=this.next),this.next&&(this.next.prev=this.prev),this.prev=void 0,this.next=void 0}getLength(){return this.value.isRemoved()?0:1}getPrev(){return this.prev}getNext(){return this.next}getValue(){return this.value}isRemoved(){return this.value.isRemoved()}}class Xr{constructor(){a(this,"dummyHead");a(this,"last");a(this,"nodeMapByIndex");a(this,"nodeMapByCreatedAt");const t=$.of(0,xe);t.setRemovedAt(xe),this.dummyHead=new qn(t),this.last=this.dummyHead,this.nodeMapByIndex=new Yr,this.nodeMapByCreatedAt=new Map,this.nodeMapByIndex.insert(this.dummyHead),this.nodeMapByCreatedAt.set(this.dummyHead.getCreatedAt().toIDString(),this.dummyHead)}static create(){return new Xr}get length(){return this.nodeMapByIndex.length}findNextBeforeExecutedAt(t,e){let r=this.nodeMapByCreatedAt.get(t.toIDString());if(!r)throw new g(d.ErrInvalidArgument,`cant find the given node: ${t.toIDString()}`);for(;r.getNext()&&r.getNext().getPositionedAt().after(e);)r=r.getNext();return r}release(t){this.last===t&&(this.last=t.getPrev()),t.release(),this.nodeMapByIndex.delete(t),this.nodeMapByCreatedAt.delete(t.getValue().getCreatedAt().toIDString())}insertAfter(t,e,r=e.getCreatedAt()){const s=this.findNextBeforeExecutedAt(t,r),i=qn.createAfter(s,e);s===this.last&&(this.last=i),this.nodeMapByIndex.insertAfter(s,i),this.nodeMapByCreatedAt.set(i.getCreatedAt().toIDString(),i)}moveAfter(t,e,r){const s=this.nodeMapByCreatedAt.get(t.toIDString());if(!s)throw new g(d.ErrInvalidArgument,`cant find the given node: ${t.toIDString()}`);const i=this.nodeMapByCreatedAt.get(e.toIDString());if(!i)throw new g(d.ErrInvalidArgument,`cant find the given node: ${e.toIDString()}`);s!==i&&(!i.getValue().getMovedAt()||r.after(i.getValue().getMovedAt()))&&(this.release(i),this.insertAfter(s.getCreatedAt(),i.getValue(),r),i.getValue().setMovedAt(r))}insert(t){this.insertAfter(this.last.getCreatedAt(),t)}getByID(t){return this.nodeMapByCreatedAt.get(t.toIDString())}subPathOf(t){const e=this.nodeMapByCreatedAt.get(t.toIDString());if(e)return String(this.nodeMapByIndex.indexOf(e))}purge(t){const e=this.nodeMapByCreatedAt.get(t.getCreatedAt().toIDString());if(!e)throw new g(d.ErrInvalidArgument,`fail to find the given createdAt: ${t.getCreatedAt().toIDString()}`);this.release(e)}getByIndex(t){if(t>=this.length)return;const[e,r]=this.nodeMapByIndex.find(t);let s=e;if(t===0&&e===this.dummyHead||r>0)do s&&(s=s.getNext());while(s&&s.isRemoved());return s}getPrevCreatedAt(t){let e=this.nodeMapByCreatedAt.get(t.toIDString());do e=e.getPrev();while(this.dummyHead!==e&&e.isRemoved());return e.getValue().getCreatedAt()}delete(t,e){const r=this.nodeMapByCreatedAt.get(t.toIDString()),s=r.isRemoved();return r.remove(e)&&!s&&this.nodeMapByIndex.splayNode(r),r.getValue()}deleteByIndex(t,e){const r=this.getByIndex(t);if(r)return r.remove(e)&&this.nodeMapByIndex.splayNode(r),r.getValue()}getHead(){return this.dummyHead.getValue()}getLast(){return this.last.getValue()}getLastCreatedAt(){return this.last.getCreatedAt()}toTestString(){const t=[];for(const e of this){const r=`${e.getCreatedAt().toIDString()}:${e.getValue().toJSON()}`;e.isRemoved()?t.push(`{${r}}`):t.push(`[${r}]`)}return t.join("")}*[Symbol.iterator](){let t=this.dummyHead.getNext();for(;t;)yield t,t=t.getNext()}}class ae extends ir{constructor(e,r){super(e);a(this,"elements");this.elements=r}static create(e,r){if(!r)return new ae(e,Xr.create());const s=Xr.create();for(const i of r)s.insertAfter(s.getLastCreatedAt(),i.deepcopy());return new ae(e,s)}subPathOf(e){return this.elements.subPathOf(e)}purge(e){this.elements.purge(e)}insertAfter(e,r){this.elements.insertAfter(e,r)}moveAfter(e,r,s){this.elements.moveAfter(e,r,s)}get(e){const r=this.elements.getByIndex(e);return r==null?void 0:r.getValue()}getByID(e){const r=this.elements.getByID(e);return r==null?void 0:r.getValue()}getHead(){return this.elements.getHead()}getLast(){return this.elements.getLast()}getPrevCreatedAt(e){return this.elements.getPrevCreatedAt(e)}delete(e,r){return this.elements.delete(e,r)}deleteByIndex(e,r){return this.elements.deleteByIndex(e,r)}getLastCreatedAt(){return this.elements.getLastCreatedAt()}get length(){return this.elements.length}*[Symbol.iterator](){for(const e of this.elements)e.isRemoved()||(yield e.getValue())}toTestString(){return this.elements.toTestString()}getDescendants(e){for(const r of this.elements){const s=r.getValue();if(e(s,this))return;s instanceof ir&&s.getDescendants(e)}}toJSON(){const e=[];for(const r of this)e.push(r.toJSON());return`[${e.join(",")}]`}toJS(){return JSON.parse(this.toJSON())}toJSForTest(){const e={};for(let r=0;r({...m,value:m.value?{attributes:xr(m.value.getAttributes()),content:m.value.getContent()}:{attributes:void 0,content:""},type:"content"}));return[h,v,f,[l,l]]}setStyle(e,r,s,i){const[,o]=this.rgaTreeSplit.findNodeWithSplit(e[1],s),[,c]=this.rgaTreeSplit.findNodeWithSplit(e[0],s),l=[],h=this.rgaTreeSplit.findBetween(c,o),f=new Map,p=[];for(const m of h){const w=m.getCreatedAt().getActorID(),k=i!=null&&i.size?i.has(w)?i.get(w):xe:qr;if(m.canStyle(s,k)){const E=f.get(w),C=m.getCreatedAt();(!E||C.after(E))&&f.set(w,C),p.push(m)}}const v=[];for(const m of p){if(m.isRemoved())continue;const[w,k]=this.rgaTreeSplit.findIndexesFromRange(m.createPosRange());l.push({type:"style",actor:s.getActorID(),from:w,to:k,value:{attributes:xr(r)}});for(const[E,C]of Object.entries(r)){const[P]=m.getValue().setAttr(E,C,s);P!==void 0&&v.push({parent:m.getValue(),child:P})}}return[f,v,l]}indexRangeToPosRange(e,r){const s=this.rgaTreeSplit.indexToPos(e);return e===r?[s,s]:[s,this.rgaTreeSplit.indexToPos(r)]}get length(){return this.rgaTreeSplit.length}getTreeByIndex(){return this.rgaTreeSplit.getTreeByIndex()}getTreeByID(){return this.rgaTreeSplit.getTreeByID()}toJSON(){const e=[];for(const r of this.rgaTreeSplit)r.isRemoved()||e.push(r.getValue().toJSON());return`[${e.join(",")}]`}toSortedJSON(){return this.toJSON()}toJSForTest(){return{createdAt:this.getCreatedAt().toTestString(),value:JSON.parse(this.toJSON()),type:"YORKIE_TEXT"}}toString(){return this.rgaTreeSplit.toString()}values(){const e=[];for(const r of this.rgaTreeSplit)if(!r.isRemoved()){const s=r.getValue();e.push({attributes:xr(s.getAttributes()),content:s.getContent()})}return e}getRGATreeSplit(){return this.rgaTreeSplit}toTestString(){return this.rgaTreeSplit.toTestString()}deepcopy(){const e=new Ae(this.rgaTreeSplit.deepcopy(),this.getCreatedAt());return e.remove(this.getRemovedAt()),e}findIndexesFromRange(e){return this.rgaTreeSplit.findIndexesFromRange(e)}getGCPairs(){const e=[];for(const r of this.rgaTreeSplit){r.getRemovedAt()&&e.push({parent:this.rgaTreeSplit,child:r});for(const s of r.getValue().getGCPairs())e.push(s)}return e}}class rn extends Ne{constructor(e,r,s,i,o,c,l){super(e,l);a(this,"fromPos");a(this,"toPos");a(this,"maxCreatedAtMapByActor");a(this,"content");a(this,"attributes");this.fromPos=r,this.toPos=s,this.maxCreatedAtMapByActor=i,this.content=o,this.attributes=c}static create(e,r,s,i,o,c,l){return new rn(e,r,s,i,o,c,l)}execute(e){const r=e.findByCreatedAt(this.getParentCreatedAt());if(!r)throw new g(d.ErrInvalidArgument,`fail to find ${this.getParentCreatedAt()}`);if(!(r instanceof Ae))throw new g(d.ErrInvalidArgument,"fail to execute, only Text can execute edit");const s=r,[,i,o]=s.edit([this.fromPos,this.toPos],this.content,this.getExecutedAt(),Object.fromEntries(this.attributes),this.maxCreatedAtMapByActor);for(const c of o)e.registerGCPair(c);return{opInfos:i.map(({from:c,to:l,value:h})=>({type:"edit",from:c,to:l,value:h,path:e.createPath(this.getParentCreatedAt())}))}}getEffectedCreatedAt(){return this.getParentCreatedAt()}toTestString(){const e=this.getParentCreatedAt().toTestString(),r=this.fromPos.toTestString(),s=this.toPos.toTestString(),i=this.content;return`${e}.EDIT(${r},${s},${i})`}getFromPos(){return this.fromPos}getToPos(){return this.toPos}getContent(){return this.content}getAttributes(){return this.attributes||new Map}getMaxCreatedAtMapByActor(){return this.maxCreatedAtMapByActor}}class nn extends Ne{constructor(e,r,s,i,o,c){super(e,c);a(this,"fromPos");a(this,"toPos");a(this,"maxCreatedAtMapByActor");a(this,"attributes");this.fromPos=r,this.toPos=s,this.maxCreatedAtMapByActor=i,this.attributes=o}static create(e,r,s,i,o,c){return new nn(e,r,s,i,o,c)}execute(e){const r=e.findByCreatedAt(this.getParentCreatedAt());if(!r)throw new g(d.ErrInvalidArgument,`fail to find ${this.getParentCreatedAt()}`);if(!(r instanceof Ae))throw new g(d.ErrInvalidArgument,"fail to execute, only Text can execute edit");const s=r,[,i,o]=s.setStyle([this.fromPos,this.toPos],this.attributes?Object.fromEntries(this.attributes):{},this.getExecutedAt(),this.maxCreatedAtMapByActor);for(const c of i)e.registerGCPair(c);return{opInfos:o.map(({from:c,to:l,value:h})=>({type:"style",from:c,to:l,value:h,path:e.createPath(this.getParentCreatedAt())}))}}getEffectedCreatedAt(){return this.getParentCreatedAt()}toTestString(){const e=this.getParentCreatedAt().toTestString(),r=this.fromPos.toTestString(),s=this.toPos.toTestString(),i=this.attributes;return`${e}.STYL(${r},${s},${JSON.stringify(i)})`}getFromPos(){return this.fromPos}getToPos(){return this.toPos}getAttributes(){return this.attributes}getMaxCreatedAtMapByActor(){return this.maxCreatedAtMapByActor}}const qc=2,Vc="root",Ht="text";function Mr(n,t){let e=0;const r=n.children;for(let s=0;s0)throw new g(d.ErrRefused,"Text node cannot have children")}updateAncestorsSize(){let t=this.parent;const e=this.isRemoved?-1:1;for(;t&&(t.size+=this.paddedSize*e,!t.isRemoved);)t=t.parent}updateDescendantsSize(){let t=0;for(const e of this._children){const r=e.updateDescendantsSize();e.isRemoved||(t+=r)}return this.size+=t,this.paddedSize}get isText(){return this.type===Ht}get paddedSize(){return this.size+(this.isText?0:qc)}isAncestorOf(t){return Kc(this,t)}get nextSibling(){const t=this.parent.findOffset(this),e=this.parent.children[t+1];if(e)return e}get prevSibling(){const t=this.parent.findOffset(this),e=this.parent.children[t-1];if(e)return e}splitText(t,e){if(t===0||t===this.size)return;const r=this.value.slice(0,t),s=this.value.slice(t);if(!s.length)return;this.value=r;const i=this.cloneText(t+e);return i.value=s,this.parent.insertAfterInternal(i,this),i}get children(){return this._children.filter(t=>!t.isRemoved)}get allChildren(){return[...this._children]}hasTextChild(){return this.children.length>0&&this.children.every(t=>t.isText)}append(...t){if(this.isText)throw new g(d.ErrRefused,"Text node cannot have children");this._children.push(...t);for(const e of t)e.parent=this,e.updateAncestorsSize()}prepend(...t){if(this.isText)throw new g(d.ErrRefused,"Text node cannot have children");this._children.unshift(...t);for(const e of t)e.parent=this}insertBefore(t,e){if(this.isText)throw new g(d.ErrRefused,"Text node cannot have children");const r=this._children.indexOf(e);if(r===-1)throw new g(d.ErrInvalidArgument,"child not found");this.insertAtInternal(t,r),t.updateAncestorsSize()}insertAfter(t,e){if(this.isText)throw new g(d.ErrRefused,"Text node cannot have children");const r=this._children.indexOf(e);if(r===-1)throw new g(d.ErrInvalidArgument,"child not found");this.insertAtInternal(t,r+1),t.updateAncestorsSize()}insertAt(t,e){if(this.isText)throw new g(d.ErrRefused,"Text node cannot have children");this.insertAtInternal(t,e),t.updateAncestorsSize()}removeChild(t){if(this.isText)throw new g(d.ErrRefused,"Text node cannot have children");const e=this._children.indexOf(t);if(e===-1)throw new g(d.ErrInvalidArgument,"child not found");this._children.splice(e,1),t.parent=void 0}splitElement(t,e){const r=this.cloneElement(e);this.parent.insertAfterInternal(r,this),r.updateAncestorsSize();const s=this.children.slice(0,t),i=this.children.slice(t);this._children=s,r._children=i,this.size=this._children.reduce((o,c)=>o+c.paddedSize,0),r.size=r._children.reduce((o,c)=>o+c.paddedSize,0);for(const o of r._children)o.parent=r;return r}insertAfterInternal(t,e){if(this.isText)throw new g(d.ErrRefused,"Text node cannot have children");const r=this._children.indexOf(e);if(r===-1)throw new g(d.ErrInvalidArgument,"child not found");this.insertAtInternal(t,r+1)}insertAtInternal(t,e){if(this.isText)throw new g(d.ErrRefused,"Text node cannot have children");this._children.splice(e,0,t),t.parent=this}findOffset(t){if(this.isText)throw new g(d.ErrRefused,"Text node cannot have children");if(t.isRemoved){const e=this._children.indexOf(t);return this.allChildren.splice(0,e).filter(s=>!s.isRemoved).length}return this.children.indexOf(t)}findBranchOffset(t){if(this.isText)throw new g(d.ErrRefused,"Text node cannot have children");let e=t;for(;e;){const r=this._children.indexOf(e);if(r!==-1)return r;e=e.parent}return-1}}function Kc(n,t){if(n===t)return!1;for(;t.parent;){if(t.parent===n)return!0;t=t.parent}return!1}var j=(n=>(n.Start="Start",n.End="End",n.Text="Text",n))(j||{});function Ro(n,t,e,r){if(t>e)throw new g(d.ErrInvalidArgument,`from is greater than to: ${t} > ${e}`);if(t>n.size)throw new g(d.ErrInvalidArgument,`from is out of range: ${t} > ${n.size}`);if(e>n.size)throw new g(d.ErrInvalidArgument,`to is out of range: ${e} > ${n.size}`);if(t===e)return;let s=0;for(const i of n.children){if(t-i.paddedSizei.size;(i.isText||l)&&r([i,i.isText?"Text":"Start"],h),Ro(i,Math.max(0,o),Math.min(c,i.size),r),h&&r([i,"End"],h)}s+=i.paddedSize}}function Lo(n,t,e=0){for(const r of n.children)Lo(r,t,e+1);t(n,e)}function Wn(n,t,e=0){for(const r of n._children)Wn(r,t,e+1);t(n,e)}function Rs(n,t,e=!0){if(t>n.size)throw new g(d.ErrInvalidArgument,`index is out of range: ${t} > ${n.size}`);if(n.isText)return{node:n,offset:t};let r=0,s=0;for(const i of n.children){if(e&&i.isText&&i.size>=t-s)return Rs(i,t-s,e);if(t===s)return{node:n,offset:r};if(!e&&i.paddedSize===t-s)return{node:n,offset:r+1};if(i.paddedSize>t-s)return Rs(i,t-s-1,e);s+=i.paddedSize,r+=1}return{node:n,offset:r}}function Jo(n){return n.isText||n.children.length===0?n:Jo(n.children[0])}function jc(n,t){if(n.sizen===t?0:n0)if(e.right)e.right.parent=e,e=e.right;else return e;else if(r<0)if(e.left)e.left.parent=e,e=e.left;else{let s=e.parent,i=e;for(;s&&i===s.left;)i=s,s=s.parent;return s}else return e}}lastEntry(){if(!this.root)return this.root;let t=this.root;for(;t.right;)t=t.right;return t}size(){return this.counter}isEmpty(){return this.counter===0}getInternal(t,e){for(;e;){const r=this.comparator(t,e.key);if(r===0)return e;r<0?e=e.left:r>0&&(e=e.right)}}putInternal(t,e,r){if(!r)return this.counter+=1,new Hc(t,e,!0);const s=this.comparator(t,r.key);return s<0?r.left=this.putInternal(t,e,r.left):s>0?r.right=this.putInternal(t,e,r.right):r.value=e,this.isRed(r.right)&&!this.isRed(r.left)&&(r=this.rotateLeft(r)),this.isRed(r.left)&&this.isRed(r.left.left)&&(r=this.rotateRight(r)),this.isRed(r.left)&&this.isRed(r.right)&&this.flipColors(r),r}removeInternal(t,e){if(this.comparator(e,t.key)<0)!this.isRed(t.left)&&!this.isRed(t.left.left)&&(t=this.moveRedLeft(t)),t.left=this.removeInternal(t.left,e);else{if(this.isRed(t.left)&&(t=this.rotateRight(t)),this.comparator(e,t.key)===0&&!t.right){this.counter-=1;return}if(!this.isRed(t.right)&&!this.isRed(t.right.left)&&(t=this.moveRedRight(t)),this.comparator(e,t.key)===0){this.counter-=1;const r=this.min(t.right);t.value=r.value,t.key=r.key,t.right=this.removeMin(t.right)}else t.right=this.removeInternal(t.right,e)}return this.fixUp(t)}min(t){return t.left?this.min(t.left):t}removeMin(t){if(t.left)return!this.isRed(t.left)&&!this.isRed(t.left.left)&&(t=this.moveRedLeft(t)),t.left=this.removeMin(t.left),this.fixUp(t)}fixUp(t){return this.isRed(t.right)&&(t=this.rotateLeft(t)),this.isRed(t.left)&&this.isRed(t.left.left)&&(t=this.rotateRight(t)),this.isRed(t.left)&&this.isRed(t.right)&&this.flipColors(t),t}moveRedLeft(t){return this.flipColors(t),this.isRed(t.right.left)&&(t.right=this.rotateRight(t.right),t=this.rotateLeft(t),this.flipColors(t)),t}moveRedRight(t){return this.flipColors(t),this.isRed(t.left.left)&&(t=this.rotateRight(t),this.flipColors(t)),t}isRed(t){return t&&t.isRed}rotateLeft(t){const e=t.right;return t.right=e.left,e.left=t,e.isRed=e.left.isRed,e.left.isRed=!0,e}rotateRight(t){const e=t.left;return t.left=e.right,e.right=t,e.isRed=e.right.isRed,e.right.isRed=!0,e}flipColors(t){t.isRed=!t.isRed,t.left.isRed=!t.left.isRed,t.right.isRed=!t.right.isRed}}class ke{constructor(t,e){a(this,"parentID");a(this,"leftSiblingID");this.parentID=t,this.leftSiblingID=e}static of(t,e){return new ke(t,e)}static fromTreePos(t){const{offset:e}=t;let{node:r}=t,s;return r.isText?(r.parent.children[0]===r&&e===0?s=r.parent:s=r,r=r.parent):e===0?s=r:s=r.children[e-1],ke.of(r.id,Y.of(s.getCreatedAt(),s.getOffset()+e))}getParentID(){return this.parentID}static fromStruct(t){return ke.of(Y.of(oe.fromStruct(t.parentID.createdAt),t.parentID.offset),Y.of(oe.fromStruct(t.leftSiblingID.createdAt),t.leftSiblingID.offset))}toStruct(){return{parentID:{createdAt:this.getParentID().getCreatedAt().toStruct(),offset:this.getParentID().getOffset()},leftSiblingID:{createdAt:this.getLeftSiblingID().getCreatedAt().toStruct(),offset:this.getLeftSiblingID().getOffset()}}}toTreeNodePair(t){const e=this.getParentID(),r=this.getLeftSiblingID(),s=t.findFloorNode(e);let i=t.findFloorNode(r);if(!s||!i)throw new g(d.ErrRefused,`cannot find node of CRDTTreePos(${e.toTestString()}, ${r.toTestString()})`);return!r.equals(e)&&r.getOffset()>0&&r.getOffset()===i.id.getOffset()&&i.insPrevID&&(i=t.findFloorNode(i.insPrevID)),[s,i]}getLeftSiblingID(){return this.leftSiblingID}equals(t){return this.getParentID().getCreatedAt().equals(t.getParentID().getCreatedAt())&&this.getParentID().getOffset()===t.getParentID().getOffset()&&this.getLeftSiblingID().getCreatedAt().equals(t.getLeftSiblingID().getCreatedAt())&&this.getLeftSiblingID().getOffset()===t.getLeftSiblingID().getOffset()}}class Y{constructor(t,e){a(this,"createdAt");a(this,"offset");this.createdAt=t,this.offset=e}static of(t,e){return new Y(t,e)}static fromStruct(t){return Y.of(oe.fromStruct(t.createdAt),t.offset)}static createComparator(){return(t,e)=>{const r=t.getCreatedAt().compare(e.getCreatedAt());return r!==0?r:t.getOffset()>e.getOffset()?1:t.getOffset(){const i=s.deepcopy();return i.parent=e,i}),e.insPrevID=this.insPrevID,e.insNextID=this.insNextID,e}get value(){if(!this.isText)throw new g(d.ErrInvalidType,`cannot get value of element node: ${this.type}`);return this._value}set value(e){if(!this.isText)throw new g(d.ErrInvalidType,`cannot set value of element node: ${this.type}`);this._value=e,this.size=e.length}get isRemoved(){return!!this.removedAt}remove(e){const r=!this.removedAt;(!this.removedAt||this.removedAt.compare(e)>0)&&(this.removedAt=e),r&&this.updateAncestorsSize()}cloneText(e){return new ie(Y.of(this.id.getCreatedAt(),e),this.type,void 0,void 0,this.removedAt)}cloneElement(e){return new ie(Y.of(e(),0),this.type,void 0,void 0,this.removedAt)}split(e,r,s){const i=this.isText?this.splitText(r,this.id.getOffset()):this.splitElement(r,s);if(i){if(i.insPrevID=this.id,this.insNextID){const o=e.findFloorNode(this.insNextID);o.insPrevID=i.id,i.insNextID=this.insNextID}this.insNextID=i.id,e.registerNode(i)}return i}getCreatedAt(){return this.id.getCreatedAt()}getOffset(){return this.id.getOffset()}canDelete(e,r){return!this.getCreatedAt().after(r)&&(!this.removedAt||e.after(this.removedAt))}canStyle(e,r){return this.isText?!1:!this.getCreatedAt().after(r)&&(!this.removedAt||e.after(this.removedAt))}setAttrs(e,r){this.attrs||(this.attrs=new Zt);const s=new Array;for(const[i,o]of Object.entries(e))s.push(this.attrs.set(i,o,r));return s}purge(e){this.attrs&&this.attrs.purge(e)}getGCPairs(){const e=[];if(!this.attrs)return e;for(const r of this.attrs)r.getRemovedAt()&&e.push({parent:this,child:r});return e}}function Ls(n){var e;if(n.isText){const r=n;return{type:r.type,value:r.value}}const t={type:n.type,children:n.children.map(Ls)};return n.attrs&&(t.attributes=xr((e=n.attrs)==null?void 0:e.toObject())),t}function js(n){if(n.isText)return n.value;let t="";return n.attrs&&n.attrs.size()&&(t=" "+Array.from(n.attrs).filter(e=>!e.isRemoved()).sort((e,r)=>e.getKey().localeCompare(r.getKey())).map(e=>{const r=JSON.parse(e.getValue());return typeof r=="string"?`${e.getKey()}="${r}"`:`${e.getKey()}="${qe(e.getValue())}"`}).join(" ")),`<${n.type}${t}>${n.children.map(e=>js(e)).join("")}`}function Mo(n){if(n.isText){const t=n;return{type:t.type,value:t.value,size:t.size,isRemoved:t.isRemoved}}return{type:n.type,children:n.children.map(Mo),size:n.size,isRemoved:n.isRemoved}}class be extends en{constructor(e,r){super(r);a(this,"indexTree");a(this,"nodeMapByID");this.indexTree=new Gc(e),this.nodeMapByID=new Fo(Y.createComparator()),this.indexTree.traverseAll(s=>{this.nodeMapByID.put(s.id,s)})}static create(e,r){return new be(e,r)}findFloorNode(e){const r=this.nodeMapByID.floorEntry(e);if(!(!r||!r.key.getCreatedAt().equals(e.getCreatedAt())))return r.value}registerNode(e){this.nodeMapByID.put(e.id,e)}findNodesAndSplitText(e,r){const[s,i]=e.toTreeNodePair(this);let o=i;const c=s===o,l=o.parent&&!c?o.parent:s;if(o.isText&&o.split(this,e.getLeftSiblingID().getOffset()-o.id.getOffset()),r){const h=l.allChildren,f=c?0:h.indexOf(o)+1;for(let p=f;p{const k=w.getCreatedAt().getActorID(),E=i?i.has(k)?i.get(k):xe:qr;if(w.canStyle(s,E)&&r){const C=v.get(k),P=w.getCreatedAt();(!C||P.after(C))&&v.set(k,P);const H=w.setAttrs(r,s),D=H.reduce((K,[,_t])=>(_t&&(K[_t.getKey()]=p[_t.getKey()]),K),{}),L=w.parent,F=w.prevSibling||w.parent;Object.keys(D).length>0&&f.push({type:"style",from:this.toIndex(L,F),to:this.toIndex(w,w),fromPath:this.toPath(L,F),toPath:this.toPath(w,w),actor:s.getActorID(),value:D});for(const[K]of H)K&&m.push({parent:w,child:K})}}),[v,m,f]}removeStyle(e,r,s,i){const[o,c]=this.findNodesAndSplitText(e[0],s),[l,h]=this.findNodesAndSplitText(e[1],s),f=[],p=new Map,v=[];return this.traverseInPosRange(o,c,l,h,([m])=>{const w=m.getCreatedAt().getActorID(),k=i?i.has(w)?i.get(w):xe:qr;if(m.canStyle(s,k)&&r){const E=p.get(w),C=m.getCreatedAt();(!E||C.after(E))&&p.set(w,C),m.attrs||(m.attrs=new Zt);for(const D of r){const L=m.attrs.remove(D,s);for(const F of L)v.push({parent:m,child:F})}const P=m.parent,H=m.prevSibling||m.parent;f.push({actor:s.getActorID(),type:"removeStyle",from:this.toIndex(P,H),to:this.toIndex(m,m),fromPath:this.toPath(P,H),toPath:this.toPath(m,m),value:r})}}),[p,v,f]}edit(e,r,s,i,o,c){const[l,h]=this.findNodesAndSplitText(e[0],i),[f,p]=this.findNodesAndSplitText(e[1],i),v=this.toIndex(l,h),m=this.toPath(l,h),w=[],k=[],E=[],C=new Map;this.traverseInPosRange(l,h,f,p,([D,L],F)=>{if(L===j.Start&&!F)for(const lr of D.children)E.push(lr);const K=D.getCreatedAt().getActorID(),_t=c?c.has(K)?c.get(K):xe:qr;if(D.canDelete(i,_t)||w.includes(D.parent)){const lr=C.get(K),on=D.getCreatedAt();(!lr||on.after(lr))&&C.set(K,on),(L===j.Text||L===j.Start)&&w.push(D),k.push([D,L])}});const P=this.makeDeletionChanges(k,i),H=[];for(const D of w)D.remove(i),D.isRemoved&&H.push({parent:this,child:D});for(const D of E)D.removedAt||l.append(D);if(s>0){let D=0,L=l,F=h;for(;D{l.isRemoved&&(K.remove(i),H.push({parent:this,child:K})),this.nodeMapByID.put(K.id,K)}),F.isRemoved||D.push(F);if(D.length){const F=D.map(K=>Ls(K));P.length&&P[P.length-1].from===v?P[P.length-1].value=F:P.push({type:"content",from:v,to:v,fromPath:m,toPath:m,actor:i.getActorID(),value:F})}}return[P,H,C]}editT(e,r,s,i,o){const c=this.findPos(e[0]),l=this.findPos(e[1]);this.edit([c,l],r,s,i,o)}move(e,r,s){throw new g(d.ErrUnimplemented,`not implemented: ${e}, ${r}, ${s}`)}purge(e){var i;(i=e.parent)==null||i.removeChild(e),this.nodeMapByID.remove(e.id);const r=e.insPrevID,s=e.insNextID;if(r){const o=this.findFloorNode(r);o.insNextID=s}if(s){const o=this.findFloorNode(s);o.insPrevID=r}e.insPrevID=void 0,e.insNextID=void 0}getGCPairs(){const e=[];return this.indexTree.traverse(r=>{r.getRemovedAt()&&e.push({parent:this,child:r});for(const s of r.getGCPairs())e.push(s)}),e}findPos(e,r=!0){const s=this.indexTree.findTreePos(e,r);return ke.fromTreePos(s)}pathToPosRange(e){const r=this.pathToIndex(e);return[this.findPos(r),this.findPos(r+1)]}pathToPos(e){const r=this.indexTree.pathToIndex(e);return this.findPos(r)}getRoot(){return this.indexTree.getRoot()}getSize(){return this.indexTree.size}getNodeSize(){return this.nodeMapByID.size()}getIndexTree(){return this.indexTree}toXML(){return js(this.indexTree.getRoot())}toJSON(){return JSON.stringify(this.getRootTreeNode())}toJSForTest(){return{createdAt:this.getCreatedAt().toTestString(),value:JSON.parse(this.toJSON()),type:"YORKIE_TREE"}}toJSInfoForTest(){const e=this.indexTree.getRoot(),r=(s,i=void 0,o=void 0,c=0)=>{var m,w,k,E;let l,h,f;const p=s.isText?{node:s,offset:0}:i&&o?this.toTreePos(i,o):null;p&&(l=this.indexTree.indexOf(p),h=this.indexTree.treePosToPath(p),f=ke.fromTreePos(p).toStruct());const v={type:s.type,parent:i==null?void 0:i.id.toTestString(),size:s.size,id:s.id.toTestString(),removedAt:(m=s.removedAt)==null?void 0:m.toTestString(),insPrev:(w=s.insPrevID)==null?void 0:w.toTestString(),insNext:(k=s.insNextID)==null?void 0:k.toTestString(),value:s.isText?s.value:void 0,isRemoved:s.isRemoved,children:[],depth:c,attributes:s.attrs?xr((E=s.attrs)==null?void 0:E.toObject()):void 0,index:l,path:h,pos:f};for(let C=0;C0&&C===s[s.length-1].to?(s[s.length-1].to=P,s[s.length-1].toPath=this.toPath(E,m)):s.push({type:"content",from:C,to:P,fromPath:this.toPath(k,p),toPath:this.toPath(E,m),actor:r.getActorID()}))}return s.reverse()}findRightToken([e,r]){if(r===j.Start){const l=e.allChildren;return l.length>0?[l[0],l[0].isText?j.Text:j.Start]:[e,j.End]}const s=e.parent,i=s.allChildren,o=i.indexOf(e);if(s&&o===i.length-1)return[s,j.End];const c=i[o+1];return[c,c.isText?j.Text:j.Start]}findLeftToken([e,r]){if(r===j.End){const l=e.allChildren;if(l.length>0){const h=l[l.length-1];return[h,h.isText?j.Text:j.End]}return[e,j.Start]}const s=e.parent,i=s.allChildren,o=i.indexOf(e);if(s&&o===0)return[s,j.Start];const c=i[o-1];return[c,c.isText?j.Text:j.End]}}class sn extends Ne{constructor(e,r,s,i,o,c,l){super(e,l);a(this,"fromPos");a(this,"toPos");a(this,"contents");a(this,"splitLevel");a(this,"maxCreatedAtMapByActor");this.fromPos=r,this.toPos=s,this.contents=i,this.splitLevel=o,this.maxCreatedAtMapByActor=c}static create(e,r,s,i,o,c,l){return new sn(e,r,s,i,o,c,l)}execute(e){var l;const r=e.findByCreatedAt(this.getParentCreatedAt());if(!r)throw new g(d.ErrInvalidArgument,`fail to find ${this.getParentCreatedAt()}`);if(!(r instanceof be))throw new g(d.ErrInvalidArgument,"fail to execute, only Tree can execute edit");const s=this.getExecutedAt(),i=r,[o,c]=i.edit([this.fromPos,this.toPos],(l=this.contents)==null?void 0:l.map(h=>h.deepcopy()),this.splitLevel,s,(()=>{let h=s.getDelimiter();return this.contents!==void 0&&(h+=this.contents.length),()=>oe.of(s.getLamport(),++h,s.getActorID())})(),this.maxCreatedAtMapByActor);for(const h of c)e.registerGCPair(h);return{opInfos:o.map(({from:h,to:f,value:p,splitLevel:v,fromPath:m,toPath:w})=>({type:"tree-edit",path:e.createPath(this.getParentCreatedAt()),from:h,to:f,value:p,splitLevel:v,fromPath:m,toPath:w}))}}getEffectedCreatedAt(){return this.getParentCreatedAt()}toTestString(){const e=this.getParentCreatedAt().toTestString(),r=`${this.fromPos.getLeftSiblingID().getCreatedAt().toTestString()}/${this.fromPos.getLeftSiblingID().getOffset()}`,s=`${this.toPos.getLeftSiblingID().getCreatedAt().toTestString()}/${this.toPos.getLeftSiblingID().getOffset()}`,i=this.contents||[];return`${e}.EDIT(${r},${s},${i.map(o=>js(o)).join("")})`}getFromPos(){return this.fromPos}getToPos(){return this.toPos}getContents(){return this.contents}getSplitLevel(){return this.splitLevel}getMaxCreatedAtMapByActor(){return this.maxCreatedAtMapByActor}}class Er{constructor(t){a(this,"vector");this.vector=t||new Map}set(t,e){this.vector.set(t,e)}get(t){return this.vector.get(t)}maxLamport(){let t=BigInt(0);for(const[,e]of this)e>t&&(t=e);return t}max(t){const e=new Map;for(const[r,s]of t){const i=this.vector.get(r),o=i&&i>s?i:s;e.set(r,o)}for(const[r,s]of this){const i=t.get(r),o=i&&i>s?i:s;e.set(r,o)}return new Er(e)}afterOrEqual(t){const e=this.vector.get(t.getActorID());return e===void 0?!1:e>=t.getLamport()}deepcopy(){const t=new Map;for(const[e,r]of this.vector)t.set(e,r);return new Er(t)}filter(t){const e=new Map;for(const[r]of t){const s=this.vector.get(r);s!==void 0&&e.set(r,s)}return new Er(e)}size(){return this.vector.size}*[Symbol.iterator](){for(const[t,e]of this.vector)yield[t,e]}}const Xc=new Er(new Map);class zt{constructor(t,e,r,s,i){a(this,"clientSeq");a(this,"serverSeq");a(this,"lamport");a(this,"actor");a(this,"versionVector");this.clientSeq=t,this.serverSeq=i,this.lamport=e,this.versionVector=s,this.actor=r}static of(t,e,r,s,i){return new zt(t,e,r,s,i)}next(){const t=this.versionVector.deepcopy();return t.set(this.actor,this.lamport+1n),new zt(this.clientSeq+1,this.lamport+1n,this.actor,t)}syncClocks(t){const e=t.lamport>this.lamport?t.lamport+1n:this.lamport+1n,r=this.versionVector.max(t.versionVector),s=new zt(this.clientSeq,e,this.actor,r);return s.versionVector.set(this.actor,e),s}setClocks(t,e){const r=t>this.lamport?t:this.lamport+1n,s=this.versionVector.max(e);return s.set(this.actor,r),zt.of(this.clientSeq,r,this.actor,s)}createTimeTicket(t){return oe.of(this.lamport,t,this.actor)}setActor(t){return new zt(this.clientSeq,this.lamport,t,this.versionVector,this.serverSeq)}setVersionVector(t){return new zt(this.clientSeq,this.lamport,this.actor,t,this.serverSeq)}getClientSeq(){return this.clientSeq}getServerSeq(){return this.serverSeq?this.serverSeq.toString():""}getLamport(){return this.lamport}getLamportAsString(){return this.lamport.toString()}getActorID(){return this.actor}getVersionVector(){return this.versionVector}toTestString(){return`${this.lamport.toString()}:${this.actor.slice(-2)}:${this.clientSeq}`}}const Zc=new zt(0,0n,Vs,Xc);class Rr{constructor({id:t,operations:e,presenceChange:r,message:s}){a(this,"id");a(this,"operations");a(this,"presenceChange");a(this,"message");this.id=t,this.operations=e||[],this.presenceChange=r,this.message=s}static create({id:t,operations:e,presenceChange:r,message:s}){return new Rr({id:t,operations:e,presenceChange:r,message:s})}getID(){return this.id}getMessage(){return this.message}hasOperations(){return this.operations.length>0}getOperations(){return this.operations}setActor(t){for(const e of this.operations)e.setActor(t);this.id=this.id.setActor(t)}hasPresenceChange(){return this.presenceChange!==void 0}getPresenceChange(){return this.presenceChange}execute(t,e,r){const s=[],i=[];for(const o of this.operations){const c=o.execute(t,r);if(!c)continue;const{opInfos:l,reverseOp:h}=c;s.push(...l),h&&i.unshift(h)}return this.presenceChange&&(this.presenceChange.type===cr.Put?e.set(this.id.getActorID(),Ie(this.presenceChange.presence)):e.delete(this.id.getActorID())),{opInfos:s,reverseOps:i}}toTestString(){return`${this.operations.map(t=>t.toTestString()).join(",")}`}toStruct(){return{changeID:V.bytesToHex(V.toChangeID(this.getID()).toBinary()),message:this.getMessage(),operations:this.getOperations().map(t=>V.bytesToHex(V.toOperation(t).toBinary())),presenceChange:this.getPresenceChange()}}static fromStruct(t){const{changeID:e,operations:r,presenceChange:s,message:i}=t;return Rr.create({id:V.bytesToChangeID(V.hexToBytes(e)),operations:r==null?void 0:r.map(o=>V.bytesToOperation(V.hexToBytes(o))),presenceChange:s,message:i})}}class Hn{constructor(t,e,r,s,i,o,c){a(this,"documentKey");a(this,"checkpoint");a(this,"isRemoved");a(this,"changes");a(this,"snapshot");a(this,"minSyncedTicket");a(this,"versionVector");this.documentKey=t,this.checkpoint=e,this.isRemoved=r,this.changes=s,this.snapshot=o,this.minSyncedTicket=c,this.versionVector=i}static create(t,e,r,s,i,o,c){return new Hn(t,e,r,s,i,o,c)}getDocumentKey(){return this.documentKey}getCheckpoint(){return this.checkpoint}getIsRemoved(){return this.isRemoved}getChanges(){return this.changes}hasChanges(){return this.changes.length>0}getChangeSize(){return this.changes.length}hasSnapshot(){return!!this.snapshot&&!!this.snapshot.length}getSnapshot(){return this.snapshot}getMinSyncedTicket(){return this.minSyncedTicket}getVersionVector(){return this.versionVector}}class Nr{constructor(t,e){a(this,"serverSeq");a(this,"clientSeq");this.serverSeq=t,this.clientSeq=e}static of(t,e){return new Nr(t,e)}increaseClientSeq(t){return t===0?this:new Nr(this.serverSeq,this.clientSeq+t)}forward(t){if(this.equals(t))return this;const e=this.serverSeq>t.serverSeq?this.serverSeq:t.serverSeq,r=Math.max(this.clientSeq,t.clientSeq);return Nr.of(e,r)}getServerSeqAsString(){return this.serverSeq.toString()}getClientSeq(){return this.clientSeq}getServerSeq(){return this.serverSeq}equals(t){return this.clientSeq===t.clientSeq&&this.serverSeq==t.serverSeq}toTestString(){return`serverSeq=${this.serverSeq}, clientSeq=${this.clientSeq}`}}const Qc=new Nr(0n,0);class Ve{constructor(t,e){a(this,"createdAt");a(this,"offset");this.createdAt=t,this.offset=e}static of(t,e){return new Ve(t,e)}static fromStruct(t){return Ve.of(oe.fromStruct(t.createdAt),t.offset)}getCreatedAt(){return this.createdAt}getOffset(){return this.offset}equals(t){return this.createdAt.compare(t.createdAt)===0&&this.offset===t.offset}hasSameCreatedAt(t){return this.createdAt.compare(t.createdAt)===0}split(t){return new Ve(this.createdAt,this.offset+t)}toStruct(){return{createdAt:this.createdAt.toStruct(),offset:this.offset}}toTestString(){return`${this.createdAt.toTestString()}:${this.offset}`}toIDString(){return`${this.createdAt.toIDString()}:${this.offset}`}}const _c=Ve.of(xe,0);class Ee{constructor(t,e){a(this,"id");a(this,"relativeOffset");this.id=t,this.relativeOffset=e}static of(t,e){return new Ee(t,e)}static fromStruct(t){const e=Ve.fromStruct(t.id);return Ee.of(e,t.relativeOffset)}getID(){return this.id}getRelativeOffset(){return this.relativeOffset}getAbsoluteID(){return Ve.of(this.id.getCreatedAt(),this.id.getOffset()+this.relativeOffset)}toTestString(){return`${this.id.toTestString()}:${this.relativeOffset}`}toStruct(){return{id:this.id.toStruct(),relativeOffset:this.relativeOffset}}equals(t){return this.id.equals(t.id)?this.relativeOffset===t.relativeOffset:!1}}class or extends Co{constructor(e,r,s){super(r);a(this,"id");a(this,"removedAt");a(this,"prev");a(this,"next");a(this,"insPrev");a(this,"insNext");this.id=e,this.removedAt=s}static create(e,r){return new or(e,r)}static createComparator(){return(e,r)=>{const s=e.getCreatedAt().compare(r.getCreatedAt());return s!==0?s:e.getOffset()>r.getOffset()?1:e.getOffset()0&&e.getID().getOffset()==t.getOffset()){if(!e.hasInsPrev())return e;e=e.getInsPrev()}return e}findFloorNode(t){const e=this.treeByID.floorEntry(t);if(e&&!(!e.key.equals(t)&&!e.key.hasSameCreatedAt(t)))return e.value}findBetween(t,e){const r=[];let s=t;for(;s&&s!==e;)r.push(s),s=s.getNext();return r}splitNode(t,e){if(e>t.getContentLength())throw new g(d.ErrInvalidArgument,"offset should be less than or equal to length");if(e===0)return t;if(e===t.getContentLength())return t.getNext();const r=t.split(e);this.treeByIndex.updateWeight(r),this.insertAfter(t,r);const s=t.getInsNext();return s&&s.setInsPrev(r),r.setInsPrev(t),r}deleteNodes(t,e,r){if(!t.length)return[[],new Map,new Map];const[s,i]=this.filterNodes(t,e,r),o=new Map,c=new Map,l=this.makeChanges(i,e);for(const h of s){const f=h.getCreatedAt().getActorID();(!o.has(f)||h.getID().getCreatedAt().after(o.get(f)))&&o.set(f,h.getID().getCreatedAt()),c.set(h.getID().toIDString(),h),h.remove(e)}return this.deleteIndexNodes(i),[l,o,c]}filterNodes(t,e,r){const s=!!r,i=[],o=[],[c,l]=this.findEdgesOfCandidates(t);o.push(c);for(const h of t){const f=h.getCreatedAt().getActorID(),p=s?r.has(f)?r.get(f):xe:qr;h.canDelete(e,p)?i.push(h):o.push(h)}return o.push(l),[i,o]}findEdgesOfCandidates(t){return[t[0].getPrev(),t[t.length-1].getNext()]}makeChanges(t,e){const r=[];let s,i;for(let o=0;on<0?Math.ceil(n):Math.floor(n);var ze=(n=>(n[n.IntegerCnt=0]="IntegerCnt",n[n.LongCnt=1]="LongCnt",n))(ze||{});class ce extends en{constructor(e,r,s){super(s);a(this,"valueType");a(this,"value");switch(this.valueType=e,e){case 0:typeof r=="number"?r>Math.pow(2,31)-1||r<-Math.pow(2,31)?this.value=O.fromNumber(r).toInt():this.value=qi(r):this.value=r.toInt();break;case 1:typeof r=="number"?this.value=O.fromNumber(r):this.value=r;break;default:throw new g(d.ErrUnimplemented,`unimplemented type: ${e}`)}}static create(e,r,s){return new ce(e,r,s)}static valueFromBytes(e,r){switch(e){case 0:return r[0]|r[1]<<8|r[2]<<16|r[3]<<24;case 1:return O.fromBytesLE(Array.from(r));default:throw new g(d.ErrUnimplemented,`unimplemented type: ${e}`)}}toJSON(){return`${this.value}`}toSortedJSON(){return this.toJSON()}toJSForTest(){return{createdAt:this.getCreatedAt().toTestString(),value:this.value,type:"YORKIE_COUNTER"}}deepcopy(){const e=ce.create(this.valueType,this.value,this.getCreatedAt());return e.setMovedAt(this.getMovedAt()),e}getType(){return this.valueType}static getCounterType(e){switch(typeof e){case"object":return e instanceof O?1:void 0;case"number":return e>Math.pow(2,31)-1||e<-Math.pow(2,31)?1:0;default:return}}static isSupport(e){return!!ce.getCounterType(e)}static isInteger(e){return e%1===0}isNumericType(){const e=this.valueType;return e===0||e===1}getValueType(){return this.valueType}getValue(){return this.value}toBytes(){switch(this.valueType){case 0:{const e=this.value;return new Uint8Array([e&255,e>>8&255,e>>16&255,e>>24&255])}case 1:{const r=this.value.toBytesLE();return Uint8Array.from(r)}default:throw new g(d.ErrUnimplemented,`unimplemented type: ${this.valueType}`)}}increase(e){function r(s){if(!s.isNumericType())throw new TypeError(`Unsupported type of value: ${typeof s.getValue()}`)}return r(this),r(e),this.valueType===1?this.value=this.value.add(e.getValue()):e.getType()===W.Long?this.value=this.value+e.getValue().toInt():this.value=O.fromNumber(this.value+qi(e.getValue())).toInt(),this}}class Jr extends Ne{constructor(e,r,s){super(e,s);a(this,"value");this.value=r}static create(e,r,s){return new Jr(e,r,s)}execute(e){const r=e.findByCreatedAt(this.getParentCreatedAt());if(!r)throw new g(d.ErrInvalidArgument,`fail to find ${this.getParentCreatedAt()}`);if(!(r instanceof ce))throw new g(d.ErrInvalidArgument,"fail to execute, only Counter can execute increase");const s=r,i=this.value.deepcopy();return s.increase(i),{opInfos:[{type:"increase",path:e.createPath(this.getParentCreatedAt()),value:i.getValue()}],reverseOp:this.toReverseOperation()}}toReverseOperation(){const e=this.value.deepcopy(),s=e.getType()===W.Long?e.getValue().multiply(-1):e.getValue()*-1;return Jr.create(this.getParentCreatedAt(),$.of(s,e.getCreatedAt()))}getEffectedCreatedAt(){return this.getParentCreatedAt()}toTestString(){return`${this.getParentCreatedAt().toTestString()}.INCREASE.${this.value.toJSON()}`}getValue(){return this.value}}class Yt extends Ne{constructor(e,r,s,i,o,c,l){super(e,l);a(this,"fromPos");a(this,"toPos");a(this,"maxCreatedAtMapByActor");a(this,"attributes");a(this,"attributesToRemove");this.fromPos=r,this.toPos=s,this.maxCreatedAtMapByActor=i,this.attributes=o,this.attributesToRemove=c}static create(e,r,s,i,o,c){return new Yt(e,r,s,i,o,new Array,c)}static createTreeRemoveStyleOperation(e,r,s,i,o,c){return new Yt(e,r,s,i,new Map,o,c)}execute(e){const r=e.findByCreatedAt(this.getParentCreatedAt());if(!r)throw new g(d.ErrInvalidArgument,`fail to find ${this.getParentCreatedAt()}`);if(!(r instanceof be))throw new g(d.ErrInvalidArgument,"fail to execute, only Tree can execute edit");const s=r;let i,o;if(this.attributes.size){const c={};[...this.attributes].forEach(([l,h])=>c[l]=h),[,o,i]=s.style([this.fromPos,this.toPos],c,this.getExecutedAt(),this.maxCreatedAtMapByActor)}else{const c=this.attributesToRemove;[,o,i]=s.removeStyle([this.fromPos,this.toPos],c,this.getExecutedAt(),this.maxCreatedAtMapByActor)}for(const c of o)e.registerGCPair(c);return{opInfos:i.map(({from:c,to:l,value:h,fromPath:f,toPath:p})=>({type:"tree-style",from:c,to:l,value:this.attributes.size?{attributes:h}:{attributesToRemove:h},fromPath:f,toPath:p,path:e.createPath(this.getParentCreatedAt())}))}}getEffectedCreatedAt(){return this.getParentCreatedAt()}toTestString(){const e=this.getParentCreatedAt().toTestString(),r=`${this.fromPos.getLeftSiblingID().getCreatedAt().toTestString()}:${this.fromPos.getLeftSiblingID().getOffset()}`,s=`${this.toPos.getLeftSiblingID().getCreatedAt().toTestString()}:${this.toPos.getLeftSiblingID().getOffset()}`;return`${e}.STYLE(${r},${s},${Object.entries(this.attributes||{}).map(([i,o])=>`${i}:"${o}"`).join(" ")})`}getFromPos(){return this.fromPos}getToPos(){return this.toPos}getAttributes(){return this.attributes}getAttributesToRemove(){return this.attributesToRemove}getMaxCreatedAtMapByActor(){return this.maxCreatedAtMapByActor}}function eu(n){const t=new qs,e=t.data;for(const[r,s]of Object.entries(n))e[r]=JSON.stringify(s);return t}function tu(n){if(n.type===cr.Put)return new Wr({type:vr.PUT,presence:eu(n.presence)});if(n.type===cr.Clear)return new Wr({type:vr.CLEAR});throw new g(d.ErrUnimplemented,"unimplemented type")}function ru(n){return new xo({serverSeq:n.getServerSeq(),clientSeq:n.getClientSeq()})}function $o(n){return new jn({clientSeq:n.getClientSeq(),lamport:n.getLamport(),actorId:ri(n.getActorID()),versionVector:Gs(n.getVersionVector())})}function I(n){if(n)return new b({lamport:n.getLamport(),delimiter:n.getDelimiter(),actorId:ri(n.getActorID())})}function Gs(n){if(!n)return;const t=new Gn;for(const[e,r]of n)t.vector[e]=BigInt(r.toString());return t}function Uo(n){switch(n){case W.Null:return N.NULL;case W.Boolean:return N.BOOLEAN;case W.Integer:return N.INTEGER;case W.Long:return N.LONG;case W.Double:return N.DOUBLE;case W.String:return N.STRING;case W.Bytes:return N.BYTES;case W.Date:return N.DATE;default:throw new g(d.ErrInvalidType,`unsupported type: ${n}`)}}function qo(n){switch(n){case ze.IntegerCnt:return N.INTEGER_CNT;case ze.LongCnt:return N.LONG_CNT;default:throw new g(d.ErrInvalidType,`unsupported type: ${n}`)}}function ns(n){if(n instanceof re)return new ue({type:N.JSON_OBJECT,createdAt:I(n.getCreatedAt()),value:ea(n)});if(n instanceof ae)return new ue({type:N.JSON_ARRAY,createdAt:I(n.getCreatedAt()),value:Bu(n)});if(n instanceof Ae)return new ue({type:N.TEXT,createdAt:I(n.getCreatedAt())});if(n instanceof $)return new ue({type:Uo(n.getType()),createdAt:I(n.getCreatedAt()),value:n.toBytes()});if(n instanceof ce)return new ue({type:qo(n.getType()),createdAt:I(n.getCreatedAt()),value:n.toBytes()});if(n instanceof be)return new ue({type:N.TREE,createdAt:I(n.getCreatedAt()),value:Lu(n)});throw new g(d.ErrUnimplemented,"unimplemented element")}function nu(n){return new jr({createdAt:I(n.getCreatedAt()),offset:n.getOffset()})}function cn(n){return new Xt({createdAt:I(n.getID().getCreatedAt()),offset:n.getID().getOffset(),relativeOffset:n.getRelativeOffset()})}function un(n){return new yr({parentId:Vr(n.getParentID()),leftSiblingId:Vr(n.getLeftSiblingID())})}function Vr(n){return new sr({createdAt:I(n.getCreatedAt()),offset:n.getOffset()})}function Vo(n){const t=new Us;if(n instanceof wr){const e=n,r=new bn;r.parentCreatedAt=I(e.getParentCreatedAt()),r.key=e.getKey(),r.value=ns(e.getValue()),r.executedAt=I(e.getExecutedAt()),t.body.case="set",t.body.value=r}else if(n instanceof tn){const e=n,r=new In;r.parentCreatedAt=I(e.getParentCreatedAt()),r.prevCreatedAt=I(e.getPrevCreatedAt()),r.value=ns(e.getValue()),r.executedAt=I(e.getExecutedAt()),t.body.case="add",t.body.value=r}else if(n instanceof nr){const e=n,r=new Sn;r.parentCreatedAt=I(e.getParentCreatedAt()),r.prevCreatedAt=I(e.getPrevCreatedAt()),r.createdAt=I(e.getCreatedAt()),r.executedAt=I(e.getExecutedAt()),t.body.case="move",t.body.value=r}else if(n instanceof ur){const e=n,r=new kn;r.parentCreatedAt=I(e.getParentCreatedAt()),r.createdAt=I(e.getCreatedAt()),r.executedAt=I(e.getExecutedAt()),t.body.case="remove",t.body.value=r}else if(n instanceof rn){const e=n,r=new xn;r.parentCreatedAt=I(e.getParentCreatedAt()),r.from=cn(e.getFromPos()),r.to=cn(e.getToPos());const s=r.createdAtMapByActor;for(const[o,c]of e.getMaxCreatedAtMapByActor())s[o]=I(c);r.content=e.getContent();const i=r.attributes;for(const[o,c]of e.getAttributes())i[o]=c;r.executedAt=I(e.getExecutedAt()),t.body.case="edit",t.body.value=r}else if(n instanceof nn){const e=n,r=new En;r.parentCreatedAt=I(e.getParentCreatedAt()),r.from=cn(e.getFromPos()),r.to=cn(e.getToPos());const s=r.createdAtMapByActor;for(const[o,c]of e.getMaxCreatedAtMapByActor())s[o]=I(c);const i=r.attributes;for(const[o,c]of e.getAttributes())i[o]=c;r.executedAt=I(e.getExecutedAt()),t.body.case="style",t.body.value=r}else if(n instanceof Jr){const e=n,r=new Nn;r.parentCreatedAt=I(e.getParentCreatedAt()),r.value=ns(e.getValue()),r.executedAt=I(e.getExecutedAt()),t.body.case="increase",t.body.value=r}else if(n instanceof sn){const e=n,r=new Cn,s=r.createdAtMapByActor;for(const[i,o]of e.getMaxCreatedAtMapByActor())s[i]=I(o);r.parentCreatedAt=I(e.getParentCreatedAt()),r.from=un(e.getFromPos()),r.to=un(e.getToPos()),r.contents=lu(e.getContents()),r.splitLevel=e.getSplitLevel(),r.executedAt=I(e.getExecutedAt()),t.body.case="treeEdit",t.body.value=r}else if(n instanceof Yt){const e=n,r=new Pn;r.parentCreatedAt=I(e.getParentCreatedAt()),r.from=un(e.getFromPos()),r.to=un(e.getToPos());const s=r.createdAtMapByActor;for(const[o,c]of e.getMaxCreatedAtMapByActor())s[o]=I(c);const i=e.getAttributesToRemove();if(i.length>0)r.attributesToRemove=i;else{const o=r.attributes;for(const[c,l]of e.getAttributes())o[c]=l}r.executedAt=I(e.getExecutedAt()),t.body.case="treeStyle",t.body.value=r}else throw new g(d.ErrUnimplemented,"unimplemented operation");return t}function su(n){const t=[];for(const e of n)t.push(Vo(e));return t}function iu(n){const t=new So({id:$o(n.getID()),message:n.getMessage()});return n.hasOperations()&&(t.operations=su(n.getOperations())),n.hasPresenceChange()&&(t.presenceChange=tu(n.getPresenceChange())),t}function ou(n){const t=[];for(const e of n)t.push(iu(e));return t}function au(n){const t=[];for(const e of n)t.push(new ko({key:e.getStrKey(),element:Hs(e.getValue())}));return t}function cu(n){const t=[];for(const e of n)t.push(new Fn({element:Hs(e.getValue())}));return t}function uu(n){const t=[];for(const e of n){const r=new Mn;r.id=nu(e.getID()),r.value=e.getValue().getContent(),r.removedAt=I(e.getRemovedAt());const s=r.attributes,i=e.getValue().getAttrs();for(const o of i){const c=new Dr;c.value=o.getValue(),c.updatedAt=I(o.getUpdatedAt()),s[o.getKey()]=c}t.push(r)}return t}function lu(n){const t=[];if(!n||!n.length)return t;for(const e of n)t.push(new $n({content:Ws(e)}));return t}function hu(n){const t={};for(const e of n)t[e.getKey()]=new Dr({value:e.getValue(),updatedAt:I(e.getUpdatedAt()),isRemoved:e.isRemoved()});return t}function Ws(n){if(!n)return[];const t=[];return Wn(n,(e,r)=>{const s=new Gr({id:Vr(e.id),type:e.type,removedAt:I(e.removedAt),depth:r});e.isText&&(s.value=e.value),e.insPrevID&&(s.insPrevId=Vr(e.insPrevID)),e.insNextID&&(s.insNextId=Vr(e.insNextID)),e.attrs&&(s.attributes=hu(e.attrs)),t.push(s)}),t}function fu(n){const t=new ne;return t.body.case="jsonObject",t.body.value=new Dn({nodes:au(n.getRHT()),createdAt:I(n.getCreatedAt()),movedAt:I(n.getMovedAt()),removedAt:I(n.getRemovedAt())}),t}function zo(n){const t=new ne;return t.body.case="jsonArray",t.body.value=new On({nodes:cu(n.getElements()),createdAt:I(n.getCreatedAt()),movedAt:I(n.getMovedAt()),removedAt:I(n.getRemovedAt())}),t}function du(n){const t=new ne;return t.body.case="primitive",t.body.value=new Bn({type:Uo(n.getType()),value:n.toBytes(),createdAt:I(n.getCreatedAt()),movedAt:I(n.getMovedAt()),removedAt:I(n.getRemovedAt())}),t}function gu(n){const t=new ne;return t.body.case="text",t.body.value=new Rn({nodes:uu(n.getRGATreeSplit()),createdAt:I(n.getCreatedAt()),movedAt:I(n.getMovedAt()),removedAt:I(n.getRemovedAt())}),t}function mu(n){const t=new ne;return t.body.case="counter",t.body.value=new Ln({type:qo(n.getType()),value:n.toBytes(),createdAt:I(n.getCreatedAt()),movedAt:I(n.getMovedAt()),removedAt:I(n.getRemovedAt())}),t}function Ko(n){const t=new ne;return t.body.case="tree",t.body.value=new Jn({nodes:Ws(n.getRoot()),createdAt:I(n.getCreatedAt()),movedAt:I(n.getMovedAt()),removedAt:I(n.getRemovedAt())}),t}function Hs(n){if(n instanceof re)return fu(n);if(n instanceof ae)return zo(n);if(n instanceof $)return du(n);if(n instanceof Ae)return gu(n);if(n instanceof ce)return mu(n);if(n instanceof be)return Ko(n);throw new g(d.ErrUnimplemented,"unimplemented element")}function pu(n){return new Qt({documentKey:n.getDocumentKey(),checkpoint:ru(n.getCheckpoint()),isRemoved:n.getIsRemoved(),changes:ou(n.getChanges()),snapshot:n.getSnapshot(),versionVector:Gs(n.getVersionVector()),minSyncedTicket:I(n.getMinSyncedTicket())})}function Vi(n){const t=n.findDetails(Oc);for(const e of t)if(e.metadata.code)return e.metadata.code;return""}function jo(n){return zt.of(n.clientSeq,BigInt(n.lamport),ei(n.actorId),Ys(n.versionVector),BigInt(n.serverSeq))}function Ys(n){if(!n)return;const t=new Er;return Object.entries(n.vector).forEach(([e,r])=>{t.set(e,BigInt(r.toString()))}),t}function S(n){if(n)return oe.of(BigInt(n.lamport),n.delimiter,ei(n.actorId))}function Xs(n){const t={};return Object.entries(n.data).forEach(([e,r])=>{t[e]=JSON.parse(r)}),t}function yu(n){const t=n.type;if(t===vr.PUT){const e=Xs(n.presence);return{type:cr.Put,presence:e}}if(t===vr.CLEAR)return{type:cr.Clear};throw new g(d.ErrInvalidType,`unsupported type: ${t}`)}function vu(n){const t=new Map;return Object.entries(n).forEach(([e,r])=>{t.set(e,Xs(r))}),t}function Go(n){switch(n){case N.NULL:return W.Null;case N.BOOLEAN:return W.Boolean;case N.INTEGER:return W.Integer;case N.LONG:return W.Long;case N.DOUBLE:return W.Double;case N.STRING:return W.String;case N.BYTES:return W.Bytes;case N.DATE:return W.Date}throw new g(d.ErrUnimplemented,`unimplemented value type: ${n}`)}function Vn(n){switch(n){case N.INTEGER_CNT:return ze.IntegerCnt;case N.LONG_CNT:return ze.LongCnt}throw new g(d.ErrUnimplemented,`unimplemented value type: ${n}`)}function ss(n){switch(n.type){case N.JSON_OBJECT:return n.value?_o(n.value):re.create(S(n.createdAt));case N.JSON_ARRAY:return n.value?Ou(n.value):ae.create(S(n.createdAt));case N.TEXT:return Ae.create(Lr.create(),S(n.createdAt));case N.TREE:return Ru(n.value);case N.NULL:case N.BOOLEAN:case N.INTEGER:case N.LONG:case N.DOUBLE:case N.STRING:case N.BYTES:case N.DATE:return $.of($.valueFromBytes(Go(n.type),n.value),S(n.createdAt));case N.INTEGER_CNT:case N.LONG_CNT:return ce.create(Vn(n.type),ce.valueFromBytes(Vn(n.type),n.value),S(n.createdAt))}}function ln(n){return Ee.of(Ve.of(S(n.createdAt),n.offset),n.relativeOffset)}function Wo(n){return Ve.of(S(n.createdAt),n.offset)}function wu(n){const t=Zr.create(n.value);Object.entries(n.attributes).forEach(([r,s])=>{t.setAttr(r,s.value,S(s.updatedAt))});const e=or.create(Wo(n.id),t);return e.remove(S(n.removedAt)),e}function br(n){return ke.of(zr(n.parentId),zr(n.leftSiblingId))}function zr(n){return Y.of(S(n.createdAt),n.offset)}function Tu(n){if(!n.length)return;const t=[];return n.forEach(e=>{const r=Zs(e.content);t.push(r)}),t}function Zs(n){if(n.length===0)return;const t=[];for(const s of n)t.push(bu(s));const e=t[t.length-1],r=new Map;r.set(n[t.length-1].depth,t[t.length-1]);for(let s=t.length-2;s>=0;s--)r.get(n[s].depth-1).prepend(t[s]),r.set(n[s].depth,t[s]);return e.updateDescendantsSize(),be.create(e,xe).getRoot()}function Au(n){const t=Zt.create();for(const[e,r]of Object.entries(n))t.setInternal(e,r.value,S(r.updatedAt),r.isRemoved);return t}function bu(n){const t=zr(n.id),e=ie.create(t,n.type),r=Object.entries(n.attributes);return e.isText?e.value=n.value:r.length&&(e.attrs=Au(n.attributes)),n.insPrevId&&(e.insPrevID=zr(n.insPrevId)),n.insNextId&&(e.insNextID=zr(n.insNextId)),e.removedAt=S(n.removedAt),e}function Ho(n){if(n.body.case==="set"){const t=n.body.value;return wr.create(t.key,ss(t.value),S(t.parentCreatedAt),S(t.executedAt))}else if(n.body.case==="add"){const t=n.body.value;return tn.create(S(t.parentCreatedAt),S(t.prevCreatedAt),ss(t.value),S(t.executedAt))}else if(n.body.case==="move"){const t=n.body.value;return nr.create(S(t.parentCreatedAt),S(t.prevCreatedAt),S(t.createdAt),S(t.executedAt))}else if(n.body.case==="remove"){const t=n.body.value;return ur.create(S(t.parentCreatedAt),S(t.createdAt),S(t.executedAt))}else if(n.body.case==="edit"){const t=n.body.value,e=new Map;Object.entries(t.createdAtMapByActor).forEach(([s,i])=>{e.set(s,S(i))});const r=new Map;return Object.entries(t.attributes).forEach(([s,i])=>{r.set(s,i)}),rn.create(S(t.parentCreatedAt),ln(t.from),ln(t.to),e,t.content,r,S(t.executedAt))}else if(n.body.case==="style"){const t=n.body.value,e=new Map;Object.entries(t.createdAtMapByActor).forEach(([s,i])=>{e.set(s,S(i))});const r=new Map;return Object.entries(t.attributes).forEach(([s,i])=>{r.set(s,i)}),nn.create(S(t.parentCreatedAt),ln(t.from),ln(t.to),e,r,S(t.executedAt))}else{if(n.body.case==="select")return;if(n.body.case==="increase"){const t=n.body.value;return Jr.create(S(t.parentCreatedAt),ss(t.value),S(t.executedAt))}else if(n.body.case==="treeEdit"){const t=n.body.value,e=new Map;return Object.entries(t.createdAtMapByActor).forEach(([r,s])=>{e.set(r,S(s))}),sn.create(S(t.parentCreatedAt),br(t.from),br(t.to),Tu(t.contents),t.splitLevel,e,S(t.executedAt))}else if(n.body.case==="treeStyle"){const t=n.body.value,e=new Map,r=t.attributesToRemove,s=new Map;return t!=null&&t.createdAtMapByActor&&Object.entries(t.createdAtMapByActor).forEach(([i,o])=>{s.set(i,S(o))}),(r==null?void 0:r.length)>0?Yt.createTreeRemoveStyleOperation(S(t.parentCreatedAt),br(t.from),br(t.to),s,r,S(t.executedAt)):(Object.entries(t.attributes).forEach(([i,o])=>{e.set(i,o)}),Yt.create(S(t.parentCreatedAt),br(t.from),br(t.to),s,e,S(t.executedAt)))}else throw new g(d.ErrUnimplemented,"unimplemented operation")}}function Iu(n){const t=[];for(const e of n){const r=Ho(e);r&&t.push(r)}return t}function Yo(n){const t=[];for(const e of n)t.push(Rr.create({id:jo(e.id),operations:Iu(e.operations),presenceChange:e.presenceChange?yu(e.presenceChange):void 0,message:e.message}));return t}function Su(n){return Nr.of(BigInt(n.serverSeq),n.clientSeq)}function ku(n){return Hn.create(n.documentKey,Su(n.checkpoint),n.isRemoved,Yo(n.changes),Ys(n.versionVector),n.snapshot,S(n.minSyncedTicket))}function Xo(n){const t=new Hr;for(const r of n.nodes){const s=Qs(r.element);t.set(r.key,s,s.getPositionedAt())}const e=new re(S(n.createdAt),t);return e.setMovedAt(S(n.movedAt)),e.setRemovedAt(S(n.removedAt)),e}function Zo(n){const t=new Xr;for(const r of n.nodes)t.insert(Qs(r.element));const e=new ae(S(n.createdAt),t);return e.setMovedAt(S(n.movedAt)),e.setRemovedAt(S(n.removedAt)),e}function xu(n){const t=$.of($.valueFromBytes(Go(n.type),n.value),S(n.createdAt));return t.setMovedAt(S(n.movedAt)),t.setRemovedAt(S(n.removedAt)),t}function Eu(n){const t=new Lr;let e=t.getHead();for(const s of n.nodes){const i=t.insertAfter(e,wu(s));s.insPrevId&&i.setInsPrev(t.findNode(Wo(s.insPrevId))),e=i}const r=new Ae(t,S(n.createdAt));return r.setMovedAt(S(n.movedAt)),r.setRemovedAt(S(n.removedAt)),r}function Nu(n){const t=ce.create(Vn(n.type),ce.valueFromBytes(Vn(n.type),n.value),S(n.createdAt));return t.setMovedAt(S(n.movedAt)),t.setRemovedAt(S(n.removedAt)),t}function Qo(n){const t=Zs(n.nodes);return be.create(t,S(n.createdAt))}function Qs(n){if(n.body.case==="jsonObject")return Xo(n.body.value);if(n.body.case==="jsonArray")return Zo(n.body.value);if(n.body.case==="primitive")return xu(n.body.value);if(n.body.case==="text")return Eu(n.body.value);if(n.body.case==="counter")return Nu(n.body.value);if(n.body.case==="tree")return Qo(n.body.value);throw new g(d.ErrUnimplemented,"unimplemented element")}function Cu(n){if(!n)return{root:re.create(xe),presences:new Map};const t=ls.fromBinary(n);return{root:Qs(t.root),presences:vu(t.presences)}}function Pu(n){const t=Gs(n);return _s(t.toBinary())}function Du(n){const t=ti(n),e=Gn.fromBinary(t);return Ys(e)}function _o(n){if(!n)throw new g(d.ErrInvalidArgument,"bytes is empty");const t=ne.fromBinary(n);return Xo(t.body.value)}function ea(n){return Hs(n).toBinary()}function Ou(n){if(!n)throw new g(d.ErrInvalidArgument,"bytes is empty");const t=ne.fromBinary(n);return Zo(t.body.value)}function Bu(n){return zo(n).toBinary()}function Ru(n){if(!n)throw new g(d.ErrInvalidArgument,"bytes is empty");const t=ne.fromBinary(n);return Qo(t.body.value)}function Lu(n){return Ko(n).toBinary()}function _s(n){return n?Array.from(n).map(t=>t.toString(16).padStart(2,"0")).join(""):""}function ei(n){return _s(n)}function ti(n){return new Uint8Array(n.match(/.{1,2}/g).map(t=>parseInt(t,16)))}function ri(n){return ti(n)}function Ju(n){const t=jn.fromBinary(n);return jo(t)}function Fu(n){const t=Us.fromBinary(n);return Ho(t)}const V={fromPresence:Xs,toChangePack:pu,fromChangePack:ku,fromChanges:Yo,toTreeNodes:Ws,fromTreeNodes:Zs,objectToBytes:ea,bytesToObject:_o,bytesToSnapshot:Cu,bytesToHex:_s,hexToBytes:ti,toHexString:ei,toUint8Array:ri,toOperation:Vo,toChangeID:$o,PbChangeID:jn,bytesToChangeID:Ju,bytesToOperation:Fu,versionVectorToHex:Pu,hexToVersionVector:Du};var ee=(n=>(n[n.Trivial=0]="Trivial",n[n.Debug=1]="Debug",n[n.Info=2]="Info",n[n.Warn=3]="Warn",n[n.Error=4]="Error",n[n.Fatal=5]="Fatal",n))(ee||{});let hr=3;function ta(n){hr=n}const x={trivial:(...n)=>{hr>0||typeof console<"u"&&console.log("YORKIE T:",...n)},debug:(...n)=>{hr>1||typeof console<"u"&&console.log("YORKIE D:",...n)},info:(...n)=>{hr>2||typeof console<"u"&&console.log("YORKIE I:",...n)},warn:(...n)=>{hr>3||typeof console<"u"&&(typeof console.warn<"u"?console.warn("YORKIE W:",...n):console.log("YORKIE W:",...n))},error:(...n)=>{hr>4||typeof console<"u"&&(typeof console.error<"u"?console.error("YORKIE E:",...n):console.log("YORKIE E:",...n))},fatal:(...n)=>{typeof console<"u"&&(typeof console.error<"u"?console.error("YORKIE F:",...n):console.log("YORKIE F:",...n))},isEnabled:n=>hr<=n};function ra(){return"xxxxxxxx-xxxx-4xxxy-xxxx-xxxxxxxxxxx".replace(/[xy]/g,n=>{const t=Math.random()*16|0;return(n==="x"?t:t&3|8).toString(16)})}class Mu{constructor(t,e,r,s,i){a(this,"reconnectStreamDelay");a(this,"doc");a(this,"docID");a(this,"syncMode");a(this,"remoteChangeEventReceived");a(this,"watchStream");a(this,"watchLoopTimerID");a(this,"watchAbortController");a(this,"unsubscribeBroadcastEvent");this.reconnectStreamDelay=t,this.doc=e,this.docID=r,this.syncMode=s,this.remoteChangeEventReceived=!1,this.unsubscribeBroadcastEvent=i}changeSyncMode(t){this.syncMode=t}needRealtimeSync(){return this.syncMode===wn.RealtimeSyncOff?!1:this.syncMode===wn.RealtimePushOnly?this.doc.hasLocalChanges():this.syncMode!==wn.Manual&&(this.doc.hasLocalChanges()||this.remoteChangeEventReceived)}async runWatchLoop(t){const e=async()=>{if(this.watchStream)return Promise.resolve();this.watchLoopTimerID&&(clearTimeout(this.watchLoopTimerID),this.watchLoopTimerID=void 0);try{[this.watchStream,this.watchAbortController]=await t(()=>{this.watchStream=void 0,this.watchAbortController=void 0,this.watchLoopTimerID=setTimeout(e,this.reconnectStreamDelay)})}catch{}};await e()}cancelWatchStream(){this.watchStream&&this.watchAbortController&&(this.watchAbortController.abort(),this.watchStream=void 0,this.watchAbortController=void 0),clearTimeout(this.watchLoopTimerID),this.watchLoopTimerID=void 0}}const is=()=>{};class $u{constructor(t){a(this,"finalized",!1);a(this,"observers",[]);a(this,"finalError");try{t(this)}catch(e){this.error(e)}}next(t){this.forEachObserver(e=>{e.next(t)})}error(t){this.forEachObserver(e=>{e.error(t)}),this.close(t)}complete(){this.forEachObserver(t=>{t.complete()}),this.close()}subscribe(t,e,r){let s;if(!t)throw new g(d.ErrInvalidArgument,"missing observer");if(this.finalized)throw new g(d.ErrRefused,"observable is finalized due to previous error");typeof t=="object"?s=t:s={next:t,error:e,complete:r},s.next===void 0&&(s.next=is),s.error===void 0&&(s.error=is),s.complete===void 0&&(s.complete=is);const i=ra(),o=this.unsubscribeOne.bind(this,i);if(this.observers.push({subscriptionID:i,observer:s}),this.finalized)try{this.finalError?s.error(this.finalError):s.complete()}catch(c){x.warn(c)}return o}unsubscribeOne(t){var e;this.observers=(e=this.observers)==null?void 0:e.filter(r=>r.subscriptionID!==t)}forEachObserver(t){if(!this.finalized)for(let e=0;et}}class kr{constructor(t,e,r,s){a(this,"id");a(this,"delimiter");a(this,"message");a(this,"root");a(this,"operations");a(this,"presenceChange");a(this,"previousPresence");a(this,"reversePresenceKeys");this.id=t,this.delimiter=No,this.root=e,this.operations=[],this.previousPresence=Ie(r),this.presenceChange=void 0,this.reversePresenceKeys=new Set,this.message=s}static create(t,e,r,s){return new kr(t,e,r,s)}push(t){this.operations.push(t)}registerElement(t,e){this.root.registerElement(t,e)}registerRemovedElement(t){this.root.registerRemovedElement(t)}registerGCPair(t){this.root.registerGCPair(t)}getChange(){return Rr.create({id:this.id,operations:this.operations,presenceChange:this.presenceChange,message:this.message})}hasChange(){return this.operations.length>0||this.presenceChange!==void 0}setPresenceChange(t){this.presenceChange=t}setReversePresence(t,e){for(const r of Object.keys(t))e!=null&&e.addToHistory?this.reversePresenceKeys.add(r):this.reversePresenceKeys.delete(r)}getReversePresence(){if(this.reversePresenceKeys.size===0)return;const t={};for(const e of this.reversePresenceKeys)t[e]=this.previousPresence[e];return t}issueTimeTicket(){return this.delimiter+=1,this.id.createTimeTicket(this.delimiter)}getLastTimeTicket(){return this.id.createTimeTicket(this.delimiter)}}class Qr{constructor(t){a(this,"rootObject");a(this,"elementPairMapByCreatedAt");a(this,"gcElementSetByCreatedAt");a(this,"gcPairMap");this.rootObject=t,this.elementPairMapByCreatedAt=new Map,this.gcElementSetByCreatedAt=new Set,this.gcPairMap=new Map,this.registerElement(t,void 0),t.getDescendants(e=>{if(e.getRemovedAt()&&this.registerRemovedElement(e),e instanceof Ae||e instanceof be)for(const r of e.getGCPairs())this.registerGCPair(r);return!1})}static create(){return new Qr(re.create(xe))}findByCreatedAt(t){const e=this.elementPairMapByCreatedAt.get(t.toIDString());if(e)return e.element}findElementPairByCreatedAt(t){return this.elementPairMapByCreatedAt.get(t.toIDString())}createSubPaths(t){let e=this.elementPairMapByCreatedAt.get(t.toIDString());if(!e)return[];const r=[];for(;e.parent;){const s=e.element.getCreatedAt(),i=e.parent.subPathOf(s);if(i===void 0)throw new g(d.ErrInvalidArgument,`cant find the given element: ${s.toIDString()}`);r.unshift(i),e=this.elementPairMapByCreatedAt.get(e.parent.getCreatedAt().toIDString())}return r.unshift("$"),r}createPath(t){return this.createSubPaths(t).join(".")}registerElement(t,e){this.elementPairMapByCreatedAt.set(t.getCreatedAt().toIDString(),{parent:e,element:t}),t instanceof ir&&t.getDescendants((r,s)=>(this.registerElement(r,s),!1))}deregisterElement(t){let e=0;const r=s=>{const i=s.getCreatedAt().toIDString();this.elementPairMapByCreatedAt.delete(i),this.gcElementSetByCreatedAt.delete(i),e++};return r(t),t instanceof ir&&t.getDescendants(s=>(r(s),!1)),e}registerRemovedElement(t){this.gcElementSetByCreatedAt.add(t.getCreatedAt().toIDString())}registerGCPair(t){if(this.gcPairMap.get(t.child.toIDString())){this.gcPairMap.delete(t.child.toIDString());return}this.gcPairMap.set(t.child.toIDString(),t)}getElementMapSize(){return this.elementPairMapByCreatedAt.size}getGarbageElementSetSize(){const t=new Set;for(const e of this.gcElementSetByCreatedAt){t.add(e);const r=this.elementPairMapByCreatedAt.get(e);r.element instanceof ir&&r.element.getDescendants(s=>(t.add(s.getCreatedAt().toIDString()),!1))}return t.size}getObject(){return this.rootObject}getGarbageLen(){return this.getGarbageElementSetSize()+this.gcPairMap.size}deepcopy(){return new Qr(this.rootObject.deepcopy())}garbageCollect(t){let e=0;for(const r of this.gcElementSetByCreatedAt){const s=this.elementPairMapByCreatedAt.get(r),i=s.element.getRemovedAt();i&&(t!=null&&t.afterOrEqual(i))&&(s.parent.purge(s.element),e+=this.deregisterElement(s.element))}for(const[,r]of this.gcPairMap){const s=r.child.getRemovedAt();s&&(t!=null&&t.afterOrEqual(s))&&(r.parent.purge(r.child),this.gcPairMap.delete(r.child.toIDString()),e+=1)}return e}toJSON(){return this.rootObject.toJSON()}toSortedJSON(){return this.rootObject.toSortedJSON()}getStats(){return{elements:this.getElementMapSize(),gcPairs:this.gcPairMap.size,gcElements:this.getGarbageElementSetSize()}}}function na(n,t){const e=new _r(n);return new Proxy(t,e.getHandlers())}class _r{constructor(t){a(this,"context");a(this,"handlers");this.context=t,this.handlers={set:(e,r,s)=>(x.isEnabled(ee.Trivial)&&x.trivial(`obj[${r}]=${JSON.stringify(s)}`),_r.setInternal(t,e,r,s),!0),get:(e,r)=>(x.isEnabled(ee.Trivial)&&x.trivial(`obj[${r}]`),r==="getID"?()=>e.getCreatedAt():r==="toJSON"||r==="toString"?()=>e.toJSON():r==="toJS"?()=>e.toJS():r==="toJSForTest"?()=>e.toJSForTest():fr(t,e.get(r))),ownKeys:e=>e.getKeys(),getOwnPropertyDescriptor:()=>({enumerable:!0,configurable:!0}),deleteProperty:(e,r)=>(x.isEnabled(ee.Trivial)&&x.trivial(`obj[${r}]`),_r.deleteInternal(t,e,r),!0)}}static setInternal(t,e,r,s){if(r.includes("."))throw new g(d.ErrInvalidObjectKey,"key must not contain the '.'.");const i=t.issueTimeTicket(),o=zn(t,s,i),c=e.set(r,o,i);t.registerElement(o,e),c&&t.registerRemovedElement(c),t.push(wr.create(r,o.deepcopy(),e.getCreatedAt(),i))}static buildObjectMembers(t,e){const r={};for(const[s,i]of Object.entries(e)){if(s.includes("."))throw new g(d.ErrInvalidObjectKey,"key must not contain the '.'.");const o=t.issueTimeTicket(),c=zn(t,i,o);r[s]=c}return r}static deleteInternal(t,e,r){const s=t.issueTimeTicket(),i=e.deleteByKey(r,s);i&&(t.push(ur.create(e.getCreatedAt(),i.getCreatedAt(),s)),t.registerRemovedElement(i))}getHandlers(){return this.handlers}}function qu(n,t){const e=new U(n,t);return new Proxy(t,e.getHandlers())}function Vu(n){return typeof n=="string"||n instanceof String?!isNaN(n):!1}function zu(n){return["concat","entries","every","filter","find","findIndex","forEach","join","keys","map","reduce","reduceRight","slice","some","toLocaleString","toString","values"].includes(n)}class U{constructor(t,e){a(this,"context");a(this,"handlers");a(this,"array");this.context=t,this.array=e,this.handlers={get:(r,s,i)=>s==="getID"?()=>r.getCreatedAt():s==="getElementByID"?o=>{const c=r.getByID(o);if(!(!c||c.isRemoved()))return tr(t,c)}:s==="getElementByIndex"?o=>{const c=r.get(o);return tr(t,c)}:s==="getLast"?()=>tr(t,r.getLast()):s==="deleteByID"?o=>{const c=U.deleteInternalByID(t,r,o);return tr(t,c)}:s==="insertAfter"?(o,c)=>{const l=U.insertAfterInternal(t,r,o,c);return tr(t,l)}:s==="insertBefore"?(o,c)=>{const l=U.insertBeforeInternal(t,r,o,c);return tr(t,l)}:s==="moveBefore"?(o,c)=>{U.moveBeforeInternal(t,r,o,c)}:s==="moveAfter"?(o,c)=>{U.moveAfterInternal(t,r,o,c)}:s==="moveFront"?o=>{U.moveFrontInternal(t,r,o)}:s==="moveLast"?o=>{U.moveLastInternal(t,r,o)}:Vu(s)?fr(t,r.get(Number(s))):s==="push"?o=>U.pushInternal(t,r,o):s==="splice"?(o,c,...l)=>U.splice(t,r,o,c,...l):s==="length"?r.length:typeof s=="symbol"&&s===Symbol.iterator?U.iteratorInternal.bind(this,t,r):s==="includes"?(o,c)=>U.includes(t,r,o,c):s==="indexOf"?(o,c)=>U.indexOf(t,r,o,c):s==="lastIndexOf"?(o,c)=>U.lastIndexOf(t,r,o,c):s==="toJSForTest"?()=>r.toJSForTest():s==="toTestString"?()=>U.toTestString(r):typeof s=="string"&&zu(s)?(...o)=>{const c=Array.from(r).map(l=>fr(t,l));return Array.prototype[s].apply(c,o)}:Reflect.get(r,s,i),deleteProperty:(r,s)=>(x.isEnabled(ee.Trivial)&&x.trivial(`array[${s}]`),U.deleteInternalByIndex(t,r,Number.parseInt(s)),!0)}}static*iteratorInternal(t,e){for(const r of e)yield tr(t,r)}static buildArrayElements(t,e){const r=[];for(const s of e){const i=t.issueTimeTicket(),o=zn(t,s,i);r.push(o)}return r}static pushInternal(t,e,r){return U.insertAfterInternal(t,e,e.getLastCreatedAt(),r),e.length}static moveBeforeInternal(t,e,r,s){const i=t.issueTimeTicket(),o=e.getPrevCreatedAt(r);e.moveAfter(o,s,i),t.push(nr.create(e.getCreatedAt(),o,s,i))}static moveAfterInternal(t,e,r,s){const i=t.issueTimeTicket();e.moveAfter(r,s,i),t.push(nr.create(e.getCreatedAt(),r,s,i))}static moveFrontInternal(t,e,r){const s=t.issueTimeTicket(),i=e.getHead();e.moveAfter(i.getCreatedAt(),r,s),t.push(nr.create(e.getCreatedAt(),i.getCreatedAt(),r,s))}static moveLastInternal(t,e,r){const s=t.issueTimeTicket(),i=e.getLastCreatedAt();e.moveAfter(i,r,s),t.push(nr.create(e.getCreatedAt(),i,r,s))}static insertAfterInternal(t,e,r,s){const i=t.issueTimeTicket(),o=zn(t,s,i);return e.insertAfter(r,o),t.registerElement(o,e),t.push(tn.create(e.getCreatedAt(),r,o.deepcopy(),i)),o}static insertBeforeInternal(t,e,r,s){return U.insertAfterInternal(t,e,e.getPrevCreatedAt(r),s)}static deleteInternalByIndex(t,e,r){const s=t.issueTimeTicket(),i=e.deleteByIndex(r,s);if(i)return t.push(ur.create(e.getCreatedAt(),i.getCreatedAt(),s)),t.registerRemovedElement(i),i}static deleteInternalByID(t,e,r){const s=t.issueTimeTicket(),i=e.delete(r,s);return t.push(ur.create(e.getCreatedAt(),i.getCreatedAt(),s)),t.registerRemovedElement(i),i}static splice(t,e,r,s,...i){const o=e.length,c=r>=0?Math.min(r,o):Math.max(o+r,0),l=s===void 0?o:s<0?c:Math.min(c+s,o),h=[];for(let f=c;f=i)return!1;if($.isSupport(r))return Array.from(e).map(h=>fr(t,h)).includes(r,o);for(let l=o;l=i)return-1;if($.isSupport(r))return Array.from(e).map(h=>fr(t,h)).indexOf(r,o);for(let l=o;l=i?i-1:s<0?s+i:s;if(o<0)return-1;if($.isSupport(r))return Array.from(e).map(h=>fr(t,h)).lastIndexOf(r,o);for(let l=o;l>0;l--)if(((c=e.get(l))==null?void 0:c.getID())===r.getID())return l;return-1}static toTestString(t){return t.toTestString()}getHandlers(){return this.handlers}}class Yn{constructor(t,e){a(this,"context");a(this,"text");this.context=t,this.text=e}initialize(t,e){this.context=t,this.text=e}getID(){return this.text.getID()}edit(t,e,r,s){if(!this.context||!this.text)throw new g(d.ErrNotInitialized,"Text is not initialized yet");if(t>e)throw new g(d.ErrInvalidArgument,"from should be less than or equal to to");const i=this.text.indexRangeToPosRange(t,e);x.isEnabled(ee.Debug)&&x.debug(`EDIT: f:${t}->${i[0].toTestString()}, t:${e}->${i[1].toTestString()} c:${r}`);const o=s?Or(s):void 0,c=this.context.issueTimeTicket(),[l,,h,f]=this.text.edit(i,r,c,o);for(const p of h)this.context.registerGCPair(p);return this.context.push(new rn(this.text.getCreatedAt(),i[0],i[1],l,r,o?new Map(Object.entries(o)):new Map,c)),this.text.findIndexesFromRange(f)}delete(t,e){return this.edit(t,e,"")}empty(){return this.edit(0,this.length,"")}setStyle(t,e,r){if(!this.context||!this.text)throw new g(d.ErrNotInitialized,"Text is not initialized yet");if(t>e)throw new g(d.ErrInvalidArgument,"from should be less than or equal to to");const s=this.text.indexRangeToPosRange(t,e);x.isEnabled(ee.Debug)&&x.debug(`STYL: f:${t}->${s[0].toTestString()}, t:${e}->${s[1].toTestString()} a:${JSON.stringify(r)}`);const i=Or(r),o=this.context.issueTimeTicket(),[c,l]=this.text.setStyle(s,i,o);for(const h of l)this.context.registerGCPair(h);return this.context.push(new nn(this.text.getCreatedAt(),s[0],s[1],c,new Map(Object.entries(i)),o)),!0}indexRangeToPosRange(t){if(!this.context||!this.text)throw new g(d.ErrNotInitialized,"Text is not initialized yet");const e=this.text.indexRangeToPosRange(t[0],t[1]);return[e[0].toStruct(),e[1].toStruct()]}posRangeToIndexRange(t){if(!this.context||!this.text)throw new g(d.ErrNotInitialized,"Text is not initialized yet");const e=this.text.findIndexesFromRange([Ee.fromStruct(t[0]),Ee.fromStruct(t[1])]);return[e[0],e[1]]}toTestString(){if(!this.context||!this.text)throw new g(d.ErrNotInitialized,"Text is not initialized yet");return this.text.toTestString()}values(){if(!this.context||!this.text)throw new g(d.ErrNotInitialized,"Text is not initialized yet");return this.text.values()}get length(){return this.text.length}getTreeByIndex(){return this.text.getTreeByIndex()}getTreeByID(){return this.text.getTreeByID()}toString(){if(!this.context||!this.text)throw new g(d.ErrNotInitialized,"Text is not initialized yet");return this.text.toString()}toJSON(){if(!this.context||!this.text)throw new g(d.ErrNotInitialized,"Text is not initialized yet");return this.text.toJSON()}toJSForTest(){if(!this.context||!this.text)throw new g(d.ErrNotInitialized,"Text is not initialized yet");return this.text.toJSForTest()}createRangeForTest(t,e){if(!this.context||!this.text)throw new g(d.ErrNotInitialized,"Text is not initialized yet");return this.text.indexRangeToPosRange(t,e)}}class Xn{constructor(t,e){a(this,"valueType");a(this,"value");a(this,"context");a(this,"counter");this.valueType=t,this.value=e}initialize(t,e){this.valueType=e.getValueType(),this.context=t,this.counter=e,this.value=e.getValue()}getID(){return this.counter.getID()}getValue(){return this.value}getValueType(){return this.valueType}increase(t){if(!this.context||!this.counter)throw new g(d.ErrNotInitialized,"Counter is not initialized yet");const e=this.context.issueTimeTicket(),r=$.of(t,e);if(!r.isNumericType())throw new TypeError(`Unsupported type of value: ${typeof r.getValue()}`);return this.counter.increase(r),this.context.push(Jr.create(this.counter.getCreatedAt(),r,e)),this}toJSForTest(){if(!this.context||!this.counter)throw new g(d.ErrNotInitialized,"Counter is not initialized yet");return this.counter.toJSForTest()}}function ni(n,t,e){const{type:r}=n,s=e.issueTimeTicket();if(r===Ht){sa(n);const{value:i}=n,o=ie.create(Y.of(s,0),r,i);t.append(o)}else{const{children:i=[]}=n,{attributes:o}=n;let c;if(typeof o=="object"&&!Eo(o)){const h=Or(o);c=new Zt;for(const[f,p]of Object.entries(h))c.set(f,p,s)}const l=ie.create(Y.of(s,0),r,void 0,c);t.append(l);for(const h of i)ni(h,l,e)}}function Ku(n,t){const{type:e}=t,r=n.issueTimeTicket();let s;if(t.type===Ht){const{value:i}=t;s=ie.create(Y.of(r,0),e,i)}else if(t){const{children:i=[]}=t,{attributes:o}=t;let c;if(typeof o=="object"&&!Eo(o)){const l=Or(o);c=new Zt;for(const[h,f]of Object.entries(l))c.set(h,f,r)}s=ie.create(Y.of(n.issueTimeTicket(),0),e,void 0,c);for(const l of i)ni(l,s,n)}return s}function sa(n){if(!n.value.length)throw new g(d.ErrInvalidArgument,"text node cannot have empty value");return!0}function zi(n){if(!n.length)return!0;if(n[0].type===Ht)for(const e of n){const{type:r}=e;if(r!==Ht)throw new g(d.ErrInvalidArgument,"element node and text node cannot be passed together");sa(e)}else for(const e of n){const{type:r}=e;if(r===Ht)throw new g(d.ErrInvalidArgument,"element node and text node cannot be passed together")}return!0}class Zn{constructor(t){a(this,"initialRoot");a(this,"context");a(this,"tree");this.initialRoot=t}initialize(t,e){this.context=t,this.tree=e}getID(){return this.tree.getID()}buildRoot(t){if(!this.initialRoot)return ie.create(Y.of(t.issueTimeTicket(),0),Vc);const e=ie.create(Y.of(t.issueTimeTicket(),0),this.initialRoot.type);for(const r of this.initialRoot.children)ni(r,e,t);return e}getSize(){if(!this.context||!this.tree)throw new g(d.ErrNotInitialized,"Tree is not initialized yet");return this.tree.getSize()}getNodeSize(){if(!this.context||!this.tree)throw new g(d.ErrNotInitialized,"Tree is not initialized yet");return this.tree.getNodeSize()}getIndexTree(){if(!this.context||!this.tree)throw new g(d.ErrNotInitialized,"Tree is not initialized yet");return this.tree.getIndexTree()}styleByPath(t,e){if(!this.context||!this.tree)throw new g(d.ErrNotInitialized,"Tree is not initialized yet");if(!t.length)throw new g(d.ErrInvalidArgument,"path should not be empty");const[r,s]=this.tree.pathToPosRange(t),i=this.context.issueTimeTicket(),o=e?Or(e):void 0,[c]=this.tree.style([r,s],o,i);this.context.push(Yt.create(this.tree.getCreatedAt(),r,s,c,o?new Map(Object.entries(o)):new Map,i))}style(t,e,r){if(!this.context||!this.tree)throw new g(d.ErrNotInitialized,"Tree is not initialized yet");if(t>e)throw new g(d.ErrInvalidArgument,"from should be less than or equal to to");const s=this.tree.findPos(t),i=this.tree.findPos(e),o=this.context.issueTimeTicket(),c=r?Or(r):void 0,[l,h]=this.tree.style([s,i],c,o);for(const f of h)this.context.registerGCPair(f);this.context.push(Yt.create(this.tree.getCreatedAt(),s,i,l,c?new Map(Object.entries(c)):new Map,o))}removeStyle(t,e,r){if(!this.context||!this.tree)throw new g(d.ErrNotInitialized,"Tree is not initialized yet");if(t>e)throw new g(d.ErrInvalidArgument,"from should be less than or equal to to");const s=this.tree.findPos(t),i=this.tree.findPos(e),o=this.context.issueTimeTicket(),[c,l]=this.tree.removeStyle([s,i],r,o);for(const h of l)this.context.registerGCPair(h);this.context.push(Yt.createTreeRemoveStyleOperation(this.tree.getCreatedAt(),s,i,c,r,o))}editInternal(t,e,r,s=0){var h;if(r.length!==0&&r[0]&&(zi(r),r[0].type!==Ht))for(const f of r){const{children:p=[]}=f;zi(p)}const i=this.context.getLastTimeTicket();let o=new Array;if(((h=r[0])==null?void 0:h.type)===Ht){let f="";for(const p of r){const{value:v}=p;f+=v}o.push(ie.create(Y.of(this.context.issueTimeTicket(),0),Ht,f))}else o=r.map(f=>f&&Ku(this.context,f)).filter(f=>f);const[,c,l]=this.tree.edit([t,e],o.length?o.map(f=>f==null?void 0:f.deepcopy()):void 0,s,i,()=>this.context.issueTimeTicket());for(const f of c)this.context.registerGCPair(f);return this.context.push(sn.create(this.tree.getCreatedAt(),t,e,o.length?o:void 0,s,l,i)),!0}editByPath(t,e,r,s=0){if(!this.context||!this.tree)throw new g(d.ErrNotInitialized,"Tree is not initialized yet");if(t.length!==e.length)throw new g(d.ErrInvalidArgument,"path length should be equal");if(!t.length||!e.length)throw new g(d.ErrInvalidArgument,"path should not be empty");const i=this.tree.pathToPos(t),o=this.tree.pathToPos(e);return this.editInternal(i,o,r?[r]:[],s)}editBulkByPath(t,e,r,s=0){if(!this.context||!this.tree)throw new g(d.ErrNotInitialized,"Tree is not initialized yet");if(t.length!==e.length)throw new g(d.ErrInvalidArgument,"path length should be equal");if(!t.length||!e.length)throw new g(d.ErrInvalidArgument,"path should not be empty");const i=this.tree.pathToPos(t),o=this.tree.pathToPos(e);return this.editInternal(i,o,r,s)}edit(t,e,r,s=0){if(!this.context||!this.tree)throw new g(d.ErrNotInitialized,"Tree is not initialized yet");if(t>e)throw new g(d.ErrInvalidArgument,"from should be less than or equal to to");const i=this.tree.findPos(t),o=this.tree.findPos(e);return this.editInternal(i,o,r?[r]:[],s)}editBulk(t,e,r,s=0){if(!this.context||!this.tree)throw new g(d.ErrNotInitialized,"Tree is not initialized yet");if(t>e)throw new g(d.ErrInvalidArgument,"from should be less than or equal to to");const i=this.tree.findPos(t),o=this.tree.findPos(e);return this.editInternal(i,o,r,s)}toXML(){if(!this.context||!this.tree)throw new g(d.ErrNotInitialized,"Tree is not initialized yet");return this.tree.toXML()}toJSON(){if(!this.context||!this.tree)throw new g(d.ErrNotInitialized,"Tree is not initialized yet");return this.tree.toJSON()}toJSForTest(){if(!this.context||!this.tree)throw new g(d.ErrNotInitialized,"Tree is not initialized yet");return this.tree.toJSForTest()}toJSInfoForTest(){if(!this.context||!this.tree)throw new g(d.ErrNotInitialized,"Tree is not initialized yet");return this.tree.toJSInfoForTest()}getRootTreeNode(){if(!this.context||!this.tree)throw new g(d.ErrNotInitialized,"Tree is not initialized yet");return this.tree.getRootTreeNode()}indexToPath(t){if(!this.context||!this.tree)throw new g(d.ErrNotInitialized,"Tree is not initialized yet");return this.tree.indexToPath(t)}pathToIndex(t){if(!this.context||!this.tree)throw new g(d.ErrNotInitialized,"Tree is not initialized yet");return this.tree.pathToIndex(t)}pathRangeToPosRange(t){if(!this.context||!this.tree)throw new g(d.ErrNotInitialized,"Tree is not initialized yet");const e=[this.tree.pathToIndex(t[0]),this.tree.pathToIndex(t[1])],r=this.tree.indexRangeToPosRange(e);return[r[0].toStruct(),r[1].toStruct()]}indexRangeToPosRange(t){if(!this.context||!this.tree)throw new g(d.ErrNotInitialized,"Tree is not initialized yet");return this.tree.indexRangeToPosStructRange(t)}posRangeToIndexRange(t){if(!this.context||!this.tree)throw new g(d.ErrNotInitialized,"Tree is not initialized yet");const e=[ke.fromStruct(t[0]),ke.fromStruct(t[1])];return this.tree.posRangeToIndexRange(e)}posRangeToPathRange(t){if(!this.context||!this.tree)throw new g(d.ErrNotInitialized,"Tree is not initialized yet");const e=[ke.fromStruct(t[0]),ke.fromStruct(t[1])];return this.tree.posRangeToPathRange(e)}}function Ki(n,t){return na(n,t)}function tr(n,t){if(t){if(t instanceof $)return t;if(t instanceof re)return na(n,t);if(t instanceof ae)return qu(n,t);if(t instanceof Ae)return new Yn(n,t);if(t instanceof ce){const e=new Xn(ze.IntegerCnt,0);return e.initialize(n,t),e}else if(t instanceof be){const e=new Zn;return e.initialize(n,t),e}}else return;throw new TypeError(`Unsupported type of element: ${typeof t}`)}function fr(n,t){const e=tr(n,t);return e instanceof $?e.getValue():e}function zn(n,t,e){let r;if($.isSupport(t))r=$.of(t,e);else if(Array.isArray(t))r=ae.create(e,U.buildArrayElements(n,t));else if(typeof t=="object")t instanceof Yn?(r=Ae.create(Lr.create(),e),t.initialize(n,r)):t instanceof Xn?(r=ce.create(t.getValueType(),t.getValue(),e),t.initialize(n,r)):t instanceof Zn?(r=be.create(t.buildRoot(n),e),t.initialize(n,r)):r=re.create(e,_r.buildObjectMembers(n,t));else throw new TypeError(`Unsupported type of value: ${typeof t}`);return r}const ji=50;class ju{constructor(){a(this,"undoStack",[]);a(this,"redoStack",[])}hasUndo(){return this.undoStack.length>0}hasRedo(){return this.redoStack.length>0}pushUndo(t){this.undoStack.length>=ji&&this.undoStack.shift(),this.undoStack.push(t)}popUndo(){return this.undoStack.pop()}pushRedo(t){this.redoStack.length>=ji&&this.redoStack.shift(),this.redoStack.push(t)}popRedo(){return this.redoStack.pop()}clearRedo(){this.redoStack=[]}getUndoStackForTest(){return this.undoStack}getRedoStackForTest(){return this.redoStack}}const Gu="yorkie-devtools-panel",Wu="yorkie-devtools-sdk";let Ir="disconnected";const Gi=new Map,vn=new Map;typeof window<"u"&&(window.transactionEventsByDocKey=vn);function hn(n,t){(t!=null&&t.force||Ir!=="disconnected")&&window.postMessage({source:Wu,...n},"*")}function Hu(n){if(!n.isEnableDevtools()||typeof window>"u"||Gi.has(n.getKey()))return;vn.set(n.getKey(),[]);const t=n.subscribe("all",e=>{e.some(r=>r.type!==_.StatusChanged&&r.type!==_.Snapshot&&r.type!==_.LocalChange&&r.type!==_.RemoteChange&&r.type!==_.Initialized&&r.type!==_.Watched&&r.type!==_.Unwatched&&r.type!==_.PresenceChanged)||(vn.get(n.getKey()).push(e),Ir==="synced"&&hn({msg:"doc::sync::partial",docKey:n.getKey(),event:e}))});Gi.set(n.getKey(),[t]),hn({msg:"refresh-devtools"},{force:!0}),window.addEventListener("message",e=>{var s;if(((s=e.data)==null?void 0:s.source)!==Gu)return;switch(e.data.msg){case"devtools::connect":if(Ir!=="disconnected")break;Ir="connected",hn({msg:"doc::available",docKey:n.getKey()}),x.info(`[YD] Devtools connected. Doc: ${n.getKey()}`);break;case"devtools::disconnect":Ir="disconnected",x.info(`[YD] Devtools disconnected. Doc: ${n.getKey()}`);break;case"devtools::subscribe":Ir="synced",hn({msg:"doc::sync::full",docKey:n.getKey(),events:vn.get(n.getKey())}),x.info(`[YD] Devtools subscribed. Doc: ${n.getKey()}`);break}})}var rr=(n=>(n.Detached="detached",n.Attached="attached",n.Removed="removed",n))(rr||{}),_=(n=>(n.StatusChanged="status-changed",n.ConnectionChanged="connection-changed",n.SyncStatusChanged="sync-status-changed",n.Snapshot="snapshot",n.LocalChange="local-change",n.RemoteChange="remote-change",n.Initialized="initialized",n.Watched="watched",n.Unwatched="unwatched",n.PresenceChanged="presence-changed",n.Broadcast="broadcast",n.LocalBroadcast="local-broadcast",n))(_||{}),Js=(n=>(n.Connected="connected",n.Disconnected="disconnected",n))(Js||{}),Fs=(n=>(n.Synced="synced",n.SyncFailed="sync-failed",n))(Fs||{});class ia{constructor(t,e){a(this,"key");a(this,"status");a(this,"opts");a(this,"changeID");a(this,"checkpoint");a(this,"localChanges");a(this,"root");a(this,"clone");a(this,"eventStream");a(this,"eventStreamObserver");a(this,"onlineClients");a(this,"presences");a(this,"history");a(this,"internalHistory");a(this,"isUpdating");this.opts=e||{},this.key=t,this.status="detached",this.root=Qr.create(),this.changeID=Zc,this.checkpoint=Qc,this.localChanges=[],this.eventStream=Uu(r=>{this.eventStreamObserver=r}),this.onlineClients=new Set,this.presences=new Map,this.isUpdating=!1,this.internalHistory=new ju,this.history={canUndo:this.canUndo.bind(this),canRedo:this.canRedo.bind(this),undo:this.undo.bind(this),redo:this.redo.bind(this)},Hu(this)}update(t,e){if(this.getStatus()==="removed")throw new g(d.ErrDocumentRemoved,`${this.key} is removed`);this.ensureClone();const r=this.changeID.getActorID(),s=kr.create(this.changeID.next(),this.clone.root,this.clone.presences.get(r)||{},e);try{const i=Ki(s,this.clone.root.getObject());this.presences.has(r)||this.clone.presences.set(r,{}),this.isUpdating=!0,t(i,new rs(s,this.clone.presences.get(r)))}catch(i){throw this.clone=void 0,i}finally{this.isUpdating=!1}if(s.hasChange()){x.isEnabled(ee.Trivial)&&x.trivial(`trying to update a local change: ${this.toJSON()}`);const i=s.getChange(),{opInfos:o,reverseOps:c}=i.execute(this.root,this.presences,J.Local),l=s.getReversePresence();l&&c.push({type:"presence",value:l}),this.localChanges.push(i),c.length>0&&this.internalHistory.pushUndo(c),o.length>0&&this.internalHistory.clearRedo(),this.changeID=i.getID();const h=[];o.length>0&&h.push({type:"local-change",source:J.Local,value:{message:i.getMessage()||"",operations:o,actor:r,clientSeq:i.getID().getClientSeq(),serverSeq:i.getID().getServerSeq()},rawChange:this.isEnableDevtools()?i.toStruct():void 0}),i.hasPresenceChange()&&h.push({type:"presence-changed",source:J.Local,value:{clientID:r,presence:this.getPresence(r)}}),this.publish(h),x.isEnabled(ee.Trivial)&&x.trivial(`after update a local change: ${this.toJSON()}`)}}subscribe(t,e,r,s){if(typeof t=="string"){if(typeof e!="function")throw new g(d.ErrInvalidArgument,"Second argument must be a callback function");if(t==="presence"){const c=e;return this.eventStream.subscribe(l=>{for(const h of l)h.type!=="initialized"&&h.type!=="watched"&&h.type!=="unwatched"&&h.type!=="presence-changed"||c(h)},r,s)}if(t==="my-presence"){const c=e;return this.eventStream.subscribe(l=>{for(const h of l)h.type!=="initialized"&&h.type!=="presence-changed"||h.type==="presence-changed"&&h.value.clientID!==this.changeID.getActorID()||c(h)},r,s)}if(t==="others"){const c=e;return this.eventStream.subscribe(l=>{for(const h of l)h.type!=="watched"&&h.type!=="unwatched"&&h.type!=="presence-changed"||h.value.clientID!==this.changeID.getActorID()&&c(h)},r,s)}if(t==="connection"){const c=e;return this.eventStream.subscribe(l=>{for(const h of l)h.type==="connection-changed"&&c(h)},r,s)}if(t==="status"){const c=e;return this.eventStream.subscribe(l=>{for(const h of l)h.type==="status-changed"&&c(h)},r,s)}if(t==="sync"){const c=e;return this.eventStream.subscribe(l=>{for(const h of l)h.type==="sync-status-changed"&&c(h)},r,s)}if(t==="local-broadcast"){const c=e;return this.eventStream.subscribe(l=>{for(const h of l)h.type==="local-broadcast"&&c(h)},r)}if(t==="broadcast"){const c=e;return this.eventStream.subscribe(l=>{for(const h of l)h.type==="broadcast"&&c(h)},r)}if(t==="all"){const c=e;return this.eventStream.subscribe(c,r,s)}const i=t,o=e;return this.eventStream.subscribe(c=>{for(const l of c){if(l.type!=="local-change"&&l.type!=="remote-change")continue;const h=[];for(const f of l.value.operations)this.isSameElementOrChildOf(f.path,i)&&h.push(f);h.length&&o({...l,value:{...l.value,operations:h}})}},r,s)}if(typeof t=="function"){const i=t,o=e,c=r;return this.eventStream.subscribe(l=>{for(const h of l)h.type!=="snapshot"&&h.type!=="local-change"&&h.type!=="remote-change"||i(h)},o,c)}throw new g(d.ErrInvalidArgument,`"${t}" is not a valid`)}publish(t){this.eventStreamObserver&&this.eventStreamObserver.next(t)}isSameElementOrChildOf(t,e){if(e===t)return!0;const r=t.split(".");return e.split(".").every((i,o)=>i===r[o])}applyChangePack(t){const e=t.hasSnapshot();for(e?this.applySnapshot(t.getCheckpoint().getServerSeq(),t.getVersionVector(),t.getSnapshot()):t.hasChanges()&&this.applyChanges(t.getChanges(),J.Remote);this.localChanges.length&&!(this.localChanges[0].getID().getClientSeq()>t.getCheckpoint().getClientSeq());)this.localChanges.shift();e&&this.applyChanges(this.localChanges,J.Remote),this.checkpoint=this.checkpoint.forward(t.getCheckpoint()),e||this.garbageCollect(t.getVersionVector()),e||this.filterVersionVector(t.getVersionVector()),t.getIsRemoved()&&this.applyStatus("removed"),x.isEnabled(ee.Trivial)&&x.trivial(`${this.root.toJSON()}`)}getCheckpoint(){return this.checkpoint}getChangeID(){return this.changeID}hasLocalChanges(){return this.localChanges.length>0}ensureClone(){this.clone||(this.clone={root:this.root.deepcopy(),presences:Ie(this.presences)})}createChangePack(){const t=Array.from(this.localChanges),e=this.checkpoint.increaseClientSeq(t.length);return Hn.create(this.key,e,!1,t,this.getVersionVector())}setActor(t){for(const e of this.localChanges)e.setActor(t);this.changeID=this.changeID.setActor(t)}isEnableDevtools(){return!!this.opts.enableDevtools}getKey(){return this.key}getStatus(){return this.status}getCloneRoot(){if(this.clone)return this.clone.root.getObject()}getRoot(){this.ensureClone();const t=kr.create(this.changeID.next(),this.clone.root,this.clone.presences.get(this.changeID.getActorID())||{});return Ki(t,this.clone.root.getObject())}garbageCollect(t){return this.opts.disableGC?0:(this.clone&&this.clone.root.garbageCollect(t),this.root.garbageCollect(t))}getRootObject(){return this.root.getObject()}getGarbageLen(){return this.root.getGarbageLen()}getGarbageLenFromClone(){return this.clone.root.getGarbageLen()}toJSON(){return this.root.toJSON()}toSortedJSON(){return this.root.toSortedJSON()}getStats(){return this.root.getStats()}toJSForTest(){return{...this.getRoot().toJSForTest(),key:"root"}}applySnapshot(t,e,r){const{root:s,presences:i}=V.bytesToSnapshot(r);this.root=new Qr(s),this.presences=i,this.changeID=this.changeID.setClocks(t,e),this.clone=void 0,this.publish([{type:"snapshot",source:J.Remote,value:{serverSeq:t.toString(),snapshot:this.isEnableDevtools()?V.bytesToHex(r):void 0,snapshotVector:V.versionVectorToHex(e)}}])}applyChanges(t,e){x.isEnabled(ee.Debug)&&x.debug(`trying to apply ${t.length} remote changes.elements:${this.root.getElementMapSize()}, removeds:${this.root.getGarbageElementSetSize()}`),x.isEnabled(ee.Trivial)&&x.trivial(t.map(r=>`${r.getID().toTestString()} ${r.toTestString()}`).join(` + */var we=null;try{we=new WebAssembly.Instance(new WebAssembly.Module(new Uint8Array([0,97,115,109,1,0,0,0,1,13,2,96,0,1,127,96,4,127,127,127,127,1,127,3,7,6,0,1,1,1,1,1,6,6,1,127,1,65,0,11,7,50,6,3,109,117,108,0,1,5,100,105,118,95,115,0,2,5,100,105,118,95,117,0,3,5,114,101,109,95,115,0,4,5,114,101,109,95,117,0,5,8,103,101,116,95,104,105,103,104,0,0,10,191,1,6,4,0,35,0,11,36,1,1,126,32,0,173,32,1,173,66,32,134,132,32,2,173,32,3,173,66,32,134,132,126,34,4,66,32,135,167,36,0,32,4,167,11,36,1,1,126,32,0,173,32,1,173,66,32,134,132,32,2,173,32,3,173,66,32,134,132,127,34,4,66,32,135,167,36,0,32,4,167,11,36,1,1,126,32,0,173,32,1,173,66,32,134,132,32,2,173,32,3,173,66,32,134,132,128,34,4,66,32,135,167,36,0,32,4,167,11,36,1,1,126,32,0,173,32,1,173,66,32,134,132,32,2,173,32,3,173,66,32,134,132,129,34,4,66,32,135,167,36,0,32,4,167,11,36,1,1,126,32,0,173,32,1,173,66,32,134,132,32,2,173,32,3,173,66,32,134,132,130,34,4,66,32,135,167,36,0,32,4,167,11])),{}).exports}catch{}function O(n,t,e){this.low=n|0,this.high=t|0,this.unsigned=!!e}O.prototype.__isLong__;Object.defineProperty(O.prototype,"__isLong__",{value:!0});function Z(n){return(n&&n.__isLong__)===!0}function Li(n){var t=Math.clz32(n&-n);return n?31-t:t}O.isLong=Z;var Ji={},Fi={};function Tr(n,t){var e,r,s;return t?(n>>>=0,(s=0<=n&&n<256)&&(r=Fi[n],r)?r:(e=B(n,0,!0),s&&(Fi[n]=e),e)):(n|=0,(s=-128<=n&&n<128)&&(r=Ji[n],r)?r:(e=B(n,n<0?-1:0,!1),s&&(Ji[n]=e),e))}O.fromInt=Tr;function Te(n,t){if(isNaN(n))return t?Wt:Se;if(t){if(n<0)return Wt;if(n>=Po)return Bo}else{if(n<=-$i)return te;if(n+1>=$i)return Oo}return n<0?Te(-n,t).neg():B(n%Br|0,n/Br|0,t)}O.fromNumber=Te;function B(n,t,e){return new O(n,t,e)}O.fromBits=B;var Un=Math.pow;function Ks(n,t,e){if(n.length===0)throw Error("empty string");if(typeof t=="number"?(e=t,t=!1):t=!!t,n==="NaN"||n==="Infinity"||n==="+Infinity"||n==="-Infinity")return t?Wt:Se;if(e=e||10,e<2||360)throw Error("interior hyphen");if(r===0)return Ks(n.substring(1),t,e).neg();for(var s=Te(Un(e,8)),i=Se,o=0;o>>0:this.low};T.toNumber=function(){return this.unsigned?(this.high>>>0)*Br+(this.low>>>0):this.high*Br+(this.low>>>0)};T.toString=function(t){if(t=t||10,t<2||36>>0,f=h.toString(t);if(o=l,o.isZero())return f+c;for(;f.length<6;)f="0"+f;c=""+f+c}};T.getHighBits=function(){return this.high};T.getHighBitsUnsigned=function(){return this.high>>>0};T.getLowBits=function(){return this.low};T.getLowBitsUnsigned=function(){return this.low>>>0};T.getNumBitsAbs=function(){if(this.isNegative())return this.eq(te)?64:this.neg().getNumBitsAbs();for(var t=this.high!=0?this.high:this.low,e=31;e>0&&!(t&1<=0};T.isOdd=function(){return(this.low&1)===1};T.isEven=function(){return(this.low&1)===0};T.equals=function(t){return Z(t)||(t=Ce(t)),this.unsigned!==t.unsigned&&this.high>>>31===1&&t.high>>>31===1?!1:this.high===t.high&&this.low===t.low};T.eq=T.equals;T.notEquals=function(t){return!this.eq(t)};T.neq=T.notEquals;T.ne=T.notEquals;T.lessThan=function(t){return this.comp(t)<0};T.lt=T.lessThan;T.lessThanOrEqual=function(t){return this.comp(t)<=0};T.lte=T.lessThanOrEqual;T.le=T.lessThanOrEqual;T.greaterThan=function(t){return this.comp(t)>0};T.gt=T.greaterThan;T.greaterThanOrEqual=function(t){return this.comp(t)>=0};T.gte=T.greaterThanOrEqual;T.ge=T.greaterThanOrEqual;T.compare=function(t){if(Z(t)||(t=Ce(t)),this.eq(t))return 0;var e=this.isNegative(),r=t.isNegative();return e&&!r?-1:!e&&r?1:this.unsigned?t.high>>>0>this.high>>>0||t.high===this.high&&t.low>>>0>this.low>>>0?-1:1:this.sub(t).isNegative()?-1:1};T.comp=T.compare;T.negate=function(){return!this.unsigned&&this.eq(te)?te:this.not().add(Sr)};T.neg=T.negate;T.add=function(t){Z(t)||(t=Ce(t));var e=this.high>>>16,r=this.high&65535,s=this.low>>>16,i=this.low&65535,o=t.high>>>16,c=t.high&65535,l=t.low>>>16,h=t.low&65535,f=0,p=0,v=0,m=0;return m+=i+h,v+=m>>>16,m&=65535,v+=s+l,p+=v>>>16,v&=65535,p+=r+c,f+=p>>>16,p&=65535,f+=e+o,f&=65535,B(v<<16|m,f<<16|p,this.unsigned)};T.subtract=function(t){return Z(t)||(t=Ce(t)),this.add(t.neg())};T.sub=T.subtract;T.multiply=function(t){if(this.isZero())return this;if(Z(t)||(t=Ce(t)),we){var e=we.mul(this.low,this.high,t.low,t.high);return B(e,we.get_high(),this.unsigned)}if(t.isZero())return this.unsigned?Wt:Se;if(this.eq(te))return t.isOdd()?te:Se;if(t.eq(te))return this.isOdd()?te:Se;if(this.isNegative())return t.isNegative()?this.neg().mul(t.neg()):this.neg().mul(t).neg();if(t.isNegative())return this.mul(t.neg()).neg();if(this.lt(Ui)&&t.lt(Ui))return Te(this.toNumber()*t.toNumber(),this.unsigned);var r=this.high>>>16,s=this.high&65535,i=this.low>>>16,o=this.low&65535,c=t.high>>>16,l=t.high&65535,h=t.low>>>16,f=t.low&65535,p=0,v=0,m=0,w=0;return w+=o*f,m+=w>>>16,w&=65535,m+=i*f,v+=m>>>16,m&=65535,m+=o*h,v+=m>>>16,m&=65535,v+=s*f,p+=v>>>16,v&=65535,v+=i*h,p+=v>>>16,v&=65535,v+=o*l,p+=v>>>16,v&=65535,p+=r*f+s*h+i*l+o*c,p&=65535,B(m<<16|w,p<<16|v,this.unsigned)};T.mul=T.multiply;T.divide=function(t){if(Z(t)||(t=Ce(t)),t.isZero())throw Error("division by zero");if(we){if(!this.unsigned&&this.high===-2147483648&&t.low===-1&&t.high===-1)return this;var e=(this.unsigned?we.div_u:we.div_s)(this.low,this.high,t.low,t.high);return B(e,we.get_high(),this.unsigned)}if(this.isZero())return this.unsigned?Wt:Se;var r,s,i;if(this.unsigned){if(t.unsigned||(t=t.toUnsigned()),t.gt(this))return Wt;if(t.gt(this.shru(1)))return Do;i=Wt}else{if(this.eq(te)){if(t.eq(Sr)||t.eq(Bs))return te;if(t.eq(te))return Sr;var o=this.shr(1);return r=o.div(t).shl(1),r.eq(Se)?t.isNegative()?Sr:Bs:(s=this.sub(t.mul(r)),i=r.add(s.div(t)),i)}else if(t.eq(te))return this.unsigned?Wt:Se;if(this.isNegative())return t.isNegative()?this.neg().div(t.neg()):this.neg().div(t).neg();if(t.isNegative())return this.div(t.neg()).neg();i=Se}for(s=this;s.gte(t);){r=Math.max(1,Math.floor(s.toNumber()/t.toNumber()));for(var c=Math.ceil(Math.log(r)/Math.LN2),l=c<=48?1:Un(2,c-48),h=Te(r),f=h.mul(t);f.isNegative()||f.gt(s);)r-=l,h=Te(r,this.unsigned),f=h.mul(t);h.isZero()&&(h=Sr),i=i.add(h),s=s.sub(f)}return i};T.div=T.divide;T.modulo=function(t){if(Z(t)||(t=Ce(t)),we){var e=(this.unsigned?we.rem_u:we.rem_s)(this.low,this.high,t.low,t.high);return B(e,we.get_high(),this.unsigned)}return this.sub(this.div(t).mul(t))};T.mod=T.modulo;T.rem=T.modulo;T.not=function(){return B(~this.low,~this.high,this.unsigned)};T.countLeadingZeros=function(){return this.high?Math.clz32(this.high):Math.clz32(this.low)+32};T.clz=T.countLeadingZeros;T.countTrailingZeros=function(){return this.low?Li(this.low):Li(this.high)+32};T.ctz=T.countTrailingZeros;T.and=function(t){return Z(t)||(t=Ce(t)),B(this.low&t.low,this.high&t.high,this.unsigned)};T.or=function(t){return Z(t)||(t=Ce(t)),B(this.low|t.low,this.high|t.high,this.unsigned)};T.xor=function(t){return Z(t)||(t=Ce(t)),B(this.low^t.low,this.high^t.high,this.unsigned)};T.shiftLeft=function(t){return Z(t)&&(t=t.toInt()),(t&=63)===0?this:t<32?B(this.low<>>32-t,this.unsigned):B(0,this.low<>>t|this.high<<32-t,this.high>>t,this.unsigned):B(this.high>>t-32,this.high>=0?0:-1,this.unsigned)};T.shr=T.shiftRight;T.shiftRightUnsigned=function(t){return Z(t)&&(t=t.toInt()),(t&=63)===0?this:t<32?B(this.low>>>t|this.high<<32-t,this.high>>>t,this.unsigned):t===32?B(this.high,0,this.unsigned):B(this.high>>>t-32,0,this.unsigned)};T.shru=T.shiftRightUnsigned;T.shr_u=T.shiftRightUnsigned;T.rotateLeft=function(t){var e;return Z(t)&&(t=t.toInt()),(t&=63)===0?this:t===32?B(this.high,this.low,this.unsigned):t<32?(e=32-t,B(this.low<>>e,this.high<>>e,this.unsigned)):(t-=32,e=32-t,B(this.high<>>e,this.low<>>e,this.unsigned))};T.rotl=T.rotateLeft;T.rotateRight=function(t){var e;return Z(t)&&(t=t.toInt()),(t&=63)===0?this:t===32?B(this.high,this.low,this.unsigned):t<32?(e=32-t,B(this.high<>>t,this.low<>>t,this.unsigned)):(t-=32,e=32-t,B(this.low<>>t,this.high<>>t,this.unsigned))};T.rotr=T.rotateRight;T.toSigned=function(){return this.unsigned?B(this.low,this.high,!1):this};T.toUnsigned=function(){return this.unsigned?this:B(this.low,this.high,!0)};T.toBytes=function(t){return t?this.toBytesLE():this.toBytesBE()};T.toBytesLE=function(){var t=this.high,e=this.low;return[e&255,e>>>8&255,e>>>16&255,e>>>24,t&255,t>>>8&255,t>>>16&255,t>>>24]};T.toBytesBE=function(){var t=this.high,e=this.low;return[t>>>24,t>>>16&255,t>>>8&255,t&255,e>>>24,e>>>16&255,e>>>8&255,e&255]};O.fromBytes=function(t,e,r){return r?O.fromBytesLE(t,e):O.fromBytesBE(t,e)};O.fromBytesLE=function(t,e){return new O(t[0]|t[1]<<8|t[2]<<16|t[3]<<24,t[4]|t[5]<<8|t[6]<<16|t[7]<<24,e)};O.fromBytesBE=function(t,e){return new O(t[4]<<24|t[5]<<16|t[6]<<8|t[7],t[0]<<24|t[1]<<16|t[2]<<8|t[3],e)};var W=(n=>(n[n.Null=0]="Null",n[n.Boolean=1]="Boolean",n[n.Integer=2]="Integer",n[n.Long=3]="Long",n[n.Double=4]="Double",n[n.String=5]="String",n[n.Bytes=6]="Bytes",n[n.Date=7]="Date",n))(W||{});class $ extends en{constructor(e,r){super(r);a(this,"valueType");a(this,"value");this.valueType=$.getPrimitiveType(e),this.value=e===void 0?null:e}static of(e,r){return new $(e,r)}static valueFromBytes(e,r){switch(e){case 0:return null;case 1:return!!r[0];case 2:return r[0]|r[1]<<8|r[2]<<16|r[3]<<24;case 4:{const s=new DataView(r.buffer);return r.forEach(function(i,o){s.setUint8(o,i)}),s.getFloat64(0,!0)}case 5:return new TextDecoder("utf-8").decode(r);case 3:return O.fromBytesLE(Array.from(r));case 6:return r;case 7:return new Date(O.fromBytesLE(Array.from(r),!0).toNumber());default:throw new g(d.ErrUnimplemented,`unimplemented type: ${e}`)}}toJSON(){return this.valueType===5?`"${qe(this.value)}"`:`${this.value}`}toSortedJSON(){return this.toJSON()}toJSForTest(){return{createdAt:this.getCreatedAt().toTestString(),value:this.value,type:"YORKIE_PRIMITIVE"}}deepcopy(){const e=$.of(this.value,this.getCreatedAt());return e.setMovedAt(this.getMovedAt()),e.setRemovedAt(this.getRemovedAt()),e}getType(){return this.valueType}static getPrimitiveType(e){switch(typeof e){case"undefined":return 0;case"boolean":return 1;case"number":return this.isInteger(e)?2:4;case"string":return 5;case"object":if(e===null)return 0;if(e instanceof O)return 3;if(e instanceof Uint8Array)return 6;if(e instanceof Date)return 7}}static isSupport(e){return $.getPrimitiveType(e)!==void 0}static isInteger(e){return e%1===0}isNumericType(){const e=this.valueType;return e===2||e===3||e===4}getValue(){return this.value}toBytes(){switch(this.valueType){case 0:return new Uint8Array;case 1:return this.value?new Uint8Array([1]):new Uint8Array([0]);case 2:{const e=this.value;return new Uint8Array([e&255,e>>8&255,e>>16&255,e>>24&255])}case 4:{const e=this.value,r=new Uint8Array(8);return new DataView(r.buffer).setFloat64(0,e,!0),r}case 5:return new TextEncoder().encode(this.value);case 3:{const r=this.value.toBytesLE();return Uint8Array.from(r)}case 6:return this.value;case 7:{const e=this.value,r=O.fromNumber(e.getTime(),!0).toBytesLE();return Uint8Array.from(r)}default:throw new g(d.ErrUnimplemented,`unimplemented type: ${this.valueType}`)}}}class qn extends Co{constructor(e){super(e);a(this,"prev");a(this,"next");this.value=e}static createAfter(e,r){const s=new qn(r),i=e.next;return e.next=s,s.prev=e,s.next=i,i&&(i.prev=s),s}remove(e){return this.value.remove(e)}getCreatedAt(){return this.value.getCreatedAt()}getPositionedAt(){return this.value.getPositionedAt()}release(){this.prev&&(this.prev.next=this.next),this.next&&(this.next.prev=this.prev),this.prev=void 0,this.next=void 0}getLength(){return this.value.isRemoved()?0:1}getPrev(){return this.prev}getNext(){return this.next}getValue(){return this.value}isRemoved(){return this.value.isRemoved()}}class Xr{constructor(){a(this,"dummyHead");a(this,"last");a(this,"nodeMapByIndex");a(this,"nodeMapByCreatedAt");const t=$.of(0,xe);t.setRemovedAt(xe),this.dummyHead=new qn(t),this.last=this.dummyHead,this.nodeMapByIndex=new Yr,this.nodeMapByCreatedAt=new Map,this.nodeMapByIndex.insert(this.dummyHead),this.nodeMapByCreatedAt.set(this.dummyHead.getCreatedAt().toIDString(),this.dummyHead)}static create(){return new Xr}get length(){return this.nodeMapByIndex.length}findNextBeforeExecutedAt(t,e){let r=this.nodeMapByCreatedAt.get(t.toIDString());if(!r)throw new g(d.ErrInvalidArgument,`cant find the given node: ${t.toIDString()}`);for(;r.getNext()&&r.getNext().getPositionedAt().after(e);)r=r.getNext();return r}release(t){this.last===t&&(this.last=t.getPrev()),t.release(),this.nodeMapByIndex.delete(t),this.nodeMapByCreatedAt.delete(t.getValue().getCreatedAt().toIDString())}insertAfter(t,e,r=e.getCreatedAt()){const s=this.findNextBeforeExecutedAt(t,r),i=qn.createAfter(s,e);s===this.last&&(this.last=i),this.nodeMapByIndex.insertAfter(s,i),this.nodeMapByCreatedAt.set(i.getCreatedAt().toIDString(),i)}moveAfter(t,e,r){const s=this.nodeMapByCreatedAt.get(t.toIDString());if(!s)throw new g(d.ErrInvalidArgument,`cant find the given node: ${t.toIDString()}`);const i=this.nodeMapByCreatedAt.get(e.toIDString());if(!i)throw new g(d.ErrInvalidArgument,`cant find the given node: ${e.toIDString()}`);s!==i&&(!i.getValue().getMovedAt()||r.after(i.getValue().getMovedAt()))&&(this.release(i),this.insertAfter(s.getCreatedAt(),i.getValue(),r),i.getValue().setMovedAt(r))}insert(t){this.insertAfter(this.last.getCreatedAt(),t)}getByID(t){return this.nodeMapByCreatedAt.get(t.toIDString())}subPathOf(t){const e=this.nodeMapByCreatedAt.get(t.toIDString());if(e)return String(this.nodeMapByIndex.indexOf(e))}purge(t){const e=this.nodeMapByCreatedAt.get(t.getCreatedAt().toIDString());if(!e)throw new g(d.ErrInvalidArgument,`fail to find the given createdAt: ${t.getCreatedAt().toIDString()}`);this.release(e)}getByIndex(t){if(t>=this.length)return;const[e,r]=this.nodeMapByIndex.find(t);let s=e;if(t===0&&e===this.dummyHead||r>0)do s&&(s=s.getNext());while(s&&s.isRemoved());return s}getPrevCreatedAt(t){let e=this.nodeMapByCreatedAt.get(t.toIDString());do e=e.getPrev();while(this.dummyHead!==e&&e.isRemoved());return e.getValue().getCreatedAt()}delete(t,e){const r=this.nodeMapByCreatedAt.get(t.toIDString()),s=r.isRemoved();return r.remove(e)&&!s&&this.nodeMapByIndex.splayNode(r),r.getValue()}deleteByIndex(t,e){const r=this.getByIndex(t);if(r)return r.remove(e)&&this.nodeMapByIndex.splayNode(r),r.getValue()}getHead(){return this.dummyHead.getValue()}getLast(){return this.last.getValue()}getLastCreatedAt(){return this.last.getCreatedAt()}toTestString(){const t=[];for(const e of this){const r=`${e.getCreatedAt().toIDString()}:${e.getValue().toJSON()}`;e.isRemoved()?t.push(`{${r}}`):t.push(`[${r}]`)}return t.join("")}*[Symbol.iterator](){let t=this.dummyHead.getNext();for(;t;)yield t,t=t.getNext()}}class ae extends ir{constructor(e,r){super(e);a(this,"elements");this.elements=r}static create(e,r){if(!r)return new ae(e,Xr.create());const s=Xr.create();for(const i of r)s.insertAfter(s.getLastCreatedAt(),i.deepcopy());return new ae(e,s)}subPathOf(e){return this.elements.subPathOf(e)}purge(e){this.elements.purge(e)}insertAfter(e,r){this.elements.insertAfter(e,r)}moveAfter(e,r,s){this.elements.moveAfter(e,r,s)}get(e){const r=this.elements.getByIndex(e);return r==null?void 0:r.getValue()}getByID(e){const r=this.elements.getByID(e);return r==null?void 0:r.getValue()}getHead(){return this.elements.getHead()}getLast(){return this.elements.getLast()}getPrevCreatedAt(e){return this.elements.getPrevCreatedAt(e)}delete(e,r){return this.elements.delete(e,r)}deleteByIndex(e,r){return this.elements.deleteByIndex(e,r)}getLastCreatedAt(){return this.elements.getLastCreatedAt()}get length(){return this.elements.length}*[Symbol.iterator](){for(const e of this.elements)e.isRemoved()||(yield e.getValue())}toTestString(){return this.elements.toTestString()}getDescendants(e){for(const r of this.elements){const s=r.getValue();if(e(s,this))return;s instanceof ir&&s.getDescendants(e)}}toJSON(){const e=[];for(const r of this)e.push(r.toJSON());return`[${e.join(",")}]`}toJS(){return JSON.parse(this.toJSON())}toJSForTest(){const e={};for(let r=0;r({...m,value:m.value?{attributes:xr(m.value.getAttributes()),content:m.value.getContent()}:{attributes:void 0,content:""},type:"content"}));return[h,v,f,[l,l]]}setStyle(e,r,s,i){const[,o]=this.rgaTreeSplit.findNodeWithSplit(e[1],s),[,c]=this.rgaTreeSplit.findNodeWithSplit(e[0],s),l=[],h=this.rgaTreeSplit.findBetween(c,o),f=new Map,p=[];for(const m of h){const w=m.getCreatedAt().getActorID(),k=i!=null&&i.size?i.has(w)?i.get(w):xe:qr;if(m.canStyle(s,k)){const E=f.get(w),C=m.getCreatedAt();(!E||C.after(E))&&f.set(w,C),p.push(m)}}const v=[];for(const m of p){if(m.isRemoved())continue;const[w,k]=this.rgaTreeSplit.findIndexesFromRange(m.createPosRange());l.push({type:"style",actor:s.getActorID(),from:w,to:k,value:{attributes:xr(r)}});for(const[E,C]of Object.entries(r)){const[P]=m.getValue().setAttr(E,C,s);P!==void 0&&v.push({parent:m.getValue(),child:P})}}return[f,v,l]}indexRangeToPosRange(e,r){const s=this.rgaTreeSplit.indexToPos(e);return e===r?[s,s]:[s,this.rgaTreeSplit.indexToPos(r)]}get length(){return this.rgaTreeSplit.length}getTreeByIndex(){return this.rgaTreeSplit.getTreeByIndex()}getTreeByID(){return this.rgaTreeSplit.getTreeByID()}toJSON(){const e=[];for(const r of this.rgaTreeSplit)r.isRemoved()||e.push(r.getValue().toJSON());return`[${e.join(",")}]`}toSortedJSON(){return this.toJSON()}toJSForTest(){return{createdAt:this.getCreatedAt().toTestString(),value:JSON.parse(this.toJSON()),type:"YORKIE_TEXT"}}toString(){return this.rgaTreeSplit.toString()}values(){const e=[];for(const r of this.rgaTreeSplit)if(!r.isRemoved()){const s=r.getValue();e.push({attributes:xr(s.getAttributes()),content:s.getContent()})}return e}getRGATreeSplit(){return this.rgaTreeSplit}toTestString(){return this.rgaTreeSplit.toTestString()}deepcopy(){const e=new Ae(this.rgaTreeSplit.deepcopy(),this.getCreatedAt());return e.remove(this.getRemovedAt()),e}findIndexesFromRange(e){return this.rgaTreeSplit.findIndexesFromRange(e)}getGCPairs(){const e=[];for(const r of this.rgaTreeSplit){r.getRemovedAt()&&e.push({parent:this.rgaTreeSplit,child:r});for(const s of r.getValue().getGCPairs())e.push(s)}return e}}class rn extends Ne{constructor(e,r,s,i,o,c,l){super(e,l);a(this,"fromPos");a(this,"toPos");a(this,"maxCreatedAtMapByActor");a(this,"content");a(this,"attributes");this.fromPos=r,this.toPos=s,this.maxCreatedAtMapByActor=i,this.content=o,this.attributes=c}static create(e,r,s,i,o,c,l){return new rn(e,r,s,i,o,c,l)}execute(e){const r=e.findByCreatedAt(this.getParentCreatedAt());if(!r)throw new g(d.ErrInvalidArgument,`fail to find ${this.getParentCreatedAt()}`);if(!(r instanceof Ae))throw new g(d.ErrInvalidArgument,"fail to execute, only Text can execute edit");const s=r,[,i,o]=s.edit([this.fromPos,this.toPos],this.content,this.getExecutedAt(),Object.fromEntries(this.attributes),this.maxCreatedAtMapByActor);for(const c of o)e.registerGCPair(c);return{opInfos:i.map(({from:c,to:l,value:h})=>({type:"edit",from:c,to:l,value:h,path:e.createPath(this.getParentCreatedAt())}))}}getEffectedCreatedAt(){return this.getParentCreatedAt()}toTestString(){const e=this.getParentCreatedAt().toTestString(),r=this.fromPos.toTestString(),s=this.toPos.toTestString(),i=this.content;return`${e}.EDIT(${r},${s},${i})`}getFromPos(){return this.fromPos}getToPos(){return this.toPos}getContent(){return this.content}getAttributes(){return this.attributes||new Map}getMaxCreatedAtMapByActor(){return this.maxCreatedAtMapByActor}}class nn extends Ne{constructor(e,r,s,i,o,c){super(e,c);a(this,"fromPos");a(this,"toPos");a(this,"maxCreatedAtMapByActor");a(this,"attributes");this.fromPos=r,this.toPos=s,this.maxCreatedAtMapByActor=i,this.attributes=o}static create(e,r,s,i,o,c){return new nn(e,r,s,i,o,c)}execute(e){const r=e.findByCreatedAt(this.getParentCreatedAt());if(!r)throw new g(d.ErrInvalidArgument,`fail to find ${this.getParentCreatedAt()}`);if(!(r instanceof Ae))throw new g(d.ErrInvalidArgument,"fail to execute, only Text can execute edit");const s=r,[,i,o]=s.setStyle([this.fromPos,this.toPos],this.attributes?Object.fromEntries(this.attributes):{},this.getExecutedAt(),this.maxCreatedAtMapByActor);for(const c of i)e.registerGCPair(c);return{opInfos:o.map(({from:c,to:l,value:h})=>({type:"style",from:c,to:l,value:h,path:e.createPath(this.getParentCreatedAt())}))}}getEffectedCreatedAt(){return this.getParentCreatedAt()}toTestString(){const e=this.getParentCreatedAt().toTestString(),r=this.fromPos.toTestString(),s=this.toPos.toTestString(),i=this.attributes;return`${e}.STYL(${r},${s},${JSON.stringify(i)})`}getFromPos(){return this.fromPos}getToPos(){return this.toPos}getAttributes(){return this.attributes}getMaxCreatedAtMapByActor(){return this.maxCreatedAtMapByActor}}const qc=2,Vc="root",Ht="text";function Mr(n,t){let e=0;const r=n.children;for(let s=0;s0)throw new g(d.ErrRefused,"Text node cannot have children")}updateAncestorsSize(){let t=this.parent;const e=this.isRemoved?-1:1;for(;t&&(t.size+=this.paddedSize*e,!t.isRemoved);)t=t.parent}updateDescendantsSize(){let t=0;for(const e of this._children){const r=e.updateDescendantsSize();e.isRemoved||(t+=r)}return this.size+=t,this.paddedSize}get isText(){return this.type===Ht}get paddedSize(){return this.size+(this.isText?0:qc)}isAncestorOf(t){return Kc(this,t)}get nextSibling(){const t=this.parent.findOffset(this),e=this.parent.children[t+1];if(e)return e}get prevSibling(){const t=this.parent.findOffset(this),e=this.parent.children[t-1];if(e)return e}splitText(t,e){if(t===0||t===this.size)return;const r=this.value.slice(0,t),s=this.value.slice(t);if(!s.length)return;this.value=r;const i=this.cloneText(t+e);return i.value=s,this.parent.insertAfterInternal(i,this),i}get children(){return this._children.filter(t=>!t.isRemoved)}get allChildren(){return[...this._children]}hasTextChild(){return this.children.length>0&&this.children.every(t=>t.isText)}append(...t){if(this.isText)throw new g(d.ErrRefused,"Text node cannot have children");this._children.push(...t);for(const e of t)e.parent=this,e.updateAncestorsSize()}prepend(...t){if(this.isText)throw new g(d.ErrRefused,"Text node cannot have children");this._children.unshift(...t);for(const e of t)e.parent=this}insertBefore(t,e){if(this.isText)throw new g(d.ErrRefused,"Text node cannot have children");const r=this._children.indexOf(e);if(r===-1)throw new g(d.ErrInvalidArgument,"child not found");this.insertAtInternal(t,r),t.updateAncestorsSize()}insertAfter(t,e){if(this.isText)throw new g(d.ErrRefused,"Text node cannot have children");const r=this._children.indexOf(e);if(r===-1)throw new g(d.ErrInvalidArgument,"child not found");this.insertAtInternal(t,r+1),t.updateAncestorsSize()}insertAt(t,e){if(this.isText)throw new g(d.ErrRefused,"Text node cannot have children");this.insertAtInternal(t,e),t.updateAncestorsSize()}removeChild(t){if(this.isText)throw new g(d.ErrRefused,"Text node cannot have children");const e=this._children.indexOf(t);if(e===-1)throw new g(d.ErrInvalidArgument,"child not found");this._children.splice(e,1),t.parent=void 0}splitElement(t,e){const r=this.cloneElement(e);this.parent.insertAfterInternal(r,this),r.updateAncestorsSize();const s=this.children.slice(0,t),i=this.children.slice(t);this._children=s,r._children=i,this.size=this._children.reduce((o,c)=>o+c.paddedSize,0),r.size=r._children.reduce((o,c)=>o+c.paddedSize,0);for(const o of r._children)o.parent=r;return r}insertAfterInternal(t,e){if(this.isText)throw new g(d.ErrRefused,"Text node cannot have children");const r=this._children.indexOf(e);if(r===-1)throw new g(d.ErrInvalidArgument,"child not found");this.insertAtInternal(t,r+1)}insertAtInternal(t,e){if(this.isText)throw new g(d.ErrRefused,"Text node cannot have children");this._children.splice(e,0,t),t.parent=this}findOffset(t){if(this.isText)throw new g(d.ErrRefused,"Text node cannot have children");if(t.isRemoved){const e=this._children.indexOf(t);return this.allChildren.splice(0,e).filter(s=>!s.isRemoved).length}return this.children.indexOf(t)}findBranchOffset(t){if(this.isText)throw new g(d.ErrRefused,"Text node cannot have children");let e=t;for(;e;){const r=this._children.indexOf(e);if(r!==-1)return r;e=e.parent}return-1}}function Kc(n,t){if(n===t)return!1;for(;t.parent;){if(t.parent===n)return!0;t=t.parent}return!1}var j=(n=>(n.Start="Start",n.End="End",n.Text="Text",n))(j||{});function Ro(n,t,e,r){if(t>e)throw new g(d.ErrInvalidArgument,`from is greater than to: ${t} > ${e}`);if(t>n.size)throw new g(d.ErrInvalidArgument,`from is out of range: ${t} > ${n.size}`);if(e>n.size)throw new g(d.ErrInvalidArgument,`to is out of range: ${e} > ${n.size}`);if(t===e)return;let s=0;for(const i of n.children){if(t-i.paddedSizei.size;(i.isText||l)&&r([i,i.isText?"Text":"Start"],h),Ro(i,Math.max(0,o),Math.min(c,i.size),r),h&&r([i,"End"],h)}s+=i.paddedSize}}function Lo(n,t,e=0){for(const r of n.children)Lo(r,t,e+1);t(n,e)}function Wn(n,t,e=0){for(const r of n._children)Wn(r,t,e+1);t(n,e)}function Rs(n,t,e=!0){if(t>n.size)throw new g(d.ErrInvalidArgument,`index is out of range: ${t} > ${n.size}`);if(n.isText)return{node:n,offset:t};let r=0,s=0;for(const i of n.children){if(e&&i.isText&&i.size>=t-s)return Rs(i,t-s,e);if(t===s)return{node:n,offset:r};if(!e&&i.paddedSize===t-s)return{node:n,offset:r+1};if(i.paddedSize>t-s)return Rs(i,t-s-1,e);s+=i.paddedSize,r+=1}return{node:n,offset:r}}function Jo(n){return n.isText||n.children.length===0?n:Jo(n.children[0])}function jc(n,t){if(n.sizen===t?0:n0)if(e.right)e.right.parent=e,e=e.right;else return e;else if(r<0)if(e.left)e.left.parent=e,e=e.left;else{let s=e.parent,i=e;for(;s&&i===s.left;)i=s,s=s.parent;return s}else return e}}lastEntry(){if(!this.root)return this.root;let t=this.root;for(;t.right;)t=t.right;return t}size(){return this.counter}isEmpty(){return this.counter===0}getInternal(t,e){for(;e;){const r=this.comparator(t,e.key);if(r===0)return e;r<0?e=e.left:r>0&&(e=e.right)}}putInternal(t,e,r){if(!r)return this.counter+=1,new Hc(t,e,!0);const s=this.comparator(t,r.key);return s<0?r.left=this.putInternal(t,e,r.left):s>0?r.right=this.putInternal(t,e,r.right):r.value=e,this.isRed(r.right)&&!this.isRed(r.left)&&(r=this.rotateLeft(r)),this.isRed(r.left)&&this.isRed(r.left.left)&&(r=this.rotateRight(r)),this.isRed(r.left)&&this.isRed(r.right)&&this.flipColors(r),r}removeInternal(t,e){if(this.comparator(e,t.key)<0)!this.isRed(t.left)&&!this.isRed(t.left.left)&&(t=this.moveRedLeft(t)),t.left=this.removeInternal(t.left,e);else{if(this.isRed(t.left)&&(t=this.rotateRight(t)),this.comparator(e,t.key)===0&&!t.right){this.counter-=1;return}if(!this.isRed(t.right)&&!this.isRed(t.right.left)&&(t=this.moveRedRight(t)),this.comparator(e,t.key)===0){this.counter-=1;const r=this.min(t.right);t.value=r.value,t.key=r.key,t.right=this.removeMin(t.right)}else t.right=this.removeInternal(t.right,e)}return this.fixUp(t)}min(t){return t.left?this.min(t.left):t}removeMin(t){if(t.left)return!this.isRed(t.left)&&!this.isRed(t.left.left)&&(t=this.moveRedLeft(t)),t.left=this.removeMin(t.left),this.fixUp(t)}fixUp(t){return this.isRed(t.right)&&(t=this.rotateLeft(t)),this.isRed(t.left)&&this.isRed(t.left.left)&&(t=this.rotateRight(t)),this.isRed(t.left)&&this.isRed(t.right)&&this.flipColors(t),t}moveRedLeft(t){return this.flipColors(t),this.isRed(t.right.left)&&(t.right=this.rotateRight(t.right),t=this.rotateLeft(t),this.flipColors(t)),t}moveRedRight(t){return this.flipColors(t),this.isRed(t.left.left)&&(t=this.rotateRight(t),this.flipColors(t)),t}isRed(t){return t&&t.isRed}rotateLeft(t){const e=t.right;return t.right=e.left,e.left=t,e.isRed=e.left.isRed,e.left.isRed=!0,e}rotateRight(t){const e=t.left;return t.left=e.right,e.right=t,e.isRed=e.right.isRed,e.right.isRed=!0,e}flipColors(t){t.isRed=!t.isRed,t.left.isRed=!t.left.isRed,t.right.isRed=!t.right.isRed}}class ke{constructor(t,e){a(this,"parentID");a(this,"leftSiblingID");this.parentID=t,this.leftSiblingID=e}static of(t,e){return new ke(t,e)}static fromTreePos(t){const{offset:e}=t;let{node:r}=t,s;return r.isText?(r.parent.children[0]===r&&e===0?s=r.parent:s=r,r=r.parent):e===0?s=r:s=r.children[e-1],ke.of(r.id,Y.of(s.getCreatedAt(),s.getOffset()+e))}getParentID(){return this.parentID}static fromStruct(t){return ke.of(Y.of(oe.fromStruct(t.parentID.createdAt),t.parentID.offset),Y.of(oe.fromStruct(t.leftSiblingID.createdAt),t.leftSiblingID.offset))}toStruct(){return{parentID:{createdAt:this.getParentID().getCreatedAt().toStruct(),offset:this.getParentID().getOffset()},leftSiblingID:{createdAt:this.getLeftSiblingID().getCreatedAt().toStruct(),offset:this.getLeftSiblingID().getOffset()}}}toTreeNodePair(t){const e=this.getParentID(),r=this.getLeftSiblingID(),s=t.findFloorNode(e);let i=t.findFloorNode(r);if(!s||!i)throw new g(d.ErrRefused,`cannot find node of CRDTTreePos(${e.toTestString()}, ${r.toTestString()})`);return!r.equals(e)&&r.getOffset()>0&&r.getOffset()===i.id.getOffset()&&i.insPrevID&&(i=t.findFloorNode(i.insPrevID)),[s,i]}getLeftSiblingID(){return this.leftSiblingID}equals(t){return this.getParentID().getCreatedAt().equals(t.getParentID().getCreatedAt())&&this.getParentID().getOffset()===t.getParentID().getOffset()&&this.getLeftSiblingID().getCreatedAt().equals(t.getLeftSiblingID().getCreatedAt())&&this.getLeftSiblingID().getOffset()===t.getLeftSiblingID().getOffset()}}class Y{constructor(t,e){a(this,"createdAt");a(this,"offset");this.createdAt=t,this.offset=e}static of(t,e){return new Y(t,e)}static fromStruct(t){return Y.of(oe.fromStruct(t.createdAt),t.offset)}static createComparator(){return(t,e)=>{const r=t.getCreatedAt().compare(e.getCreatedAt());return r!==0?r:t.getOffset()>e.getOffset()?1:t.getOffset(){const i=s.deepcopy();return i.parent=e,i}),e.insPrevID=this.insPrevID,e.insNextID=this.insNextID,e}get value(){if(!this.isText)throw new g(d.ErrInvalidType,`cannot get value of element node: ${this.type}`);return this._value}set value(e){if(!this.isText)throw new g(d.ErrInvalidType,`cannot set value of element node: ${this.type}`);this._value=e,this.size=e.length}get isRemoved(){return!!this.removedAt}remove(e){const r=!this.removedAt;(!this.removedAt||this.removedAt.compare(e)>0)&&(this.removedAt=e),r&&this.updateAncestorsSize()}cloneText(e){return new ie(Y.of(this.id.getCreatedAt(),e),this.type,void 0,void 0,this.removedAt)}cloneElement(e){return new ie(Y.of(e(),0),this.type,void 0,void 0,this.removedAt)}split(e,r,s){const i=this.isText?this.splitText(r,this.id.getOffset()):this.splitElement(r,s);if(i){if(i.insPrevID=this.id,this.insNextID){const o=e.findFloorNode(this.insNextID);o.insPrevID=i.id,i.insNextID=this.insNextID}this.insNextID=i.id,e.registerNode(i)}return i}getCreatedAt(){return this.id.getCreatedAt()}getOffset(){return this.id.getOffset()}canDelete(e,r){return!this.getCreatedAt().after(r)&&(!this.removedAt||e.after(this.removedAt))}canStyle(e,r){return this.isText?!1:!this.getCreatedAt().after(r)&&(!this.removedAt||e.after(this.removedAt))}setAttrs(e,r){this.attrs||(this.attrs=new Zt);const s=new Array;for(const[i,o]of Object.entries(e))s.push(this.attrs.set(i,o,r));return s}purge(e){this.attrs&&this.attrs.purge(e)}getGCPairs(){const e=[];if(!this.attrs)return e;for(const r of this.attrs)r.getRemovedAt()&&e.push({parent:this,child:r});return e}}function Ls(n){var e;if(n.isText){const r=n;return{type:r.type,value:r.value}}const t={type:n.type,children:n.children.map(Ls)};return n.attrs&&(t.attributes=xr((e=n.attrs)==null?void 0:e.toObject())),t}function js(n){if(n.isText)return n.value;let t="";return n.attrs&&n.attrs.size()&&(t=" "+Array.from(n.attrs).filter(e=>!e.isRemoved()).sort((e,r)=>e.getKey().localeCompare(r.getKey())).map(e=>{const r=JSON.parse(e.getValue());return typeof r=="string"?`${e.getKey()}="${r}"`:`${e.getKey()}="${qe(e.getValue())}"`}).join(" ")),`<${n.type}${t}>${n.children.map(e=>js(e)).join("")}`}function Mo(n){if(n.isText){const t=n;return{type:t.type,value:t.value,size:t.size,isRemoved:t.isRemoved}}return{type:n.type,children:n.children.map(Mo),size:n.size,isRemoved:n.isRemoved}}class be extends en{constructor(e,r){super(r);a(this,"indexTree");a(this,"nodeMapByID");this.indexTree=new Gc(e),this.nodeMapByID=new Fo(Y.createComparator()),this.indexTree.traverseAll(s=>{this.nodeMapByID.put(s.id,s)})}static create(e,r){return new be(e,r)}findFloorNode(e){const r=this.nodeMapByID.floorEntry(e);if(!(!r||!r.key.getCreatedAt().equals(e.getCreatedAt())))return r.value}registerNode(e){this.nodeMapByID.put(e.id,e)}findNodesAndSplitText(e,r){const[s,i]=e.toTreeNodePair(this);let o=i;const c=s===o,l=o.parent&&!c?o.parent:s;if(o.isText&&o.split(this,e.getLeftSiblingID().getOffset()-o.id.getOffset()),r){const h=l.allChildren,f=c?0:h.indexOf(o)+1;for(let p=f;p{const k=w.getCreatedAt().getActorID(),E=i?i.has(k)?i.get(k):xe:qr;if(w.canStyle(s,E)&&r){const C=v.get(k),P=w.getCreatedAt();(!C||P.after(C))&&v.set(k,P);const H=w.setAttrs(r,s),D=H.reduce((K,[,_t])=>(_t&&(K[_t.getKey()]=p[_t.getKey()]),K),{}),L=w.parent,F=w.prevSibling||w.parent;Object.keys(D).length>0&&f.push({type:"style",from:this.toIndex(L,F),to:this.toIndex(w,w),fromPath:this.toPath(L,F),toPath:this.toPath(w,w),actor:s.getActorID(),value:D});for(const[K]of H)K&&m.push({parent:w,child:K})}}),[v,m,f]}removeStyle(e,r,s,i){const[o,c]=this.findNodesAndSplitText(e[0],s),[l,h]=this.findNodesAndSplitText(e[1],s),f=[],p=new Map,v=[];return this.traverseInPosRange(o,c,l,h,([m])=>{const w=m.getCreatedAt().getActorID(),k=i?i.has(w)?i.get(w):xe:qr;if(m.canStyle(s,k)&&r){const E=p.get(w),C=m.getCreatedAt();(!E||C.after(E))&&p.set(w,C),m.attrs||(m.attrs=new Zt);for(const D of r){const L=m.attrs.remove(D,s);for(const F of L)v.push({parent:m,child:F})}const P=m.parent,H=m.prevSibling||m.parent;f.push({actor:s.getActorID(),type:"removeStyle",from:this.toIndex(P,H),to:this.toIndex(m,m),fromPath:this.toPath(P,H),toPath:this.toPath(m,m),value:r})}}),[p,v,f]}edit(e,r,s,i,o,c){const[l,h]=this.findNodesAndSplitText(e[0],i),[f,p]=this.findNodesAndSplitText(e[1],i),v=this.toIndex(l,h),m=this.toPath(l,h),w=[],k=[],E=[],C=new Map;this.traverseInPosRange(l,h,f,p,([D,L],F)=>{if(L===j.Start&&!F)for(const lr of D.children)E.push(lr);const K=D.getCreatedAt().getActorID(),_t=c?c.has(K)?c.get(K):xe:qr;if(D.canDelete(i,_t)||w.includes(D.parent)){const lr=C.get(K),on=D.getCreatedAt();(!lr||on.after(lr))&&C.set(K,on),(L===j.Text||L===j.Start)&&w.push(D),k.push([D,L])}});const P=this.makeDeletionChanges(k,i),H=[];for(const D of w)D.remove(i),D.isRemoved&&H.push({parent:this,child:D});for(const D of E)D.removedAt||l.append(D);if(s>0){let D=0,L=l,F=h;for(;D{l.isRemoved&&(K.remove(i),H.push({parent:this,child:K})),this.nodeMapByID.put(K.id,K)}),F.isRemoved||D.push(F);if(D.length){const F=D.map(K=>Ls(K));P.length&&P[P.length-1].from===v?P[P.length-1].value=F:P.push({type:"content",from:v,to:v,fromPath:m,toPath:m,actor:i.getActorID(),value:F})}}return[P,H,C]}editT(e,r,s,i,o){const c=this.findPos(e[0]),l=this.findPos(e[1]);this.edit([c,l],r,s,i,o)}move(e,r,s){throw new g(d.ErrUnimplemented,`not implemented: ${e}, ${r}, ${s}`)}purge(e){var i;(i=e.parent)==null||i.removeChild(e),this.nodeMapByID.remove(e.id);const r=e.insPrevID,s=e.insNextID;if(r){const o=this.findFloorNode(r);o.insNextID=s}if(s){const o=this.findFloorNode(s);o.insPrevID=r}e.insPrevID=void 0,e.insNextID=void 0}getGCPairs(){const e=[];return this.indexTree.traverse(r=>{r.getRemovedAt()&&e.push({parent:this,child:r});for(const s of r.getGCPairs())e.push(s)}),e}findPos(e,r=!0){const s=this.indexTree.findTreePos(e,r);return ke.fromTreePos(s)}pathToPosRange(e){const r=this.pathToIndex(e);return[this.findPos(r),this.findPos(r+1)]}pathToPos(e){const r=this.indexTree.pathToIndex(e);return this.findPos(r)}getRoot(){return this.indexTree.getRoot()}getSize(){return this.indexTree.size}getNodeSize(){return this.nodeMapByID.size()}getIndexTree(){return this.indexTree}toXML(){return js(this.indexTree.getRoot())}toJSON(){return JSON.stringify(this.getRootTreeNode())}toJSForTest(){return{createdAt:this.getCreatedAt().toTestString(),value:JSON.parse(this.toJSON()),type:"YORKIE_TREE"}}toJSInfoForTest(){const e=this.indexTree.getRoot(),r=(s,i=void 0,o=void 0,c=0)=>{var m,w,k,E;let l,h,f;const p=s.isText?{node:s,offset:0}:i&&o?this.toTreePos(i,o):null;p&&(l=this.indexTree.indexOf(p),h=this.indexTree.treePosToPath(p),f=ke.fromTreePos(p).toStruct());const v={type:s.type,parent:i==null?void 0:i.id.toTestString(),size:s.size,id:s.id.toTestString(),removedAt:(m=s.removedAt)==null?void 0:m.toTestString(),insPrev:(w=s.insPrevID)==null?void 0:w.toTestString(),insNext:(k=s.insNextID)==null?void 0:k.toTestString(),value:s.isText?s.value:void 0,isRemoved:s.isRemoved,children:[],depth:c,attributes:s.attrs?xr((E=s.attrs)==null?void 0:E.toObject()):void 0,index:l,path:h,pos:f};for(let C=0;C0&&C===s[s.length-1].to?(s[s.length-1].to=P,s[s.length-1].toPath=this.toPath(E,m)):s.push({type:"content",from:C,to:P,fromPath:this.toPath(k,p),toPath:this.toPath(E,m),actor:r.getActorID()}))}return s.reverse()}findRightToken([e,r]){if(r===j.Start){const l=e.allChildren;return l.length>0?[l[0],l[0].isText?j.Text:j.Start]:[e,j.End]}const s=e.parent,i=s.allChildren,o=i.indexOf(e);if(s&&o===i.length-1)return[s,j.End];const c=i[o+1];return[c,c.isText?j.Text:j.Start]}findLeftToken([e,r]){if(r===j.End){const l=e.allChildren;if(l.length>0){const h=l[l.length-1];return[h,h.isText?j.Text:j.End]}return[e,j.Start]}const s=e.parent,i=s.allChildren,o=i.indexOf(e);if(s&&o===0)return[s,j.Start];const c=i[o-1];return[c,c.isText?j.Text:j.End]}}class sn extends Ne{constructor(e,r,s,i,o,c,l){super(e,l);a(this,"fromPos");a(this,"toPos");a(this,"contents");a(this,"splitLevel");a(this,"maxCreatedAtMapByActor");this.fromPos=r,this.toPos=s,this.contents=i,this.splitLevel=o,this.maxCreatedAtMapByActor=c}static create(e,r,s,i,o,c,l){return new sn(e,r,s,i,o,c,l)}execute(e){var l;const r=e.findByCreatedAt(this.getParentCreatedAt());if(!r)throw new g(d.ErrInvalidArgument,`fail to find ${this.getParentCreatedAt()}`);if(!(r instanceof be))throw new g(d.ErrInvalidArgument,"fail to execute, only Tree can execute edit");const s=this.getExecutedAt(),i=r,[o,c]=i.edit([this.fromPos,this.toPos],(l=this.contents)==null?void 0:l.map(h=>h.deepcopy()),this.splitLevel,s,(()=>{let h=s.getDelimiter();return this.contents!==void 0&&(h+=this.contents.length),()=>oe.of(s.getLamport(),++h,s.getActorID())})(),this.maxCreatedAtMapByActor);for(const h of c)e.registerGCPair(h);return{opInfos:o.map(({from:h,to:f,value:p,splitLevel:v,fromPath:m,toPath:w})=>({type:"tree-edit",path:e.createPath(this.getParentCreatedAt()),from:h,to:f,value:p,splitLevel:v,fromPath:m,toPath:w}))}}getEffectedCreatedAt(){return this.getParentCreatedAt()}toTestString(){const e=this.getParentCreatedAt().toTestString(),r=`${this.fromPos.getLeftSiblingID().getCreatedAt().toTestString()}/${this.fromPos.getLeftSiblingID().getOffset()}`,s=`${this.toPos.getLeftSiblingID().getCreatedAt().toTestString()}/${this.toPos.getLeftSiblingID().getOffset()}`,i=this.contents||[];return`${e}.EDIT(${r},${s},${i.map(o=>js(o)).join("")})`}getFromPos(){return this.fromPos}getToPos(){return this.toPos}getContents(){return this.contents}getSplitLevel(){return this.splitLevel}getMaxCreatedAtMapByActor(){return this.maxCreatedAtMapByActor}}class Er{constructor(t){a(this,"vector");this.vector=t||new Map}set(t,e){this.vector.set(t,e)}get(t){return this.vector.get(t)}maxLamport(){let t=BigInt(0);for(const[,e]of this)e>t&&(t=e);return t}max(t){const e=new Map;for(const[r,s]of t){const i=this.vector.get(r),o=i&&i>s?i:s;e.set(r,o)}for(const[r,s]of this){const i=t.get(r),o=i&&i>s?i:s;e.set(r,o)}return new Er(e)}afterOrEqual(t){const e=this.vector.get(t.getActorID());return e===void 0?!1:e>=t.getLamport()}deepcopy(){const t=new Map;for(const[e,r]of this.vector)t.set(e,r);return new Er(t)}filter(t){const e=new Map;for(const[r]of t){const s=this.vector.get(r);s!==void 0&&e.set(r,s)}return new Er(e)}size(){return this.vector.size}*[Symbol.iterator](){for(const[t,e]of this.vector)yield[t,e]}}const Xc=new Er(new Map);class zt{constructor(t,e,r,s,i){a(this,"clientSeq");a(this,"serverSeq");a(this,"lamport");a(this,"actor");a(this,"versionVector");this.clientSeq=t,this.serverSeq=i,this.lamport=e,this.versionVector=s,this.actor=r}static of(t,e,r,s,i){return new zt(t,e,r,s,i)}next(){const t=this.versionVector.deepcopy();return t.set(this.actor,this.lamport+1n),new zt(this.clientSeq+1,this.lamport+1n,this.actor,t)}syncClocks(t){const e=t.lamport>this.lamport?t.lamport+1n:this.lamport+1n,r=this.versionVector.max(t.versionVector),s=new zt(this.clientSeq,e,this.actor,r);return s.versionVector.set(this.actor,e),s}setClocks(t,e){const r=t>this.lamport?t:this.lamport+1n,s=this.versionVector.max(e);return s.set(this.actor,r),zt.of(this.clientSeq,r,this.actor,s)}createTimeTicket(t){return oe.of(this.lamport,t,this.actor)}setActor(t){return new zt(this.clientSeq,this.lamport,t,this.versionVector,this.serverSeq)}setVersionVector(t){return new zt(this.clientSeq,this.lamport,this.actor,t,this.serverSeq)}getClientSeq(){return this.clientSeq}getServerSeq(){return this.serverSeq?this.serverSeq.toString():""}getLamport(){return this.lamport}getLamportAsString(){return this.lamport.toString()}getActorID(){return this.actor}getVersionVector(){return this.versionVector}toTestString(){return`${this.lamport.toString()}:${this.actor.slice(-2)}:${this.clientSeq}`}}const Zc=new zt(0,0n,Vs,Xc);class Rr{constructor({id:t,operations:e,presenceChange:r,message:s}){a(this,"id");a(this,"operations");a(this,"presenceChange");a(this,"message");this.id=t,this.operations=e||[],this.presenceChange=r,this.message=s}static create({id:t,operations:e,presenceChange:r,message:s}){return new Rr({id:t,operations:e,presenceChange:r,message:s})}getID(){return this.id}getMessage(){return this.message}hasOperations(){return this.operations.length>0}getOperations(){return this.operations}setActor(t){for(const e of this.operations)e.setActor(t);this.id=this.id.setActor(t)}hasPresenceChange(){return this.presenceChange!==void 0}getPresenceChange(){return this.presenceChange}execute(t,e,r){const s=[],i=[];for(const o of this.operations){const c=o.execute(t,r);if(!c)continue;const{opInfos:l,reverseOp:h}=c;s.push(...l),h&&i.unshift(h)}return this.presenceChange&&(this.presenceChange.type===cr.Put?e.set(this.id.getActorID(),Ie(this.presenceChange.presence)):e.delete(this.id.getActorID())),{opInfos:s,reverseOps:i}}toTestString(){return`${this.operations.map(t=>t.toTestString()).join(",")}`}toStruct(){return{changeID:V.bytesToHex(V.toChangeID(this.getID()).toBinary()),message:this.getMessage(),operations:this.getOperations().map(t=>V.bytesToHex(V.toOperation(t).toBinary())),presenceChange:this.getPresenceChange()}}static fromStruct(t){const{changeID:e,operations:r,presenceChange:s,message:i}=t;return Rr.create({id:V.bytesToChangeID(V.hexToBytes(e)),operations:r==null?void 0:r.map(o=>V.bytesToOperation(V.hexToBytes(o))),presenceChange:s,message:i})}}class Hn{constructor(t,e,r,s,i,o,c){a(this,"documentKey");a(this,"checkpoint");a(this,"isRemoved");a(this,"changes");a(this,"snapshot");a(this,"minSyncedTicket");a(this,"versionVector");this.documentKey=t,this.checkpoint=e,this.isRemoved=r,this.changes=s,this.snapshot=o,this.minSyncedTicket=c,this.versionVector=i}static create(t,e,r,s,i,o,c){return new Hn(t,e,r,s,i,o,c)}getDocumentKey(){return this.documentKey}getCheckpoint(){return this.checkpoint}getIsRemoved(){return this.isRemoved}getChanges(){return this.changes}hasChanges(){return this.changes.length>0}getChangeSize(){return this.changes.length}hasSnapshot(){return!!this.snapshot&&!!this.snapshot.length}getSnapshot(){return this.snapshot}getMinSyncedTicket(){return this.minSyncedTicket}getVersionVector(){return this.versionVector}}class Nr{constructor(t,e){a(this,"serverSeq");a(this,"clientSeq");this.serverSeq=t,this.clientSeq=e}static of(t,e){return new Nr(t,e)}increaseClientSeq(t){return t===0?this:new Nr(this.serverSeq,this.clientSeq+t)}forward(t){if(this.equals(t))return this;const e=this.serverSeq>t.serverSeq?this.serverSeq:t.serverSeq,r=Math.max(this.clientSeq,t.clientSeq);return Nr.of(e,r)}getServerSeqAsString(){return this.serverSeq.toString()}getClientSeq(){return this.clientSeq}getServerSeq(){return this.serverSeq}equals(t){return this.clientSeq===t.clientSeq&&this.serverSeq==t.serverSeq}toTestString(){return`serverSeq=${this.serverSeq}, clientSeq=${this.clientSeq}`}}const Qc=new Nr(0n,0);class Ve{constructor(t,e){a(this,"createdAt");a(this,"offset");this.createdAt=t,this.offset=e}static of(t,e){return new Ve(t,e)}static fromStruct(t){return Ve.of(oe.fromStruct(t.createdAt),t.offset)}getCreatedAt(){return this.createdAt}getOffset(){return this.offset}equals(t){return this.createdAt.compare(t.createdAt)===0&&this.offset===t.offset}hasSameCreatedAt(t){return this.createdAt.compare(t.createdAt)===0}split(t){return new Ve(this.createdAt,this.offset+t)}toStruct(){return{createdAt:this.createdAt.toStruct(),offset:this.offset}}toTestString(){return`${this.createdAt.toTestString()}:${this.offset}`}toIDString(){return`${this.createdAt.toIDString()}:${this.offset}`}}const _c=Ve.of(xe,0);class Ee{constructor(t,e){a(this,"id");a(this,"relativeOffset");this.id=t,this.relativeOffset=e}static of(t,e){return new Ee(t,e)}static fromStruct(t){const e=Ve.fromStruct(t.id);return Ee.of(e,t.relativeOffset)}getID(){return this.id}getRelativeOffset(){return this.relativeOffset}getAbsoluteID(){return Ve.of(this.id.getCreatedAt(),this.id.getOffset()+this.relativeOffset)}toTestString(){return`${this.id.toTestString()}:${this.relativeOffset}`}toStruct(){return{id:this.id.toStruct(),relativeOffset:this.relativeOffset}}equals(t){return this.id.equals(t.id)?this.relativeOffset===t.relativeOffset:!1}}class or extends Co{constructor(e,r,s){super(r);a(this,"id");a(this,"removedAt");a(this,"prev");a(this,"next");a(this,"insPrev");a(this,"insNext");this.id=e,this.removedAt=s}static create(e,r){return new or(e,r)}static createComparator(){return(e,r)=>{const s=e.getCreatedAt().compare(r.getCreatedAt());return s!==0?s:e.getOffset()>r.getOffset()?1:e.getOffset()0&&e.getID().getOffset()==t.getOffset()){if(!e.hasInsPrev())return e;e=e.getInsPrev()}return e}findFloorNode(t){const e=this.treeByID.floorEntry(t);if(e&&!(!e.key.equals(t)&&!e.key.hasSameCreatedAt(t)))return e.value}findBetween(t,e){const r=[];let s=t;for(;s&&s!==e;)r.push(s),s=s.getNext();return r}splitNode(t,e){if(e>t.getContentLength())throw new g(d.ErrInvalidArgument,"offset should be less than or equal to length");if(e===0)return t;if(e===t.getContentLength())return t.getNext();const r=t.split(e);this.treeByIndex.updateWeight(r),this.insertAfter(t,r);const s=t.getInsNext();return s&&s.setInsPrev(r),r.setInsPrev(t),r}deleteNodes(t,e,r){if(!t.length)return[[],new Map,new Map];const[s,i]=this.filterNodes(t,e,r),o=new Map,c=new Map,l=this.makeChanges(i,e);for(const h of s){const f=h.getCreatedAt().getActorID();(!o.has(f)||h.getID().getCreatedAt().after(o.get(f)))&&o.set(f,h.getID().getCreatedAt()),c.set(h.getID().toIDString(),h),h.remove(e)}return this.deleteIndexNodes(i),[l,o,c]}filterNodes(t,e,r){const s=!!r,i=[],o=[],[c,l]=this.findEdgesOfCandidates(t);o.push(c);for(const h of t){const f=h.getCreatedAt().getActorID(),p=s?r.has(f)?r.get(f):xe:qr;h.canDelete(e,p)?i.push(h):o.push(h)}return o.push(l),[i,o]}findEdgesOfCandidates(t){return[t[0].getPrev(),t[t.length-1].getNext()]}makeChanges(t,e){const r=[];let s,i;for(let o=0;on<0?Math.ceil(n):Math.floor(n);var ze=(n=>(n[n.IntegerCnt=0]="IntegerCnt",n[n.LongCnt=1]="LongCnt",n))(ze||{});class ce extends en{constructor(e,r,s){super(s);a(this,"valueType");a(this,"value");switch(this.valueType=e,e){case 0:typeof r=="number"?r>Math.pow(2,31)-1||r<-Math.pow(2,31)?this.value=O.fromNumber(r).toInt():this.value=qi(r):this.value=r.toInt();break;case 1:typeof r=="number"?this.value=O.fromNumber(r):this.value=r;break;default:throw new g(d.ErrUnimplemented,`unimplemented type: ${e}`)}}static create(e,r,s){return new ce(e,r,s)}static valueFromBytes(e,r){switch(e){case 0:return r[0]|r[1]<<8|r[2]<<16|r[3]<<24;case 1:return O.fromBytesLE(Array.from(r));default:throw new g(d.ErrUnimplemented,`unimplemented type: ${e}`)}}toJSON(){return`${this.value}`}toSortedJSON(){return this.toJSON()}toJSForTest(){return{createdAt:this.getCreatedAt().toTestString(),value:this.value,type:"YORKIE_COUNTER"}}deepcopy(){const e=ce.create(this.valueType,this.value,this.getCreatedAt());return e.setMovedAt(this.getMovedAt()),e}getType(){return this.valueType}static getCounterType(e){switch(typeof e){case"object":return e instanceof O?1:void 0;case"number":return e>Math.pow(2,31)-1||e<-Math.pow(2,31)?1:0;default:return}}static isSupport(e){return!!ce.getCounterType(e)}static isInteger(e){return e%1===0}isNumericType(){const e=this.valueType;return e===0||e===1}getValueType(){return this.valueType}getValue(){return this.value}toBytes(){switch(this.valueType){case 0:{const e=this.value;return new Uint8Array([e&255,e>>8&255,e>>16&255,e>>24&255])}case 1:{const r=this.value.toBytesLE();return Uint8Array.from(r)}default:throw new g(d.ErrUnimplemented,`unimplemented type: ${this.valueType}`)}}increase(e){function r(s){if(!s.isNumericType())throw new TypeError(`Unsupported type of value: ${typeof s.getValue()}`)}return r(this),r(e),this.valueType===1?this.value=this.value.add(e.getValue()):e.getType()===W.Long?this.value=this.value+e.getValue().toInt():this.value=O.fromNumber(this.value+qi(e.getValue())).toInt(),this}}class Jr extends Ne{constructor(e,r,s){super(e,s);a(this,"value");this.value=r}static create(e,r,s){return new Jr(e,r,s)}execute(e){const r=e.findByCreatedAt(this.getParentCreatedAt());if(!r)throw new g(d.ErrInvalidArgument,`fail to find ${this.getParentCreatedAt()}`);if(!(r instanceof ce))throw new g(d.ErrInvalidArgument,"fail to execute, only Counter can execute increase");const s=r,i=this.value.deepcopy();return s.increase(i),{opInfos:[{type:"increase",path:e.createPath(this.getParentCreatedAt()),value:i.getValue()}],reverseOp:this.toReverseOperation()}}toReverseOperation(){const e=this.value.deepcopy(),s=e.getType()===W.Long?e.getValue().multiply(-1):e.getValue()*-1;return Jr.create(this.getParentCreatedAt(),$.of(s,e.getCreatedAt()))}getEffectedCreatedAt(){return this.getParentCreatedAt()}toTestString(){return`${this.getParentCreatedAt().toTestString()}.INCREASE.${this.value.toJSON()}`}getValue(){return this.value}}class Yt extends Ne{constructor(e,r,s,i,o,c,l){super(e,l);a(this,"fromPos");a(this,"toPos");a(this,"maxCreatedAtMapByActor");a(this,"attributes");a(this,"attributesToRemove");this.fromPos=r,this.toPos=s,this.maxCreatedAtMapByActor=i,this.attributes=o,this.attributesToRemove=c}static create(e,r,s,i,o,c){return new Yt(e,r,s,i,o,new Array,c)}static createTreeRemoveStyleOperation(e,r,s,i,o,c){return new Yt(e,r,s,i,new Map,o,c)}execute(e){const r=e.findByCreatedAt(this.getParentCreatedAt());if(!r)throw new g(d.ErrInvalidArgument,`fail to find ${this.getParentCreatedAt()}`);if(!(r instanceof be))throw new g(d.ErrInvalidArgument,"fail to execute, only Tree can execute edit");const s=r;let i,o;if(this.attributes.size){const c={};[...this.attributes].forEach(([l,h])=>c[l]=h),[,o,i]=s.style([this.fromPos,this.toPos],c,this.getExecutedAt(),this.maxCreatedAtMapByActor)}else{const c=this.attributesToRemove;[,o,i]=s.removeStyle([this.fromPos,this.toPos],c,this.getExecutedAt(),this.maxCreatedAtMapByActor)}for(const c of o)e.registerGCPair(c);return{opInfos:i.map(({from:c,to:l,value:h,fromPath:f,toPath:p})=>({type:"tree-style",from:c,to:l,value:this.attributes.size?{attributes:h}:{attributesToRemove:h},fromPath:f,toPath:p,path:e.createPath(this.getParentCreatedAt())}))}}getEffectedCreatedAt(){return this.getParentCreatedAt()}toTestString(){const e=this.getParentCreatedAt().toTestString(),r=`${this.fromPos.getLeftSiblingID().getCreatedAt().toTestString()}:${this.fromPos.getLeftSiblingID().getOffset()}`,s=`${this.toPos.getLeftSiblingID().getCreatedAt().toTestString()}:${this.toPos.getLeftSiblingID().getOffset()}`;return`${e}.STYLE(${r},${s},${Object.entries(this.attributes||{}).map(([i,o])=>`${i}:"${o}"`).join(" ")})`}getFromPos(){return this.fromPos}getToPos(){return this.toPos}getAttributes(){return this.attributes}getAttributesToRemove(){return this.attributesToRemove}getMaxCreatedAtMapByActor(){return this.maxCreatedAtMapByActor}}function eu(n){const t=new qs,e=t.data;for(const[r,s]of Object.entries(n))e[r]=JSON.stringify(s);return t}function tu(n){if(n.type===cr.Put)return new Wr({type:vr.PUT,presence:eu(n.presence)});if(n.type===cr.Clear)return new Wr({type:vr.CLEAR});throw new g(d.ErrUnimplemented,"unimplemented type")}function ru(n){return new xo({serverSeq:n.getServerSeq(),clientSeq:n.getClientSeq()})}function $o(n){return new jn({clientSeq:n.getClientSeq(),lamport:n.getLamport(),actorId:ri(n.getActorID()),versionVector:Gs(n.getVersionVector())})}function I(n){if(n)return new b({lamport:n.getLamport(),delimiter:n.getDelimiter(),actorId:ri(n.getActorID())})}function Gs(n){if(!n)return;const t=new Gn;for(const[e,r]of n)t.vector[e]=BigInt(r.toString());return t}function Uo(n){switch(n){case W.Null:return N.NULL;case W.Boolean:return N.BOOLEAN;case W.Integer:return N.INTEGER;case W.Long:return N.LONG;case W.Double:return N.DOUBLE;case W.String:return N.STRING;case W.Bytes:return N.BYTES;case W.Date:return N.DATE;default:throw new g(d.ErrInvalidType,`unsupported type: ${n}`)}}function qo(n){switch(n){case ze.IntegerCnt:return N.INTEGER_CNT;case ze.LongCnt:return N.LONG_CNT;default:throw new g(d.ErrInvalidType,`unsupported type: ${n}`)}}function ns(n){if(n instanceof re)return new ue({type:N.JSON_OBJECT,createdAt:I(n.getCreatedAt()),value:ea(n)});if(n instanceof ae)return new ue({type:N.JSON_ARRAY,createdAt:I(n.getCreatedAt()),value:Bu(n)});if(n instanceof Ae)return new ue({type:N.TEXT,createdAt:I(n.getCreatedAt())});if(n instanceof $)return new ue({type:Uo(n.getType()),createdAt:I(n.getCreatedAt()),value:n.toBytes()});if(n instanceof ce)return new ue({type:qo(n.getType()),createdAt:I(n.getCreatedAt()),value:n.toBytes()});if(n instanceof be)return new ue({type:N.TREE,createdAt:I(n.getCreatedAt()),value:Lu(n)});throw new g(d.ErrUnimplemented,"unimplemented element")}function nu(n){return new jr({createdAt:I(n.getCreatedAt()),offset:n.getOffset()})}function cn(n){return new Xt({createdAt:I(n.getID().getCreatedAt()),offset:n.getID().getOffset(),relativeOffset:n.getRelativeOffset()})}function un(n){return new yr({parentId:Vr(n.getParentID()),leftSiblingId:Vr(n.getLeftSiblingID())})}function Vr(n){return new sr({createdAt:I(n.getCreatedAt()),offset:n.getOffset()})}function Vo(n){const t=new Us;if(n instanceof wr){const e=n,r=new bn;r.parentCreatedAt=I(e.getParentCreatedAt()),r.key=e.getKey(),r.value=ns(e.getValue()),r.executedAt=I(e.getExecutedAt()),t.body.case="set",t.body.value=r}else if(n instanceof tn){const e=n,r=new In;r.parentCreatedAt=I(e.getParentCreatedAt()),r.prevCreatedAt=I(e.getPrevCreatedAt()),r.value=ns(e.getValue()),r.executedAt=I(e.getExecutedAt()),t.body.case="add",t.body.value=r}else if(n instanceof nr){const e=n,r=new Sn;r.parentCreatedAt=I(e.getParentCreatedAt()),r.prevCreatedAt=I(e.getPrevCreatedAt()),r.createdAt=I(e.getCreatedAt()),r.executedAt=I(e.getExecutedAt()),t.body.case="move",t.body.value=r}else if(n instanceof ur){const e=n,r=new kn;r.parentCreatedAt=I(e.getParentCreatedAt()),r.createdAt=I(e.getCreatedAt()),r.executedAt=I(e.getExecutedAt()),t.body.case="remove",t.body.value=r}else if(n instanceof rn){const e=n,r=new xn;r.parentCreatedAt=I(e.getParentCreatedAt()),r.from=cn(e.getFromPos()),r.to=cn(e.getToPos());const s=r.createdAtMapByActor;for(const[o,c]of e.getMaxCreatedAtMapByActor())s[o]=I(c);r.content=e.getContent();const i=r.attributes;for(const[o,c]of e.getAttributes())i[o]=c;r.executedAt=I(e.getExecutedAt()),t.body.case="edit",t.body.value=r}else if(n instanceof nn){const e=n,r=new En;r.parentCreatedAt=I(e.getParentCreatedAt()),r.from=cn(e.getFromPos()),r.to=cn(e.getToPos());const s=r.createdAtMapByActor;for(const[o,c]of e.getMaxCreatedAtMapByActor())s[o]=I(c);const i=r.attributes;for(const[o,c]of e.getAttributes())i[o]=c;r.executedAt=I(e.getExecutedAt()),t.body.case="style",t.body.value=r}else if(n instanceof Jr){const e=n,r=new Nn;r.parentCreatedAt=I(e.getParentCreatedAt()),r.value=ns(e.getValue()),r.executedAt=I(e.getExecutedAt()),t.body.case="increase",t.body.value=r}else if(n instanceof sn){const e=n,r=new Cn,s=r.createdAtMapByActor;for(const[i,o]of e.getMaxCreatedAtMapByActor())s[i]=I(o);r.parentCreatedAt=I(e.getParentCreatedAt()),r.from=un(e.getFromPos()),r.to=un(e.getToPos()),r.contents=lu(e.getContents()),r.splitLevel=e.getSplitLevel(),r.executedAt=I(e.getExecutedAt()),t.body.case="treeEdit",t.body.value=r}else if(n instanceof Yt){const e=n,r=new Pn;r.parentCreatedAt=I(e.getParentCreatedAt()),r.from=un(e.getFromPos()),r.to=un(e.getToPos());const s=r.createdAtMapByActor;for(const[o,c]of e.getMaxCreatedAtMapByActor())s[o]=I(c);const i=e.getAttributesToRemove();if(i.length>0)r.attributesToRemove=i;else{const o=r.attributes;for(const[c,l]of e.getAttributes())o[c]=l}r.executedAt=I(e.getExecutedAt()),t.body.case="treeStyle",t.body.value=r}else throw new g(d.ErrUnimplemented,"unimplemented operation");return t}function su(n){const t=[];for(const e of n)t.push(Vo(e));return t}function iu(n){const t=new So({id:$o(n.getID()),message:n.getMessage()});return n.hasOperations()&&(t.operations=su(n.getOperations())),n.hasPresenceChange()&&(t.presenceChange=tu(n.getPresenceChange())),t}function ou(n){const t=[];for(const e of n)t.push(iu(e));return t}function au(n){const t=[];for(const e of n)t.push(new ko({key:e.getStrKey(),element:Hs(e.getValue())}));return t}function cu(n){const t=[];for(const e of n)t.push(new Fn({element:Hs(e.getValue())}));return t}function uu(n){const t=[];for(const e of n){const r=new Mn;r.id=nu(e.getID()),r.value=e.getValue().getContent(),r.removedAt=I(e.getRemovedAt());const s=r.attributes,i=e.getValue().getAttrs();for(const o of i){const c=new Dr;c.value=o.getValue(),c.updatedAt=I(o.getUpdatedAt()),s[o.getKey()]=c}t.push(r)}return t}function lu(n){const t=[];if(!n||!n.length)return t;for(const e of n)t.push(new $n({content:Ws(e)}));return t}function hu(n){const t={};for(const e of n)t[e.getKey()]=new Dr({value:e.getValue(),updatedAt:I(e.getUpdatedAt()),isRemoved:e.isRemoved()});return t}function Ws(n){if(!n)return[];const t=[];return Wn(n,(e,r)=>{const s=new Gr({id:Vr(e.id),type:e.type,removedAt:I(e.removedAt),depth:r});e.isText&&(s.value=e.value),e.insPrevID&&(s.insPrevId=Vr(e.insPrevID)),e.insNextID&&(s.insNextId=Vr(e.insNextID)),e.attrs&&(s.attributes=hu(e.attrs)),t.push(s)}),t}function fu(n){const t=new ne;return t.body.case="jsonObject",t.body.value=new Dn({nodes:au(n.getRHT()),createdAt:I(n.getCreatedAt()),movedAt:I(n.getMovedAt()),removedAt:I(n.getRemovedAt())}),t}function zo(n){const t=new ne;return t.body.case="jsonArray",t.body.value=new On({nodes:cu(n.getElements()),createdAt:I(n.getCreatedAt()),movedAt:I(n.getMovedAt()),removedAt:I(n.getRemovedAt())}),t}function du(n){const t=new ne;return t.body.case="primitive",t.body.value=new Bn({type:Uo(n.getType()),value:n.toBytes(),createdAt:I(n.getCreatedAt()),movedAt:I(n.getMovedAt()),removedAt:I(n.getRemovedAt())}),t}function gu(n){const t=new ne;return t.body.case="text",t.body.value=new Rn({nodes:uu(n.getRGATreeSplit()),createdAt:I(n.getCreatedAt()),movedAt:I(n.getMovedAt()),removedAt:I(n.getRemovedAt())}),t}function mu(n){const t=new ne;return t.body.case="counter",t.body.value=new Ln({type:qo(n.getType()),value:n.toBytes(),createdAt:I(n.getCreatedAt()),movedAt:I(n.getMovedAt()),removedAt:I(n.getRemovedAt())}),t}function Ko(n){const t=new ne;return t.body.case="tree",t.body.value=new Jn({nodes:Ws(n.getRoot()),createdAt:I(n.getCreatedAt()),movedAt:I(n.getMovedAt()),removedAt:I(n.getRemovedAt())}),t}function Hs(n){if(n instanceof re)return fu(n);if(n instanceof ae)return zo(n);if(n instanceof $)return du(n);if(n instanceof Ae)return gu(n);if(n instanceof ce)return mu(n);if(n instanceof be)return Ko(n);throw new g(d.ErrUnimplemented,"unimplemented element")}function pu(n){return new Qt({documentKey:n.getDocumentKey(),checkpoint:ru(n.getCheckpoint()),isRemoved:n.getIsRemoved(),changes:ou(n.getChanges()),snapshot:n.getSnapshot(),versionVector:Gs(n.getVersionVector()),minSyncedTicket:I(n.getMinSyncedTicket())})}function Vi(n){const t=n.findDetails(Oc);for(const e of t)if(e.metadata.code)return e.metadata.code;return""}function jo(n){return zt.of(n.clientSeq,BigInt(n.lamport),ei(n.actorId),Ys(n.versionVector),BigInt(n.serverSeq))}function Ys(n){if(!n)return;const t=new Er;return Object.entries(n.vector).forEach(([e,r])=>{t.set(e,BigInt(r.toString()))}),t}function S(n){if(n)return oe.of(BigInt(n.lamport),n.delimiter,ei(n.actorId))}function Xs(n){const t={};return Object.entries(n.data).forEach(([e,r])=>{t[e]=JSON.parse(r)}),t}function yu(n){const t=n.type;if(t===vr.PUT){const e=Xs(n.presence);return{type:cr.Put,presence:e}}if(t===vr.CLEAR)return{type:cr.Clear};throw new g(d.ErrInvalidType,`unsupported type: ${t}`)}function vu(n){const t=new Map;return Object.entries(n).forEach(([e,r])=>{t.set(e,Xs(r))}),t}function Go(n){switch(n){case N.NULL:return W.Null;case N.BOOLEAN:return W.Boolean;case N.INTEGER:return W.Integer;case N.LONG:return W.Long;case N.DOUBLE:return W.Double;case N.STRING:return W.String;case N.BYTES:return W.Bytes;case N.DATE:return W.Date}throw new g(d.ErrUnimplemented,`unimplemented value type: ${n}`)}function Vn(n){switch(n){case N.INTEGER_CNT:return ze.IntegerCnt;case N.LONG_CNT:return ze.LongCnt}throw new g(d.ErrUnimplemented,`unimplemented value type: ${n}`)}function ss(n){switch(n.type){case N.JSON_OBJECT:return n.value?_o(n.value):re.create(S(n.createdAt));case N.JSON_ARRAY:return n.value?Ou(n.value):ae.create(S(n.createdAt));case N.TEXT:return Ae.create(Lr.create(),S(n.createdAt));case N.TREE:return Ru(n.value);case N.NULL:case N.BOOLEAN:case N.INTEGER:case N.LONG:case N.DOUBLE:case N.STRING:case N.BYTES:case N.DATE:return $.of($.valueFromBytes(Go(n.type),n.value),S(n.createdAt));case N.INTEGER_CNT:case N.LONG_CNT:return ce.create(Vn(n.type),ce.valueFromBytes(Vn(n.type),n.value),S(n.createdAt))}}function ln(n){return Ee.of(Ve.of(S(n.createdAt),n.offset),n.relativeOffset)}function Wo(n){return Ve.of(S(n.createdAt),n.offset)}function wu(n){const t=Zr.create(n.value);Object.entries(n.attributes).forEach(([r,s])=>{t.setAttr(r,s.value,S(s.updatedAt))});const e=or.create(Wo(n.id),t);return e.remove(S(n.removedAt)),e}function br(n){return ke.of(zr(n.parentId),zr(n.leftSiblingId))}function zr(n){return Y.of(S(n.createdAt),n.offset)}function Tu(n){if(!n.length)return;const t=[];return n.forEach(e=>{const r=Zs(e.content);t.push(r)}),t}function Zs(n){if(n.length===0)return;const t=[];for(const s of n)t.push(bu(s));const e=t[t.length-1],r=new Map;r.set(n[t.length-1].depth,t[t.length-1]);for(let s=t.length-2;s>=0;s--)r.get(n[s].depth-1).prepend(t[s]),r.set(n[s].depth,t[s]);return e.updateDescendantsSize(),be.create(e,xe).getRoot()}function Au(n){const t=Zt.create();for(const[e,r]of Object.entries(n))t.setInternal(e,r.value,S(r.updatedAt),r.isRemoved);return t}function bu(n){const t=zr(n.id),e=ie.create(t,n.type),r=Object.entries(n.attributes);return e.isText?e.value=n.value:r.length&&(e.attrs=Au(n.attributes)),n.insPrevId&&(e.insPrevID=zr(n.insPrevId)),n.insNextId&&(e.insNextID=zr(n.insNextId)),e.removedAt=S(n.removedAt),e}function Ho(n){if(n.body.case==="set"){const t=n.body.value;return wr.create(t.key,ss(t.value),S(t.parentCreatedAt),S(t.executedAt))}else if(n.body.case==="add"){const t=n.body.value;return tn.create(S(t.parentCreatedAt),S(t.prevCreatedAt),ss(t.value),S(t.executedAt))}else if(n.body.case==="move"){const t=n.body.value;return nr.create(S(t.parentCreatedAt),S(t.prevCreatedAt),S(t.createdAt),S(t.executedAt))}else if(n.body.case==="remove"){const t=n.body.value;return ur.create(S(t.parentCreatedAt),S(t.createdAt),S(t.executedAt))}else if(n.body.case==="edit"){const t=n.body.value,e=new Map;Object.entries(t.createdAtMapByActor).forEach(([s,i])=>{e.set(s,S(i))});const r=new Map;return Object.entries(t.attributes).forEach(([s,i])=>{r.set(s,i)}),rn.create(S(t.parentCreatedAt),ln(t.from),ln(t.to),e,t.content,r,S(t.executedAt))}else if(n.body.case==="style"){const t=n.body.value,e=new Map;Object.entries(t.createdAtMapByActor).forEach(([s,i])=>{e.set(s,S(i))});const r=new Map;return Object.entries(t.attributes).forEach(([s,i])=>{r.set(s,i)}),nn.create(S(t.parentCreatedAt),ln(t.from),ln(t.to),e,r,S(t.executedAt))}else{if(n.body.case==="select")return;if(n.body.case==="increase"){const t=n.body.value;return Jr.create(S(t.parentCreatedAt),ss(t.value),S(t.executedAt))}else if(n.body.case==="treeEdit"){const t=n.body.value,e=new Map;return Object.entries(t.createdAtMapByActor).forEach(([r,s])=>{e.set(r,S(s))}),sn.create(S(t.parentCreatedAt),br(t.from),br(t.to),Tu(t.contents),t.splitLevel,e,S(t.executedAt))}else if(n.body.case==="treeStyle"){const t=n.body.value,e=new Map,r=t.attributesToRemove,s=new Map;return t!=null&&t.createdAtMapByActor&&Object.entries(t.createdAtMapByActor).forEach(([i,o])=>{s.set(i,S(o))}),(r==null?void 0:r.length)>0?Yt.createTreeRemoveStyleOperation(S(t.parentCreatedAt),br(t.from),br(t.to),s,r,S(t.executedAt)):(Object.entries(t.attributes).forEach(([i,o])=>{e.set(i,o)}),Yt.create(S(t.parentCreatedAt),br(t.from),br(t.to),s,e,S(t.executedAt)))}else throw new g(d.ErrUnimplemented,"unimplemented operation")}}function Iu(n){const t=[];for(const e of n){const r=Ho(e);r&&t.push(r)}return t}function Yo(n){const t=[];for(const e of n)t.push(Rr.create({id:jo(e.id),operations:Iu(e.operations),presenceChange:e.presenceChange?yu(e.presenceChange):void 0,message:e.message}));return t}function Su(n){return Nr.of(BigInt(n.serverSeq),n.clientSeq)}function ku(n){return Hn.create(n.documentKey,Su(n.checkpoint),n.isRemoved,Yo(n.changes),Ys(n.versionVector),n.snapshot,S(n.minSyncedTicket))}function Xo(n){const t=new Hr;for(const r of n.nodes){const s=Qs(r.element);t.set(r.key,s,s.getPositionedAt())}const e=new re(S(n.createdAt),t);return e.setMovedAt(S(n.movedAt)),e.setRemovedAt(S(n.removedAt)),e}function Zo(n){const t=new Xr;for(const r of n.nodes)t.insert(Qs(r.element));const e=new ae(S(n.createdAt),t);return e.setMovedAt(S(n.movedAt)),e.setRemovedAt(S(n.removedAt)),e}function xu(n){const t=$.of($.valueFromBytes(Go(n.type),n.value),S(n.createdAt));return t.setMovedAt(S(n.movedAt)),t.setRemovedAt(S(n.removedAt)),t}function Eu(n){const t=new Lr;let e=t.getHead();for(const s of n.nodes){const i=t.insertAfter(e,wu(s));s.insPrevId&&i.setInsPrev(t.findNode(Wo(s.insPrevId))),e=i}const r=new Ae(t,S(n.createdAt));return r.setMovedAt(S(n.movedAt)),r.setRemovedAt(S(n.removedAt)),r}function Nu(n){const t=ce.create(Vn(n.type),ce.valueFromBytes(Vn(n.type),n.value),S(n.createdAt));return t.setMovedAt(S(n.movedAt)),t.setRemovedAt(S(n.removedAt)),t}function Qo(n){const t=Zs(n.nodes);return be.create(t,S(n.createdAt))}function Qs(n){if(n.body.case==="jsonObject")return Xo(n.body.value);if(n.body.case==="jsonArray")return Zo(n.body.value);if(n.body.case==="primitive")return xu(n.body.value);if(n.body.case==="text")return Eu(n.body.value);if(n.body.case==="counter")return Nu(n.body.value);if(n.body.case==="tree")return Qo(n.body.value);throw new g(d.ErrUnimplemented,"unimplemented element")}function Cu(n){if(!n)return{root:re.create(xe),presences:new Map};const t=ls.fromBinary(n);return{root:Qs(t.root),presences:vu(t.presences)}}function Pu(n){const t=Gs(n);return _s(t.toBinary())}function Du(n){const t=ti(n),e=Gn.fromBinary(t);return Ys(e)}function _o(n){if(!n)throw new g(d.ErrInvalidArgument,"bytes is empty");const t=ne.fromBinary(n);return Xo(t.body.value)}function ea(n){return Hs(n).toBinary()}function Ou(n){if(!n)throw new g(d.ErrInvalidArgument,"bytes is empty");const t=ne.fromBinary(n);return Zo(t.body.value)}function Bu(n){return zo(n).toBinary()}function Ru(n){if(!n)throw new g(d.ErrInvalidArgument,"bytes is empty");const t=ne.fromBinary(n);return Qo(t.body.value)}function Lu(n){return Ko(n).toBinary()}function _s(n){return n?Array.from(n).map(t=>t.toString(16).padStart(2,"0")).join(""):""}function ei(n){return _s(n)}function ti(n){return new Uint8Array(n.match(/.{1,2}/g).map(t=>parseInt(t,16)))}function ri(n){return ti(n)}function Ju(n){const t=jn.fromBinary(n);return jo(t)}function Fu(n){const t=Us.fromBinary(n);return Ho(t)}const V={fromPresence:Xs,toChangePack:pu,fromChangePack:ku,fromChanges:Yo,toTreeNodes:Ws,fromTreeNodes:Zs,objectToBytes:ea,bytesToObject:_o,bytesToSnapshot:Cu,bytesToHex:_s,hexToBytes:ti,toHexString:ei,toUint8Array:ri,toOperation:Vo,toChangeID:$o,PbChangeID:jn,bytesToChangeID:Ju,bytesToOperation:Fu,versionVectorToHex:Pu,hexToVersionVector:Du};var ee=(n=>(n[n.Trivial=0]="Trivial",n[n.Debug=1]="Debug",n[n.Info=2]="Info",n[n.Warn=3]="Warn",n[n.Error=4]="Error",n[n.Fatal=5]="Fatal",n))(ee||{});let hr=3;function ta(n){hr=n}const x={trivial:(...n)=>{hr>0||typeof console<"u"&&console.log("YORKIE T:",...n)},debug:(...n)=>{hr>1||typeof console<"u"&&console.log("YORKIE D:",...n)},info:(...n)=>{hr>2||typeof console<"u"&&console.log("YORKIE I:",...n)},warn:(...n)=>{hr>3||typeof console<"u"&&(typeof console.warn<"u"?console.warn("YORKIE W:",...n):console.log("YORKIE W:",...n))},error:(...n)=>{hr>4||typeof console<"u"&&(typeof console.error<"u"?console.error("YORKIE E:",...n):console.log("YORKIE E:",...n))},fatal:(...n)=>{typeof console<"u"&&(typeof console.error<"u"?console.error("YORKIE F:",...n):console.log("YORKIE F:",...n))},isEnabled:n=>hr<=n};function ra(){return"xxxxxxxx-xxxx-4xxxy-xxxx-xxxxxxxxxxx".replace(/[xy]/g,n=>{const t=Math.random()*16|0;return(n==="x"?t:t&3|8).toString(16)})}class Mu{constructor(t,e,r,s,i){a(this,"reconnectStreamDelay");a(this,"doc");a(this,"docID");a(this,"syncMode");a(this,"remoteChangeEventReceived");a(this,"watchStream");a(this,"watchLoopTimerID");a(this,"watchAbortController");a(this,"unsubscribeBroadcastEvent");this.reconnectStreamDelay=t,this.doc=e,this.docID=r,this.syncMode=s,this.remoteChangeEventReceived=!1,this.unsubscribeBroadcastEvent=i}changeSyncMode(t){this.syncMode=t}needRealtimeSync(){return this.syncMode===wn.RealtimeSyncOff?!1:this.syncMode===wn.RealtimePushOnly?this.doc.hasLocalChanges():this.syncMode!==wn.Manual&&(this.doc.hasLocalChanges()||this.remoteChangeEventReceived)}async runWatchLoop(t){const e=async()=>{if(this.watchStream)return Promise.resolve();this.watchLoopTimerID&&(clearTimeout(this.watchLoopTimerID),this.watchLoopTimerID=void 0);try{[this.watchStream,this.watchAbortController]=await t(()=>{this.watchStream=void 0,this.watchAbortController=void 0,this.watchLoopTimerID=setTimeout(e,this.reconnectStreamDelay)})}catch{}};await e()}cancelWatchStream(){this.watchStream&&this.watchAbortController&&(this.watchAbortController.abort(),this.watchStream=void 0,this.watchAbortController=void 0),clearTimeout(this.watchLoopTimerID),this.watchLoopTimerID=void 0}}const is=()=>{};class $u{constructor(t){a(this,"finalized",!1);a(this,"observers",[]);a(this,"finalError");try{t(this)}catch(e){this.error(e)}}next(t){this.forEachObserver(e=>{e.next(t)})}error(t){this.forEachObserver(e=>{e.error(t)}),this.close(t)}complete(){this.forEachObserver(t=>{t.complete()}),this.close()}subscribe(t,e,r){let s;if(!t)throw new g(d.ErrInvalidArgument,"missing observer");if(this.finalized)throw new g(d.ErrRefused,"observable is finalized due to previous error");typeof t=="object"?s=t:s={next:t,error:e,complete:r},s.next===void 0&&(s.next=is),s.error===void 0&&(s.error=is),s.complete===void 0&&(s.complete=is);const i=ra(),o=this.unsubscribeOne.bind(this,i);if(this.observers.push({subscriptionID:i,observer:s}),this.finalized)try{this.finalError?s.error(this.finalError):s.complete()}catch(c){x.warn(c)}return o}unsubscribeOne(t){var e;this.observers=(e=this.observers)==null?void 0:e.filter(r=>r.subscriptionID!==t)}forEachObserver(t){if(!this.finalized)for(let e=0;et}}class kr{constructor(t,e,r,s){a(this,"id");a(this,"delimiter");a(this,"message");a(this,"root");a(this,"operations");a(this,"presenceChange");a(this,"previousPresence");a(this,"reversePresenceKeys");this.id=t,this.delimiter=No,this.root=e,this.operations=[],this.previousPresence=Ie(r),this.presenceChange=void 0,this.reversePresenceKeys=new Set,this.message=s}static create(t,e,r,s){return new kr(t,e,r,s)}push(t){this.operations.push(t)}registerElement(t,e){this.root.registerElement(t,e)}registerRemovedElement(t){this.root.registerRemovedElement(t)}registerGCPair(t){this.root.registerGCPair(t)}getChange(){return Rr.create({id:this.id,operations:this.operations,presenceChange:this.presenceChange,message:this.message})}hasChange(){return this.operations.length>0||this.presenceChange!==void 0}setPresenceChange(t){this.presenceChange=t}setReversePresence(t,e){for(const r of Object.keys(t))e!=null&&e.addToHistory?this.reversePresenceKeys.add(r):this.reversePresenceKeys.delete(r)}getReversePresence(){if(this.reversePresenceKeys.size===0)return;const t={};for(const e of this.reversePresenceKeys)t[e]=this.previousPresence[e];return t}issueTimeTicket(){return this.delimiter+=1,this.id.createTimeTicket(this.delimiter)}getLastTimeTicket(){return this.id.createTimeTicket(this.delimiter)}}class Qr{constructor(t){a(this,"rootObject");a(this,"elementPairMapByCreatedAt");a(this,"gcElementSetByCreatedAt");a(this,"gcPairMap");this.rootObject=t,this.elementPairMapByCreatedAt=new Map,this.gcElementSetByCreatedAt=new Set,this.gcPairMap=new Map,this.registerElement(t,void 0),t.getDescendants(e=>{if(e.getRemovedAt()&&this.registerRemovedElement(e),e instanceof Ae||e instanceof be)for(const r of e.getGCPairs())this.registerGCPair(r);return!1})}static create(){return new Qr(re.create(xe))}findByCreatedAt(t){const e=this.elementPairMapByCreatedAt.get(t.toIDString());if(e)return e.element}findElementPairByCreatedAt(t){return this.elementPairMapByCreatedAt.get(t.toIDString())}createSubPaths(t){let e=this.elementPairMapByCreatedAt.get(t.toIDString());if(!e)return[];const r=[];for(;e.parent;){const s=e.element.getCreatedAt(),i=e.parent.subPathOf(s);if(i===void 0)throw new g(d.ErrInvalidArgument,`cant find the given element: ${s.toIDString()}`);r.unshift(i),e=this.elementPairMapByCreatedAt.get(e.parent.getCreatedAt().toIDString())}return r.unshift("$"),r}createPath(t){return this.createSubPaths(t).join(".")}registerElement(t,e){this.elementPairMapByCreatedAt.set(t.getCreatedAt().toIDString(),{parent:e,element:t}),t instanceof ir&&t.getDescendants((r,s)=>(this.registerElement(r,s),!1))}deregisterElement(t){let e=0;const r=s=>{const i=s.getCreatedAt().toIDString();this.elementPairMapByCreatedAt.delete(i),this.gcElementSetByCreatedAt.delete(i),e++};return r(t),t instanceof ir&&t.getDescendants(s=>(r(s),!1)),e}registerRemovedElement(t){this.gcElementSetByCreatedAt.add(t.getCreatedAt().toIDString())}registerGCPair(t){if(this.gcPairMap.get(t.child.toIDString())){this.gcPairMap.delete(t.child.toIDString());return}this.gcPairMap.set(t.child.toIDString(),t)}getElementMapSize(){return this.elementPairMapByCreatedAt.size}getGarbageElementSetSize(){const t=new Set;for(const e of this.gcElementSetByCreatedAt){t.add(e);const r=this.elementPairMapByCreatedAt.get(e);r.element instanceof ir&&r.element.getDescendants(s=>(t.add(s.getCreatedAt().toIDString()),!1))}return t.size}getObject(){return this.rootObject}getGarbageLen(){return this.getGarbageElementSetSize()+this.gcPairMap.size}deepcopy(){return new Qr(this.rootObject.deepcopy())}garbageCollect(t){let e=0;for(const r of this.gcElementSetByCreatedAt){const s=this.elementPairMapByCreatedAt.get(r),i=s.element.getRemovedAt();i&&(t!=null&&t.afterOrEqual(i))&&(s.parent.purge(s.element),e+=this.deregisterElement(s.element))}for(const[,r]of this.gcPairMap){const s=r.child.getRemovedAt();s&&(t!=null&&t.afterOrEqual(s))&&(r.parent.purge(r.child),this.gcPairMap.delete(r.child.toIDString()),e+=1)}return e}toJSON(){return this.rootObject.toJSON()}toSortedJSON(){return this.rootObject.toSortedJSON()}getStats(){return{elements:this.getElementMapSize(),gcPairs:this.gcPairMap.size,gcElements:this.getGarbageElementSetSize()}}}function na(n,t){const e=new _r(n);return new Proxy(t,e.getHandlers())}class _r{constructor(t){a(this,"context");a(this,"handlers");this.context=t,this.handlers={set:(e,r,s)=>(x.isEnabled(ee.Trivial)&&x.trivial(`obj[${r}]=${JSON.stringify(s)}`),_r.setInternal(t,e,r,s),!0),get:(e,r)=>(x.isEnabled(ee.Trivial)&&x.trivial(`obj[${r}]`),r==="getID"?()=>e.getCreatedAt():r==="toJSON"||r==="toString"?()=>e.toJSON():r==="toJS"?()=>e.toJS():r==="toJSForTest"?()=>e.toJSForTest():fr(t,e.get(r))),ownKeys:e=>e.getKeys(),getOwnPropertyDescriptor:()=>({enumerable:!0,configurable:!0}),deleteProperty:(e,r)=>(x.isEnabled(ee.Trivial)&&x.trivial(`obj[${r}]`),_r.deleteInternal(t,e,r),!0)}}static setInternal(t,e,r,s){if(r.includes("."))throw new g(d.ErrInvalidObjectKey,"key must not contain the '.'.");const i=t.issueTimeTicket(),o=zn(t,s,i),c=e.set(r,o,i);t.registerElement(o,e),c&&t.registerRemovedElement(c),t.push(wr.create(r,o.deepcopy(),e.getCreatedAt(),i))}static buildObjectMembers(t,e){const r={};for(const[s,i]of Object.entries(e)){if(s.includes("."))throw new g(d.ErrInvalidObjectKey,"key must not contain the '.'.");const o=t.issueTimeTicket(),c=zn(t,i,o);r[s]=c}return r}static deleteInternal(t,e,r){const s=t.issueTimeTicket(),i=e.deleteByKey(r,s);i&&(t.push(ur.create(e.getCreatedAt(),i.getCreatedAt(),s)),t.registerRemovedElement(i))}getHandlers(){return this.handlers}}function qu(n,t){const e=new U(n,t);return new Proxy(t,e.getHandlers())}function Vu(n){return typeof n=="string"||n instanceof String?!isNaN(n):!1}function zu(n){return["concat","entries","every","filter","find","findIndex","forEach","join","keys","map","reduce","reduceRight","slice","some","toLocaleString","toString","values"].includes(n)}class U{constructor(t,e){a(this,"context");a(this,"handlers");a(this,"array");this.context=t,this.array=e,this.handlers={get:(r,s,i)=>s==="getID"?()=>r.getCreatedAt():s==="getElementByID"?o=>{const c=r.getByID(o);if(!(!c||c.isRemoved()))return tr(t,c)}:s==="getElementByIndex"?o=>{const c=r.get(o);return tr(t,c)}:s==="getLast"?()=>tr(t,r.getLast()):s==="deleteByID"?o=>{const c=U.deleteInternalByID(t,r,o);return tr(t,c)}:s==="insertAfter"?(o,c)=>{const l=U.insertAfterInternal(t,r,o,c);return tr(t,l)}:s==="insertBefore"?(o,c)=>{const l=U.insertBeforeInternal(t,r,o,c);return tr(t,l)}:s==="moveBefore"?(o,c)=>{U.moveBeforeInternal(t,r,o,c)}:s==="moveAfter"?(o,c)=>{U.moveAfterInternal(t,r,o,c)}:s==="moveFront"?o=>{U.moveFrontInternal(t,r,o)}:s==="moveLast"?o=>{U.moveLastInternal(t,r,o)}:Vu(s)?fr(t,r.get(Number(s))):s==="push"?o=>U.pushInternal(t,r,o):s==="splice"?(o,c,...l)=>U.splice(t,r,o,c,...l):s==="length"?r.length:typeof s=="symbol"&&s===Symbol.iterator?U.iteratorInternal.bind(this,t,r):s==="includes"?(o,c)=>U.includes(t,r,o,c):s==="indexOf"?(o,c)=>U.indexOf(t,r,o,c):s==="lastIndexOf"?(o,c)=>U.lastIndexOf(t,r,o,c):s==="toJSForTest"?()=>r.toJSForTest():s==="toTestString"?()=>U.toTestString(r):typeof s=="string"&&zu(s)?(...o)=>{const c=Array.from(r).map(l=>fr(t,l));return Array.prototype[s].apply(c,o)}:Reflect.get(r,s,i),deleteProperty:(r,s)=>(x.isEnabled(ee.Trivial)&&x.trivial(`array[${s}]`),U.deleteInternalByIndex(t,r,Number.parseInt(s)),!0)}}static*iteratorInternal(t,e){for(const r of e)yield tr(t,r)}static buildArrayElements(t,e){const r=[];for(const s of e){const i=t.issueTimeTicket(),o=zn(t,s,i);r.push(o)}return r}static pushInternal(t,e,r){return U.insertAfterInternal(t,e,e.getLastCreatedAt(),r),e.length}static moveBeforeInternal(t,e,r,s){const i=t.issueTimeTicket(),o=e.getPrevCreatedAt(r);e.moveAfter(o,s,i),t.push(nr.create(e.getCreatedAt(),o,s,i))}static moveAfterInternal(t,e,r,s){const i=t.issueTimeTicket();e.moveAfter(r,s,i),t.push(nr.create(e.getCreatedAt(),r,s,i))}static moveFrontInternal(t,e,r){const s=t.issueTimeTicket(),i=e.getHead();e.moveAfter(i.getCreatedAt(),r,s),t.push(nr.create(e.getCreatedAt(),i.getCreatedAt(),r,s))}static moveLastInternal(t,e,r){const s=t.issueTimeTicket(),i=e.getLastCreatedAt();e.moveAfter(i,r,s),t.push(nr.create(e.getCreatedAt(),i,r,s))}static insertAfterInternal(t,e,r,s){const i=t.issueTimeTicket(),o=zn(t,s,i);return e.insertAfter(r,o),t.registerElement(o,e),t.push(tn.create(e.getCreatedAt(),r,o.deepcopy(),i)),o}static insertBeforeInternal(t,e,r,s){return U.insertAfterInternal(t,e,e.getPrevCreatedAt(r),s)}static deleteInternalByIndex(t,e,r){const s=t.issueTimeTicket(),i=e.deleteByIndex(r,s);if(i)return t.push(ur.create(e.getCreatedAt(),i.getCreatedAt(),s)),t.registerRemovedElement(i),i}static deleteInternalByID(t,e,r){const s=t.issueTimeTicket(),i=e.delete(r,s);return t.push(ur.create(e.getCreatedAt(),i.getCreatedAt(),s)),t.registerRemovedElement(i),i}static splice(t,e,r,s,...i){const o=e.length,c=r>=0?Math.min(r,o):Math.max(o+r,0),l=s===void 0?o:s<0?c:Math.min(c+s,o),h=[];for(let f=c;f=i)return!1;if($.isSupport(r))return Array.from(e).map(h=>fr(t,h)).includes(r,o);for(let l=o;l=i)return-1;if($.isSupport(r))return Array.from(e).map(h=>fr(t,h)).indexOf(r,o);for(let l=o;l=i?i-1:s<0?s+i:s;if(o<0)return-1;if($.isSupport(r))return Array.from(e).map(h=>fr(t,h)).lastIndexOf(r,o);for(let l=o;l>0;l--)if(((c=e.get(l))==null?void 0:c.getID())===r.getID())return l;return-1}static toTestString(t){return t.toTestString()}getHandlers(){return this.handlers}}class Yn{constructor(t,e){a(this,"context");a(this,"text");this.context=t,this.text=e}initialize(t,e){this.context=t,this.text=e}getID(){return this.text.getID()}edit(t,e,r,s){if(!this.context||!this.text)throw new g(d.ErrNotInitialized,"Text is not initialized yet");if(t>e)throw new g(d.ErrInvalidArgument,"from should be less than or equal to to");const i=this.text.indexRangeToPosRange(t,e);x.isEnabled(ee.Debug)&&x.debug(`EDIT: f:${t}->${i[0].toTestString()}, t:${e}->${i[1].toTestString()} c:${r}`);const o=s?Or(s):void 0,c=this.context.issueTimeTicket(),[l,,h,f]=this.text.edit(i,r,c,o);for(const p of h)this.context.registerGCPair(p);return this.context.push(new rn(this.text.getCreatedAt(),i[0],i[1],l,r,o?new Map(Object.entries(o)):new Map,c)),this.text.findIndexesFromRange(f)}delete(t,e){return this.edit(t,e,"")}empty(){return this.edit(0,this.length,"")}setStyle(t,e,r){if(!this.context||!this.text)throw new g(d.ErrNotInitialized,"Text is not initialized yet");if(t>e)throw new g(d.ErrInvalidArgument,"from should be less than or equal to to");const s=this.text.indexRangeToPosRange(t,e);x.isEnabled(ee.Debug)&&x.debug(`STYL: f:${t}->${s[0].toTestString()}, t:${e}->${s[1].toTestString()} a:${JSON.stringify(r)}`);const i=Or(r),o=this.context.issueTimeTicket(),[c,l]=this.text.setStyle(s,i,o);for(const h of l)this.context.registerGCPair(h);return this.context.push(new nn(this.text.getCreatedAt(),s[0],s[1],c,new Map(Object.entries(i)),o)),!0}indexRangeToPosRange(t){if(!this.context||!this.text)throw new g(d.ErrNotInitialized,"Text is not initialized yet");const e=this.text.indexRangeToPosRange(t[0],t[1]);return[e[0].toStruct(),e[1].toStruct()]}posRangeToIndexRange(t){if(!this.context||!this.text)throw new g(d.ErrNotInitialized,"Text is not initialized yet");const e=this.text.findIndexesFromRange([Ee.fromStruct(t[0]),Ee.fromStruct(t[1])]);return[e[0],e[1]]}toTestString(){if(!this.context||!this.text)throw new g(d.ErrNotInitialized,"Text is not initialized yet");return this.text.toTestString()}values(){if(!this.context||!this.text)throw new g(d.ErrNotInitialized,"Text is not initialized yet");return this.text.values()}get length(){return this.text.length}getTreeByIndex(){return this.text.getTreeByIndex()}getTreeByID(){return this.text.getTreeByID()}toString(){if(!this.context||!this.text)throw new g(d.ErrNotInitialized,"Text is not initialized yet");return this.text.toString()}toJSON(){if(!this.context||!this.text)throw new g(d.ErrNotInitialized,"Text is not initialized yet");return this.text.toJSON()}toJSForTest(){if(!this.context||!this.text)throw new g(d.ErrNotInitialized,"Text is not initialized yet");return this.text.toJSForTest()}createRangeForTest(t,e){if(!this.context||!this.text)throw new g(d.ErrNotInitialized,"Text is not initialized yet");return this.text.indexRangeToPosRange(t,e)}}class Xn{constructor(t,e){a(this,"valueType");a(this,"value");a(this,"context");a(this,"counter");this.valueType=t,this.value=e}initialize(t,e){this.valueType=e.getValueType(),this.context=t,this.counter=e,this.value=e.getValue()}getID(){return this.counter.getID()}getValue(){return this.value}getValueType(){return this.valueType}increase(t){if(!this.context||!this.counter)throw new g(d.ErrNotInitialized,"Counter is not initialized yet");const e=this.context.issueTimeTicket(),r=$.of(t,e);if(!r.isNumericType())throw new TypeError(`Unsupported type of value: ${typeof r.getValue()}`);return this.counter.increase(r),this.context.push(Jr.create(this.counter.getCreatedAt(),r,e)),this}toJSForTest(){if(!this.context||!this.counter)throw new g(d.ErrNotInitialized,"Counter is not initialized yet");return this.counter.toJSForTest()}}function ni(n,t,e){const{type:r}=n,s=e.issueTimeTicket();if(r===Ht){sa(n);const{value:i}=n,o=ie.create(Y.of(s,0),r,i);t.append(o)}else{const{children:i=[]}=n,{attributes:o}=n;let c;if(typeof o=="object"&&!Eo(o)){const h=Or(o);c=new Zt;for(const[f,p]of Object.entries(h))c.set(f,p,s)}const l=ie.create(Y.of(s,0),r,void 0,c);t.append(l);for(const h of i)ni(h,l,e)}}function Ku(n,t){const{type:e}=t,r=n.issueTimeTicket();let s;if(t.type===Ht){const{value:i}=t;s=ie.create(Y.of(r,0),e,i)}else if(t){const{children:i=[]}=t,{attributes:o}=t;let c;if(typeof o=="object"&&!Eo(o)){const l=Or(o);c=new Zt;for(const[h,f]of Object.entries(l))c.set(h,f,r)}s=ie.create(Y.of(n.issueTimeTicket(),0),e,void 0,c);for(const l of i)ni(l,s,n)}return s}function sa(n){if(!n.value.length)throw new g(d.ErrInvalidArgument,"text node cannot have empty value");return!0}function zi(n){if(!n.length)return!0;if(n[0].type===Ht)for(const e of n){const{type:r}=e;if(r!==Ht)throw new g(d.ErrInvalidArgument,"element node and text node cannot be passed together");sa(e)}else for(const e of n){const{type:r}=e;if(r===Ht)throw new g(d.ErrInvalidArgument,"element node and text node cannot be passed together")}return!0}class Zn{constructor(t){a(this,"initialRoot");a(this,"context");a(this,"tree");this.initialRoot=t}initialize(t,e){this.context=t,this.tree=e}getID(){return this.tree.getID()}buildRoot(t){if(!this.initialRoot)return ie.create(Y.of(t.issueTimeTicket(),0),Vc);const e=ie.create(Y.of(t.issueTimeTicket(),0),this.initialRoot.type);for(const r of this.initialRoot.children)ni(r,e,t);return e}getSize(){if(!this.context||!this.tree)throw new g(d.ErrNotInitialized,"Tree is not initialized yet");return this.tree.getSize()}getNodeSize(){if(!this.context||!this.tree)throw new g(d.ErrNotInitialized,"Tree is not initialized yet");return this.tree.getNodeSize()}getIndexTree(){if(!this.context||!this.tree)throw new g(d.ErrNotInitialized,"Tree is not initialized yet");return this.tree.getIndexTree()}styleByPath(t,e){if(!this.context||!this.tree)throw new g(d.ErrNotInitialized,"Tree is not initialized yet");if(!t.length)throw new g(d.ErrInvalidArgument,"path should not be empty");const[r,s]=this.tree.pathToPosRange(t),i=this.context.issueTimeTicket(),o=e?Or(e):void 0,[c]=this.tree.style([r,s],o,i);this.context.push(Yt.create(this.tree.getCreatedAt(),r,s,c,o?new Map(Object.entries(o)):new Map,i))}style(t,e,r){if(!this.context||!this.tree)throw new g(d.ErrNotInitialized,"Tree is not initialized yet");if(t>e)throw new g(d.ErrInvalidArgument,"from should be less than or equal to to");const s=this.tree.findPos(t),i=this.tree.findPos(e),o=this.context.issueTimeTicket(),c=r?Or(r):void 0,[l,h]=this.tree.style([s,i],c,o);for(const f of h)this.context.registerGCPair(f);this.context.push(Yt.create(this.tree.getCreatedAt(),s,i,l,c?new Map(Object.entries(c)):new Map,o))}removeStyle(t,e,r){if(!this.context||!this.tree)throw new g(d.ErrNotInitialized,"Tree is not initialized yet");if(t>e)throw new g(d.ErrInvalidArgument,"from should be less than or equal to to");const s=this.tree.findPos(t),i=this.tree.findPos(e),o=this.context.issueTimeTicket(),[c,l]=this.tree.removeStyle([s,i],r,o);for(const h of l)this.context.registerGCPair(h);this.context.push(Yt.createTreeRemoveStyleOperation(this.tree.getCreatedAt(),s,i,c,r,o))}editInternal(t,e,r,s=0){var h;if(r.length!==0&&r[0]&&(zi(r),r[0].type!==Ht))for(const f of r){const{children:p=[]}=f;zi(p)}const i=this.context.getLastTimeTicket();let o=new Array;if(((h=r[0])==null?void 0:h.type)===Ht){let f="";for(const p of r){const{value:v}=p;f+=v}o.push(ie.create(Y.of(this.context.issueTimeTicket(),0),Ht,f))}else o=r.map(f=>f&&Ku(this.context,f)).filter(f=>f);const[,c,l]=this.tree.edit([t,e],o.length?o.map(f=>f==null?void 0:f.deepcopy()):void 0,s,i,()=>this.context.issueTimeTicket());for(const f of c)this.context.registerGCPair(f);return this.context.push(sn.create(this.tree.getCreatedAt(),t,e,o.length?o:void 0,s,l,i)),!0}editByPath(t,e,r,s=0){if(!this.context||!this.tree)throw new g(d.ErrNotInitialized,"Tree is not initialized yet");if(t.length!==e.length)throw new g(d.ErrInvalidArgument,"path length should be equal");if(!t.length||!e.length)throw new g(d.ErrInvalidArgument,"path should not be empty");const i=this.tree.pathToPos(t),o=this.tree.pathToPos(e);return this.editInternal(i,o,r?[r]:[],s)}editBulkByPath(t,e,r,s=0){if(!this.context||!this.tree)throw new g(d.ErrNotInitialized,"Tree is not initialized yet");if(t.length!==e.length)throw new g(d.ErrInvalidArgument,"path length should be equal");if(!t.length||!e.length)throw new g(d.ErrInvalidArgument,"path should not be empty");const i=this.tree.pathToPos(t),o=this.tree.pathToPos(e);return this.editInternal(i,o,r,s)}edit(t,e,r,s=0){if(!this.context||!this.tree)throw new g(d.ErrNotInitialized,"Tree is not initialized yet");if(t>e)throw new g(d.ErrInvalidArgument,"from should be less than or equal to to");const i=this.tree.findPos(t),o=this.tree.findPos(e);return this.editInternal(i,o,r?[r]:[],s)}editBulk(t,e,r,s=0){if(!this.context||!this.tree)throw new g(d.ErrNotInitialized,"Tree is not initialized yet");if(t>e)throw new g(d.ErrInvalidArgument,"from should be less than or equal to to");const i=this.tree.findPos(t),o=this.tree.findPos(e);return this.editInternal(i,o,r,s)}toXML(){if(!this.context||!this.tree)throw new g(d.ErrNotInitialized,"Tree is not initialized yet");return this.tree.toXML()}toJSON(){if(!this.context||!this.tree)throw new g(d.ErrNotInitialized,"Tree is not initialized yet");return this.tree.toJSON()}toJSForTest(){if(!this.context||!this.tree)throw new g(d.ErrNotInitialized,"Tree is not initialized yet");return this.tree.toJSForTest()}toJSInfoForTest(){if(!this.context||!this.tree)throw new g(d.ErrNotInitialized,"Tree is not initialized yet");return this.tree.toJSInfoForTest()}getRootTreeNode(){if(!this.context||!this.tree)throw new g(d.ErrNotInitialized,"Tree is not initialized yet");return this.tree.getRootTreeNode()}indexToPath(t){if(!this.context||!this.tree)throw new g(d.ErrNotInitialized,"Tree is not initialized yet");return this.tree.indexToPath(t)}pathToIndex(t){if(!this.context||!this.tree)throw new g(d.ErrNotInitialized,"Tree is not initialized yet");return this.tree.pathToIndex(t)}pathRangeToPosRange(t){if(!this.context||!this.tree)throw new g(d.ErrNotInitialized,"Tree is not initialized yet");const e=[this.tree.pathToIndex(t[0]),this.tree.pathToIndex(t[1])],r=this.tree.indexRangeToPosRange(e);return[r[0].toStruct(),r[1].toStruct()]}indexRangeToPosRange(t){if(!this.context||!this.tree)throw new g(d.ErrNotInitialized,"Tree is not initialized yet");return this.tree.indexRangeToPosStructRange(t)}posRangeToIndexRange(t){if(!this.context||!this.tree)throw new g(d.ErrNotInitialized,"Tree is not initialized yet");const e=[ke.fromStruct(t[0]),ke.fromStruct(t[1])];return this.tree.posRangeToIndexRange(e)}posRangeToPathRange(t){if(!this.context||!this.tree)throw new g(d.ErrNotInitialized,"Tree is not initialized yet");const e=[ke.fromStruct(t[0]),ke.fromStruct(t[1])];return this.tree.posRangeToPathRange(e)}}function Ki(n,t){return na(n,t)}function tr(n,t){if(t){if(t instanceof $)return t;if(t instanceof re)return na(n,t);if(t instanceof ae)return qu(n,t);if(t instanceof Ae)return new Yn(n,t);if(t instanceof ce){const e=new Xn(ze.IntegerCnt,0);return e.initialize(n,t),e}else if(t instanceof be){const e=new Zn;return e.initialize(n,t),e}}else return;throw new TypeError(`Unsupported type of element: ${typeof t}`)}function fr(n,t){const e=tr(n,t);return e instanceof $?e.getValue():e}function zn(n,t,e){let r;if($.isSupport(t))r=$.of(t,e);else if(Array.isArray(t))r=ae.create(e,U.buildArrayElements(n,t));else if(typeof t=="object")t instanceof Yn?(r=Ae.create(Lr.create(),e),t.initialize(n,r)):t instanceof Xn?(r=ce.create(t.getValueType(),t.getValue(),e),t.initialize(n,r)):t instanceof Zn?(r=be.create(t.buildRoot(n),e),t.initialize(n,r)):r=re.create(e,_r.buildObjectMembers(n,t));else throw new TypeError(`Unsupported type of value: ${typeof t}`);return r}const ji=50;class ju{constructor(){a(this,"undoStack",[]);a(this,"redoStack",[])}hasUndo(){return this.undoStack.length>0}hasRedo(){return this.redoStack.length>0}pushUndo(t){this.undoStack.length>=ji&&this.undoStack.shift(),this.undoStack.push(t)}popUndo(){return this.undoStack.pop()}pushRedo(t){this.redoStack.length>=ji&&this.redoStack.shift(),this.redoStack.push(t)}popRedo(){return this.redoStack.pop()}clearRedo(){this.redoStack=[]}getUndoStackForTest(){return this.undoStack}getRedoStackForTest(){return this.redoStack}}const Gu="yorkie-devtools-panel",Wu="yorkie-devtools-sdk";let Ir="disconnected";const Gi=new Map,vn=new Map;typeof window<"u"&&(window.transactionEventsByDocKey=vn);function hn(n,t){(t!=null&&t.force||Ir!=="disconnected")&&window.postMessage({source:Wu,...n},"*")}function Hu(n){if(!n.isEnableDevtools()||typeof window>"u"||Gi.has(n.getKey()))return;vn.set(n.getKey(),[]);const t=n.subscribe("all",e=>{e.some(r=>r.type!==_.StatusChanged&&r.type!==_.Snapshot&&r.type!==_.LocalChange&&r.type!==_.RemoteChange&&r.type!==_.Initialized&&r.type!==_.Watched&&r.type!==_.Unwatched&&r.type!==_.PresenceChanged)||(vn.get(n.getKey()).push(e),Ir==="synced"&&hn({msg:"doc::sync::partial",docKey:n.getKey(),event:e}))});Gi.set(n.getKey(),[t]),hn({msg:"refresh-devtools"},{force:!0}),window.addEventListener("message",e=>{var s;if(((s=e.data)==null?void 0:s.source)!==Gu)return;switch(e.data.msg){case"devtools::connect":if(Ir!=="disconnected")break;Ir="connected",hn({msg:"doc::available",docKey:n.getKey()}),x.info(`[YD] Devtools connected. Doc: ${n.getKey()}`);break;case"devtools::disconnect":Ir="disconnected",x.info(`[YD] Devtools disconnected. Doc: ${n.getKey()}`);break;case"devtools::subscribe":Ir="synced",hn({msg:"doc::sync::full",docKey:n.getKey(),events:vn.get(n.getKey())}),x.info(`[YD] Devtools subscribed. Doc: ${n.getKey()}`);break}})}var rr=(n=>(n.Detached="detached",n.Attached="attached",n.Removed="removed",n))(rr||{}),_=(n=>(n.StatusChanged="status-changed",n.ConnectionChanged="connection-changed",n.SyncStatusChanged="sync-status-changed",n.Snapshot="snapshot",n.LocalChange="local-change",n.RemoteChange="remote-change",n.Initialized="initialized",n.Watched="watched",n.Unwatched="unwatched",n.PresenceChanged="presence-changed",n.Broadcast="broadcast",n.LocalBroadcast="local-broadcast",n))(_||{}),Js=(n=>(n.Connected="connected",n.Disconnected="disconnected",n))(Js||{}),Fs=(n=>(n.Synced="synced",n.SyncFailed="sync-failed",n))(Fs||{});class ia{constructor(t,e){a(this,"key");a(this,"status");a(this,"opts");a(this,"changeID");a(this,"checkpoint");a(this,"localChanges");a(this,"root");a(this,"clone");a(this,"eventStream");a(this,"eventStreamObserver");a(this,"onlineClients");a(this,"presences");a(this,"history");a(this,"internalHistory");a(this,"isUpdating");this.opts=e||{},this.key=t,this.status="detached",this.root=Qr.create(),this.changeID=Zc,this.checkpoint=Qc,this.localChanges=[],this.eventStream=Uu(r=>{this.eventStreamObserver=r}),this.onlineClients=new Set,this.presences=new Map,this.isUpdating=!1,this.internalHistory=new ju,this.history={canUndo:this.canUndo.bind(this),canRedo:this.canRedo.bind(this),undo:this.undo.bind(this),redo:this.redo.bind(this)},Hu(this)}update(t,e){if(this.getStatus()==="removed")throw new g(d.ErrDocumentRemoved,`${this.key} is removed`);this.ensureClone();const r=this.changeID.getActorID(),s=kr.create(this.changeID.next(),this.clone.root,this.clone.presences.get(r)||{},e);try{const i=Ki(s,this.clone.root.getObject());this.presences.has(r)||this.clone.presences.set(r,{}),this.isUpdating=!0,t(i,new rs(s,this.clone.presences.get(r)))}catch(i){throw this.clone=void 0,i}finally{this.isUpdating=!1}if(s.hasChange()){x.isEnabled(ee.Trivial)&&x.trivial(`trying to update a local change: ${this.toJSON()}`);const i=s.getChange(),{opInfos:o,reverseOps:c}=i.execute(this.root,this.presences,J.Local),l=s.getReversePresence();l&&c.push({type:"presence",value:l}),this.localChanges.push(i),c.length>0&&this.internalHistory.pushUndo(c),o.length>0&&this.internalHistory.clearRedo(),this.changeID=i.getID();const h=[];o.length>0&&h.push({type:"local-change",source:J.Local,value:{message:i.getMessage()||"",operations:o,actor:r,clientSeq:i.getID().getClientSeq(),serverSeq:i.getID().getServerSeq()},rawChange:this.isEnableDevtools()?i.toStruct():void 0}),i.hasPresenceChange()&&h.push({type:"presence-changed",source:J.Local,value:{clientID:r,presence:this.getPresence(r)}}),this.publish(h),x.isEnabled(ee.Trivial)&&x.trivial(`after update a local change: ${this.toJSON()}`)}}subscribe(t,e,r,s){if(typeof t=="string"){if(typeof e!="function")throw new g(d.ErrInvalidArgument,"Second argument must be a callback function");if(t==="presence"){const c=e;return this.eventStream.subscribe(l=>{for(const h of l)h.type!=="initialized"&&h.type!=="watched"&&h.type!=="unwatched"&&h.type!=="presence-changed"||c(h)},r,s)}if(t==="my-presence"){const c=e;return this.eventStream.subscribe(l=>{for(const h of l)h.type!=="initialized"&&h.type!=="presence-changed"||h.type==="presence-changed"&&h.value.clientID!==this.changeID.getActorID()||c(h)},r,s)}if(t==="others"){const c=e;return this.eventStream.subscribe(l=>{for(const h of l)h.type!=="watched"&&h.type!=="unwatched"&&h.type!=="presence-changed"||h.value.clientID!==this.changeID.getActorID()&&c(h)},r,s)}if(t==="connection"){const c=e;return this.eventStream.subscribe(l=>{for(const h of l)h.type==="connection-changed"&&c(h)},r,s)}if(t==="status"){const c=e;return this.eventStream.subscribe(l=>{for(const h of l)h.type==="status-changed"&&c(h)},r,s)}if(t==="sync"){const c=e;return this.eventStream.subscribe(l=>{for(const h of l)h.type==="sync-status-changed"&&c(h)},r,s)}if(t==="local-broadcast"){const c=e;return this.eventStream.subscribe(l=>{for(const h of l)h.type==="local-broadcast"&&c(h)},r)}if(t==="broadcast"){const c=e;return this.eventStream.subscribe(l=>{for(const h of l)h.type==="broadcast"&&c(h)},r)}if(t==="all"){const c=e;return this.eventStream.subscribe(c,r,s)}const i=t,o=e;return this.eventStream.subscribe(c=>{for(const l of c){if(l.type!=="local-change"&&l.type!=="remote-change")continue;const h=[];for(const f of l.value.operations)this.isSameElementOrChildOf(f.path,i)&&h.push(f);h.length&&o({...l,value:{...l.value,operations:h}})}},r,s)}if(typeof t=="function"){const i=t,o=e,c=r;return this.eventStream.subscribe(l=>{for(const h of l)h.type!=="snapshot"&&h.type!=="local-change"&&h.type!=="remote-change"||i(h)},o,c)}throw new g(d.ErrInvalidArgument,`"${t}" is not a valid`)}publish(t){this.eventStreamObserver&&this.eventStreamObserver.next(t)}isSameElementOrChildOf(t,e){if(e===t)return!0;const r=t.split(".");return e.split(".").every((i,o)=>i===r[o])}removePushedLocalChanges(t){for(;this.localChanges.length&&!(this.localChanges[0].getID().getClientSeq()>t);)this.localChanges.shift()}applyChangePack(t){const e=t.hasSnapshot();e?this.applySnapshot(t.getCheckpoint().getServerSeq(),t.getVersionVector(),t.getSnapshot(),t.getCheckpoint().getClientSeq()):(this.applyChanges(t.getChanges(),J.Remote),this.removePushedLocalChanges(t.getCheckpoint().getClientSeq())),this.checkpoint=this.checkpoint.forward(t.getCheckpoint()),e||this.garbageCollect(t.getVersionVector()),e||this.filterVersionVector(t.getVersionVector()),t.getIsRemoved()&&this.applyStatus("removed"),x.isEnabled(ee.Trivial)&&x.trivial(`${this.root.toJSON()}`)}getCheckpoint(){return this.checkpoint}getChangeID(){return this.changeID}hasLocalChanges(){return this.localChanges.length>0}ensureClone(){this.clone||(this.clone={root:this.root.deepcopy(),presences:Ie(this.presences)})}createChangePack(){const t=Array.from(this.localChanges),e=this.checkpoint.increaseClientSeq(t.length);return Hn.create(this.key,e,!1,t,this.getVersionVector())}setActor(t){for(const e of this.localChanges)e.setActor(t);this.changeID=this.changeID.setActor(t)}isEnableDevtools(){return!!this.opts.enableDevtools}getKey(){return this.key}getStatus(){return this.status}getCloneRoot(){if(this.clone)return this.clone.root.getObject()}getRoot(){this.ensureClone();const t=kr.create(this.changeID.next(),this.clone.root,this.clone.presences.get(this.changeID.getActorID())||{});return Ki(t,this.clone.root.getObject())}garbageCollect(t){return this.opts.disableGC?0:(this.clone&&this.clone.root.garbageCollect(t),this.root.garbageCollect(t))}getRootObject(){return this.root.getObject()}getGarbageLen(){return this.root.getGarbageLen()}getGarbageLenFromClone(){return this.clone.root.getGarbageLen()}toJSON(){return this.root.toJSON()}toSortedJSON(){return this.root.toSortedJSON()}getStats(){return this.root.getStats()}toJSForTest(){return{...this.getRoot().toJSForTest(),key:"root"}}applySnapshot(t,e,r,s=-1){const{root:i,presences:o}=V.bytesToSnapshot(r);this.root=new Qr(i),this.presences=o,this.changeID=this.changeID.setClocks(t,e),this.clone=void 0,this.removePushedLocalChanges(s),this.applyChanges(this.localChanges,J.Local),this.publish([{type:"snapshot",source:J.Remote,value:{serverSeq:t.toString(),snapshot:this.isEnableDevtools()?V.bytesToHex(r):void 0,snapshotVector:V.versionVectorToHex(e)}}])}applyChanges(t,e){x.isEnabled(ee.Debug)&&x.debug(`trying to apply ${t.length} remote changes.elements:${this.root.getElementMapSize()}, removeds:${this.root.getGarbageElementSetSize()}`),x.isEnabled(ee.Trivial)&&x.trivial(t.map(r=>`${r.getID().toTestString()} ${r.toTestString()}`).join(` `));for(const r of t)this.applyChange(r,e);x.isEnabled(ee.Debug)&&x.debug(`after appling ${t.length} remote changes.elements:${this.root.getElementMapSize()}, removeds:${this.root.getGarbageElementSetSize()}`)}applyChange(t,e){this.ensureClone(),t.execute(this.clone.root,this.clone.presences,e);const r=[],s=t.getID().getActorID();if(t.hasPresenceChange()&&this.onlineClients.has(s)){const o=t.getPresenceChange();switch(o.type){case cr.Put:r.push(this.presences.has(s)?{type:"presence-changed",source:e,value:{clientID:s,presence:o.presence}}:{type:"watched",source:J.Remote,value:{clientID:s,presence:o.presence}});break;case cr.Clear:r.push({type:"unwatched",source:J.Remote,value:{clientID:s,presence:this.getPresence(s)}}),this.removeOnlineClient(s);break}}const{opInfos:i}=t.execute(this.root,this.presences,e);if(this.changeID=this.changeID.syncClocks(t.getID()),i.length>0){const o=this.isEnableDevtools()?t.toStruct():void 0;r.push(e===J.Remote?{type:"remote-change",source:e,value:{actor:s,clientSeq:t.getID().getClientSeq(),serverSeq:t.getID().getServerSeq(),message:t.getMessage()||"",operations:i},rawChange:o}:{type:"local-change",source:e,value:{actor:s,clientSeq:t.getID().getClientSeq(),serverSeq:t.getID().getServerSeq(),message:t.getMessage()||"",operations:i},rawChange:o})}r.length>0&&this.publish(r)}applyWatchStream(t){if(t.body.case==="initialization"){const e=t.body.value.clientIds,r=new Set;for(const s of e)s!==this.changeID.getActorID()&&r.add(s);this.setOnlineClients(r),this.publish([{type:"initialized",source:J.Local,value:this.getPresences()}]);return}if(t.body.case==="event"){const{type:e,publisher:r}=t.body.value,s=[];if(e===pr.DOCUMENT_WATCHED){if(this.onlineClients.has(r)&&this.hasPresence(r))return;this.addOnlineClient(r),this.hasPresence(r)&&s.push({type:"watched",source:J.Remote,value:{clientID:r,presence:this.getPresence(r)}})}else if(e===pr.DOCUMENT_UNWATCHED){const i=this.getPresence(r);this.removeOnlineClient(r),i&&s.push({type:"unwatched",source:J.Remote,value:{clientID:r,presence:i}})}else if(e===pr.DOCUMENT_BROADCAST&&t.body.value.body){const{topic:i,payload:o}=t.body.value.body,c=new TextDecoder;s.push({type:"broadcast",value:{clientID:r,topic:i,payload:JSON.parse(c.decode(o))}})}s.length>0&&this.publish(s)}}applyStatus(t){this.status=t,t==="detached"&&this.setActor(Vs),this.publish([{source:t==="removed"?J.Remote:J.Local,type:"status-changed",value:t==="attached"?{status:t,actorID:this.changeID.getActorID()}:{status:t}}])}applyDocEvent(t){if(t.type==="status-changed"){this.applyStatus(t.value.status),t.value.status==="attached"&&this.setActor(t.value.actorID);return}if(t.type==="snapshot"){const{snapshot:e,serverSeq:r,snapshotVector:s}=t.value;if(!e)return;this.applySnapshot(BigInt(r),V.hexToVersionVector(s),V.hexToBytes(e));return}if(t.type==="local-change"||t.type==="remote-change"){if(!t.rawChange)return;const e=Rr.fromStruct(t.rawChange);this.applyChange(e,t.source)}if(t.type==="initialized"){const e=new Set;for(const{clientID:r,presence:s}of t.value)e.add(r),this.presences.set(r,s);this.setOnlineClients(e);return}if(t.type==="watched"){const{clientID:e,presence:r}=t.value;this.addOnlineClient(e),this.presences.set(e,r);return}if(t.type==="unwatched"){const{clientID:e}=t.value;this.removeOnlineClient(e),this.presences.delete(e)}if(t.type==="presence-changed"){const{clientID:e,presence:r}=t.value;this.presences.set(e,r)}}applyTransactionEvent(t){for(const e of t)this.applyDocEvent(e)}getValueByPath(t){if(!t.startsWith("$"))throw new g(d.ErrInvalidArgument,'path must start with "$"');const e=t.split(".");e.shift();let r=this.getRoot();for(const s of e)if(r=r[s],r===void 0)return;return r}setOnlineClients(t){this.onlineClients=t}resetOnlineClients(){this.onlineClients=new Set}addOnlineClient(t){this.onlineClients.add(t)}removeOnlineClient(t){this.onlineClients.delete(t)}hasPresence(t){return this.presences.has(t)}getMyPresence(){if(this.status!=="attached")return{};const t=this.presences.get(this.changeID.getActorID());return t?Ie(t):{}}getPresence(t){if(t===this.changeID.getActorID())return this.getMyPresence();if(!this.onlineClients.has(t))return;const e=this.presences.get(t);return e?Ie(e):void 0}getPresenceForTest(t){const e=this.presences.get(t);return e?Ie(e):void 0}getPresences(){const t=[];t.push({clientID:this.changeID.getActorID(),presence:Ie(this.getMyPresence())});for(const e of this.onlineClients)this.presences.has(e)&&t.push({clientID:e,presence:Ie(this.presences.get(e))});return t}getSelfForTest(){return{clientID:this.getChangeID().getActorID(),presence:this.getMyPresence()}}getOthersForTest(){const t=this.getChangeID().getActorID();return this.getPresences().filter(e=>e.clientID!==t).sort((e,r)=>e.clientID>r.clientID?1:-1)}canUndo(){return this.internalHistory.hasUndo()&&!this.isUpdating}filterVersionVector(t){const r=this.changeID.getVersionVector().filter(t);this.changeID=this.changeID.setVersionVector(r)}canRedo(){return this.internalHistory.hasRedo()&&!this.isUpdating}undo(){if(this.isUpdating)throw new g(d.ErrRefused,"Undo is not allowed during an update");const t=this.internalHistory.popUndo();if(t===void 0)throw new g(d.ErrRefused,"There is no operation to be undone");this.ensureClone();const e=kr.create(this.changeID.next(),this.clone.root,this.clone.presences.get(this.changeID.getActorID())||{});for(const h of t){if(!(h instanceof Ne)){new rs(e,Ie(this.clone.presences.get(this.changeID.getActorID()))).set(h.value,{addToHistory:!0});continue}const f=e.issueTimeTicket();h.setExecutedAt(f),e.push(h)}const r=e.getChange();r.execute(this.clone.root,this.clone.presences,J.UndoRedo);const{opInfos:s,reverseOps:i}=r.execute(this.root,this.presences,J.UndoRedo),o=e.getReversePresence();if(o&&i.push({type:"presence",value:o}),i.length>0&&this.internalHistory.pushRedo(i),!r.hasPresenceChange()&&s.length===0)return;this.localChanges.push(r),this.changeID=r.getID();const c=this.changeID.getActorID(),l=[];s.length>0&&l.push({type:"local-change",source:J.UndoRedo,value:{message:r.getMessage()||"",operations:s,actor:c,clientSeq:r.getID().getClientSeq(),serverSeq:r.getID().getServerSeq()},rawChange:this.isEnableDevtools()?r.toStruct():void 0}),r.hasPresenceChange()&&l.push({type:"presence-changed",source:J.UndoRedo,value:{clientID:c,presence:this.getPresence(c)}}),this.publish(l)}redo(){if(this.isUpdating)throw new g(d.ErrRefused,"Redo is not allowed during an update");const t=this.internalHistory.popRedo();if(t===void 0)throw new g(d.ErrRefused,"There is no operation to be redone");this.ensureClone();const e=kr.create(this.changeID.next(),this.clone.root,this.clone.presences.get(this.changeID.getActorID())||{});for(const h of t){if(!(h instanceof Ne)){new rs(e,Ie(this.clone.presences.get(this.changeID.getActorID()))).set(h.value,{addToHistory:!0});continue}const f=e.issueTimeTicket();h.setExecutedAt(f),e.push(h)}const r=e.getChange();r.execute(this.clone.root,this.clone.presences,J.UndoRedo);const{opInfos:s,reverseOps:i}=r.execute(this.root,this.presences,J.UndoRedo),o=e.getReversePresence();if(o&&i.push({type:"presence",value:o}),i.length>0&&this.internalHistory.pushUndo(i),!r.hasPresenceChange()&&s.length===0)return;this.localChanges.push(r),this.changeID=r.getID();const c=this.changeID.getActorID(),l=[];s.length>0&&l.push({type:"local-change",source:J.UndoRedo,value:{message:r.getMessage()||"",operations:s,actor:c,clientSeq:r.getID().getClientSeq(),serverSeq:r.getID().getServerSeq()},rawChange:this.isEnableDevtools()?r.toStruct():void 0}),r.hasPresenceChange()&&l.push({type:"presence-changed",source:J.UndoRedo,value:{clientID:c,presence:this.getPresence(c)}}),this.publish(l)}getUndoStackForTest(){return this.internalHistory.getUndoStackForTest()}getRedoStackForTest(){return this.internalHistory.getRedoStackForTest()}broadcast(t,e,r){const s={type:"local-broadcast",value:{topic:t,payload:e},options:r};this.publish([s])}getVersionVector(){return this.changeID.getVersionVector()}}function Yu(n,t){return e=>async r=>(n&&r.header.set("x-api-key",n),t&&r.header.set("authorization",t),await e(r))}const Xu="yorkie-js-sdk",Zu="0.5.4",Qu="Yorkie JS SDK",_u="./src/yorkie.ts",el={access:"public",main:"./dist/yorkie-js-sdk.js",typings:"./dist/yorkie-js-sdk.d.ts"},tl=["dist"],rl={build:"tsc && vite build","build:proto":"npx buf generate","build:docs":"typedoc","build:ghpages":"mkdir -p ghpages/examples && cp -r docs ghpages/api-reference && find ../../examples -name 'dist' -type d -exec sh -c 'cp -r {} ghpages/examples/$(basename $(dirname {}))' \\;",dev:"vite build -c vite.preview.ts && vite preview",test:"vitest run","test:watch":"vitest","test:bench":"vitest bench","test:ci":"vitest run --coverage","test:yorkie.dev":"TEST_RPC_ADDR=https://api.yorkie.dev vitest run --coverage",prepare:"pnpm build"},nl={node:">=18.0.0",npm:">=7.1.0"},sl={type:"git",url:"git+https://github.com/yorkie-team/yorkie-js-sdk.git"},il={name:"hackerwins",email:"susukang98@gmail.com"},ol="Apache-2.0",al={url:"https://github.com/yorkie-team/yorkie-js-sdk/issues"},cl="https://github.com/yorkie-team/yorkie-js-sdk#readme",ul={"@buf/googleapis_googleapis.bufbuild_es":"^1.4.0-20240524201209-f0e53af8f2fc.3","@bufbuild/buf":"^1.28.1","@bufbuild/protoc-gen-es":"^1.6.0","@connectrpc/protoc-gen-connect-es":"^1.4.0","@types/google-protobuf":"^3.15.5","@types/long":"^4.0.1","@typescript-eslint/eslint-plugin":"^6.21.0","@typescript-eslint/parser":"^6.21.0","@vitest/coverage-istanbul":"^0.34.5","@vitest/coverage-v8":"^0.34.5","eslint-plugin-tsdoc":"^0.2.16",prettier:"^2.7.1","ts-node":"^10.9.1",typedoc:"^0.25.13",typescript:"^5.3.3","typescript-transform-paths":"^3.3.1",vite:"^5.0.12","vite-plugin-commonjs":"^0.10.1","vite-plugin-dts":"^3.9.1","vite-tsconfig-paths":"^4.2.1",vitest:"^0.34.5"},ll={"@bufbuild/protobuf":"^1.6.0","@connectrpc/connect":"^1.4.0","@connectrpc/connect-web":"^1.4.0",long:"^5.2.0"},Wi={name:Xu,version:Zu,description:Qu,main:_u,publishConfig:el,files:tl,scripts:rl,engines:nl,repository:sl,author:il,license:ol,bugs:al,homepage:cl,devDependencies:ul,dependencies:ll};function hl(){return n=>async t=>(t.header.set("x-yorkie-user-agent",Wi.name+"/"+Wi.version),await n(t))}const fl=n=>{try{if(JSON.stringify(n)===void 0)return!1}catch{return!1}return!0};var wn=(n=>(n.Manual="manual",n.Realtime="realtime",n.RealtimePushOnly="realtime-pushonly",n.RealtimeSyncOff="realtime-syncoff",n))(wn||{});const fn={syncLoopDuration:50,retrySyncLoopDelay:1e3,reconnectStreamDelay:1e3},os={maxRetries:1/0,initialRetryInterval:1e3,maxBackoff:2e4};class oa{constructor(t,e){a(this,"id");a(this,"key");a(this,"status");a(this,"attachmentMap");a(this,"apiKey");a(this,"conditions");a(this,"syncLoopDuration");a(this,"reconnectStreamDelay");a(this,"retrySyncLoopDelay");a(this,"rpcClient");a(this,"taskQueue");a(this,"processing",!1);e=e||fn,this.key=e.key?e.key:ra(),this.status="deactivated",this.attachmentMap=new Map,this.apiKey=e.apiKey||"",this.conditions={SyncLoop:!1,WatchLoop:!1},this.syncLoopDuration=e.syncLoopDuration||fn.syncLoopDuration,this.reconnectStreamDelay=e.reconnectStreamDelay||fn.reconnectStreamDelay,this.retrySyncLoopDelay=e.retrySyncLoopDelay||fn.retrySyncLoopDelay,this.rpcClient=cc(Dc,Pc({baseUrl:t,interceptors:[Yu(e.apiKey,e.token),hl()]})),this.taskQueue=[]}activate(){return this.isActive()?Promise.resolve():this.enqueueTask(async()=>this.rpcClient.activateClient({clientKey:this.key},{headers:{"x-shard-key":this.apiKey}}).then(t=>{this.id=t.clientId,this.status="activated",this.runSyncLoop(),x.info(`[AC] c:"${this.getKey()}" activated, id:"${this.id}"`)}).catch(t=>{throw x.error(`[AC] c:"${this.getKey()}" err :`,t),this.handleConnectError(t),t}))}deactivate(){return this.status==="deactivated"?Promise.resolve():this.enqueueTask(async()=>this.rpcClient.deactivateClient({clientId:this.id},{headers:{"x-shard-key":this.apiKey}}).then(()=>{this.deactivateInternal(),x.info(`[DC] c"${this.getKey()}" deactivated`)}).catch(t=>{throw x.error(`[DC] c:"${this.getKey()}" err :`,t),this.handleConnectError(t),t}))}attach(t,e={}){if(!this.isActive())throw new g(d.ErrClientNotActivated,`${this.key} is not active`);if(t.getStatus()!==rr.Detached)throw new g(d.ErrDocumentNotDetached,`${t.getKey()} is not detached`);t.setActor(this.id),t.update((i,o)=>o.set(e.initialPresence||{}));const r=t.subscribe("local-broadcast",async i=>{var f;const{topic:o,payload:c}=i.value,l=(f=i.options)==null?void 0:f.error,h=i.options;try{await this.broadcast(t.getKey(),o,c,h)}catch(p){p instanceof Error&&(l==null||l(p))}}),s=e.syncMode??"realtime";return this.enqueueTask(async()=>this.rpcClient.attachDocument({clientId:this.id,changePack:V.toChangePack(t.createChangePack())},{headers:{"x-shard-key":`${this.apiKey}/${t.getKey()}`}}).then(async i=>{const o=V.fromChangePack(i.changePack);if(t.applyChangePack(o),t.getStatus()===rr.Removed)return t;t.applyStatus(rr.Attached),this.attachmentMap.set(t.getKey(),new Mu(this.reconnectStreamDelay,t,i.documentId,s,r)),s!=="manual"&&await this.runWatchLoop(t.getKey()),x.info(`[AD] c:"${this.getKey()}" attaches d:"${t.getKey()}"`);const c=t.getRootObject();if(e.initialRoot){const l=e.initialRoot;t.update(h=>{for(const[f,p]of Object.entries(l))if(!c.has(f)){const v=f;h[v]=p}})}return t}).catch(i=>{throw x.error(`[AD] c:"${this.getKey()}" err :`,i),this.handleConnectError(i),i}))}detach(t,e={}){if(!this.isActive())throw new g(d.ErrClientNotActivated,`${this.key} is not active`);const r=this.attachmentMap.get(t.getKey());if(!r)throw new g(d.ErrDocumentNotAttached,`${t.getKey()} is not attached`);return t.update((s,i)=>i.clear()),this.enqueueTask(async()=>this.rpcClient.detachDocument({clientId:this.id,documentId:r.docID,changePack:V.toChangePack(t.createChangePack()),removeIfNotAttached:e.removeIfNotAttached??!1},{headers:{"x-shard-key":`${this.apiKey}/${t.getKey()}`}}).then(s=>{const i=V.fromChangePack(s.changePack);return t.applyChangePack(i),t.getStatus()!==rr.Removed&&t.applyStatus(rr.Detached),this.detachInternal(t.getKey()),x.info(`[DD] c:"${this.getKey()}" detaches d:"${t.getKey()}"`),t}).catch(s=>{throw x.error(`[DD] c:"${this.getKey()}" err :`,s),this.handleConnectError(s),s}))}async changeSyncMode(t,e){if(!this.isActive())throw new g(d.ErrClientNotActivated,`${this.key} is not active`);const r=this.attachmentMap.get(t.getKey());if(!r)throw new g(d.ErrDocumentNotAttached,`${t.getKey()} is not attached`);const s=r.syncMode;return s===e?t:(r.changeSyncMode(e),e==="manual"?(r.cancelWatchStream(),t):(e==="realtime"&&(r.remoteChangeEventReceived=!0),s==="manual"&&await this.runWatchLoop(t.getKey()),t))}sync(t){if(!this.isActive())throw new g(d.ErrClientNotActivated,`${this.key} is not active`);if(t){const e=this.attachmentMap.get(t.getKey());if(!e)throw new g(d.ErrDocumentNotAttached,`${t.getKey()} is not attached`);return this.enqueueTask(async()=>this.syncInternal(e,"realtime").catch(r=>{throw x.error(`[SY] c:"${this.getKey()}" err :`,r),this.handleConnectError(r),r}))}return this.enqueueTask(async()=>{const e=[];for(const[,r]of this.attachmentMap)e.push(this.syncInternal(r,r.syncMode));return Promise.all(e).catch(r=>{throw x.error(`[SY] c:"${this.getKey()}" err :`,r),this.handleConnectError(r),r})})}remove(t){if(!this.isActive())throw new g(d.ErrClientNotActivated,`${this.key} is not active`);const e=this.attachmentMap.get(t.getKey());if(!e)throw new g(d.ErrDocumentNotAttached,`${t.getKey()} is not attached`);t.setActor(this.id);const r=V.toChangePack(t.createChangePack());return r.isRemoved=!0,this.enqueueTask(async()=>this.rpcClient.removeDocument({clientId:this.id,documentId:e.docID,changePack:r},{headers:{"x-shard-key":`${this.apiKey}/${t.getKey()}`}}).then(s=>{const i=V.fromChangePack(s.changePack);t.applyChangePack(i),this.detachInternal(t.getKey()),x.info(`[RD] c:"${this.getKey()}" removes d:"${t.getKey()}"`)}).catch(s=>{throw x.error(`[RD] c:"${this.getKey()}" err :`,s),this.handleConnectError(s),s}))}getID(){return this.id}getKey(){return this.key}isActive(){return this.status==="activated"}getStatus(){return this.status}getCondition(t){return this.conditions[t]}broadcast(t,e,r,s){if(!this.isActive())throw new g(d.ErrClientNotActivated,`${this.key} is not active`);const i=this.attachmentMap.get(t);if(!i)throw new g(d.ErrDocumentNotAttached,`${t} is not attached`);if(!fl(r))throw new g(d.ErrInvalidArgument,"payload is not serializable");const o=(s==null?void 0:s.maxRetries)??os.maxRetries,c=os.maxBackoff;let l=0;const h=p=>Math.min(os.initialRetryInterval*2**p,c),f=async()=>this.enqueueTask(async()=>this.rpcClient.broadcast({clientId:this.id,documentId:i.docID,topic:e,payload:new TextEncoder().encode(JSON.stringify(r))},{headers:{"x-shard-key":`${this.apiKey}/${t}`}}).then(()=>{x.info(`[BC] c:"${this.getKey()}" broadcasts d:"${t}" t:"${e}"`)}).catch(p=>{if(x.error(`[BC] c:"${this.getKey()}" err:`,p),this.handleConnectError(p))if(lf(),h(l-1)),x.info(`[BC] c:"${this.getKey()}" retry attempt ${l}/${o}`);else throw x.error(`[BC] c:"${this.getKey()}" exceeded maximum retry attempts`),p;else throw p}));return f()}runSyncLoop(){const t=()=>{if(!this.isActive()){x.debug(`[SL] c:"${this.getKey()}" exit sync loop`),this.conditions.SyncLoop=!1;return}const e=[];for(const[,r]of this.attachmentMap)r.needRealtimeSync()&&(r.remoteChangeEventReceived=!1,e.push(this.syncInternal(r,r.syncMode)));Promise.all(e).then(()=>setTimeout(t,this.syncLoopDuration)).catch(r=>{x.error(`[SL] c:"${this.getKey()}" sync failed:`,r),this.handleConnectError(r)?setTimeout(t,this.retrySyncLoopDelay):this.conditions.SyncLoop=!1})};x.debug(`[SL] c:"${this.getKey()}" run sync loop`),this.conditions.SyncLoop=!0,t()}async runWatchLoop(t){const e=this.attachmentMap.get(t);if(!e)throw new g(d.ErrDocumentNotAttached,`${t} is not attached`);return this.conditions.WatchLoop=!0,e.runWatchLoop(r=>{if(!this.isActive())return this.conditions.WatchLoop=!1,Promise.reject(new g(d.ErrClientNotActivated,`${this.key} is not active`));const s=new AbortController,i=this.rpcClient.watchDocument({clientId:this.id,documentId:e.docID},{headers:{"x-shard-key":`${this.apiKey}/${t}`},signal:s.signal});return e.doc.publish([{type:_.ConnectionChanged,value:Js.Connected}]),x.info(`[WD] c:"${this.getKey()}" watches d:"${t}"`),new Promise((o,c)=>{(async()=>{try{for await(const h of i)this.handleWatchDocumentsResponse(e,h),h.body.case==="initialization"&&o([i,s])}catch(h){e.doc.resetOnlineClients(),e.doc.publish([{type:_.Initialized,source:J.Local,value:e.doc.getPresences()}]),e.doc.publish([{type:_.ConnectionChanged,value:Js.Disconnected}]),x.debug(`[WD] c:"${this.getKey()}" unwatches`),this.handleConnectError(h)?r():this.conditions.WatchLoop=!1,c(h)}})()})})}handleWatchDocumentsResponse(t,e){if(e.body.case==="event"&&e.body.value.type===pr.DOCUMENT_CHANGED){t.remoteChangeEventReceived=!0;return}t.doc.applyWatchStream(e)}deactivateInternal(){this.status="deactivated";for(const[t,e]of this.attachmentMap)this.detachInternal(t),e.doc.applyStatus(rr.Detached)}detachInternal(t){const e=this.attachmentMap.get(t);e&&(e.cancelWatchStream(),e.unsubscribeBroadcastEvent(),this.attachmentMap.delete(t))}syncInternal(t,e){const{doc:r,docID:s}=t,i=r.createChangePack();return this.rpcClient.pushPullChanges({clientId:this.id,documentId:s,changePack:V.toChangePack(i),pushOnly:e==="realtime-pushonly"},{headers:{"x-shard-key":`${this.apiKey}/${r.getKey()}`}}).then(o=>{const c=V.fromChangePack(o.changePack);if(c.hasChanges()&&(t.syncMode==="realtime-pushonly"||t.syncMode==="realtime-syncoff"))return r;r.applyChangePack(c),t.doc.publish([{type:_.SyncStatusChanged,value:Fs.Synced}]),r.getStatus()===rr.Removed&&this.detachInternal(r.getKey());const l=r.getKey(),h=c.getChangeSize();return x.info(`[PP] c:"${this.getKey()}" sync d:"${l}", push:${i.getChangeSize()} pull:${h} cp:${c.getCheckpoint().toTestString()}`),r}).catch(o=>{throw r.publish([{type:_.SyncStatusChanged,value:Fs.SyncFailed}]),x.error(`[PP] c:"${this.getKey()}" err :`,o),o})}handleConnectError(t){return t instanceof G?t.code===R.Canceled||t.code===R.Unknown||t.code===R.ResourceExhausted||t.code===R.Unavailable?!0:((Vi(t)===d.ErrClientNotActivated||Vi(t)===d.ErrClientNotFound)&&this.deactivateInternal(),!1):!1}enqueueTask(t){return new Promise((e,r)=>{this.taskQueue.push(()=>t().then(e).catch(r)),this.processing||this.processNext()})}async processNext(){if(this.taskQueue.length===0){this.processing=!1;return}try{this.processing=!0,await this.taskQueue.shift()()}catch{x.error(`[TQ] c:"${this.getKey()}" process failed, id:"${this.id}"`)}this.processNext()}}const Hi={Client:oa,Document:ia,Primitive:$,Text:Yn,Counter:Xn,Tree:Zn,LogLevel:ee,setLogLevel:ta,IntType:ze.IntegerCnt,LongType:ze.LongCnt};typeof globalThis<"u"&&(globalThis.yorkie={Client:oa,Document:ia,Primitive:$,Text:Yn,Counter:Xn,Tree:Zn,LogLevel:ee,setLogLevel:ta,IntType:ze.IntegerCnt,LongType:ze.LongCnt});const Yi=["Ali","Beatriz","Charles","Diya","Eric","Fatima","Gabriel","Hanna","Johnson","Perry","Parker","Kelly"],dl=()=>{const n=Math.floor(Math.random()*Yi.length);return Yi[n]},Xi=["red","yellow","orange","green","blue","purple"],gl=()=>{const n=Math.floor(Math.random()*Xi.length);return Xi[n]};async function ml(){const n=new Hi.Client("https://api.yorkie.dev",{apiKey:"cedaovjuioqlk4pjqn6g"});await n.activate();const t=new Hi.Document("profile-stack",{enableDevtools:!0});t.subscribe("presence",e=>{e.type!==_.PresenceChanged&&pl(t.getPresences(),n.getID())}),await n.attach(t,{initialPresence:{name:dl(),color:gl()}}),window.addEventListener("beforeunload",()=>{n.deactivate()})}const as=4,cs=(n,t,e)=>{const r=document.createElement("div");return r.className="peer",e==="main"?r.innerHTML=`
    profile diff --git a/examples/profile-stack/index.html b/examples/profile-stack/index.html index c344aeac8..6cedf529e 100644 --- a/examples/profile-stack/index.html +++ b/examples/profile-stack/index.html @@ -5,7 +5,7 @@ Profile Stack - Yorkie Example - + diff --git a/examples/react-tldraw/assets/index-Bx94zqRc.js b/examples/react-tldraw/assets/index-DiI1EHxC.js similarity index 99% rename from examples/react-tldraw/assets/index-Bx94zqRc.js rename to examples/react-tldraw/assets/index-DiI1EHxC.js index ed3e0184d..14ccb9ef7 100644 --- a/examples/react-tldraw/assets/index-Bx94zqRc.js +++ b/examples/react-tldraw/assets/index-DiI1EHxC.js @@ -547,7 +547,7 @@ For more information, see https://radix-ui.com/primitives/docs/components/alert- * limitations under the License. * * SPDX-License-Identifier: Apache-2.0 - */var wi=null;try{wi=new WebAssembly.Instance(new WebAssembly.Module(new Uint8Array([0,97,115,109,1,0,0,0,1,13,2,96,0,1,127,96,4,127,127,127,127,1,127,3,7,6,0,1,1,1,1,1,6,6,1,127,1,65,0,11,7,50,6,3,109,117,108,0,1,5,100,105,118,95,115,0,2,5,100,105,118,95,117,0,3,5,114,101,109,95,115,0,4,5,114,101,109,95,117,0,5,8,103,101,116,95,104,105,103,104,0,0,10,191,1,6,4,0,35,0,11,36,1,1,126,32,0,173,32,1,173,66,32,134,132,32,2,173,32,3,173,66,32,134,132,126,34,4,66,32,135,167,36,0,32,4,167,11,36,1,1,126,32,0,173,32,1,173,66,32,134,132,32,2,173,32,3,173,66,32,134,132,127,34,4,66,32,135,167,36,0,32,4,167,11,36,1,1,126,32,0,173,32,1,173,66,32,134,132,32,2,173,32,3,173,66,32,134,132,128,34,4,66,32,135,167,36,0,32,4,167,11,36,1,1,126,32,0,173,32,1,173,66,32,134,132,32,2,173,32,3,173,66,32,134,132,129,34,4,66,32,135,167,36,0,32,4,167,11,36,1,1,126,32,0,173,32,1,173,66,32,134,132,32,2,173,32,3,173,66,32,134,132,130,34,4,66,32,135,167,36,0,32,4,167,11])),{}).exports}catch{}function at(e,t,n){this.low=e|0,this.high=t|0,this.unsigned=!!n}at.prototype.__isLong__;Object.defineProperty(at.prototype,"__isLong__",{value:!0});function qn(e){return(e&&e.__isLong__)===!0}function Sx(e){var t=Math.clz32(e&-e);return e?31-t:t}at.isLong=qn;var xx={},Ax={};function _l(e,t){var n,r,i;return t?(e>>>=0,(i=0<=e&&e<256)&&(r=Ax[e],r)?r:(n=ct(e,0,!0),i&&(Ax[e]=n),n)):(e|=0,(i=-128<=e&&e<128)&&(r=xx[e],r)?r:(n=ct(e,e<0?-1:0,!1),i&&(xx[e]=n),n))}at.fromInt=_l;function Si(e,t){if(isNaN(e))return t?hs:qi;if(t){if(e<0)return hs;if(e>=FP)return _P}else{if(e<=-Dx)return yr;if(e+1>=Dx)return OP}return e<0?Si(-e,t).neg():ct(e%ld|0,e/ld|0,t)}at.fromNumber=Si;function ct(e,t,n){return new at(e,t,n)}at.fromBits=ct;var om=Math.pow;function OC(e,t,n){if(e.length===0)throw Error("empty string");if(typeof t=="number"?(n=t,t=!1):t=!!t,e==="NaN"||e==="Infinity"||e==="+Infinity"||e==="-Infinity")return t?hs:qi;if(n=n||10,n<2||360)throw Error("interior hyphen");if(r===0)return OC(e.substring(1),t,n).neg();for(var i=Si(om(n,8)),o=qi,a=0;a>>0:this.low};he.toNumber=function(){return this.unsigned?(this.high>>>0)*ld+(this.low>>>0):this.high*ld+(this.low>>>0)};he.toString=function(t){if(t=t||10,t<2||36>>0,h=d.toString(t);if(a=u,a.isZero())return h+s;for(;h.length<6;)h="0"+h;s=""+h+s}};he.getHighBits=function(){return this.high};he.getHighBitsUnsigned=function(){return this.high>>>0};he.getLowBits=function(){return this.low};he.getLowBitsUnsigned=function(){return this.low>>>0};he.getNumBitsAbs=function(){if(this.isNegative())return this.eq(yr)?64:this.neg().getNumBitsAbs();for(var t=this.high!=0?this.high:this.low,n=31;n>0&&!(t&1<=0};he.isOdd=function(){return(this.low&1)===1};he.isEven=function(){return(this.low&1)===0};he.equals=function(t){return qn(t)||(t=co(t)),this.unsigned!==t.unsigned&&this.high>>>31===1&&t.high>>>31===1?!1:this.high===t.high&&this.low===t.low};he.eq=he.equals;he.notEquals=function(t){return!this.eq(t)};he.neq=he.notEquals;he.ne=he.notEquals;he.lessThan=function(t){return this.comp(t)<0};he.lt=he.lessThan;he.lessThanOrEqual=function(t){return this.comp(t)<=0};he.lte=he.lessThanOrEqual;he.le=he.lessThanOrEqual;he.greaterThan=function(t){return this.comp(t)>0};he.gt=he.greaterThan;he.greaterThanOrEqual=function(t){return this.comp(t)>=0};he.gte=he.greaterThanOrEqual;he.ge=he.greaterThanOrEqual;he.compare=function(t){if(qn(t)||(t=co(t)),this.eq(t))return 0;var n=this.isNegative(),r=t.isNegative();return n&&!r?-1:!n&&r?1:this.unsigned?t.high>>>0>this.high>>>0||t.high===this.high&&t.low>>>0>this.low>>>0?-1:1:this.sub(t).isNegative()?-1:1};he.comp=he.compare;he.negate=function(){return!this.unsigned&&this.eq(yr)?yr:this.not().add(Ic)};he.neg=he.negate;he.add=function(t){qn(t)||(t=co(t));var n=this.high>>>16,r=this.high&65535,i=this.low>>>16,o=this.low&65535,a=t.high>>>16,s=t.high&65535,u=t.low>>>16,d=t.low&65535,h=0,p=0,g=0,m=0;return m+=o+d,g+=m>>>16,m&=65535,g+=i+u,p+=g>>>16,g&=65535,p+=r+s,h+=p>>>16,p&=65535,h+=n+a,h&=65535,ct(g<<16|m,h<<16|p,this.unsigned)};he.subtract=function(t){return qn(t)||(t=co(t)),this.add(t.neg())};he.sub=he.subtract;he.multiply=function(t){if(this.isZero())return this;if(qn(t)||(t=co(t)),wi){var n=wi.mul(this.low,this.high,t.low,t.high);return ct(n,wi.get_high(),this.unsigned)}if(t.isZero())return this.unsigned?hs:qi;if(this.eq(yr))return t.isOdd()?yr:qi;if(t.eq(yr))return this.isOdd()?yr:qi;if(this.isNegative())return t.isNegative()?this.neg().mul(t.neg()):this.neg().mul(t).neg();if(t.isNegative())return this.mul(t.neg()).neg();if(this.lt(Ix)&&t.lt(Ix))return Si(this.toNumber()*t.toNumber(),this.unsigned);var r=this.high>>>16,i=this.high&65535,o=this.low>>>16,a=this.low&65535,s=t.high>>>16,u=t.high&65535,d=t.low>>>16,h=t.low&65535,p=0,g=0,m=0,v=0;return v+=a*h,m+=v>>>16,v&=65535,m+=o*h,g+=m>>>16,m&=65535,m+=a*d,g+=m>>>16,m&=65535,g+=i*h,p+=g>>>16,g&=65535,g+=o*d,p+=g>>>16,g&=65535,g+=a*u,p+=g>>>16,g&=65535,p+=r*h+i*d+o*u+a*s,p&=65535,ct(m<<16|v,p<<16|g,this.unsigned)};he.mul=he.multiply;he.divide=function(t){if(qn(t)||(t=co(t)),t.isZero())throw Error("division by zero");if(wi){if(!this.unsigned&&this.high===-2147483648&&t.low===-1&&t.high===-1)return this;var n=(this.unsigned?wi.div_u:wi.div_s)(this.low,this.high,t.low,t.high);return ct(n,wi.get_high(),this.unsigned)}if(this.isZero())return this.unsigned?hs:qi;var r,i,o;if(this.unsigned){if(t.unsigned||(t=t.toUnsigned()),t.gt(this))return hs;if(t.gt(this.shru(1)))return LP;o=hs}else{if(this.eq(yr)){if(t.eq(Ic)||t.eq(gy))return yr;if(t.eq(yr))return Ic;var a=this.shr(1);return r=a.div(t).shl(1),r.eq(qi)?t.isNegative()?Ic:gy:(i=this.sub(t.mul(r)),o=r.add(i.div(t)),o)}else if(t.eq(yr))return this.unsigned?hs:qi;if(this.isNegative())return t.isNegative()?this.neg().div(t.neg()):this.neg().div(t).neg();if(t.isNegative())return this.div(t.neg()).neg();o=qi}for(i=this;i.gte(t);){r=Math.max(1,Math.floor(i.toNumber()/t.toNumber()));for(var s=Math.ceil(Math.log(r)/Math.LN2),u=s<=48?1:om(2,s-48),d=Si(r),h=d.mul(t);h.isNegative()||h.gt(i);)r-=u,d=Si(r,this.unsigned),h=d.mul(t);d.isZero()&&(d=Ic),o=o.add(d),i=i.sub(h)}return o};he.div=he.divide;he.modulo=function(t){if(qn(t)||(t=co(t)),wi){var n=(this.unsigned?wi.rem_u:wi.rem_s)(this.low,this.high,t.low,t.high);return ct(n,wi.get_high(),this.unsigned)}return this.sub(this.div(t).mul(t))};he.mod=he.modulo;he.rem=he.modulo;he.not=function(){return ct(~this.low,~this.high,this.unsigned)};he.countLeadingZeros=function(){return this.high?Math.clz32(this.high):Math.clz32(this.low)+32};he.clz=he.countLeadingZeros;he.countTrailingZeros=function(){return this.low?Sx(this.low):Sx(this.high)+32};he.ctz=he.countTrailingZeros;he.and=function(t){return qn(t)||(t=co(t)),ct(this.low&t.low,this.high&t.high,this.unsigned)};he.or=function(t){return qn(t)||(t=co(t)),ct(this.low|t.low,this.high|t.high,this.unsigned)};he.xor=function(t){return qn(t)||(t=co(t)),ct(this.low^t.low,this.high^t.high,this.unsigned)};he.shiftLeft=function(t){return qn(t)&&(t=t.toInt()),(t&=63)===0?this:t<32?ct(this.low<>>32-t,this.unsigned):ct(0,this.low<>>t|this.high<<32-t,this.high>>t,this.unsigned):ct(this.high>>t-32,this.high>=0?0:-1,this.unsigned)};he.shr=he.shiftRight;he.shiftRightUnsigned=function(t){return qn(t)&&(t=t.toInt()),(t&=63)===0?this:t<32?ct(this.low>>>t|this.high<<32-t,this.high>>>t,this.unsigned):t===32?ct(this.high,0,this.unsigned):ct(this.high>>>t-32,0,this.unsigned)};he.shru=he.shiftRightUnsigned;he.shr_u=he.shiftRightUnsigned;he.rotateLeft=function(t){var n;return qn(t)&&(t=t.toInt()),(t&=63)===0?this:t===32?ct(this.high,this.low,this.unsigned):t<32?(n=32-t,ct(this.low<>>n,this.high<>>n,this.unsigned)):(t-=32,n=32-t,ct(this.high<>>n,this.low<>>n,this.unsigned))};he.rotl=he.rotateLeft;he.rotateRight=function(t){var n;return qn(t)&&(t=t.toInt()),(t&=63)===0?this:t===32?ct(this.high,this.low,this.unsigned):t<32?(n=32-t,ct(this.high<>>t,this.low<>>t,this.unsigned)):(t-=32,n=32-t,ct(this.low<>>t,this.high<>>t,this.unsigned))};he.rotr=he.rotateRight;he.toSigned=function(){return this.unsigned?ct(this.low,this.high,!1):this};he.toUnsigned=function(){return this.unsigned?this:ct(this.low,this.high,!0)};he.toBytes=function(t){return t?this.toBytesLE():this.toBytesBE()};he.toBytesLE=function(){var t=this.high,n=this.low;return[n&255,n>>>8&255,n>>>16&255,n>>>24,t&255,t>>>8&255,t>>>16&255,t>>>24]};he.toBytesBE=function(){var t=this.high,n=this.low;return[t>>>24,t>>>16&255,t>>>8&255,t&255,n>>>24,n>>>16&255,n>>>8&255,n&255]};at.fromBytes=function(t,n,r){return r?at.fromBytesLE(t,n):at.fromBytesBE(t,n)};at.fromBytesLE=function(t,n){return new at(t[0]|t[1]<<8|t[2]<<16|t[3]<<24,t[4]|t[5]<<8|t[6]<<16|t[7]<<24,n)};at.fromBytesBE=function(t,n){return new at(t[4]<<24|t[5]<<16|t[6]<<8|t[7],t[0]<<24|t[1]<<16|t[2]<<8|t[3],n)};var Cn=(e=>(e[e.Null=0]="Null",e[e.Boolean=1]="Boolean",e[e.Integer=2]="Integer",e[e.Long=3]="Long",e[e.Double=4]="Double",e[e.String=5]="String",e[e.Bytes=6]="Bytes",e[e.Date=7]="Date",e))(Cn||{});class Gt extends Fh{constructor(n,r){super(r);A(this,"valueType");A(this,"value");this.valueType=Gt.getPrimitiveType(n),this.value=n===void 0?null:n}static of(n,r){return new Gt(n,r)}static valueFromBytes(n,r){switch(n){case 0:return null;case 1:return!!r[0];case 2:return r[0]|r[1]<<8|r[2]<<16|r[3]<<24;case 4:{const i=new DataView(r.buffer);return r.forEach(function(o,a){i.setUint8(a,o)}),i.getFloat64(0,!0)}case 5:return new TextDecoder("utf-8").decode(r);case 3:return at.fromBytesLE(Array.from(r));case 6:return r;case 7:return new Date(at.fromBytesLE(Array.from(r),!0).toNumber());default:throw new Y(W.ErrUnimplemented,`unimplemented type: ${n}`)}}toJSON(){return this.valueType===5?`"${Oo(this.value)}"`:`${this.value}`}toSortedJSON(){return this.toJSON()}toJSForTest(){return{createdAt:this.getCreatedAt().toTestString(),value:this.value,type:"YORKIE_PRIMITIVE"}}deepcopy(){const n=Gt.of(this.value,this.getCreatedAt());return n.setMovedAt(this.getMovedAt()),n.setRemovedAt(this.getRemovedAt()),n}getType(){return this.valueType}static getPrimitiveType(n){switch(typeof n){case"undefined":return 0;case"boolean":return 1;case"number":return this.isInteger(n)?2:4;case"string":return 5;case"object":if(n===null)return 0;if(n instanceof at)return 3;if(n instanceof Uint8Array)return 6;if(n instanceof Date)return 7}}static isSupport(n){return Gt.getPrimitiveType(n)!==void 0}static isInteger(n){return n%1===0}isNumericType(){const n=this.valueType;return n===2||n===3||n===4}getValue(){return this.value}toBytes(){switch(this.valueType){case 0:return new Uint8Array;case 1:return this.value?new Uint8Array([1]):new Uint8Array([0]);case 2:{const n=this.value;return new Uint8Array([n&255,n>>8&255,n>>16&255,n>>24&255])}case 4:{const n=this.value,r=new Uint8Array(8);return new DataView(r.buffer).setFloat64(0,n,!0),r}case 5:return new TextEncoder().encode(this.value);case 3:{const r=this.value.toBytesLE();return Uint8Array.from(r)}case 6:return this.value;case 7:{const n=this.value,r=at.fromNumber(n.getTime(),!0).toBytesLE();return Uint8Array.from(r)}default:throw new Y(W.ErrUnimplemented,`unimplemented type: ${this.valueType}`)}}}class am extends RP{constructor(n){super(n);A(this,"prev");A(this,"next");this.value=n}static createAfter(n,r){const i=new am(r),o=n.next;return n.next=i,i.prev=n,i.next=o,o&&(o.prev=i),i}remove(n){return this.value.remove(n)}getCreatedAt(){return this.value.getCreatedAt()}getPositionedAt(){return this.value.getPositionedAt()}release(){this.prev&&(this.prev.next=this.next),this.next&&(this.next.prev=this.prev),this.prev=void 0,this.next=void 0}getLength(){return this.value.isRemoved()?0:1}getPrev(){return this.prev}getNext(){return this.next}getValue(){return this.value}isRemoved(){return this.value.isRemoved()}}class dh{constructor(){A(this,"dummyHead");A(this,"last");A(this,"nodeMapByIndex");A(this,"nodeMapByCreatedAt");const t=Gt.of(0,to);t.setRemovedAt(to),this.dummyHead=new am(t),this.last=this.dummyHead,this.nodeMapByIndex=new ch,this.nodeMapByCreatedAt=new Map,this.nodeMapByIndex.insert(this.dummyHead),this.nodeMapByCreatedAt.set(this.dummyHead.getCreatedAt().toIDString(),this.dummyHead)}static create(){return new dh}get length(){return this.nodeMapByIndex.length}findNextBeforeExecutedAt(t,n){let r=this.nodeMapByCreatedAt.get(t.toIDString());if(!r)throw new Y(W.ErrInvalidArgument,`cant find the given node: ${t.toIDString()}`);for(;r.getNext()&&r.getNext().getPositionedAt().after(n);)r=r.getNext();return r}release(t){this.last===t&&(this.last=t.getPrev()),t.release(),this.nodeMapByIndex.delete(t),this.nodeMapByCreatedAt.delete(t.getValue().getCreatedAt().toIDString())}insertAfter(t,n,r=n.getCreatedAt()){const i=this.findNextBeforeExecutedAt(t,r),o=am.createAfter(i,n);i===this.last&&(this.last=o),this.nodeMapByIndex.insertAfter(i,o),this.nodeMapByCreatedAt.set(o.getCreatedAt().toIDString(),o)}moveAfter(t,n,r){const i=this.nodeMapByCreatedAt.get(t.toIDString());if(!i)throw new Y(W.ErrInvalidArgument,`cant find the given node: ${t.toIDString()}`);const o=this.nodeMapByCreatedAt.get(n.toIDString());if(!o)throw new Y(W.ErrInvalidArgument,`cant find the given node: ${n.toIDString()}`);i!==o&&(!o.getValue().getMovedAt()||r.after(o.getValue().getMovedAt()))&&(this.release(o),this.insertAfter(i.getCreatedAt(),o.getValue(),r),o.getValue().setMovedAt(r))}insert(t){this.insertAfter(this.last.getCreatedAt(),t)}getByID(t){return this.nodeMapByCreatedAt.get(t.toIDString())}subPathOf(t){const n=this.nodeMapByCreatedAt.get(t.toIDString());if(n)return String(this.nodeMapByIndex.indexOf(n))}purge(t){const n=this.nodeMapByCreatedAt.get(t.getCreatedAt().toIDString());if(!n)throw new Y(W.ErrInvalidArgument,`fail to find the given createdAt: ${t.getCreatedAt().toIDString()}`);this.release(n)}getByIndex(t){if(t>=this.length)return;const[n,r]=this.nodeMapByIndex.find(t);let i=n;if(t===0&&n===this.dummyHead||r>0)do i&&(i=i.getNext());while(i&&i.isRemoved());return i}getPrevCreatedAt(t){let n=this.nodeMapByCreatedAt.get(t.toIDString());do n=n.getPrev();while(this.dummyHead!==n&&n.isRemoved());return n.getValue().getCreatedAt()}delete(t,n){const r=this.nodeMapByCreatedAt.get(t.toIDString()),i=r.isRemoved();return r.remove(n)&&!i&&this.nodeMapByIndex.splayNode(r),r.getValue()}deleteByIndex(t,n){const r=this.getByIndex(t);if(r)return r.remove(n)&&this.nodeMapByIndex.splayNode(r),r.getValue()}getHead(){return this.dummyHead.getValue()}getLast(){return this.last.getValue()}getLastCreatedAt(){return this.last.getCreatedAt()}toTestString(){const t=[];for(const n of this){const r=`${n.getCreatedAt().toIDString()}:${n.getValue().toJSON()}`;n.isRemoved()?t.push(`{${r}}`):t.push(`[${r}]`)}return t.join("")}*[Symbol.iterator](){let t=this.dummyHead.getNext();for(;t;)yield t,t=t.getNext()}}class Ur extends vu{constructor(n,r){super(n);A(this,"elements");this.elements=r}static create(n,r){if(!r)return new Ur(n,dh.create());const i=dh.create();for(const o of r)i.insertAfter(i.getLastCreatedAt(),o.deepcopy());return new Ur(n,i)}subPathOf(n){return this.elements.subPathOf(n)}purge(n){this.elements.purge(n)}insertAfter(n,r){this.elements.insertAfter(n,r)}moveAfter(n,r,i){this.elements.moveAfter(n,r,i)}get(n){const r=this.elements.getByIndex(n);return r==null?void 0:r.getValue()}getByID(n){const r=this.elements.getByID(n);return r==null?void 0:r.getValue()}getHead(){return this.elements.getHead()}getLast(){return this.elements.getLast()}getPrevCreatedAt(n){return this.elements.getPrevCreatedAt(n)}delete(n,r){return this.elements.delete(n,r)}deleteByIndex(n,r){return this.elements.deleteByIndex(n,r)}getLastCreatedAt(){return this.elements.getLastCreatedAt()}get length(){return this.elements.length}*[Symbol.iterator](){for(const n of this.elements)n.isRemoved()||(yield n.getValue())}toTestString(){return this.elements.toTestString()}getDescendants(n){for(const r of this.elements){const i=r.getValue();if(n(i,this))return;i instanceof vu&&i.getDescendants(n)}}toJSON(){const n=[];for(const r of this)n.push(r.toJSON());return`[${n.join(",")}]`}toJS(){return JSON.parse(this.toJSON())}toJSForTest(){const n={};for(let r=0;r({...m,value:m.value?{attributes:zc(m.value.getAttributes()),content:m.value.getContent()}:{attributes:void 0,content:""},type:"content"}));return[d,g,h,[u,u]]}setStyle(n,r,i,o){const[,a]=this.rgaTreeSplit.findNodeWithSplit(n[1],i),[,s]=this.rgaTreeSplit.findNodeWithSplit(n[0],i),u=[],d=this.rgaTreeSplit.findBetween(s,a),h=new Map,p=[];for(const m of d){const v=m.getCreatedAt().getActorID(),E=o!=null&&o.size?o.has(v)?o.get(v):to:M0;if(m.canStyle(i,E)){const w=h.get(v),C=m.getCreatedAt();(!w||C.after(w))&&h.set(v,C),p.push(m)}}const g=[];for(const m of p){if(m.isRemoved())continue;const[v,E]=this.rgaTreeSplit.findIndexesFromRange(m.createPosRange());u.push({type:"style",actor:i.getActorID(),from:v,to:E,value:{attributes:zc(r)}});for(const[w,C]of Object.entries(r)){const[b]=m.getValue().setAttr(w,C,i);b!==void 0&&g.push({parent:m.getValue(),child:b})}}return[h,g,u]}indexRangeToPosRange(n,r){const i=this.rgaTreeSplit.indexToPos(n);return n===r?[i,i]:[i,this.rgaTreeSplit.indexToPos(r)]}get length(){return this.rgaTreeSplit.length}getTreeByIndex(){return this.rgaTreeSplit.getTreeByIndex()}getTreeByID(){return this.rgaTreeSplit.getTreeByID()}toJSON(){const n=[];for(const r of this.rgaTreeSplit)r.isRemoved()||n.push(r.getValue().toJSON());return`[${n.join(",")}]`}toSortedJSON(){return this.toJSON()}toJSForTest(){return{createdAt:this.getCreatedAt().toTestString(),value:JSON.parse(this.toJSON()),type:"YORKIE_TEXT"}}toString(){return this.rgaTreeSplit.toString()}values(){const n=[];for(const r of this.rgaTreeSplit)if(!r.isRemoved()){const i=r.getValue();n.push({attributes:zc(i.getAttributes()),content:i.getContent()})}return n}getRGATreeSplit(){return this.rgaTreeSplit}toTestString(){return this.rgaTreeSplit.toTestString()}deepcopy(){const n=new Ti(this.rgaTreeSplit.deepcopy(),this.getCreatedAt());return n.remove(this.getRemovedAt()),n}findIndexesFromRange(n){return this.rgaTreeSplit.findIndexesFromRange(n)}getGCPairs(){const n=[];for(const r of this.rgaTreeSplit){r.getRemovedAt()&&n.push({parent:this.rgaTreeSplit,child:r});for(const i of r.getValue().getGCPairs())n.push(i)}return n}}class Oh extends so{constructor(n,r,i,o,a,s,u){super(n,u);A(this,"fromPos");A(this,"toPos");A(this,"maxCreatedAtMapByActor");A(this,"content");A(this,"attributes");this.fromPos=r,this.toPos=i,this.maxCreatedAtMapByActor=o,this.content=a,this.attributes=s}static create(n,r,i,o,a,s,u){return new Oh(n,r,i,o,a,s,u)}execute(n){const r=n.findByCreatedAt(this.getParentCreatedAt());if(!r)throw new Y(W.ErrInvalidArgument,`fail to find ${this.getParentCreatedAt()}`);if(!(r instanceof Ti))throw new Y(W.ErrInvalidArgument,"fail to execute, only Text can execute edit");const i=r,[,o,a]=i.edit([this.fromPos,this.toPos],this.content,this.getExecutedAt(),Object.fromEntries(this.attributes),this.maxCreatedAtMapByActor);for(const s of a)n.registerGCPair(s);return{opInfos:o.map(({from:s,to:u,value:d})=>({type:"edit",from:s,to:u,value:d,path:n.createPath(this.getParentCreatedAt())}))}}getEffectedCreatedAt(){return this.getParentCreatedAt()}toTestString(){const n=this.getParentCreatedAt().toTestString(),r=this.fromPos.toTestString(),i=this.toPos.toTestString(),o=this.content;return`${n}.EDIT(${r},${i},${o})`}getFromPos(){return this.fromPos}getToPos(){return this.toPos}getContent(){return this.content}getAttributes(){return this.attributes||new Map}getMaxCreatedAtMapByActor(){return this.maxCreatedAtMapByActor}}class _h extends so{constructor(n,r,i,o,a,s){super(n,s);A(this,"fromPos");A(this,"toPos");A(this,"maxCreatedAtMapByActor");A(this,"attributes");this.fromPos=r,this.toPos=i,this.maxCreatedAtMapByActor=o,this.attributes=a}static create(n,r,i,o,a,s){return new _h(n,r,i,o,a,s)}execute(n){const r=n.findByCreatedAt(this.getParentCreatedAt());if(!r)throw new Y(W.ErrInvalidArgument,`fail to find ${this.getParentCreatedAt()}`);if(!(r instanceof Ti))throw new Y(W.ErrInvalidArgument,"fail to execute, only Text can execute edit");const i=r,[,o,a]=i.setStyle([this.fromPos,this.toPos],this.attributes?Object.fromEntries(this.attributes):{},this.getExecutedAt(),this.maxCreatedAtMapByActor);for(const s of o)n.registerGCPair(s);return{opInfos:a.map(({from:s,to:u,value:d})=>({type:"style",from:s,to:u,value:d,path:n.createPath(this.getParentCreatedAt())}))}}getEffectedCreatedAt(){return this.getParentCreatedAt()}toTestString(){const n=this.getParentCreatedAt().toTestString(),r=this.fromPos.toTestString(),i=this.toPos.toTestString(),o=this.attributes;return`${n}.STYL(${r},${i},${JSON.stringify(o)})`}getFromPos(){return this.fromPos}getToPos(){return this.toPos}getAttributes(){return this.attributes}getMaxCreatedAtMapByActor(){return this.maxCreatedAtMapByActor}}const mKe=2,vKe="root",vs="text";function a0(e,t){let n=0;const r=e.children;for(let i=0;i0)throw new Y(W.ErrRefused,"Text node cannot have children")}updateAncestorsSize(){let t=this.parent;const n=this.isRemoved?-1:1;for(;t&&(t.size+=this.paddedSize*n,!t.isRemoved);)t=t.parent}updateDescendantsSize(){let t=0;for(const n of this._children){const r=n.updateDescendantsSize();n.isRemoved||(t+=r)}return this.size+=t,this.paddedSize}get isText(){return this.type===vs}get paddedSize(){return this.size+(this.isText?0:mKe)}isAncestorOf(t){return EKe(this,t)}get nextSibling(){const t=this.parent.findOffset(this),n=this.parent.children[t+1];if(n)return n}get prevSibling(){const t=this.parent.findOffset(this),n=this.parent.children[t-1];if(n)return n}splitText(t,n){if(t===0||t===this.size)return;const r=this.value.slice(0,t),i=this.value.slice(t);if(!i.length)return;this.value=r;const o=this.cloneText(t+n);return o.value=i,this.parent.insertAfterInternal(o,this),o}get children(){return this._children.filter(t=>!t.isRemoved)}get allChildren(){return[...this._children]}hasTextChild(){return this.children.length>0&&this.children.every(t=>t.isText)}append(...t){if(this.isText)throw new Y(W.ErrRefused,"Text node cannot have children");this._children.push(...t);for(const n of t)n.parent=this,n.updateAncestorsSize()}prepend(...t){if(this.isText)throw new Y(W.ErrRefused,"Text node cannot have children");this._children.unshift(...t);for(const n of t)n.parent=this}insertBefore(t,n){if(this.isText)throw new Y(W.ErrRefused,"Text node cannot have children");const r=this._children.indexOf(n);if(r===-1)throw new Y(W.ErrInvalidArgument,"child not found");this.insertAtInternal(t,r),t.updateAncestorsSize()}insertAfter(t,n){if(this.isText)throw new Y(W.ErrRefused,"Text node cannot have children");const r=this._children.indexOf(n);if(r===-1)throw new Y(W.ErrInvalidArgument,"child not found");this.insertAtInternal(t,r+1),t.updateAncestorsSize()}insertAt(t,n){if(this.isText)throw new Y(W.ErrRefused,"Text node cannot have children");this.insertAtInternal(t,n),t.updateAncestorsSize()}removeChild(t){if(this.isText)throw new Y(W.ErrRefused,"Text node cannot have children");const n=this._children.indexOf(t);if(n===-1)throw new Y(W.ErrInvalidArgument,"child not found");this._children.splice(n,1),t.parent=void 0}splitElement(t,n){const r=this.cloneElement(n);this.parent.insertAfterInternal(r,this),r.updateAncestorsSize();const i=this.children.slice(0,t),o=this.children.slice(t);this._children=i,r._children=o,this.size=this._children.reduce((a,s)=>a+s.paddedSize,0),r.size=r._children.reduce((a,s)=>a+s.paddedSize,0);for(const a of r._children)a.parent=r;return r}insertAfterInternal(t,n){if(this.isText)throw new Y(W.ErrRefused,"Text node cannot have children");const r=this._children.indexOf(n);if(r===-1)throw new Y(W.ErrInvalidArgument,"child not found");this.insertAtInternal(t,r+1)}insertAtInternal(t,n){if(this.isText)throw new Y(W.ErrRefused,"Text node cannot have children");this._children.splice(n,0,t),t.parent=this}findOffset(t){if(this.isText)throw new Y(W.ErrRefused,"Text node cannot have children");if(t.isRemoved){const n=this._children.indexOf(t);return this.allChildren.splice(0,n).filter(i=>!i.isRemoved).length}return this.children.indexOf(t)}findBranchOffset(t){if(this.isText)throw new Y(W.ErrRefused,"Text node cannot have children");let n=t;for(;n;){const r=this._children.indexOf(n);if(r!==-1)return r;n=n.parent}return-1}}function EKe(e,t){if(e===t)return!1;for(;t.parent;){if(t.parent===e)return!0;t=t.parent}return!1}var sn=(e=>(e.Start="Start",e.End="End",e.Text="Text",e))(sn||{});function NP(e,t,n,r){if(t>n)throw new Y(W.ErrInvalidArgument,`from is greater than to: ${t} > ${n}`);if(t>e.size)throw new Y(W.ErrInvalidArgument,`from is out of range: ${t} > ${e.size}`);if(n>e.size)throw new Y(W.ErrInvalidArgument,`to is out of range: ${n} > ${e.size}`);if(t===n)return;let i=0;for(const o of e.children){if(t-o.paddedSizeo.size;(o.isText||u)&&r([o,o.isText?"Text":"Start"],d),NP(o,Math.max(0,a),Math.min(s,o.size),r),d&&r([o,"End"],d)}i+=o.paddedSize}}function zP(e,t,n=0){for(const r of e.children)zP(r,t,n+1);t(e,n)}function y1(e,t,n=0){for(const r of e._children)y1(r,t,n+1);t(e,n)}function my(e,t,n=!0){if(t>e.size)throw new Y(W.ErrInvalidArgument,`index is out of range: ${t} > ${e.size}`);if(e.isText)return{node:e,offset:t};let r=0,i=0;for(const o of e.children){if(n&&o.isText&&o.size>=t-i)return my(o,t-i,n);if(t===i)return{node:e,offset:r};if(!n&&o.paddedSize===t-i)return{node:e,offset:r+1};if(o.paddedSize>t-i)return my(o,t-i-1,n);i+=o.paddedSize,r+=1}return{node:e,offset:r}}function HP(e){return e.isText||e.children.length===0?e:HP(e.children[0])}function CKe(e,t){if(e.sizee===t?0:e0)if(n.right)n.right.parent=n,n=n.right;else return n;else if(r<0)if(n.left)n.left.parent=n,n=n.left;else{let i=n.parent,o=n;for(;i&&o===i.left;)o=i,i=i.parent;return i}else return n}}lastEntry(){if(!this.root)return this.root;let t=this.root;for(;t.right;)t=t.right;return t}size(){return this.counter}isEmpty(){return this.counter===0}getInternal(t,n){for(;n;){const r=this.comparator(t,n.key);if(r===0)return n;r<0?n=n.left:r>0&&(n=n.right)}}putInternal(t,n,r){if(!r)return this.counter+=1,new SKe(t,n,!0);const i=this.comparator(t,r.key);return i<0?r.left=this.putInternal(t,n,r.left):i>0?r.right=this.putInternal(t,n,r.right):r.value=n,this.isRed(r.right)&&!this.isRed(r.left)&&(r=this.rotateLeft(r)),this.isRed(r.left)&&this.isRed(r.left.left)&&(r=this.rotateRight(r)),this.isRed(r.left)&&this.isRed(r.right)&&this.flipColors(r),r}removeInternal(t,n){if(this.comparator(n,t.key)<0)!this.isRed(t.left)&&!this.isRed(t.left.left)&&(t=this.moveRedLeft(t)),t.left=this.removeInternal(t.left,n);else{if(this.isRed(t.left)&&(t=this.rotateRight(t)),this.comparator(n,t.key)===0&&!t.right){this.counter-=1;return}if(!this.isRed(t.right)&&!this.isRed(t.right.left)&&(t=this.moveRedRight(t)),this.comparator(n,t.key)===0){this.counter-=1;const r=this.min(t.right);t.value=r.value,t.key=r.key,t.right=this.removeMin(t.right)}else t.right=this.removeInternal(t.right,n)}return this.fixUp(t)}min(t){return t.left?this.min(t.left):t}removeMin(t){if(t.left)return!this.isRed(t.left)&&!this.isRed(t.left.left)&&(t=this.moveRedLeft(t)),t.left=this.removeMin(t.left),this.fixUp(t)}fixUp(t){return this.isRed(t.right)&&(t=this.rotateLeft(t)),this.isRed(t.left)&&this.isRed(t.left.left)&&(t=this.rotateRight(t)),this.isRed(t.left)&&this.isRed(t.right)&&this.flipColors(t),t}moveRedLeft(t){return this.flipColors(t),this.isRed(t.right.left)&&(t.right=this.rotateRight(t.right),t=this.rotateLeft(t),this.flipColors(t)),t}moveRedRight(t){return this.flipColors(t),this.isRed(t.left.left)&&(t=this.rotateRight(t),this.flipColors(t)),t}isRed(t){return t&&t.isRed}rotateLeft(t){const n=t.right;return t.right=n.left,n.left=t,n.isRed=n.left.isRed,n.left.isRed=!0,n}rotateRight(t){const n=t.left;return t.left=n.right,n.right=t,n.isRed=n.right.isRed,n.right.isRed=!0,n}flipColors(t){t.isRed=!t.isRed,t.left.isRed=!t.left.isRed,t.right.isRed=!t.right.isRed}}class Xi{constructor(t,n){A(this,"parentID");A(this,"leftSiblingID");this.parentID=t,this.leftSiblingID=n}static of(t,n){return new Xi(t,n)}static fromTreePos(t){const{offset:n}=t;let{node:r}=t,i;return r.isText?(r.parent.children[0]===r&&n===0?i=r.parent:i=r,r=r.parent):n===0?i=r:i=r.children[n-1],Xi.of(r.id,Rn.of(i.getCreatedAt(),i.getOffset()+n))}getParentID(){return this.parentID}static fromStruct(t){return Xi.of(Rn.of(jr.fromStruct(t.parentID.createdAt),t.parentID.offset),Rn.of(jr.fromStruct(t.leftSiblingID.createdAt),t.leftSiblingID.offset))}toStruct(){return{parentID:{createdAt:this.getParentID().getCreatedAt().toStruct(),offset:this.getParentID().getOffset()},leftSiblingID:{createdAt:this.getLeftSiblingID().getCreatedAt().toStruct(),offset:this.getLeftSiblingID().getOffset()}}}toTreeNodePair(t){const n=this.getParentID(),r=this.getLeftSiblingID(),i=t.findFloorNode(n);let o=t.findFloorNode(r);if(!i||!o)throw new Y(W.ErrRefused,`cannot find node of CRDTTreePos(${n.toTestString()}, ${r.toTestString()})`);return!r.equals(n)&&r.getOffset()>0&&r.getOffset()===o.id.getOffset()&&o.insPrevID&&(o=t.findFloorNode(o.insPrevID)),[i,o]}getLeftSiblingID(){return this.leftSiblingID}equals(t){return this.getParentID().getCreatedAt().equals(t.getParentID().getCreatedAt())&&this.getParentID().getOffset()===t.getParentID().getOffset()&&this.getLeftSiblingID().getCreatedAt().equals(t.getLeftSiblingID().getCreatedAt())&&this.getLeftSiblingID().getOffset()===t.getLeftSiblingID().getOffset()}}class Rn{constructor(t,n){A(this,"createdAt");A(this,"offset");this.createdAt=t,this.offset=n}static of(t,n){return new Rn(t,n)}static fromStruct(t){return Rn.of(jr.fromStruct(t.createdAt),t.offset)}static createComparator(){return(t,n)=>{const r=t.getCreatedAt().compare(n.getCreatedAt());return r!==0?r:t.getOffset()>n.getOffset()?1:t.getOffset(){const o=i.deepcopy();return o.parent=n,o}),n.insPrevID=this.insPrevID,n.insNextID=this.insNextID,n}get value(){if(!this.isText)throw new Y(W.ErrInvalidType,`cannot get value of element node: ${this.type}`);return this._value}set value(n){if(!this.isText)throw new Y(W.ErrInvalidType,`cannot set value of element node: ${this.type}`);this._value=n,this.size=n.length}get isRemoved(){return!!this.removedAt}remove(n){const r=!this.removedAt;(!this.removedAt||this.removedAt.compare(n)>0)&&(this.removedAt=n),r&&this.updateAncestorsSize()}cloneText(n){return new Nr(Rn.of(this.id.getCreatedAt(),n),this.type,void 0,void 0,this.removedAt)}cloneElement(n){return new Nr(Rn.of(n(),0),this.type,void 0,void 0,this.removedAt)}split(n,r,i){const o=this.isText?this.splitText(r,this.id.getOffset()):this.splitElement(r,i);if(o){if(o.insPrevID=this.id,this.insNextID){const a=n.findFloorNode(this.insNextID);a.insPrevID=o.id,o.insNextID=this.insNextID}this.insNextID=o.id,n.registerNode(o)}return o}getCreatedAt(){return this.id.getCreatedAt()}getOffset(){return this.id.getOffset()}canDelete(n,r){return!this.getCreatedAt().after(r)&&(!this.removedAt||n.after(this.removedAt))}canStyle(n,r){return this.isText?!1:!this.getCreatedAt().after(r)&&(!this.removedAt||n.after(this.removedAt))}setAttrs(n,r){this.attrs||(this.attrs=new Is);const i=new Array;for(const[o,a]of Object.entries(n))i.push(this.attrs.set(o,a,r));return i}purge(n){this.attrs&&this.attrs.purge(n)}getGCPairs(){const n=[];if(!this.attrs)return n;for(const r of this.attrs)r.getRemovedAt()&&n.push({parent:this,child:r});return n}}function vy(e){var n;if(e.isText){const r=e;return{type:r.type,value:r.value}}const t={type:e.type,children:e.children.map(vy)};return e.attrs&&(t.attributes=zc((n=e.attrs)==null?void 0:n.toObject())),t}function _C(e){if(e.isText)return e.value;let t="";return e.attrs&&e.attrs.size()&&(t=" "+Array.from(e.attrs).filter(n=>!n.isRemoved()).sort((n,r)=>n.getKey().localeCompare(r.getKey())).map(n=>{const r=JSON.parse(n.getValue());return typeof r=="string"?`${n.getKey()}="${r}"`:`${n.getKey()}="${Oo(n.getValue())}"`}).join(" ")),`<${e.type}${t}>${e.children.map(n=>_C(n)).join("")}`}function UP(e){if(e.isText){const t=e;return{type:t.type,value:t.value,size:t.size,isRemoved:t.isRemoved}}return{type:e.type,children:e.children.map(UP),size:e.size,isRemoved:e.isRemoved}}class Pi extends Fh{constructor(n,r){super(r);A(this,"indexTree");A(this,"nodeMapByID");this.indexTree=new bKe(n),this.nodeMapByID=new jP(Rn.createComparator()),this.indexTree.traverseAll(i=>{this.nodeMapByID.put(i.id,i)})}static create(n,r){return new Pi(n,r)}findFloorNode(n){const r=this.nodeMapByID.floorEntry(n);if(!(!r||!r.key.getCreatedAt().equals(n.getCreatedAt())))return r.value}registerNode(n){this.nodeMapByID.put(n.id,n)}findNodesAndSplitText(n,r){const[i,o]=n.toTreeNodePair(this);let a=o;const s=i===a,u=a.parent&&!s?a.parent:i;if(a.isText&&a.split(this,n.getLeftSiblingID().getOffset()-a.id.getOffset()),r){const d=u.allChildren,h=s?0:d.indexOf(a)+1;for(let p=h;p{const E=v.getCreatedAt().getActorID(),w=o?o.has(E)?o.get(E):to:M0;if(v.canStyle(i,w)&&r){const C=g.get(E),b=v.getCreatedAt();(!C||b.after(C))&&g.set(E,b);const k=v.setAttrs(r,i),I=k.reduce((D,[,$])=>($&&(D[$.getKey()]=p[$.getKey()]),D),{}),B=v.parent,T=v.prevSibling||v.parent;Object.keys(I).length>0&&h.push({type:"style",from:this.toIndex(B,T),to:this.toIndex(v,v),fromPath:this.toPath(B,T),toPath:this.toPath(v,v),actor:i.getActorID(),value:I});for(const[D]of k)D&&m.push({parent:v,child:D})}}),[g,m,h]}removeStyle(n,r,i,o){const[a,s]=this.findNodesAndSplitText(n[0],i),[u,d]=this.findNodesAndSplitText(n[1],i),h=[],p=new Map,g=[];return this.traverseInPosRange(a,s,u,d,([m])=>{const v=m.getCreatedAt().getActorID(),E=o?o.has(v)?o.get(v):to:M0;if(m.canStyle(i,E)&&r){const w=p.get(v),C=m.getCreatedAt();(!w||C.after(w))&&p.set(v,C),m.attrs||(m.attrs=new Is);for(const I of r){const B=m.attrs.remove(I,i);for(const T of B)g.push({parent:m,child:T})}const b=m.parent,k=m.prevSibling||m.parent;h.push({actor:i.getActorID(),type:"removeStyle",from:this.toIndex(b,k),to:this.toIndex(m,m),fromPath:this.toPath(b,k),toPath:this.toPath(m,m),value:r})}}),[p,g,h]}edit(n,r,i,o,a,s){const[u,d]=this.findNodesAndSplitText(n[0],o),[h,p]=this.findNodesAndSplitText(n[1],o),g=this.toIndex(u,d),m=this.toPath(u,d),v=[],E=[],w=[],C=new Map;this.traverseInPosRange(u,d,h,p,([I,B],T)=>{if(B===sn.Start&&!T)for(const O of I.children)w.push(O);const D=I.getCreatedAt().getActorID(),$=s?s.has(D)?s.get(D):to:M0;if(I.canDelete(o,$)||v.includes(I.parent)){const O=C.get(D),H=I.getCreatedAt();(!O||H.after(O))&&C.set(D,H),(B===sn.Text||B===sn.Start)&&v.push(I),E.push([I,B])}});const b=this.makeDeletionChanges(E,o),k=[];for(const I of v)I.remove(o),I.isRemoved&&k.push({parent:this,child:I});for(const I of w)I.removedAt||u.append(I);if(i>0){let I=0,B=u,T=d;for(;I{u.isRemoved&&(D.remove(o),k.push({parent:this,child:D})),this.nodeMapByID.put(D.id,D)}),T.isRemoved||I.push(T);if(I.length){const T=I.map(D=>vy(D));b.length&&b[b.length-1].from===g?b[b.length-1].value=T:b.push({type:"content",from:g,to:g,fromPath:m,toPath:m,actor:o.getActorID(),value:T})}}return[b,k,C]}editT(n,r,i,o,a){const s=this.findPos(n[0]),u=this.findPos(n[1]);this.edit([s,u],r,i,o,a)}move(n,r,i){throw new Y(W.ErrUnimplemented,`not implemented: ${n}, ${r}, ${i}`)}purge(n){var o;(o=n.parent)==null||o.removeChild(n),this.nodeMapByID.remove(n.id);const r=n.insPrevID,i=n.insNextID;if(r){const a=this.findFloorNode(r);a.insNextID=i}if(i){const a=this.findFloorNode(i);a.insPrevID=r}n.insPrevID=void 0,n.insNextID=void 0}getGCPairs(){const n=[];return this.indexTree.traverse(r=>{r.getRemovedAt()&&n.push({parent:this,child:r});for(const i of r.getGCPairs())n.push(i)}),n}findPos(n,r=!0){const i=this.indexTree.findTreePos(n,r);return Xi.fromTreePos(i)}pathToPosRange(n){const r=this.pathToIndex(n);return[this.findPos(r),this.findPos(r+1)]}pathToPos(n){const r=this.indexTree.pathToIndex(n);return this.findPos(r)}getRoot(){return this.indexTree.getRoot()}getSize(){return this.indexTree.size}getNodeSize(){return this.nodeMapByID.size()}getIndexTree(){return this.indexTree}toXML(){return _C(this.indexTree.getRoot())}toJSON(){return JSON.stringify(this.getRootTreeNode())}toJSForTest(){return{createdAt:this.getCreatedAt().toTestString(),value:JSON.parse(this.toJSON()),type:"YORKIE_TREE"}}toJSInfoForTest(){const n=this.indexTree.getRoot(),r=(i,o=void 0,a=void 0,s=0)=>{var m,v,E,w;let u,d,h;const p=i.isText?{node:i,offset:0}:o&&a?this.toTreePos(o,a):null;p&&(u=this.indexTree.indexOf(p),d=this.indexTree.treePosToPath(p),h=Xi.fromTreePos(p).toStruct());const g={type:i.type,parent:o==null?void 0:o.id.toTestString(),size:i.size,id:i.id.toTestString(),removedAt:(m=i.removedAt)==null?void 0:m.toTestString(),insPrev:(v=i.insPrevID)==null?void 0:v.toTestString(),insNext:(E=i.insNextID)==null?void 0:E.toTestString(),value:i.isText?i.value:void 0,isRemoved:i.isRemoved,children:[],depth:s,attributes:i.attrs?zc((w=i.attrs)==null?void 0:w.toObject()):void 0,index:u,path:d,pos:h};for(let C=0;C0&&C===i[i.length-1].to?(i[i.length-1].to=b,i[i.length-1].toPath=this.toPath(w,m)):i.push({type:"content",from:C,to:b,fromPath:this.toPath(E,p),toPath:this.toPath(w,m),actor:r.getActorID()}))}return i.reverse()}findRightToken([n,r]){if(r===sn.Start){const u=n.allChildren;return u.length>0?[u[0],u[0].isText?sn.Text:sn.Start]:[n,sn.End]}const i=n.parent,o=i.allChildren,a=o.indexOf(n);if(i&&a===o.length-1)return[i,sn.End];const s=o[a+1];return[s,s.isText?sn.Text:sn.Start]}findLeftToken([n,r]){if(r===sn.End){const u=n.allChildren;if(u.length>0){const d=u[u.length-1];return[d,d.isText?sn.Text:sn.End]}return[n,sn.Start]}const i=n.parent,o=i.allChildren,a=o.indexOf(n);if(i&&a===0)return[i,sn.Start];const s=o[a-1];return[s,s.isText?sn.Text:sn.End]}}class Nh extends so{constructor(n,r,i,o,a,s,u){super(n,u);A(this,"fromPos");A(this,"toPos");A(this,"contents");A(this,"splitLevel");A(this,"maxCreatedAtMapByActor");this.fromPos=r,this.toPos=i,this.contents=o,this.splitLevel=a,this.maxCreatedAtMapByActor=s}static create(n,r,i,o,a,s,u){return new Nh(n,r,i,o,a,s,u)}execute(n){var u;const r=n.findByCreatedAt(this.getParentCreatedAt());if(!r)throw new Y(W.ErrInvalidArgument,`fail to find ${this.getParentCreatedAt()}`);if(!(r instanceof Pi))throw new Y(W.ErrInvalidArgument,"fail to execute, only Tree can execute edit");const i=this.getExecutedAt(),o=r,[a,s]=o.edit([this.fromPos,this.toPos],(u=this.contents)==null?void 0:u.map(d=>d.deepcopy()),this.splitLevel,i,(()=>{let d=i.getDelimiter();return this.contents!==void 0&&(d+=this.contents.length),()=>jr.of(i.getLamport(),++d,i.getActorID())})(),this.maxCreatedAtMapByActor);for(const d of s)n.registerGCPair(d);return{opInfos:a.map(({from:d,to:h,value:p,splitLevel:g,fromPath:m,toPath:v})=>({type:"tree-edit",path:n.createPath(this.getParentCreatedAt()),from:d,to:h,value:p,splitLevel:g,fromPath:m,toPath:v}))}}getEffectedCreatedAt(){return this.getParentCreatedAt()}toTestString(){const n=this.getParentCreatedAt().toTestString(),r=`${this.fromPos.getLeftSiblingID().getCreatedAt().toTestString()}/${this.fromPos.getLeftSiblingID().getOffset()}`,i=`${this.toPos.getLeftSiblingID().getCreatedAt().toTestString()}/${this.toPos.getLeftSiblingID().getOffset()}`,o=this.contents||[];return`${n}.EDIT(${r},${i},${o.map(a=>_C(a)).join("")})`}getFromPos(){return this.fromPos}getToPos(){return this.toPos}getContents(){return this.contents}getSplitLevel(){return this.splitLevel}getMaxCreatedAtMapByActor(){return this.maxCreatedAtMapByActor}}class Hc{constructor(t){A(this,"vector");this.vector=t||new Map}set(t,n){this.vector.set(t,n)}get(t){return this.vector.get(t)}maxLamport(){let t=BigInt(0);for(const[,n]of this)n>t&&(t=n);return t}max(t){const n=new Map;for(const[r,i]of t){const o=this.vector.get(r),a=o&&o>i?o:i;n.set(r,a)}for(const[r,i]of this){const o=t.get(r),a=o&&o>i?o:i;n.set(r,a)}return new Hc(n)}afterOrEqual(t){const n=this.vector.get(t.getActorID());return n===void 0?!1:n>=t.getLamport()}deepcopy(){const t=new Map;for(const[n,r]of this.vector)t.set(n,r);return new Hc(t)}filter(t){const n=new Map;for(const[r]of t){const i=this.vector.get(r);i!==void 0&&n.set(r,i)}return new Hc(n)}size(){return this.vector.size}*[Symbol.iterator](){for(const[t,n]of this.vector)yield[t,n]}}const AKe=new Hc(new Map);class as{constructor(t,n,r,i,o){A(this,"clientSeq");A(this,"serverSeq");A(this,"lamport");A(this,"actor");A(this,"versionVector");this.clientSeq=t,this.serverSeq=o,this.lamport=n,this.versionVector=i,this.actor=r}static of(t,n,r,i,o){return new as(t,n,r,i,o)}next(){const t=this.versionVector.deepcopy();return t.set(this.actor,this.lamport+1n),new as(this.clientSeq+1,this.lamport+1n,this.actor,t)}syncClocks(t){const n=t.lamport>this.lamport?t.lamport+1n:this.lamport+1n,r=this.versionVector.max(t.versionVector),i=new as(this.clientSeq,n,this.actor,r);return i.versionVector.set(this.actor,n),i}setClocks(t,n){const r=t>this.lamport?t:this.lamport+1n,i=this.versionVector.max(n);return i.set(this.actor,r),as.of(this.clientSeq,r,this.actor,i)}createTimeTicket(t){return jr.of(this.lamport,t,this.actor)}setActor(t){return new as(this.clientSeq,this.lamport,t,this.versionVector,this.serverSeq)}setVersionVector(t){return new as(this.clientSeq,this.lamport,this.actor,t,this.serverSeq)}getClientSeq(){return this.clientSeq}getServerSeq(){return this.serverSeq?this.serverSeq.toString():""}getLamport(){return this.lamport}getLamportAsString(){return this.lamport.toString()}getActorID(){return this.actor}getVersionVector(){return this.versionVector}toTestString(){return`${this.lamport.toString()}:${this.actor.slice(-2)}:${this.clientSeq}`}}const kKe=new as(0,0n,FC,AKe);class cd{constructor({id:t,operations:n,presenceChange:r,message:i}){A(this,"id");A(this,"operations");A(this,"presenceChange");A(this,"message");this.id=t,this.operations=n||[],this.presenceChange=r,this.message=i}static create({id:t,operations:n,presenceChange:r,message:i}){return new cd({id:t,operations:n,presenceChange:r,message:i})}getID(){return this.id}getMessage(){return this.message}hasOperations(){return this.operations.length>0}getOperations(){return this.operations}setActor(t){for(const n of this.operations)n.setActor(t);this.id=this.id.setActor(t)}hasPresenceChange(){return this.presenceChange!==void 0}getPresenceChange(){return this.presenceChange}execute(t,n,r){const i=[],o=[];for(const a of this.operations){const s=a.execute(t,r);if(!s)continue;const{opInfos:u,reverseOp:d}=s;i.push(...u),d&&o.unshift(d)}return this.presenceChange&&(this.presenceChange.type===Iu.Put?n.set(this.id.getActorID(),Gi(this.presenceChange.presence)):n.delete(this.id.getActorID())),{opInfos:i,reverseOps:o}}toTestString(){return`${this.operations.map(t=>t.toTestString()).join(",")}`}toStruct(){return{changeID:rn.bytesToHex(rn.toChangeID(this.getID()).toBinary()),message:this.getMessage(),operations:this.getOperations().map(t=>rn.bytesToHex(rn.toOperation(t).toBinary())),presenceChange:this.getPresenceChange()}}static fromStruct(t){const{changeID:n,operations:r,presenceChange:i,message:o}=t;return cd.create({id:rn.bytesToChangeID(rn.hexToBytes(n)),operations:r==null?void 0:r.map(a=>rn.bytesToOperation(rn.hexToBytes(a))),presenceChange:i,message:o})}}class E1{constructor(t,n,r,i,o,a,s){A(this,"documentKey");A(this,"checkpoint");A(this,"isRemoved");A(this,"changes");A(this,"snapshot");A(this,"minSyncedTicket");A(this,"versionVector");this.documentKey=t,this.checkpoint=n,this.isRemoved=r,this.changes=i,this.snapshot=a,this.minSyncedTicket=s,this.versionVector=o}static create(t,n,r,i,o,a,s){return new E1(t,n,r,i,o,a,s)}getDocumentKey(){return this.documentKey}getCheckpoint(){return this.checkpoint}getIsRemoved(){return this.isRemoved}getChanges(){return this.changes}hasChanges(){return this.changes.length>0}getChangeSize(){return this.changes.length}hasSnapshot(){return!!this.snapshot&&!!this.snapshot.length}getSnapshot(){return this.snapshot}getMinSyncedTicket(){return this.minSyncedTicket}getVersionVector(){return this.versionVector}}class jc{constructor(t,n){A(this,"serverSeq");A(this,"clientSeq");this.serverSeq=t,this.clientSeq=n}static of(t,n){return new jc(t,n)}increaseClientSeq(t){return t===0?this:new jc(this.serverSeq,this.clientSeq+t)}forward(t){if(this.equals(t))return this;const n=this.serverSeq>t.serverSeq?this.serverSeq:t.serverSeq,r=Math.max(this.clientSeq,t.clientSeq);return jc.of(n,r)}getServerSeqAsString(){return this.serverSeq.toString()}getClientSeq(){return this.clientSeq}getServerSeq(){return this.serverSeq}equals(t){return this.clientSeq===t.clientSeq&&this.serverSeq==t.serverSeq}toTestString(){return`serverSeq=${this.serverSeq}, clientSeq=${this.clientSeq}`}}const DKe=new jc(0n,0);class zo{constructor(t,n){A(this,"createdAt");A(this,"offset");this.createdAt=t,this.offset=n}static of(t,n){return new zo(t,n)}static fromStruct(t){return zo.of(jr.fromStruct(t.createdAt),t.offset)}getCreatedAt(){return this.createdAt}getOffset(){return this.offset}equals(t){return this.createdAt.compare(t.createdAt)===0&&this.offset===t.offset}hasSameCreatedAt(t){return this.createdAt.compare(t.createdAt)===0}split(t){return new zo(this.createdAt,this.offset+t)}toStruct(){return{createdAt:this.createdAt.toStruct(),offset:this.offset}}toTestString(){return`${this.createdAt.toTestString()}:${this.offset}`}toIDString(){return`${this.createdAt.toIDString()}:${this.offset}`}}const IKe=zo.of(to,0);class no{constructor(t,n){A(this,"id");A(this,"relativeOffset");this.id=t,this.relativeOffset=n}static of(t,n){return new no(t,n)}static fromStruct(t){const n=zo.fromStruct(t.id);return no.of(n,t.relativeOffset)}getID(){return this.id}getRelativeOffset(){return this.relativeOffset}getAbsoluteID(){return zo.of(this.id.getCreatedAt(),this.id.getOffset()+this.relativeOffset)}toTestString(){return`${this.id.toTestString()}:${this.relativeOffset}`}toStruct(){return{id:this.id.toStruct(),relativeOffset:this.relativeOffset}}equals(t){return this.id.equals(t.id)?this.relativeOffset===t.relativeOffset:!1}}class yu extends RP{constructor(n,r,i){super(r);A(this,"id");A(this,"removedAt");A(this,"prev");A(this,"next");A(this,"insPrev");A(this,"insNext");this.id=n,this.removedAt=i}static create(n,r){return new yu(n,r)}static createComparator(){return(n,r)=>{const i=n.getCreatedAt().compare(r.getCreatedAt());return i!==0?i:n.getOffset()>r.getOffset()?1:n.getOffset()0&&n.getID().getOffset()==t.getOffset()){if(!n.hasInsPrev())return n;n=n.getInsPrev()}return n}findFloorNode(t){const n=this.treeByID.floorEntry(t);if(n&&!(!n.key.equals(t)&&!n.key.hasSameCreatedAt(t)))return n.value}findBetween(t,n){const r=[];let i=t;for(;i&&i!==n;)r.push(i),i=i.getNext();return r}splitNode(t,n){if(n>t.getContentLength())throw new Y(W.ErrInvalidArgument,"offset should be less than or equal to length");if(n===0)return t;if(n===t.getContentLength())return t.getNext();const r=t.split(n);this.treeByIndex.updateWeight(r),this.insertAfter(t,r);const i=t.getInsNext();return i&&i.setInsPrev(r),r.setInsPrev(t),r}deleteNodes(t,n,r){if(!t.length)return[[],new Map,new Map];const[i,o]=this.filterNodes(t,n,r),a=new Map,s=new Map,u=this.makeChanges(o,n);for(const d of i){const h=d.getCreatedAt().getActorID();(!a.has(h)||d.getID().getCreatedAt().after(a.get(h)))&&a.set(h,d.getID().getCreatedAt()),s.set(d.getID().toIDString(),d),d.remove(n)}return this.deleteIndexNodes(o),[u,a,s]}filterNodes(t,n,r){const i=!!r,o=[],a=[],[s,u]=this.findEdgesOfCandidates(t);a.push(s);for(const d of t){const h=d.getCreatedAt().getActorID(),p=i?r.has(h)?r.get(h):to:M0;d.canDelete(n,p)?o.push(d):a.push(d)}return a.push(u),[o,a]}findEdgesOfCandidates(t){return[t[0].getPrev(),t[t.length-1].getNext()]}makeChanges(t,n){const r=[];let i,o;for(let a=0;ae<0?Math.ceil(e):Math.floor(e);var Ko=(e=>(e[e.IntegerCnt=0]="IntegerCnt",e[e.LongCnt=1]="LongCnt",e))(Ko||{});class Kr extends Fh{constructor(n,r,i){super(i);A(this,"valueType");A(this,"value");switch(this.valueType=n,n){case 0:typeof r=="number"?r>Math.pow(2,31)-1||r<-Math.pow(2,31)?this.value=at.fromNumber(r).toInt():this.value=Tx(r):this.value=r.toInt();break;case 1:typeof r=="number"?this.value=at.fromNumber(r):this.value=r;break;default:throw new Y(W.ErrUnimplemented,`unimplemented type: ${n}`)}}static create(n,r,i){return new Kr(n,r,i)}static valueFromBytes(n,r){switch(n){case 0:return r[0]|r[1]<<8|r[2]<<16|r[3]<<24;case 1:return at.fromBytesLE(Array.from(r));default:throw new Y(W.ErrUnimplemented,`unimplemented type: ${n}`)}}toJSON(){return`${this.value}`}toSortedJSON(){return this.toJSON()}toJSForTest(){return{createdAt:this.getCreatedAt().toTestString(),value:this.value,type:"YORKIE_COUNTER"}}deepcopy(){const n=Kr.create(this.valueType,this.value,this.getCreatedAt());return n.setMovedAt(this.getMovedAt()),n}getType(){return this.valueType}static getCounterType(n){switch(typeof n){case"object":return n instanceof at?1:void 0;case"number":return n>Math.pow(2,31)-1||n<-Math.pow(2,31)?1:0;default:return}}static isSupport(n){return!!Kr.getCounterType(n)}static isInteger(n){return n%1===0}isNumericType(){const n=this.valueType;return n===0||n===1}getValueType(){return this.valueType}getValue(){return this.value}toBytes(){switch(this.valueType){case 0:{const n=this.value;return new Uint8Array([n&255,n>>8&255,n>>16&255,n>>24&255])}case 1:{const r=this.value.toBytesLE();return Uint8Array.from(r)}default:throw new Y(W.ErrUnimplemented,`unimplemented type: ${this.valueType}`)}}increase(n){function r(i){if(!i.isNumericType())throw new TypeError(`Unsupported type of value: ${typeof i.getValue()}`)}return r(this),r(n),this.valueType===1?this.value=this.value.add(n.getValue()):n.getType()===Cn.Long?this.value=this.value+n.getValue().toInt():this.value=at.fromNumber(this.value+Tx(n.getValue())).toInt(),this}}class hd extends so{constructor(n,r,i){super(n,i);A(this,"value");this.value=r}static create(n,r,i){return new hd(n,r,i)}execute(n){const r=n.findByCreatedAt(this.getParentCreatedAt());if(!r)throw new Y(W.ErrInvalidArgument,`fail to find ${this.getParentCreatedAt()}`);if(!(r instanceof Kr))throw new Y(W.ErrInvalidArgument,"fail to execute, only Counter can execute increase");const i=r,o=this.value.deepcopy();return i.increase(o),{opInfos:[{type:"increase",path:n.createPath(this.getParentCreatedAt()),value:o.getValue()}],reverseOp:this.toReverseOperation()}}toReverseOperation(){const n=this.value.deepcopy(),i=n.getType()===Cn.Long?n.getValue().multiply(-1):n.getValue()*-1;return hd.create(this.getParentCreatedAt(),Gt.of(i,n.getCreatedAt()))}getEffectedCreatedAt(){return this.getParentCreatedAt()}toTestString(){return`${this.getParentCreatedAt().toTestString()}.INCREASE.${this.value.toJSON()}`}getValue(){return this.value}}class ys extends so{constructor(n,r,i,o,a,s,u){super(n,u);A(this,"fromPos");A(this,"toPos");A(this,"maxCreatedAtMapByActor");A(this,"attributes");A(this,"attributesToRemove");this.fromPos=r,this.toPos=i,this.maxCreatedAtMapByActor=o,this.attributes=a,this.attributesToRemove=s}static create(n,r,i,o,a,s){return new ys(n,r,i,o,a,new Array,s)}static createTreeRemoveStyleOperation(n,r,i,o,a,s){return new ys(n,r,i,o,new Map,a,s)}execute(n){const r=n.findByCreatedAt(this.getParentCreatedAt());if(!r)throw new Y(W.ErrInvalidArgument,`fail to find ${this.getParentCreatedAt()}`);if(!(r instanceof Pi))throw new Y(W.ErrInvalidArgument,"fail to execute, only Tree can execute edit");const i=r;let o,a;if(this.attributes.size){const s={};[...this.attributes].forEach(([u,d])=>s[u]=d),[,a,o]=i.style([this.fromPos,this.toPos],s,this.getExecutedAt(),this.maxCreatedAtMapByActor)}else{const s=this.attributesToRemove;[,a,o]=i.removeStyle([this.fromPos,this.toPos],s,this.getExecutedAt(),this.maxCreatedAtMapByActor)}for(const s of a)n.registerGCPair(s);return{opInfos:o.map(({from:s,to:u,value:d,fromPath:h,toPath:p})=>({type:"tree-style",from:s,to:u,value:this.attributes.size?{attributes:d}:{attributesToRemove:d},fromPath:h,toPath:p,path:n.createPath(this.getParentCreatedAt())}))}}getEffectedCreatedAt(){return this.getParentCreatedAt()}toTestString(){const n=this.getParentCreatedAt().toTestString(),r=`${this.fromPos.getLeftSiblingID().getCreatedAt().toTestString()}:${this.fromPos.getLeftSiblingID().getOffset()}`,i=`${this.toPos.getLeftSiblingID().getCreatedAt().toTestString()}:${this.toPos.getLeftSiblingID().getOffset()}`;return`${n}.STYLE(${r},${i},${Object.entries(this.attributes||{}).map(([o,a])=>`${o}:"${a}"`).join(" ")})`}getFromPos(){return this.fromPos}getToPos(){return this.toPos}getAttributes(){return this.attributes}getAttributesToRemove(){return this.attributesToRemove}getMaxCreatedAtMapByActor(){return this.maxCreatedAtMapByActor}}function TKe(e){const t=new RC,n=t.data;for(const[r,i]of Object.entries(e))n[r]=JSON.stringify(i);return t}function PKe(e){if(e.type===Iu.Put)return new uh({type:Il.PUT,presence:TKe(e.presence)});if(e.type===Iu.Clear)return new uh({type:Il.CLEAR});throw new Y(W.ErrUnimplemented,"unimplemented type")}function BKe(e){return new BP({serverSeq:e.getServerSeq(),clientSeq:e.getClientSeq()})}function KP(e){return new m1({clientSeq:e.getClientSeq(),lamport:e.getLamport(),actorId:YC(e.getActorID()),versionVector:NC(e.getVersionVector())})}function Te(e){if(e)return new De({lamport:e.getLamport(),delimiter:e.getDelimiter(),actorId:YC(e.getActorID())})}function NC(e){if(!e)return;const t=new v1;for(const[n,r]of e)t.vector[n]=BigInt(r.toString());return t}function VP(e){switch(e){case Cn.Null:return Ve.NULL;case Cn.Boolean:return Ve.BOOLEAN;case Cn.Integer:return Ve.INTEGER;case Cn.Long:return Ve.LONG;case Cn.Double:return Ve.DOUBLE;case Cn.String:return Ve.STRING;case Cn.Bytes:return Ve.BYTES;case Cn.Date:return Ve.DATE;default:throw new Y(W.ErrInvalidType,`unsupported type: ${e}`)}}function GP(e){switch(e){case Ko.IntegerCnt:return Ve.INTEGER_CNT;case Ko.LongCnt:return Ve.LONG_CNT;default:throw new Y(W.ErrInvalidType,`unsupported type: ${e}`)}}function t2(e){if(e instanceof wr)return new ci({type:Ve.JSON_OBJECT,createdAt:Te(e.getCreatedAt()),value:oB(e)});if(e instanceof Ur)return new ci({type:Ve.JSON_ARRAY,createdAt:Te(e.getCreatedAt()),value:uVe(e)});if(e instanceof Ti)return new ci({type:Ve.TEXT,createdAt:Te(e.getCreatedAt())});if(e instanceof Gt)return new ci({type:VP(e.getType()),createdAt:Te(e.getCreatedAt()),value:e.toBytes()});if(e instanceof Kr)return new ci({type:GP(e.getType()),createdAt:Te(e.getCreatedAt()),value:e.toBytes()});if(e instanceof Pi)return new ci({type:Ve.TREE,createdAt:Te(e.getCreatedAt()),value:cVe(e)});throw new Y(W.ErrUnimplemented,"unimplemented element")}function MKe(e){return new ah({createdAt:Te(e.getCreatedAt()),offset:e.getOffset()})}function bp(e){return new Ds({createdAt:Te(e.getID().getCreatedAt()),offset:e.getID().getOffset(),relativeOffset:e.getRelativeOffset()})}function wp(e){return new Dl({parentId:$0(e.getParentID()),leftSiblingId:$0(e.getLeftSiblingID())})}function $0(e){return new mu({createdAt:Te(e.getCreatedAt()),offset:e.getOffset()})}function JP(e){const t=new $C;if(e instanceof Tl){const n=e,r=new Hg;r.parentCreatedAt=Te(n.getParentCreatedAt()),r.key=n.getKey(),r.value=t2(n.getValue()),r.executedAt=Te(n.getExecutedAt()),t.body.case="set",t.body.value=r}else if(e instanceof Lh){const n=e,r=new jg;r.parentCreatedAt=Te(n.getParentCreatedAt()),r.prevCreatedAt=Te(n.getPrevCreatedAt()),r.value=t2(n.getValue()),r.executedAt=Te(n.getExecutedAt()),t.body.case="add",t.body.value=r}else if(e instanceof au){const n=e,r=new Ug;r.parentCreatedAt=Te(n.getParentCreatedAt()),r.prevCreatedAt=Te(n.getPrevCreatedAt()),r.createdAt=Te(n.getCreatedAt()),r.executedAt=Te(n.getExecutedAt()),t.body.case="move",t.body.value=r}else if(e instanceof Tu){const n=e,r=new Kg;r.parentCreatedAt=Te(n.getParentCreatedAt()),r.createdAt=Te(n.getCreatedAt()),r.executedAt=Te(n.getExecutedAt()),t.body.case="remove",t.body.value=r}else if(e instanceof Oh){const n=e,r=new Vg;r.parentCreatedAt=Te(n.getParentCreatedAt()),r.from=bp(n.getFromPos()),r.to=bp(n.getToPos());const i=r.createdAtMapByActor;for(const[a,s]of n.getMaxCreatedAtMapByActor())i[a]=Te(s);r.content=n.getContent();const o=r.attributes;for(const[a,s]of n.getAttributes())o[a]=s;r.executedAt=Te(n.getExecutedAt()),t.body.case="edit",t.body.value=r}else if(e instanceof _h){const n=e,r=new Gg;r.parentCreatedAt=Te(n.getParentCreatedAt()),r.from=bp(n.getFromPos()),r.to=bp(n.getToPos());const i=r.createdAtMapByActor;for(const[a,s]of n.getMaxCreatedAtMapByActor())i[a]=Te(s);const o=r.attributes;for(const[a,s]of n.getAttributes())o[a]=s;r.executedAt=Te(n.getExecutedAt()),t.body.case="style",t.body.value=r}else if(e instanceof hd){const n=e,r=new Jg;r.parentCreatedAt=Te(n.getParentCreatedAt()),r.value=t2(n.getValue()),r.executedAt=Te(n.getExecutedAt()),t.body.case="increase",t.body.value=r}else if(e instanceof Nh){const n=e,r=new Wg,i=r.createdAtMapByActor;for(const[o,a]of n.getMaxCreatedAtMapByActor())i[o]=Te(a);r.parentCreatedAt=Te(n.getParentCreatedAt()),r.from=wp(n.getFromPos()),r.to=wp(n.getToPos()),r.contents=NKe(n.getContents()),r.splitLevel=n.getSplitLevel(),r.executedAt=Te(n.getExecutedAt()),t.body.case="treeEdit",t.body.value=r}else if(e instanceof ys){const n=e,r=new Yg;r.parentCreatedAt=Te(n.getParentCreatedAt()),r.from=wp(n.getFromPos()),r.to=wp(n.getToPos());const i=r.createdAtMapByActor;for(const[a,s]of n.getMaxCreatedAtMapByActor())i[a]=Te(s);const o=n.getAttributesToRemove();if(o.length>0)r.attributesToRemove=o;else{const a=r.attributes;for(const[s,u]of n.getAttributes())a[s]=u}r.executedAt=Te(n.getExecutedAt()),t.body.case="treeStyle",t.body.value=r}else throw new Y(W.ErrUnimplemented,"unimplemented operation");return t}function $Ke(e){const t=[];for(const n of e)t.push(JP(n));return t}function RKe(e){const t=new TP({id:KP(e.getID()),message:e.getMessage()});return e.hasOperations()&&(t.operations=$Ke(e.getOperations())),e.hasPresenceChange()&&(t.presenceChange=PKe(e.getPresenceChange())),t}function FKe(e){const t=[];for(const n of e)t.push(RKe(n));return t}function LKe(e){const t=[];for(const n of e)t.push(new PP({key:n.getStrKey(),element:HC(n.getValue())}));return t}function OKe(e){const t=[];for(const n of e)t.push(new nm({element:HC(n.getValue())}));return t}function _Ke(e){const t=[];for(const n of e){const r=new rm;r.id=MKe(n.getID()),r.value=n.getValue().getContent(),r.removedAt=Te(n.getRemovedAt());const i=r.attributes,o=n.getValue().getAttrs();for(const a of o){const s=new sd;s.value=a.getValue(),s.updatedAt=Te(a.getUpdatedAt()),i[a.getKey()]=s}t.push(r)}return t}function NKe(e){const t=[];if(!e||!e.length)return t;for(const n of e)t.push(new im({content:zC(n)}));return t}function zKe(e){const t={};for(const n of e)t[n.getKey()]=new sd({value:n.getValue(),updatedAt:Te(n.getUpdatedAt()),isRemoved:n.isRemoved()});return t}function zC(e){if(!e)return[];const t=[];return y1(e,(n,r)=>{const i=new sh({id:$0(n.id),type:n.type,removedAt:Te(n.removedAt),depth:r});n.isText&&(i.value=n.value),n.insPrevID&&(i.insPrevId=$0(n.insPrevID)),n.insNextID&&(i.insNextId=$0(n.insNextID)),n.attrs&&(i.attributes=zKe(n.attrs)),t.push(i)}),t}function HKe(e){const t=new Sr;return t.body.case="jsonObject",t.body.value=new qg({nodes:LKe(e.getRHT()),createdAt:Te(e.getCreatedAt()),movedAt:Te(e.getMovedAt()),removedAt:Te(e.getRemovedAt())}),t}function WP(e){const t=new Sr;return t.body.case="jsonArray",t.body.value=new Xg({nodes:OKe(e.getElements()),createdAt:Te(e.getCreatedAt()),movedAt:Te(e.getMovedAt()),removedAt:Te(e.getRemovedAt())}),t}function jKe(e){const t=new Sr;return t.body.case="primitive",t.body.value=new Zg({type:VP(e.getType()),value:e.toBytes(),createdAt:Te(e.getCreatedAt()),movedAt:Te(e.getMovedAt()),removedAt:Te(e.getRemovedAt())}),t}function UKe(e){const t=new Sr;return t.body.case="text",t.body.value=new Qg({nodes:_Ke(e.getRGATreeSplit()),createdAt:Te(e.getCreatedAt()),movedAt:Te(e.getMovedAt()),removedAt:Te(e.getRemovedAt())}),t}function KKe(e){const t=new Sr;return t.body.case="counter",t.body.value=new em({type:GP(e.getType()),value:e.toBytes(),createdAt:Te(e.getCreatedAt()),movedAt:Te(e.getMovedAt()),removedAt:Te(e.getRemovedAt())}),t}function YP(e){const t=new Sr;return t.body.case="tree",t.body.value=new tm({nodes:zC(e.getRoot()),createdAt:Te(e.getCreatedAt()),movedAt:Te(e.getMovedAt()),removedAt:Te(e.getRemovedAt())}),t}function HC(e){if(e instanceof wr)return HKe(e);if(e instanceof Ur)return WP(e);if(e instanceof Gt)return jKe(e);if(e instanceof Ti)return UKe(e);if(e instanceof Kr)return KKe(e);if(e instanceof Pi)return YP(e);throw new Y(W.ErrUnimplemented,"unimplemented element")}function VKe(e){return new Rs({documentKey:e.getDocumentKey(),checkpoint:BKe(e.getCheckpoint()),isRemoved:e.getIsRemoved(),changes:FKe(e.getChanges()),snapshot:e.getSnapshot(),versionVector:NC(e.getVersionVector()),minSyncedTicket:Te(e.getMinSyncedTicket())})}function Px(e){const t=e.findDetails(sKe);for(const n of t)if(n.metadata.code)return n.metadata.code;return""}function qP(e){return as.of(e.clientSeq,BigInt(e.lamport),JC(e.actorId),jC(e.versionVector),BigInt(e.serverSeq))}function jC(e){if(!e)return;const t=new Hc;return Object.entries(e.vector).forEach(([n,r])=>{t.set(n,BigInt(r.toString()))}),t}function Pe(e){if(e)return jr.of(BigInt(e.lamport),e.delimiter,JC(e.actorId))}function UC(e){const t={};return Object.entries(e.data).forEach(([n,r])=>{t[n]=JSON.parse(r)}),t}function GKe(e){const t=e.type;if(t===Il.PUT){const n=UC(e.presence);return{type:Iu.Put,presence:n}}if(t===Il.CLEAR)return{type:Iu.Clear};throw new Y(W.ErrInvalidType,`unsupported type: ${t}`)}function JKe(e){const t=new Map;return Object.entries(e).forEach(([n,r])=>{t.set(n,UC(r))}),t}function XP(e){switch(e){case Ve.NULL:return Cn.Null;case Ve.BOOLEAN:return Cn.Boolean;case Ve.INTEGER:return Cn.Integer;case Ve.LONG:return Cn.Long;case Ve.DOUBLE:return Cn.Double;case Ve.STRING:return Cn.String;case Ve.BYTES:return Cn.Bytes;case Ve.DATE:return Cn.Date}throw new Y(W.ErrUnimplemented,`unimplemented value type: ${e}`)}function sm(e){switch(e){case Ve.INTEGER_CNT:return Ko.IntegerCnt;case Ve.LONG_CNT:return Ko.LongCnt}throw new Y(W.ErrUnimplemented,`unimplemented value type: ${e}`)}function n2(e){switch(e.type){case Ve.JSON_OBJECT:return e.value?iB(e.value):wr.create(Pe(e.createdAt));case Ve.JSON_ARRAY:return e.value?sVe(e.value):Ur.create(Pe(e.createdAt));case Ve.TEXT:return Ti.create(dd.create(),Pe(e.createdAt));case Ve.TREE:return lVe(e.value);case Ve.NULL:case Ve.BOOLEAN:case Ve.INTEGER:case Ve.LONG:case Ve.DOUBLE:case Ve.STRING:case Ve.BYTES:case Ve.DATE:return Gt.of(Gt.valueFromBytes(XP(e.type),e.value),Pe(e.createdAt));case Ve.INTEGER_CNT:case Ve.LONG_CNT:return Kr.create(sm(e.type),Kr.valueFromBytes(sm(e.type),e.value),Pe(e.createdAt))}}function Sp(e){return no.of(zo.of(Pe(e.createdAt),e.offset),e.relativeOffset)}function ZP(e){return zo.of(Pe(e.createdAt),e.offset)}function WKe(e){const t=hh.create(e.value);Object.entries(e.attributes).forEach(([r,i])=>{t.setAttr(r,i.value,Pe(i.updatedAt))});const n=yu.create(ZP(e.id),t);return n.remove(Pe(e.removedAt)),n}function dc(e){return Xi.of(R0(e.parentId),R0(e.leftSiblingId))}function R0(e){return Rn.of(Pe(e.createdAt),e.offset)}function YKe(e){if(!e.length)return;const t=[];return e.forEach(n=>{const r=KC(n.content);t.push(r)}),t}function KC(e){if(e.length===0)return;const t=[];for(const i of e)t.push(XKe(i));const n=t[t.length-1],r=new Map;r.set(e[t.length-1].depth,t[t.length-1]);for(let i=t.length-2;i>=0;i--)r.get(e[i].depth-1).prepend(t[i]),r.set(e[i].depth,t[i]);return n.updateDescendantsSize(),Pi.create(n,to).getRoot()}function qKe(e){const t=Is.create();for(const[n,r]of Object.entries(e))t.setInternal(n,r.value,Pe(r.updatedAt),r.isRemoved);return t}function XKe(e){const t=R0(e.id),n=Nr.create(t,e.type),r=Object.entries(e.attributes);return n.isText?n.value=e.value:r.length&&(n.attrs=qKe(e.attributes)),e.insPrevId&&(n.insPrevID=R0(e.insPrevId)),e.insNextId&&(n.insNextID=R0(e.insNextId)),n.removedAt=Pe(e.removedAt),n}function QP(e){if(e.body.case==="set"){const t=e.body.value;return Tl.create(t.key,n2(t.value),Pe(t.parentCreatedAt),Pe(t.executedAt))}else if(e.body.case==="add"){const t=e.body.value;return Lh.create(Pe(t.parentCreatedAt),Pe(t.prevCreatedAt),n2(t.value),Pe(t.executedAt))}else if(e.body.case==="move"){const t=e.body.value;return au.create(Pe(t.parentCreatedAt),Pe(t.prevCreatedAt),Pe(t.createdAt),Pe(t.executedAt))}else if(e.body.case==="remove"){const t=e.body.value;return Tu.create(Pe(t.parentCreatedAt),Pe(t.createdAt),Pe(t.executedAt))}else if(e.body.case==="edit"){const t=e.body.value,n=new Map;Object.entries(t.createdAtMapByActor).forEach(([i,o])=>{n.set(i,Pe(o))});const r=new Map;return Object.entries(t.attributes).forEach(([i,o])=>{r.set(i,o)}),Oh.create(Pe(t.parentCreatedAt),Sp(t.from),Sp(t.to),n,t.content,r,Pe(t.executedAt))}else if(e.body.case==="style"){const t=e.body.value,n=new Map;Object.entries(t.createdAtMapByActor).forEach(([i,o])=>{n.set(i,Pe(o))});const r=new Map;return Object.entries(t.attributes).forEach(([i,o])=>{r.set(i,o)}),_h.create(Pe(t.parentCreatedAt),Sp(t.from),Sp(t.to),n,r,Pe(t.executedAt))}else{if(e.body.case==="select")return;if(e.body.case==="increase"){const t=e.body.value;return hd.create(Pe(t.parentCreatedAt),n2(t.value),Pe(t.executedAt))}else if(e.body.case==="treeEdit"){const t=e.body.value,n=new Map;return Object.entries(t.createdAtMapByActor).forEach(([r,i])=>{n.set(r,Pe(i))}),Nh.create(Pe(t.parentCreatedAt),dc(t.from),dc(t.to),YKe(t.contents),t.splitLevel,n,Pe(t.executedAt))}else if(e.body.case==="treeStyle"){const t=e.body.value,n=new Map,r=t.attributesToRemove,i=new Map;return t!=null&&t.createdAtMapByActor&&Object.entries(t.createdAtMapByActor).forEach(([o,a])=>{i.set(o,Pe(a))}),(r==null?void 0:r.length)>0?ys.createTreeRemoveStyleOperation(Pe(t.parentCreatedAt),dc(t.from),dc(t.to),i,r,Pe(t.executedAt)):(Object.entries(t.attributes).forEach(([o,a])=>{n.set(o,a)}),ys.create(Pe(t.parentCreatedAt),dc(t.from),dc(t.to),i,n,Pe(t.executedAt)))}else throw new Y(W.ErrUnimplemented,"unimplemented operation")}}function ZKe(e){const t=[];for(const n of e){const r=QP(n);r&&t.push(r)}return t}function eB(e){const t=[];for(const n of e)t.push(cd.create({id:qP(n.id),operations:ZKe(n.operations),presenceChange:n.presenceChange?GKe(n.presenceChange):void 0,message:n.message}));return t}function QKe(e){return jc.of(BigInt(e.serverSeq),e.clientSeq)}function eVe(e){return E1.create(e.documentKey,QKe(e.checkpoint),e.isRemoved,eB(e.changes),jC(e.versionVector),e.snapshot,Pe(e.minSyncedTicket))}function tB(e){const t=new lh;for(const r of e.nodes){const i=VC(r.element);t.set(r.key,i,i.getPositionedAt())}const n=new wr(Pe(e.createdAt),t);return n.setMovedAt(Pe(e.movedAt)),n.setRemovedAt(Pe(e.removedAt)),n}function nB(e){const t=new dh;for(const r of e.nodes)t.insert(VC(r.element));const n=new Ur(Pe(e.createdAt),t);return n.setMovedAt(Pe(e.movedAt)),n.setRemovedAt(Pe(e.removedAt)),n}function tVe(e){const t=Gt.of(Gt.valueFromBytes(XP(e.type),e.value),Pe(e.createdAt));return t.setMovedAt(Pe(e.movedAt)),t.setRemovedAt(Pe(e.removedAt)),t}function nVe(e){const t=new dd;let n=t.getHead();for(const i of e.nodes){const o=t.insertAfter(n,WKe(i));i.insPrevId&&o.setInsPrev(t.findNode(ZP(i.insPrevId))),n=o}const r=new Ti(t,Pe(e.createdAt));return r.setMovedAt(Pe(e.movedAt)),r.setRemovedAt(Pe(e.removedAt)),r}function rVe(e){const t=Kr.create(sm(e.type),Kr.valueFromBytes(sm(e.type),e.value),Pe(e.createdAt));return t.setMovedAt(Pe(e.movedAt)),t.setRemovedAt(Pe(e.removedAt)),t}function rB(e){const t=KC(e.nodes);return Pi.create(t,Pe(e.createdAt))}function VC(e){if(e.body.case==="jsonObject")return tB(e.body.value);if(e.body.case==="jsonArray")return nB(e.body.value);if(e.body.case==="primitive")return tVe(e.body.value);if(e.body.case==="text")return nVe(e.body.value);if(e.body.case==="counter")return rVe(e.body.value);if(e.body.case==="tree")return rB(e.body.value);throw new Y(W.ErrUnimplemented,"unimplemented element")}function iVe(e){if(!e)return{root:wr.create(to),presences:new Map};const t=G3.fromBinary(e);return{root:VC(t.root),presences:JKe(t.presences)}}function oVe(e){const t=NC(e);return GC(t.toBinary())}function aVe(e){const t=WC(e),n=v1.fromBinary(t);return jC(n)}function iB(e){if(!e)throw new Y(W.ErrInvalidArgument,"bytes is empty");const t=Sr.fromBinary(e);return tB(t.body.value)}function oB(e){return HC(e).toBinary()}function sVe(e){if(!e)throw new Y(W.ErrInvalidArgument,"bytes is empty");const t=Sr.fromBinary(e);return nB(t.body.value)}function uVe(e){return WP(e).toBinary()}function lVe(e){if(!e)throw new Y(W.ErrInvalidArgument,"bytes is empty");const t=Sr.fromBinary(e);return rB(t.body.value)}function cVe(e){return YP(e).toBinary()}function GC(e){return e?Array.from(e).map(t=>t.toString(16).padStart(2,"0")).join(""):""}function JC(e){return GC(e)}function WC(e){return new Uint8Array(e.match(/.{1,2}/g).map(t=>parseInt(t,16)))}function YC(e){return WC(e)}function dVe(e){const t=m1.fromBinary(e);return qP(t)}function hVe(e){const t=$C.fromBinary(e);return QP(t)}const rn={fromPresence:UC,toChangePack:VKe,fromChangePack:eVe,fromChanges:eB,toTreeNodes:zC,fromTreeNodes:KC,objectToBytes:oB,bytesToObject:iB,bytesToSnapshot:iVe,bytesToHex:GC,hexToBytes:WC,toHexString:JC,toUint8Array:YC,toOperation:JP,toChangeID:KP,PbChangeID:m1,bytesToChangeID:dVe,bytesToOperation:hVe,versionVectorToHex:oVe,hexToVersionVector:aVe};var or=(e=>(e[e.Trivial=0]="Trivial",e[e.Debug=1]="Debug",e[e.Info=2]="Info",e[e.Warn=3]="Warn",e[e.Error=4]="Error",e[e.Fatal=5]="Fatal",e))(or||{});let tl=3;function aB(e){tl=e}const $e={trivial:(...e)=>{tl>0||typeof console<"u"&&console.log("YORKIE T:",...e)},debug:(...e)=>{tl>1||typeof console<"u"&&console.log("YORKIE D:",...e)},info:(...e)=>{tl>2||typeof console<"u"&&console.log("YORKIE I:",...e)},warn:(...e)=>{tl>3||typeof console<"u"&&(typeof console.warn<"u"?console.warn("YORKIE W:",...e):console.log("YORKIE W:",...e))},error:(...e)=>{tl>4||typeof console<"u"&&(typeof console.error<"u"?console.error("YORKIE E:",...e):console.log("YORKIE E:",...e))},fatal:(...e)=>{typeof console<"u"&&(typeof console.error<"u"?console.error("YORKIE F:",...e):console.log("YORKIE F:",...e))},isEnabled:e=>tl<=e};function sB(){return"xxxxxxxx-xxxx-4xxxy-xxxx-xxxxxxxxxxx".replace(/[xy]/g,e=>{const t=Math.random()*16|0;return(e==="x"?t:t&3|8).toString(16)})}class fVe{constructor(t,n,r,i,o){A(this,"reconnectStreamDelay");A(this,"doc");A(this,"docID");A(this,"syncMode");A(this,"remoteChangeEventReceived");A(this,"watchStream");A(this,"watchLoopTimerID");A(this,"watchAbortController");A(this,"unsubscribeBroadcastEvent");this.reconnectStreamDelay=t,this.doc=n,this.docID=r,this.syncMode=i,this.remoteChangeEventReceived=!1,this.unsubscribeBroadcastEvent=o}changeSyncMode(t){this.syncMode=t}needRealtimeSync(){return this.syncMode===Yp.RealtimeSyncOff?!1:this.syncMode===Yp.RealtimePushOnly?this.doc.hasLocalChanges():this.syncMode!==Yp.Manual&&(this.doc.hasLocalChanges()||this.remoteChangeEventReceived)}async runWatchLoop(t){const n=async()=>{if(this.watchStream)return Promise.resolve();this.watchLoopTimerID&&(clearTimeout(this.watchLoopTimerID),this.watchLoopTimerID=void 0);try{[this.watchStream,this.watchAbortController]=await t(()=>{this.watchStream=void 0,this.watchAbortController=void 0,this.watchLoopTimerID=setTimeout(n,this.reconnectStreamDelay)})}catch{}};await n()}cancelWatchStream(){this.watchStream&&this.watchAbortController&&(this.watchAbortController.abort(),this.watchStream=void 0,this.watchAbortController=void 0),clearTimeout(this.watchLoopTimerID),this.watchLoopTimerID=void 0}}const r2=()=>{};class pVe{constructor(t){A(this,"finalized",!1);A(this,"observers",[]);A(this,"finalError");try{t(this)}catch(n){this.error(n)}}next(t){this.forEachObserver(n=>{n.next(t)})}error(t){this.forEachObserver(n=>{n.error(t)}),this.close(t)}complete(){this.forEachObserver(t=>{t.complete()}),this.close()}subscribe(t,n,r){let i;if(!t)throw new Y(W.ErrInvalidArgument,"missing observer");if(this.finalized)throw new Y(W.ErrRefused,"observable is finalized due to previous error");typeof t=="object"?i=t:i={next:t,error:n,complete:r},i.next===void 0&&(i.next=r2),i.error===void 0&&(i.error=r2),i.complete===void 0&&(i.complete=r2);const o=sB(),a=this.unsubscribeOne.bind(this,o);if(this.observers.push({subscriptionID:o,observer:i}),this.finalized)try{this.finalError?i.error(this.finalError):i.complete()}catch(s){$e.warn(s)}return a}unsubscribeOne(t){var n;this.observers=(n=this.observers)==null?void 0:n.filter(r=>r.subscriptionID!==t)}forEachObserver(t){if(!this.finalized)for(let n=0;nt}}class Tc{constructor(t,n,r,i){A(this,"id");A(this,"delimiter");A(this,"message");A(this,"root");A(this,"operations");A(this,"presenceChange");A(this,"previousPresence");A(this,"reversePresenceKeys");this.id=t,this.delimiter=$P,this.root=n,this.operations=[],this.previousPresence=Gi(r),this.presenceChange=void 0,this.reversePresenceKeys=new Set,this.message=i}static create(t,n,r,i){return new Tc(t,n,r,i)}push(t){this.operations.push(t)}registerElement(t,n){this.root.registerElement(t,n)}registerRemovedElement(t){this.root.registerRemovedElement(t)}registerGCPair(t){this.root.registerGCPair(t)}getChange(){return cd.create({id:this.id,operations:this.operations,presenceChange:this.presenceChange,message:this.message})}hasChange(){return this.operations.length>0||this.presenceChange!==void 0}setPresenceChange(t){this.presenceChange=t}setReversePresence(t,n){for(const r of Object.keys(t))n!=null&&n.addToHistory?this.reversePresenceKeys.add(r):this.reversePresenceKeys.delete(r)}getReversePresence(){if(this.reversePresenceKeys.size===0)return;const t={};for(const n of this.reversePresenceKeys)t[n]=this.previousPresence[n];return t}issueTimeTicket(){return this.delimiter+=1,this.id.createTimeTicket(this.delimiter)}getLastTimeTicket(){return this.id.createTimeTicket(this.delimiter)}}class fh{constructor(t){A(this,"rootObject");A(this,"elementPairMapByCreatedAt");A(this,"gcElementSetByCreatedAt");A(this,"gcPairMap");this.rootObject=t,this.elementPairMapByCreatedAt=new Map,this.gcElementSetByCreatedAt=new Set,this.gcPairMap=new Map,this.registerElement(t,void 0),t.getDescendants(n=>{if(n.getRemovedAt()&&this.registerRemovedElement(n),n instanceof Ti||n instanceof Pi)for(const r of n.getGCPairs())this.registerGCPair(r);return!1})}static create(){return new fh(wr.create(to))}findByCreatedAt(t){const n=this.elementPairMapByCreatedAt.get(t.toIDString());if(n)return n.element}findElementPairByCreatedAt(t){return this.elementPairMapByCreatedAt.get(t.toIDString())}createSubPaths(t){let n=this.elementPairMapByCreatedAt.get(t.toIDString());if(!n)return[];const r=[];for(;n.parent;){const i=n.element.getCreatedAt(),o=n.parent.subPathOf(i);if(o===void 0)throw new Y(W.ErrInvalidArgument,`cant find the given element: ${i.toIDString()}`);r.unshift(o),n=this.elementPairMapByCreatedAt.get(n.parent.getCreatedAt().toIDString())}return r.unshift("$"),r}createPath(t){return this.createSubPaths(t).join(".")}registerElement(t,n){this.elementPairMapByCreatedAt.set(t.getCreatedAt().toIDString(),{parent:n,element:t}),t instanceof vu&&t.getDescendants((r,i)=>(this.registerElement(r,i),!1))}deregisterElement(t){let n=0;const r=i=>{const o=i.getCreatedAt().toIDString();this.elementPairMapByCreatedAt.delete(o),this.gcElementSetByCreatedAt.delete(o),n++};return r(t),t instanceof vu&&t.getDescendants(i=>(r(i),!1)),n}registerRemovedElement(t){this.gcElementSetByCreatedAt.add(t.getCreatedAt().toIDString())}registerGCPair(t){if(this.gcPairMap.get(t.child.toIDString())){this.gcPairMap.delete(t.child.toIDString());return}this.gcPairMap.set(t.child.toIDString(),t)}getElementMapSize(){return this.elementPairMapByCreatedAt.size}getGarbageElementSetSize(){const t=new Set;for(const n of this.gcElementSetByCreatedAt){t.add(n);const r=this.elementPairMapByCreatedAt.get(n);r.element instanceof vu&&r.element.getDescendants(i=>(t.add(i.getCreatedAt().toIDString()),!1))}return t.size}getObject(){return this.rootObject}getGarbageLen(){return this.getGarbageElementSetSize()+this.gcPairMap.size}deepcopy(){return new fh(this.rootObject.deepcopy())}garbageCollect(t){let n=0;for(const r of this.gcElementSetByCreatedAt){const i=this.elementPairMapByCreatedAt.get(r),o=i.element.getRemovedAt();o&&(t!=null&&t.afterOrEqual(o))&&(i.parent.purge(i.element),n+=this.deregisterElement(i.element))}for(const[,r]of this.gcPairMap){const i=r.child.getRemovedAt();i&&(t!=null&&t.afterOrEqual(i))&&(r.parent.purge(r.child),this.gcPairMap.delete(r.child.toIDString()),n+=1)}return n}toJSON(){return this.rootObject.toJSON()}toSortedJSON(){return this.rootObject.toSortedJSON()}getStats(){return{elements:this.getElementMapSize(),gcPairs:this.gcPairMap.size,gcElements:this.getGarbageElementSetSize()}}}function uB(e,t){const n=new ph(e);return new Proxy(t,n.getHandlers())}class ph{constructor(t){A(this,"context");A(this,"handlers");this.context=t,this.handlers={set:(n,r,i)=>($e.isEnabled(or.Trivial)&&$e.trivial(`obj[${r}]=${JSON.stringify(i)}`),ph.setInternal(t,n,r,i),!0),get:(n,r)=>($e.isEnabled(or.Trivial)&&$e.trivial(`obj[${r}]`),r==="getID"?()=>n.getCreatedAt():r==="toJSON"||r==="toString"?()=>n.toJSON():r==="toJS"?()=>n.toJS():r==="toJSForTest"?()=>n.toJSForTest():nl(t,n.get(r))),ownKeys:n=>n.getKeys(),getOwnPropertyDescriptor:()=>({enumerable:!0,configurable:!0}),deleteProperty:(n,r)=>($e.isEnabled(or.Trivial)&&$e.trivial(`obj[${r}]`),ph.deleteInternal(t,n,r),!0)}}static setInternal(t,n,r,i){if(r.includes("."))throw new Y(W.ErrInvalidObjectKey,"key must not contain the '.'.");const o=t.issueTimeTicket(),a=um(t,i,o),s=n.set(r,a,o);t.registerElement(a,n),s&&t.registerRemovedElement(s),t.push(Tl.create(r,a.deepcopy(),n.getCreatedAt(),o))}static buildObjectMembers(t,n){const r={};for(const[i,o]of Object.entries(n)){if(i.includes("."))throw new Y(W.ErrInvalidObjectKey,"key must not contain the '.'.");const a=t.issueTimeTicket(),s=um(t,o,a);r[i]=s}return r}static deleteInternal(t,n,r){const i=t.issueTimeTicket(),o=n.deleteByKey(r,i);o&&(t.push(Tu.create(n.getCreatedAt(),o.getCreatedAt(),i)),t.registerRemovedElement(o))}getHandlers(){return this.handlers}}function mVe(e,t){const n=new qt(e,t);return new Proxy(t,n.getHandlers())}function vVe(e){return typeof e=="string"||e instanceof String?!isNaN(e):!1}function yVe(e){return["concat","entries","every","filter","find","findIndex","forEach","join","keys","map","reduce","reduceRight","slice","some","toLocaleString","toString","values"].includes(e)}class qt{constructor(t,n){A(this,"context");A(this,"handlers");A(this,"array");this.context=t,this.array=n,this.handlers={get:(r,i,o)=>i==="getID"?()=>r.getCreatedAt():i==="getElementByID"?a=>{const s=r.getByID(a);if(!(!s||s.isRemoved()))return Xs(t,s)}:i==="getElementByIndex"?a=>{const s=r.get(a);return Xs(t,s)}:i==="getLast"?()=>Xs(t,r.getLast()):i==="deleteByID"?a=>{const s=qt.deleteInternalByID(t,r,a);return Xs(t,s)}:i==="insertAfter"?(a,s)=>{const u=qt.insertAfterInternal(t,r,a,s);return Xs(t,u)}:i==="insertBefore"?(a,s)=>{const u=qt.insertBeforeInternal(t,r,a,s);return Xs(t,u)}:i==="moveBefore"?(a,s)=>{qt.moveBeforeInternal(t,r,a,s)}:i==="moveAfter"?(a,s)=>{qt.moveAfterInternal(t,r,a,s)}:i==="moveFront"?a=>{qt.moveFrontInternal(t,r,a)}:i==="moveLast"?a=>{qt.moveLastInternal(t,r,a)}:vVe(i)?nl(t,r.get(Number(i))):i==="push"?a=>qt.pushInternal(t,r,a):i==="splice"?(a,s,...u)=>qt.splice(t,r,a,s,...u):i==="length"?r.length:typeof i=="symbol"&&i===Symbol.iterator?qt.iteratorInternal.bind(this,t,r):i==="includes"?(a,s)=>qt.includes(t,r,a,s):i==="indexOf"?(a,s)=>qt.indexOf(t,r,a,s):i==="lastIndexOf"?(a,s)=>qt.lastIndexOf(t,r,a,s):i==="toJSForTest"?()=>r.toJSForTest():i==="toTestString"?()=>qt.toTestString(r):typeof i=="string"&&yVe(i)?(...a)=>{const s=Array.from(r).map(u=>nl(t,u));return Array.prototype[i].apply(s,a)}:Reflect.get(r,i,o),deleteProperty:(r,i)=>($e.isEnabled(or.Trivial)&&$e.trivial(`array[${i}]`),qt.deleteInternalByIndex(t,r,Number.parseInt(i)),!0)}}static*iteratorInternal(t,n){for(const r of n)yield Xs(t,r)}static buildArrayElements(t,n){const r=[];for(const i of n){const o=t.issueTimeTicket(),a=um(t,i,o);r.push(a)}return r}static pushInternal(t,n,r){return qt.insertAfterInternal(t,n,n.getLastCreatedAt(),r),n.length}static moveBeforeInternal(t,n,r,i){const o=t.issueTimeTicket(),a=n.getPrevCreatedAt(r);n.moveAfter(a,i,o),t.push(au.create(n.getCreatedAt(),a,i,o))}static moveAfterInternal(t,n,r,i){const o=t.issueTimeTicket();n.moveAfter(r,i,o),t.push(au.create(n.getCreatedAt(),r,i,o))}static moveFrontInternal(t,n,r){const i=t.issueTimeTicket(),o=n.getHead();n.moveAfter(o.getCreatedAt(),r,i),t.push(au.create(n.getCreatedAt(),o.getCreatedAt(),r,i))}static moveLastInternal(t,n,r){const i=t.issueTimeTicket(),o=n.getLastCreatedAt();n.moveAfter(o,r,i),t.push(au.create(n.getCreatedAt(),o,r,i))}static insertAfterInternal(t,n,r,i){const o=t.issueTimeTicket(),a=um(t,i,o);return n.insertAfter(r,a),t.registerElement(a,n),t.push(Lh.create(n.getCreatedAt(),r,a.deepcopy(),o)),a}static insertBeforeInternal(t,n,r,i){return qt.insertAfterInternal(t,n,n.getPrevCreatedAt(r),i)}static deleteInternalByIndex(t,n,r){const i=t.issueTimeTicket(),o=n.deleteByIndex(r,i);if(o)return t.push(Tu.create(n.getCreatedAt(),o.getCreatedAt(),i)),t.registerRemovedElement(o),o}static deleteInternalByID(t,n,r){const i=t.issueTimeTicket(),o=n.delete(r,i);return t.push(Tu.create(n.getCreatedAt(),o.getCreatedAt(),i)),t.registerRemovedElement(o),o}static splice(t,n,r,i,...o){const a=n.length,s=r>=0?Math.min(r,a):Math.max(a+r,0),u=i===void 0?a:i<0?s:Math.min(s+i,a),d=[];for(let h=s;h=o)return!1;if(Gt.isSupport(r))return Array.from(n).map(d=>nl(t,d)).includes(r,a);for(let u=a;u=o)return-1;if(Gt.isSupport(r))return Array.from(n).map(d=>nl(t,d)).indexOf(r,a);for(let u=a;u=o?o-1:i<0?i+o:i;if(a<0)return-1;if(Gt.isSupport(r))return Array.from(n).map(d=>nl(t,d)).lastIndexOf(r,a);for(let u=a;u>0;u--)if(((s=n.get(u))==null?void 0:s.getID())===r.getID())return u;return-1}static toTestString(t){return t.toTestString()}getHandlers(){return this.handlers}}class C1{constructor(t,n){A(this,"context");A(this,"text");this.context=t,this.text=n}initialize(t,n){this.context=t,this.text=n}getID(){return this.text.getID()}edit(t,n,r,i){if(!this.context||!this.text)throw new Y(W.ErrNotInitialized,"Text is not initialized yet");if(t>n)throw new Y(W.ErrInvalidArgument,"from should be less than or equal to to");const o=this.text.indexRangeToPosRange(t,n);$e.isEnabled(or.Debug)&&$e.debug(`EDIT: f:${t}->${o[0].toTestString()}, t:${n}->${o[1].toTestString()} c:${r}`);const a=i?ud(i):void 0,s=this.context.issueTimeTicket(),[u,,d,h]=this.text.edit(o,r,s,a);for(const p of d)this.context.registerGCPair(p);return this.context.push(new Oh(this.text.getCreatedAt(),o[0],o[1],u,r,a?new Map(Object.entries(a)):new Map,s)),this.text.findIndexesFromRange(h)}delete(t,n){return this.edit(t,n,"")}empty(){return this.edit(0,this.length,"")}setStyle(t,n,r){if(!this.context||!this.text)throw new Y(W.ErrNotInitialized,"Text is not initialized yet");if(t>n)throw new Y(W.ErrInvalidArgument,"from should be less than or equal to to");const i=this.text.indexRangeToPosRange(t,n);$e.isEnabled(or.Debug)&&$e.debug(`STYL: f:${t}->${i[0].toTestString()}, t:${n}->${i[1].toTestString()} a:${JSON.stringify(r)}`);const o=ud(r),a=this.context.issueTimeTicket(),[s,u]=this.text.setStyle(i,o,a);for(const d of u)this.context.registerGCPair(d);return this.context.push(new _h(this.text.getCreatedAt(),i[0],i[1],s,new Map(Object.entries(o)),a)),!0}indexRangeToPosRange(t){if(!this.context||!this.text)throw new Y(W.ErrNotInitialized,"Text is not initialized yet");const n=this.text.indexRangeToPosRange(t[0],t[1]);return[n[0].toStruct(),n[1].toStruct()]}posRangeToIndexRange(t){if(!this.context||!this.text)throw new Y(W.ErrNotInitialized,"Text is not initialized yet");const n=this.text.findIndexesFromRange([no.fromStruct(t[0]),no.fromStruct(t[1])]);return[n[0],n[1]]}toTestString(){if(!this.context||!this.text)throw new Y(W.ErrNotInitialized,"Text is not initialized yet");return this.text.toTestString()}values(){if(!this.context||!this.text)throw new Y(W.ErrNotInitialized,"Text is not initialized yet");return this.text.values()}get length(){return this.text.length}getTreeByIndex(){return this.text.getTreeByIndex()}getTreeByID(){return this.text.getTreeByID()}toString(){if(!this.context||!this.text)throw new Y(W.ErrNotInitialized,"Text is not initialized yet");return this.text.toString()}toJSON(){if(!this.context||!this.text)throw new Y(W.ErrNotInitialized,"Text is not initialized yet");return this.text.toJSON()}toJSForTest(){if(!this.context||!this.text)throw new Y(W.ErrNotInitialized,"Text is not initialized yet");return this.text.toJSForTest()}createRangeForTest(t,n){if(!this.context||!this.text)throw new Y(W.ErrNotInitialized,"Text is not initialized yet");return this.text.indexRangeToPosRange(t,n)}}class b1{constructor(t,n){A(this,"valueType");A(this,"value");A(this,"context");A(this,"counter");this.valueType=t,this.value=n}initialize(t,n){this.valueType=n.getValueType(),this.context=t,this.counter=n,this.value=n.getValue()}getID(){return this.counter.getID()}getValue(){return this.value}getValueType(){return this.valueType}increase(t){if(!this.context||!this.counter)throw new Y(W.ErrNotInitialized,"Counter is not initialized yet");const n=this.context.issueTimeTicket(),r=Gt.of(t,n);if(!r.isNumericType())throw new TypeError(`Unsupported type of value: ${typeof r.getValue()}`);return this.counter.increase(r),this.context.push(hd.create(this.counter.getCreatedAt(),r,n)),this}toJSForTest(){if(!this.context||!this.counter)throw new Y(W.ErrNotInitialized,"Counter is not initialized yet");return this.counter.toJSForTest()}}function qC(e,t,n){const{type:r}=e,i=n.issueTimeTicket();if(r===vs){lB(e);const{value:o}=e,a=Nr.create(Rn.of(i,0),r,o);t.append(a)}else{const{children:o=[]}=e,{attributes:a}=e;let s;if(typeof a=="object"&&!MP(a)){const d=ud(a);s=new Is;for(const[h,p]of Object.entries(d))s.set(h,p,i)}const u=Nr.create(Rn.of(i,0),r,void 0,s);t.append(u);for(const d of o)qC(d,u,n)}}function EVe(e,t){const{type:n}=t,r=e.issueTimeTicket();let i;if(t.type===vs){const{value:o}=t;i=Nr.create(Rn.of(r,0),n,o)}else if(t){const{children:o=[]}=t,{attributes:a}=t;let s;if(typeof a=="object"&&!MP(a)){const u=ud(a);s=new Is;for(const[d,h]of Object.entries(u))s.set(d,h,r)}i=Nr.create(Rn.of(e.issueTimeTicket(),0),n,void 0,s);for(const u of o)qC(u,i,e)}return i}function lB(e){if(!e.value.length)throw new Y(W.ErrInvalidArgument,"text node cannot have empty value");return!0}function Bx(e){if(!e.length)return!0;if(e[0].type===vs)for(const n of e){const{type:r}=n;if(r!==vs)throw new Y(W.ErrInvalidArgument,"element node and text node cannot be passed together");lB(n)}else for(const n of e){const{type:r}=n;if(r===vs)throw new Y(W.ErrInvalidArgument,"element node and text node cannot be passed together")}return!0}class w1{constructor(t){A(this,"initialRoot");A(this,"context");A(this,"tree");this.initialRoot=t}initialize(t,n){this.context=t,this.tree=n}getID(){return this.tree.getID()}buildRoot(t){if(!this.initialRoot)return Nr.create(Rn.of(t.issueTimeTicket(),0),vKe);const n=Nr.create(Rn.of(t.issueTimeTicket(),0),this.initialRoot.type);for(const r of this.initialRoot.children)qC(r,n,t);return n}getSize(){if(!this.context||!this.tree)throw new Y(W.ErrNotInitialized,"Tree is not initialized yet");return this.tree.getSize()}getNodeSize(){if(!this.context||!this.tree)throw new Y(W.ErrNotInitialized,"Tree is not initialized yet");return this.tree.getNodeSize()}getIndexTree(){if(!this.context||!this.tree)throw new Y(W.ErrNotInitialized,"Tree is not initialized yet");return this.tree.getIndexTree()}styleByPath(t,n){if(!this.context||!this.tree)throw new Y(W.ErrNotInitialized,"Tree is not initialized yet");if(!t.length)throw new Y(W.ErrInvalidArgument,"path should not be empty");const[r,i]=this.tree.pathToPosRange(t),o=this.context.issueTimeTicket(),a=n?ud(n):void 0,[s]=this.tree.style([r,i],a,o);this.context.push(ys.create(this.tree.getCreatedAt(),r,i,s,a?new Map(Object.entries(a)):new Map,o))}style(t,n,r){if(!this.context||!this.tree)throw new Y(W.ErrNotInitialized,"Tree is not initialized yet");if(t>n)throw new Y(W.ErrInvalidArgument,"from should be less than or equal to to");const i=this.tree.findPos(t),o=this.tree.findPos(n),a=this.context.issueTimeTicket(),s=r?ud(r):void 0,[u,d]=this.tree.style([i,o],s,a);for(const h of d)this.context.registerGCPair(h);this.context.push(ys.create(this.tree.getCreatedAt(),i,o,u,s?new Map(Object.entries(s)):new Map,a))}removeStyle(t,n,r){if(!this.context||!this.tree)throw new Y(W.ErrNotInitialized,"Tree is not initialized yet");if(t>n)throw new Y(W.ErrInvalidArgument,"from should be less than or equal to to");const i=this.tree.findPos(t),o=this.tree.findPos(n),a=this.context.issueTimeTicket(),[s,u]=this.tree.removeStyle([i,o],r,a);for(const d of u)this.context.registerGCPair(d);this.context.push(ys.createTreeRemoveStyleOperation(this.tree.getCreatedAt(),i,o,s,r,a))}editInternal(t,n,r,i=0){var d;if(r.length!==0&&r[0]&&(Bx(r),r[0].type!==vs))for(const h of r){const{children:p=[]}=h;Bx(p)}const o=this.context.getLastTimeTicket();let a=new Array;if(((d=r[0])==null?void 0:d.type)===vs){let h="";for(const p of r){const{value:g}=p;h+=g}a.push(Nr.create(Rn.of(this.context.issueTimeTicket(),0),vs,h))}else a=r.map(h=>h&&EVe(this.context,h)).filter(h=>h);const[,s,u]=this.tree.edit([t,n],a.length?a.map(h=>h==null?void 0:h.deepcopy()):void 0,i,o,()=>this.context.issueTimeTicket());for(const h of s)this.context.registerGCPair(h);return this.context.push(Nh.create(this.tree.getCreatedAt(),t,n,a.length?a:void 0,i,u,o)),!0}editByPath(t,n,r,i=0){if(!this.context||!this.tree)throw new Y(W.ErrNotInitialized,"Tree is not initialized yet");if(t.length!==n.length)throw new Y(W.ErrInvalidArgument,"path length should be equal");if(!t.length||!n.length)throw new Y(W.ErrInvalidArgument,"path should not be empty");const o=this.tree.pathToPos(t),a=this.tree.pathToPos(n);return this.editInternal(o,a,r?[r]:[],i)}editBulkByPath(t,n,r,i=0){if(!this.context||!this.tree)throw new Y(W.ErrNotInitialized,"Tree is not initialized yet");if(t.length!==n.length)throw new Y(W.ErrInvalidArgument,"path length should be equal");if(!t.length||!n.length)throw new Y(W.ErrInvalidArgument,"path should not be empty");const o=this.tree.pathToPos(t),a=this.tree.pathToPos(n);return this.editInternal(o,a,r,i)}edit(t,n,r,i=0){if(!this.context||!this.tree)throw new Y(W.ErrNotInitialized,"Tree is not initialized yet");if(t>n)throw new Y(W.ErrInvalidArgument,"from should be less than or equal to to");const o=this.tree.findPos(t),a=this.tree.findPos(n);return this.editInternal(o,a,r?[r]:[],i)}editBulk(t,n,r,i=0){if(!this.context||!this.tree)throw new Y(W.ErrNotInitialized,"Tree is not initialized yet");if(t>n)throw new Y(W.ErrInvalidArgument,"from should be less than or equal to to");const o=this.tree.findPos(t),a=this.tree.findPos(n);return this.editInternal(o,a,r,i)}toXML(){if(!this.context||!this.tree)throw new Y(W.ErrNotInitialized,"Tree is not initialized yet");return this.tree.toXML()}toJSON(){if(!this.context||!this.tree)throw new Y(W.ErrNotInitialized,"Tree is not initialized yet");return this.tree.toJSON()}toJSForTest(){if(!this.context||!this.tree)throw new Y(W.ErrNotInitialized,"Tree is not initialized yet");return this.tree.toJSForTest()}toJSInfoForTest(){if(!this.context||!this.tree)throw new Y(W.ErrNotInitialized,"Tree is not initialized yet");return this.tree.toJSInfoForTest()}getRootTreeNode(){if(!this.context||!this.tree)throw new Y(W.ErrNotInitialized,"Tree is not initialized yet");return this.tree.getRootTreeNode()}indexToPath(t){if(!this.context||!this.tree)throw new Y(W.ErrNotInitialized,"Tree is not initialized yet");return this.tree.indexToPath(t)}pathToIndex(t){if(!this.context||!this.tree)throw new Y(W.ErrNotInitialized,"Tree is not initialized yet");return this.tree.pathToIndex(t)}pathRangeToPosRange(t){if(!this.context||!this.tree)throw new Y(W.ErrNotInitialized,"Tree is not initialized yet");const n=[this.tree.pathToIndex(t[0]),this.tree.pathToIndex(t[1])],r=this.tree.indexRangeToPosRange(n);return[r[0].toStruct(),r[1].toStruct()]}indexRangeToPosRange(t){if(!this.context||!this.tree)throw new Y(W.ErrNotInitialized,"Tree is not initialized yet");return this.tree.indexRangeToPosStructRange(t)}posRangeToIndexRange(t){if(!this.context||!this.tree)throw new Y(W.ErrNotInitialized,"Tree is not initialized yet");const n=[Xi.fromStruct(t[0]),Xi.fromStruct(t[1])];return this.tree.posRangeToIndexRange(n)}posRangeToPathRange(t){if(!this.context||!this.tree)throw new Y(W.ErrNotInitialized,"Tree is not initialized yet");const n=[Xi.fromStruct(t[0]),Xi.fromStruct(t[1])];return this.tree.posRangeToPathRange(n)}}function Mx(e,t){return uB(e,t)}function Xs(e,t){if(t){if(t instanceof Gt)return t;if(t instanceof wr)return uB(e,t);if(t instanceof Ur)return mVe(e,t);if(t instanceof Ti)return new C1(e,t);if(t instanceof Kr){const n=new b1(Ko.IntegerCnt,0);return n.initialize(e,t),n}else if(t instanceof Pi){const n=new w1;return n.initialize(e,t),n}}else return;throw new TypeError(`Unsupported type of element: ${typeof t}`)}function nl(e,t){const n=Xs(e,t);return n instanceof Gt?n.getValue():n}function um(e,t,n){let r;if(Gt.isSupport(t))r=Gt.of(t,n);else if(Array.isArray(t))r=Ur.create(n,qt.buildArrayElements(e,t));else if(typeof t=="object")t instanceof C1?(r=Ti.create(dd.create(),n),t.initialize(e,r)):t instanceof b1?(r=Kr.create(t.getValueType(),t.getValue(),n),t.initialize(e,r)):t instanceof w1?(r=Pi.create(t.buildRoot(e),n),t.initialize(e,r)):r=wr.create(n,ph.buildObjectMembers(e,t));else throw new TypeError(`Unsupported type of value: ${typeof t}`);return r}const $x=50;class CVe{constructor(){A(this,"undoStack",[]);A(this,"redoStack",[])}hasUndo(){return this.undoStack.length>0}hasRedo(){return this.redoStack.length>0}pushUndo(t){this.undoStack.length>=$x&&this.undoStack.shift(),this.undoStack.push(t)}popUndo(){return this.undoStack.pop()}pushRedo(t){this.redoStack.length>=$x&&this.redoStack.shift(),this.redoStack.push(t)}popRedo(){return this.redoStack.pop()}clearRedo(){this.redoStack=[]}getUndoStackForTest(){return this.undoStack}getRedoStackForTest(){return this.redoStack}}const bVe="yorkie-devtools-panel",wVe="yorkie-devtools-sdk";let fc="disconnected";const Rx=new Map,Wp=new Map;typeof window<"u"&&(window.transactionEventsByDocKey=Wp);function xp(e,t){(t!=null&&t.force||fc!=="disconnected")&&window.postMessage({source:wVe,...e},"*")}function SVe(e){if(!e.isEnableDevtools()||typeof window>"u"||Rx.has(e.getKey()))return;Wp.set(e.getKey(),[]);const t=e.subscribe("all",n=>{n.some(r=>r.type!==Un.StatusChanged&&r.type!==Un.Snapshot&&r.type!==Un.LocalChange&&r.type!==Un.RemoteChange&&r.type!==Un.Initialized&&r.type!==Un.Watched&&r.type!==Un.Unwatched&&r.type!==Un.PresenceChanged)||(Wp.get(e.getKey()).push(n),fc==="synced"&&xp({msg:"doc::sync::partial",docKey:e.getKey(),event:n}))});Rx.set(e.getKey(),[t]),xp({msg:"refresh-devtools"},{force:!0}),window.addEventListener("message",n=>{var i;if(((i=n.data)==null?void 0:i.source)!==bVe)return;switch(n.data.msg){case"devtools::connect":if(fc!=="disconnected")break;fc="connected",xp({msg:"doc::available",docKey:e.getKey()}),$e.info(`[YD] Devtools connected. Doc: ${e.getKey()}`);break;case"devtools::disconnect":fc="disconnected",$e.info(`[YD] Devtools disconnected. Doc: ${e.getKey()}`);break;case"devtools::subscribe":fc="synced",xp({msg:"doc::sync::full",docKey:e.getKey(),events:Wp.get(e.getKey())}),$e.info(`[YD] Devtools subscribed. Doc: ${e.getKey()}`);break}})}var Zs=(e=>(e.Detached="detached",e.Attached="attached",e.Removed="removed",e))(Zs||{}),Un=(e=>(e.StatusChanged="status-changed",e.ConnectionChanged="connection-changed",e.SyncStatusChanged="sync-status-changed",e.Snapshot="snapshot",e.LocalChange="local-change",e.RemoteChange="remote-change",e.Initialized="initialized",e.Watched="watched",e.Unwatched="unwatched",e.PresenceChanged="presence-changed",e.Broadcast="broadcast",e.LocalBroadcast="local-broadcast",e))(Un||{}),yy=(e=>(e.Connected="connected",e.Disconnected="disconnected",e))(yy||{}),Ey=(e=>(e.Synced="synced",e.SyncFailed="sync-failed",e))(Ey||{});class XC{constructor(t,n){A(this,"key");A(this,"status");A(this,"opts");A(this,"changeID");A(this,"checkpoint");A(this,"localChanges");A(this,"root");A(this,"clone");A(this,"eventStream");A(this,"eventStreamObserver");A(this,"onlineClients");A(this,"presences");A(this,"history");A(this,"internalHistory");A(this,"isUpdating");this.opts=n||{},this.key=t,this.status="detached",this.root=fh.create(),this.changeID=kKe,this.checkpoint=DKe,this.localChanges=[],this.eventStream=gVe(r=>{this.eventStreamObserver=r}),this.onlineClients=new Set,this.presences=new Map,this.isUpdating=!1,this.internalHistory=new CVe,this.history={canUndo:this.canUndo.bind(this),canRedo:this.canRedo.bind(this),undo:this.undo.bind(this),redo:this.redo.bind(this)},SVe(this)}update(t,n){if(this.getStatus()==="removed")throw new Y(W.ErrDocumentRemoved,`${this.key} is removed`);this.ensureClone();const r=this.changeID.getActorID(),i=Tc.create(this.changeID.next(),this.clone.root,this.clone.presences.get(r)||{},n);try{const o=Mx(i,this.clone.root.getObject());this.presences.has(r)||this.clone.presences.set(r,{}),this.isUpdating=!0,t(o,new e2(i,this.clone.presences.get(r)))}catch(o){throw this.clone=void 0,o}finally{this.isUpdating=!1}if(i.hasChange()){$e.isEnabled(or.Trivial)&&$e.trivial(`trying to update a local change: ${this.toJSON()}`);const o=i.getChange(),{opInfos:a,reverseOps:s}=o.execute(this.root,this.presences,xt.Local),u=i.getReversePresence();u&&s.push({type:"presence",value:u}),this.localChanges.push(o),s.length>0&&this.internalHistory.pushUndo(s),a.length>0&&this.internalHistory.clearRedo(),this.changeID=o.getID();const d=[];a.length>0&&d.push({type:"local-change",source:xt.Local,value:{message:o.getMessage()||"",operations:a,actor:r,clientSeq:o.getID().getClientSeq(),serverSeq:o.getID().getServerSeq()},rawChange:this.isEnableDevtools()?o.toStruct():void 0}),o.hasPresenceChange()&&d.push({type:"presence-changed",source:xt.Local,value:{clientID:r,presence:this.getPresence(r)}}),this.publish(d),$e.isEnabled(or.Trivial)&&$e.trivial(`after update a local change: ${this.toJSON()}`)}}subscribe(t,n,r,i){if(typeof t=="string"){if(typeof n!="function")throw new Y(W.ErrInvalidArgument,"Second argument must be a callback function");if(t==="presence"){const s=n;return this.eventStream.subscribe(u=>{for(const d of u)d.type!=="initialized"&&d.type!=="watched"&&d.type!=="unwatched"&&d.type!=="presence-changed"||s(d)},r,i)}if(t==="my-presence"){const s=n;return this.eventStream.subscribe(u=>{for(const d of u)d.type!=="initialized"&&d.type!=="presence-changed"||d.type==="presence-changed"&&d.value.clientID!==this.changeID.getActorID()||s(d)},r,i)}if(t==="others"){const s=n;return this.eventStream.subscribe(u=>{for(const d of u)d.type!=="watched"&&d.type!=="unwatched"&&d.type!=="presence-changed"||d.value.clientID!==this.changeID.getActorID()&&s(d)},r,i)}if(t==="connection"){const s=n;return this.eventStream.subscribe(u=>{for(const d of u)d.type==="connection-changed"&&s(d)},r,i)}if(t==="status"){const s=n;return this.eventStream.subscribe(u=>{for(const d of u)d.type==="status-changed"&&s(d)},r,i)}if(t==="sync"){const s=n;return this.eventStream.subscribe(u=>{for(const d of u)d.type==="sync-status-changed"&&s(d)},r,i)}if(t==="local-broadcast"){const s=n;return this.eventStream.subscribe(u=>{for(const d of u)d.type==="local-broadcast"&&s(d)},r)}if(t==="broadcast"){const s=n;return this.eventStream.subscribe(u=>{for(const d of u)d.type==="broadcast"&&s(d)},r)}if(t==="all"){const s=n;return this.eventStream.subscribe(s,r,i)}const o=t,a=n;return this.eventStream.subscribe(s=>{for(const u of s){if(u.type!=="local-change"&&u.type!=="remote-change")continue;const d=[];for(const h of u.value.operations)this.isSameElementOrChildOf(h.path,o)&&d.push(h);d.length&&a({...u,value:{...u.value,operations:d}})}},r,i)}if(typeof t=="function"){const o=t,a=n,s=r;return this.eventStream.subscribe(u=>{for(const d of u)d.type!=="snapshot"&&d.type!=="local-change"&&d.type!=="remote-change"||o(d)},a,s)}throw new Y(W.ErrInvalidArgument,`"${t}" is not a valid`)}publish(t){this.eventStreamObserver&&this.eventStreamObserver.next(t)}isSameElementOrChildOf(t,n){if(n===t)return!0;const r=t.split(".");return n.split(".").every((o,a)=>o===r[a])}applyChangePack(t){const n=t.hasSnapshot();for(n?this.applySnapshot(t.getCheckpoint().getServerSeq(),t.getVersionVector(),t.getSnapshot()):t.hasChanges()&&this.applyChanges(t.getChanges(),xt.Remote);this.localChanges.length&&!(this.localChanges[0].getID().getClientSeq()>t.getCheckpoint().getClientSeq());)this.localChanges.shift();n&&this.applyChanges(this.localChanges,xt.Remote),this.checkpoint=this.checkpoint.forward(t.getCheckpoint()),n||this.garbageCollect(t.getVersionVector()),n||this.filterVersionVector(t.getVersionVector()),t.getIsRemoved()&&this.applyStatus("removed"),$e.isEnabled(or.Trivial)&&$e.trivial(`${this.root.toJSON()}`)}getCheckpoint(){return this.checkpoint}getChangeID(){return this.changeID}hasLocalChanges(){return this.localChanges.length>0}ensureClone(){this.clone||(this.clone={root:this.root.deepcopy(),presences:Gi(this.presences)})}createChangePack(){const t=Array.from(this.localChanges),n=this.checkpoint.increaseClientSeq(t.length);return E1.create(this.key,n,!1,t,this.getVersionVector())}setActor(t){for(const n of this.localChanges)n.setActor(t);this.changeID=this.changeID.setActor(t)}isEnableDevtools(){return!!this.opts.enableDevtools}getKey(){return this.key}getStatus(){return this.status}getCloneRoot(){if(this.clone)return this.clone.root.getObject()}getRoot(){this.ensureClone();const t=Tc.create(this.changeID.next(),this.clone.root,this.clone.presences.get(this.changeID.getActorID())||{});return Mx(t,this.clone.root.getObject())}garbageCollect(t){return this.opts.disableGC?0:(this.clone&&this.clone.root.garbageCollect(t),this.root.garbageCollect(t))}getRootObject(){return this.root.getObject()}getGarbageLen(){return this.root.getGarbageLen()}getGarbageLenFromClone(){return this.clone.root.getGarbageLen()}toJSON(){return this.root.toJSON()}toSortedJSON(){return this.root.toSortedJSON()}getStats(){return this.root.getStats()}toJSForTest(){return{...this.getRoot().toJSForTest(),key:"root"}}applySnapshot(t,n,r){const{root:i,presences:o}=rn.bytesToSnapshot(r);this.root=new fh(i),this.presences=o,this.changeID=this.changeID.setClocks(t,n),this.clone=void 0,this.publish([{type:"snapshot",source:xt.Remote,value:{serverSeq:t.toString(),snapshot:this.isEnableDevtools()?rn.bytesToHex(r):void 0,snapshotVector:rn.versionVectorToHex(n)}}])}applyChanges(t,n){$e.isEnabled(or.Debug)&&$e.debug(`trying to apply ${t.length} remote changes.elements:${this.root.getElementMapSize()}, removeds:${this.root.getGarbageElementSetSize()}`),$e.isEnabled(or.Trivial)&&$e.trivial(t.map(r=>`${r.getID().toTestString()} ${r.toTestString()}`).join(` + */var wi=null;try{wi=new WebAssembly.Instance(new WebAssembly.Module(new Uint8Array([0,97,115,109,1,0,0,0,1,13,2,96,0,1,127,96,4,127,127,127,127,1,127,3,7,6,0,1,1,1,1,1,6,6,1,127,1,65,0,11,7,50,6,3,109,117,108,0,1,5,100,105,118,95,115,0,2,5,100,105,118,95,117,0,3,5,114,101,109,95,115,0,4,5,114,101,109,95,117,0,5,8,103,101,116,95,104,105,103,104,0,0,10,191,1,6,4,0,35,0,11,36,1,1,126,32,0,173,32,1,173,66,32,134,132,32,2,173,32,3,173,66,32,134,132,126,34,4,66,32,135,167,36,0,32,4,167,11,36,1,1,126,32,0,173,32,1,173,66,32,134,132,32,2,173,32,3,173,66,32,134,132,127,34,4,66,32,135,167,36,0,32,4,167,11,36,1,1,126,32,0,173,32,1,173,66,32,134,132,32,2,173,32,3,173,66,32,134,132,128,34,4,66,32,135,167,36,0,32,4,167,11,36,1,1,126,32,0,173,32,1,173,66,32,134,132,32,2,173,32,3,173,66,32,134,132,129,34,4,66,32,135,167,36,0,32,4,167,11,36,1,1,126,32,0,173,32,1,173,66,32,134,132,32,2,173,32,3,173,66,32,134,132,130,34,4,66,32,135,167,36,0,32,4,167,11])),{}).exports}catch{}function at(e,t,n){this.low=e|0,this.high=t|0,this.unsigned=!!n}at.prototype.__isLong__;Object.defineProperty(at.prototype,"__isLong__",{value:!0});function qn(e){return(e&&e.__isLong__)===!0}function Sx(e){var t=Math.clz32(e&-e);return e?31-t:t}at.isLong=qn;var xx={},Ax={};function _l(e,t){var n,r,i;return t?(e>>>=0,(i=0<=e&&e<256)&&(r=Ax[e],r)?r:(n=ct(e,0,!0),i&&(Ax[e]=n),n)):(e|=0,(i=-128<=e&&e<128)&&(r=xx[e],r)?r:(n=ct(e,e<0?-1:0,!1),i&&(xx[e]=n),n))}at.fromInt=_l;function Si(e,t){if(isNaN(e))return t?hs:qi;if(t){if(e<0)return hs;if(e>=FP)return _P}else{if(e<=-Dx)return yr;if(e+1>=Dx)return OP}return e<0?Si(-e,t).neg():ct(e%ld|0,e/ld|0,t)}at.fromNumber=Si;function ct(e,t,n){return new at(e,t,n)}at.fromBits=ct;var om=Math.pow;function OC(e,t,n){if(e.length===0)throw Error("empty string");if(typeof t=="number"?(n=t,t=!1):t=!!t,e==="NaN"||e==="Infinity"||e==="+Infinity"||e==="-Infinity")return t?hs:qi;if(n=n||10,n<2||360)throw Error("interior hyphen");if(r===0)return OC(e.substring(1),t,n).neg();for(var i=Si(om(n,8)),o=qi,a=0;a>>0:this.low};he.toNumber=function(){return this.unsigned?(this.high>>>0)*ld+(this.low>>>0):this.high*ld+(this.low>>>0)};he.toString=function(t){if(t=t||10,t<2||36>>0,h=d.toString(t);if(a=u,a.isZero())return h+s;for(;h.length<6;)h="0"+h;s=""+h+s}};he.getHighBits=function(){return this.high};he.getHighBitsUnsigned=function(){return this.high>>>0};he.getLowBits=function(){return this.low};he.getLowBitsUnsigned=function(){return this.low>>>0};he.getNumBitsAbs=function(){if(this.isNegative())return this.eq(yr)?64:this.neg().getNumBitsAbs();for(var t=this.high!=0?this.high:this.low,n=31;n>0&&!(t&1<=0};he.isOdd=function(){return(this.low&1)===1};he.isEven=function(){return(this.low&1)===0};he.equals=function(t){return qn(t)||(t=co(t)),this.unsigned!==t.unsigned&&this.high>>>31===1&&t.high>>>31===1?!1:this.high===t.high&&this.low===t.low};he.eq=he.equals;he.notEquals=function(t){return!this.eq(t)};he.neq=he.notEquals;he.ne=he.notEquals;he.lessThan=function(t){return this.comp(t)<0};he.lt=he.lessThan;he.lessThanOrEqual=function(t){return this.comp(t)<=0};he.lte=he.lessThanOrEqual;he.le=he.lessThanOrEqual;he.greaterThan=function(t){return this.comp(t)>0};he.gt=he.greaterThan;he.greaterThanOrEqual=function(t){return this.comp(t)>=0};he.gte=he.greaterThanOrEqual;he.ge=he.greaterThanOrEqual;he.compare=function(t){if(qn(t)||(t=co(t)),this.eq(t))return 0;var n=this.isNegative(),r=t.isNegative();return n&&!r?-1:!n&&r?1:this.unsigned?t.high>>>0>this.high>>>0||t.high===this.high&&t.low>>>0>this.low>>>0?-1:1:this.sub(t).isNegative()?-1:1};he.comp=he.compare;he.negate=function(){return!this.unsigned&&this.eq(yr)?yr:this.not().add(Ic)};he.neg=he.negate;he.add=function(t){qn(t)||(t=co(t));var n=this.high>>>16,r=this.high&65535,i=this.low>>>16,o=this.low&65535,a=t.high>>>16,s=t.high&65535,u=t.low>>>16,d=t.low&65535,h=0,p=0,g=0,m=0;return m+=o+d,g+=m>>>16,m&=65535,g+=i+u,p+=g>>>16,g&=65535,p+=r+s,h+=p>>>16,p&=65535,h+=n+a,h&=65535,ct(g<<16|m,h<<16|p,this.unsigned)};he.subtract=function(t){return qn(t)||(t=co(t)),this.add(t.neg())};he.sub=he.subtract;he.multiply=function(t){if(this.isZero())return this;if(qn(t)||(t=co(t)),wi){var n=wi.mul(this.low,this.high,t.low,t.high);return ct(n,wi.get_high(),this.unsigned)}if(t.isZero())return this.unsigned?hs:qi;if(this.eq(yr))return t.isOdd()?yr:qi;if(t.eq(yr))return this.isOdd()?yr:qi;if(this.isNegative())return t.isNegative()?this.neg().mul(t.neg()):this.neg().mul(t).neg();if(t.isNegative())return this.mul(t.neg()).neg();if(this.lt(Ix)&&t.lt(Ix))return Si(this.toNumber()*t.toNumber(),this.unsigned);var r=this.high>>>16,i=this.high&65535,o=this.low>>>16,a=this.low&65535,s=t.high>>>16,u=t.high&65535,d=t.low>>>16,h=t.low&65535,p=0,g=0,m=0,v=0;return v+=a*h,m+=v>>>16,v&=65535,m+=o*h,g+=m>>>16,m&=65535,m+=a*d,g+=m>>>16,m&=65535,g+=i*h,p+=g>>>16,g&=65535,g+=o*d,p+=g>>>16,g&=65535,g+=a*u,p+=g>>>16,g&=65535,p+=r*h+i*d+o*u+a*s,p&=65535,ct(m<<16|v,p<<16|g,this.unsigned)};he.mul=he.multiply;he.divide=function(t){if(qn(t)||(t=co(t)),t.isZero())throw Error("division by zero");if(wi){if(!this.unsigned&&this.high===-2147483648&&t.low===-1&&t.high===-1)return this;var n=(this.unsigned?wi.div_u:wi.div_s)(this.low,this.high,t.low,t.high);return ct(n,wi.get_high(),this.unsigned)}if(this.isZero())return this.unsigned?hs:qi;var r,i,o;if(this.unsigned){if(t.unsigned||(t=t.toUnsigned()),t.gt(this))return hs;if(t.gt(this.shru(1)))return LP;o=hs}else{if(this.eq(yr)){if(t.eq(Ic)||t.eq(gy))return yr;if(t.eq(yr))return Ic;var a=this.shr(1);return r=a.div(t).shl(1),r.eq(qi)?t.isNegative()?Ic:gy:(i=this.sub(t.mul(r)),o=r.add(i.div(t)),o)}else if(t.eq(yr))return this.unsigned?hs:qi;if(this.isNegative())return t.isNegative()?this.neg().div(t.neg()):this.neg().div(t).neg();if(t.isNegative())return this.div(t.neg()).neg();o=qi}for(i=this;i.gte(t);){r=Math.max(1,Math.floor(i.toNumber()/t.toNumber()));for(var s=Math.ceil(Math.log(r)/Math.LN2),u=s<=48?1:om(2,s-48),d=Si(r),h=d.mul(t);h.isNegative()||h.gt(i);)r-=u,d=Si(r,this.unsigned),h=d.mul(t);d.isZero()&&(d=Ic),o=o.add(d),i=i.sub(h)}return o};he.div=he.divide;he.modulo=function(t){if(qn(t)||(t=co(t)),wi){var n=(this.unsigned?wi.rem_u:wi.rem_s)(this.low,this.high,t.low,t.high);return ct(n,wi.get_high(),this.unsigned)}return this.sub(this.div(t).mul(t))};he.mod=he.modulo;he.rem=he.modulo;he.not=function(){return ct(~this.low,~this.high,this.unsigned)};he.countLeadingZeros=function(){return this.high?Math.clz32(this.high):Math.clz32(this.low)+32};he.clz=he.countLeadingZeros;he.countTrailingZeros=function(){return this.low?Sx(this.low):Sx(this.high)+32};he.ctz=he.countTrailingZeros;he.and=function(t){return qn(t)||(t=co(t)),ct(this.low&t.low,this.high&t.high,this.unsigned)};he.or=function(t){return qn(t)||(t=co(t)),ct(this.low|t.low,this.high|t.high,this.unsigned)};he.xor=function(t){return qn(t)||(t=co(t)),ct(this.low^t.low,this.high^t.high,this.unsigned)};he.shiftLeft=function(t){return qn(t)&&(t=t.toInt()),(t&=63)===0?this:t<32?ct(this.low<>>32-t,this.unsigned):ct(0,this.low<>>t|this.high<<32-t,this.high>>t,this.unsigned):ct(this.high>>t-32,this.high>=0?0:-1,this.unsigned)};he.shr=he.shiftRight;he.shiftRightUnsigned=function(t){return qn(t)&&(t=t.toInt()),(t&=63)===0?this:t<32?ct(this.low>>>t|this.high<<32-t,this.high>>>t,this.unsigned):t===32?ct(this.high,0,this.unsigned):ct(this.high>>>t-32,0,this.unsigned)};he.shru=he.shiftRightUnsigned;he.shr_u=he.shiftRightUnsigned;he.rotateLeft=function(t){var n;return qn(t)&&(t=t.toInt()),(t&=63)===0?this:t===32?ct(this.high,this.low,this.unsigned):t<32?(n=32-t,ct(this.low<>>n,this.high<>>n,this.unsigned)):(t-=32,n=32-t,ct(this.high<>>n,this.low<>>n,this.unsigned))};he.rotl=he.rotateLeft;he.rotateRight=function(t){var n;return qn(t)&&(t=t.toInt()),(t&=63)===0?this:t===32?ct(this.high,this.low,this.unsigned):t<32?(n=32-t,ct(this.high<>>t,this.low<>>t,this.unsigned)):(t-=32,n=32-t,ct(this.low<>>t,this.high<>>t,this.unsigned))};he.rotr=he.rotateRight;he.toSigned=function(){return this.unsigned?ct(this.low,this.high,!1):this};he.toUnsigned=function(){return this.unsigned?this:ct(this.low,this.high,!0)};he.toBytes=function(t){return t?this.toBytesLE():this.toBytesBE()};he.toBytesLE=function(){var t=this.high,n=this.low;return[n&255,n>>>8&255,n>>>16&255,n>>>24,t&255,t>>>8&255,t>>>16&255,t>>>24]};he.toBytesBE=function(){var t=this.high,n=this.low;return[t>>>24,t>>>16&255,t>>>8&255,t&255,n>>>24,n>>>16&255,n>>>8&255,n&255]};at.fromBytes=function(t,n,r){return r?at.fromBytesLE(t,n):at.fromBytesBE(t,n)};at.fromBytesLE=function(t,n){return new at(t[0]|t[1]<<8|t[2]<<16|t[3]<<24,t[4]|t[5]<<8|t[6]<<16|t[7]<<24,n)};at.fromBytesBE=function(t,n){return new at(t[4]<<24|t[5]<<16|t[6]<<8|t[7],t[0]<<24|t[1]<<16|t[2]<<8|t[3],n)};var Cn=(e=>(e[e.Null=0]="Null",e[e.Boolean=1]="Boolean",e[e.Integer=2]="Integer",e[e.Long=3]="Long",e[e.Double=4]="Double",e[e.String=5]="String",e[e.Bytes=6]="Bytes",e[e.Date=7]="Date",e))(Cn||{});class Gt extends Fh{constructor(n,r){super(r);A(this,"valueType");A(this,"value");this.valueType=Gt.getPrimitiveType(n),this.value=n===void 0?null:n}static of(n,r){return new Gt(n,r)}static valueFromBytes(n,r){switch(n){case 0:return null;case 1:return!!r[0];case 2:return r[0]|r[1]<<8|r[2]<<16|r[3]<<24;case 4:{const i=new DataView(r.buffer);return r.forEach(function(o,a){i.setUint8(a,o)}),i.getFloat64(0,!0)}case 5:return new TextDecoder("utf-8").decode(r);case 3:return at.fromBytesLE(Array.from(r));case 6:return r;case 7:return new Date(at.fromBytesLE(Array.from(r),!0).toNumber());default:throw new Y(W.ErrUnimplemented,`unimplemented type: ${n}`)}}toJSON(){return this.valueType===5?`"${Oo(this.value)}"`:`${this.value}`}toSortedJSON(){return this.toJSON()}toJSForTest(){return{createdAt:this.getCreatedAt().toTestString(),value:this.value,type:"YORKIE_PRIMITIVE"}}deepcopy(){const n=Gt.of(this.value,this.getCreatedAt());return n.setMovedAt(this.getMovedAt()),n.setRemovedAt(this.getRemovedAt()),n}getType(){return this.valueType}static getPrimitiveType(n){switch(typeof n){case"undefined":return 0;case"boolean":return 1;case"number":return this.isInteger(n)?2:4;case"string":return 5;case"object":if(n===null)return 0;if(n instanceof at)return 3;if(n instanceof Uint8Array)return 6;if(n instanceof Date)return 7}}static isSupport(n){return Gt.getPrimitiveType(n)!==void 0}static isInteger(n){return n%1===0}isNumericType(){const n=this.valueType;return n===2||n===3||n===4}getValue(){return this.value}toBytes(){switch(this.valueType){case 0:return new Uint8Array;case 1:return this.value?new Uint8Array([1]):new Uint8Array([0]);case 2:{const n=this.value;return new Uint8Array([n&255,n>>8&255,n>>16&255,n>>24&255])}case 4:{const n=this.value,r=new Uint8Array(8);return new DataView(r.buffer).setFloat64(0,n,!0),r}case 5:return new TextEncoder().encode(this.value);case 3:{const r=this.value.toBytesLE();return Uint8Array.from(r)}case 6:return this.value;case 7:{const n=this.value,r=at.fromNumber(n.getTime(),!0).toBytesLE();return Uint8Array.from(r)}default:throw new Y(W.ErrUnimplemented,`unimplemented type: ${this.valueType}`)}}}class am extends RP{constructor(n){super(n);A(this,"prev");A(this,"next");this.value=n}static createAfter(n,r){const i=new am(r),o=n.next;return n.next=i,i.prev=n,i.next=o,o&&(o.prev=i),i}remove(n){return this.value.remove(n)}getCreatedAt(){return this.value.getCreatedAt()}getPositionedAt(){return this.value.getPositionedAt()}release(){this.prev&&(this.prev.next=this.next),this.next&&(this.next.prev=this.prev),this.prev=void 0,this.next=void 0}getLength(){return this.value.isRemoved()?0:1}getPrev(){return this.prev}getNext(){return this.next}getValue(){return this.value}isRemoved(){return this.value.isRemoved()}}class dh{constructor(){A(this,"dummyHead");A(this,"last");A(this,"nodeMapByIndex");A(this,"nodeMapByCreatedAt");const t=Gt.of(0,to);t.setRemovedAt(to),this.dummyHead=new am(t),this.last=this.dummyHead,this.nodeMapByIndex=new ch,this.nodeMapByCreatedAt=new Map,this.nodeMapByIndex.insert(this.dummyHead),this.nodeMapByCreatedAt.set(this.dummyHead.getCreatedAt().toIDString(),this.dummyHead)}static create(){return new dh}get length(){return this.nodeMapByIndex.length}findNextBeforeExecutedAt(t,n){let r=this.nodeMapByCreatedAt.get(t.toIDString());if(!r)throw new Y(W.ErrInvalidArgument,`cant find the given node: ${t.toIDString()}`);for(;r.getNext()&&r.getNext().getPositionedAt().after(n);)r=r.getNext();return r}release(t){this.last===t&&(this.last=t.getPrev()),t.release(),this.nodeMapByIndex.delete(t),this.nodeMapByCreatedAt.delete(t.getValue().getCreatedAt().toIDString())}insertAfter(t,n,r=n.getCreatedAt()){const i=this.findNextBeforeExecutedAt(t,r),o=am.createAfter(i,n);i===this.last&&(this.last=o),this.nodeMapByIndex.insertAfter(i,o),this.nodeMapByCreatedAt.set(o.getCreatedAt().toIDString(),o)}moveAfter(t,n,r){const i=this.nodeMapByCreatedAt.get(t.toIDString());if(!i)throw new Y(W.ErrInvalidArgument,`cant find the given node: ${t.toIDString()}`);const o=this.nodeMapByCreatedAt.get(n.toIDString());if(!o)throw new Y(W.ErrInvalidArgument,`cant find the given node: ${n.toIDString()}`);i!==o&&(!o.getValue().getMovedAt()||r.after(o.getValue().getMovedAt()))&&(this.release(o),this.insertAfter(i.getCreatedAt(),o.getValue(),r),o.getValue().setMovedAt(r))}insert(t){this.insertAfter(this.last.getCreatedAt(),t)}getByID(t){return this.nodeMapByCreatedAt.get(t.toIDString())}subPathOf(t){const n=this.nodeMapByCreatedAt.get(t.toIDString());if(n)return String(this.nodeMapByIndex.indexOf(n))}purge(t){const n=this.nodeMapByCreatedAt.get(t.getCreatedAt().toIDString());if(!n)throw new Y(W.ErrInvalidArgument,`fail to find the given createdAt: ${t.getCreatedAt().toIDString()}`);this.release(n)}getByIndex(t){if(t>=this.length)return;const[n,r]=this.nodeMapByIndex.find(t);let i=n;if(t===0&&n===this.dummyHead||r>0)do i&&(i=i.getNext());while(i&&i.isRemoved());return i}getPrevCreatedAt(t){let n=this.nodeMapByCreatedAt.get(t.toIDString());do n=n.getPrev();while(this.dummyHead!==n&&n.isRemoved());return n.getValue().getCreatedAt()}delete(t,n){const r=this.nodeMapByCreatedAt.get(t.toIDString()),i=r.isRemoved();return r.remove(n)&&!i&&this.nodeMapByIndex.splayNode(r),r.getValue()}deleteByIndex(t,n){const r=this.getByIndex(t);if(r)return r.remove(n)&&this.nodeMapByIndex.splayNode(r),r.getValue()}getHead(){return this.dummyHead.getValue()}getLast(){return this.last.getValue()}getLastCreatedAt(){return this.last.getCreatedAt()}toTestString(){const t=[];for(const n of this){const r=`${n.getCreatedAt().toIDString()}:${n.getValue().toJSON()}`;n.isRemoved()?t.push(`{${r}}`):t.push(`[${r}]`)}return t.join("")}*[Symbol.iterator](){let t=this.dummyHead.getNext();for(;t;)yield t,t=t.getNext()}}class Ur extends vu{constructor(n,r){super(n);A(this,"elements");this.elements=r}static create(n,r){if(!r)return new Ur(n,dh.create());const i=dh.create();for(const o of r)i.insertAfter(i.getLastCreatedAt(),o.deepcopy());return new Ur(n,i)}subPathOf(n){return this.elements.subPathOf(n)}purge(n){this.elements.purge(n)}insertAfter(n,r){this.elements.insertAfter(n,r)}moveAfter(n,r,i){this.elements.moveAfter(n,r,i)}get(n){const r=this.elements.getByIndex(n);return r==null?void 0:r.getValue()}getByID(n){const r=this.elements.getByID(n);return r==null?void 0:r.getValue()}getHead(){return this.elements.getHead()}getLast(){return this.elements.getLast()}getPrevCreatedAt(n){return this.elements.getPrevCreatedAt(n)}delete(n,r){return this.elements.delete(n,r)}deleteByIndex(n,r){return this.elements.deleteByIndex(n,r)}getLastCreatedAt(){return this.elements.getLastCreatedAt()}get length(){return this.elements.length}*[Symbol.iterator](){for(const n of this.elements)n.isRemoved()||(yield n.getValue())}toTestString(){return this.elements.toTestString()}getDescendants(n){for(const r of this.elements){const i=r.getValue();if(n(i,this))return;i instanceof vu&&i.getDescendants(n)}}toJSON(){const n=[];for(const r of this)n.push(r.toJSON());return`[${n.join(",")}]`}toJS(){return JSON.parse(this.toJSON())}toJSForTest(){const n={};for(let r=0;r({...m,value:m.value?{attributes:zc(m.value.getAttributes()),content:m.value.getContent()}:{attributes:void 0,content:""},type:"content"}));return[d,g,h,[u,u]]}setStyle(n,r,i,o){const[,a]=this.rgaTreeSplit.findNodeWithSplit(n[1],i),[,s]=this.rgaTreeSplit.findNodeWithSplit(n[0],i),u=[],d=this.rgaTreeSplit.findBetween(s,a),h=new Map,p=[];for(const m of d){const v=m.getCreatedAt().getActorID(),E=o!=null&&o.size?o.has(v)?o.get(v):to:M0;if(m.canStyle(i,E)){const w=h.get(v),C=m.getCreatedAt();(!w||C.after(w))&&h.set(v,C),p.push(m)}}const g=[];for(const m of p){if(m.isRemoved())continue;const[v,E]=this.rgaTreeSplit.findIndexesFromRange(m.createPosRange());u.push({type:"style",actor:i.getActorID(),from:v,to:E,value:{attributes:zc(r)}});for(const[w,C]of Object.entries(r)){const[b]=m.getValue().setAttr(w,C,i);b!==void 0&&g.push({parent:m.getValue(),child:b})}}return[h,g,u]}indexRangeToPosRange(n,r){const i=this.rgaTreeSplit.indexToPos(n);return n===r?[i,i]:[i,this.rgaTreeSplit.indexToPos(r)]}get length(){return this.rgaTreeSplit.length}getTreeByIndex(){return this.rgaTreeSplit.getTreeByIndex()}getTreeByID(){return this.rgaTreeSplit.getTreeByID()}toJSON(){const n=[];for(const r of this.rgaTreeSplit)r.isRemoved()||n.push(r.getValue().toJSON());return`[${n.join(",")}]`}toSortedJSON(){return this.toJSON()}toJSForTest(){return{createdAt:this.getCreatedAt().toTestString(),value:JSON.parse(this.toJSON()),type:"YORKIE_TEXT"}}toString(){return this.rgaTreeSplit.toString()}values(){const n=[];for(const r of this.rgaTreeSplit)if(!r.isRemoved()){const i=r.getValue();n.push({attributes:zc(i.getAttributes()),content:i.getContent()})}return n}getRGATreeSplit(){return this.rgaTreeSplit}toTestString(){return this.rgaTreeSplit.toTestString()}deepcopy(){const n=new Ti(this.rgaTreeSplit.deepcopy(),this.getCreatedAt());return n.remove(this.getRemovedAt()),n}findIndexesFromRange(n){return this.rgaTreeSplit.findIndexesFromRange(n)}getGCPairs(){const n=[];for(const r of this.rgaTreeSplit){r.getRemovedAt()&&n.push({parent:this.rgaTreeSplit,child:r});for(const i of r.getValue().getGCPairs())n.push(i)}return n}}class Oh extends so{constructor(n,r,i,o,a,s,u){super(n,u);A(this,"fromPos");A(this,"toPos");A(this,"maxCreatedAtMapByActor");A(this,"content");A(this,"attributes");this.fromPos=r,this.toPos=i,this.maxCreatedAtMapByActor=o,this.content=a,this.attributes=s}static create(n,r,i,o,a,s,u){return new Oh(n,r,i,o,a,s,u)}execute(n){const r=n.findByCreatedAt(this.getParentCreatedAt());if(!r)throw new Y(W.ErrInvalidArgument,`fail to find ${this.getParentCreatedAt()}`);if(!(r instanceof Ti))throw new Y(W.ErrInvalidArgument,"fail to execute, only Text can execute edit");const i=r,[,o,a]=i.edit([this.fromPos,this.toPos],this.content,this.getExecutedAt(),Object.fromEntries(this.attributes),this.maxCreatedAtMapByActor);for(const s of a)n.registerGCPair(s);return{opInfos:o.map(({from:s,to:u,value:d})=>({type:"edit",from:s,to:u,value:d,path:n.createPath(this.getParentCreatedAt())}))}}getEffectedCreatedAt(){return this.getParentCreatedAt()}toTestString(){const n=this.getParentCreatedAt().toTestString(),r=this.fromPos.toTestString(),i=this.toPos.toTestString(),o=this.content;return`${n}.EDIT(${r},${i},${o})`}getFromPos(){return this.fromPos}getToPos(){return this.toPos}getContent(){return this.content}getAttributes(){return this.attributes||new Map}getMaxCreatedAtMapByActor(){return this.maxCreatedAtMapByActor}}class _h extends so{constructor(n,r,i,o,a,s){super(n,s);A(this,"fromPos");A(this,"toPos");A(this,"maxCreatedAtMapByActor");A(this,"attributes");this.fromPos=r,this.toPos=i,this.maxCreatedAtMapByActor=o,this.attributes=a}static create(n,r,i,o,a,s){return new _h(n,r,i,o,a,s)}execute(n){const r=n.findByCreatedAt(this.getParentCreatedAt());if(!r)throw new Y(W.ErrInvalidArgument,`fail to find ${this.getParentCreatedAt()}`);if(!(r instanceof Ti))throw new Y(W.ErrInvalidArgument,"fail to execute, only Text can execute edit");const i=r,[,o,a]=i.setStyle([this.fromPos,this.toPos],this.attributes?Object.fromEntries(this.attributes):{},this.getExecutedAt(),this.maxCreatedAtMapByActor);for(const s of o)n.registerGCPair(s);return{opInfos:a.map(({from:s,to:u,value:d})=>({type:"style",from:s,to:u,value:d,path:n.createPath(this.getParentCreatedAt())}))}}getEffectedCreatedAt(){return this.getParentCreatedAt()}toTestString(){const n=this.getParentCreatedAt().toTestString(),r=this.fromPos.toTestString(),i=this.toPos.toTestString(),o=this.attributes;return`${n}.STYL(${r},${i},${JSON.stringify(o)})`}getFromPos(){return this.fromPos}getToPos(){return this.toPos}getAttributes(){return this.attributes}getMaxCreatedAtMapByActor(){return this.maxCreatedAtMapByActor}}const mKe=2,vKe="root",vs="text";function a0(e,t){let n=0;const r=e.children;for(let i=0;i0)throw new Y(W.ErrRefused,"Text node cannot have children")}updateAncestorsSize(){let t=this.parent;const n=this.isRemoved?-1:1;for(;t&&(t.size+=this.paddedSize*n,!t.isRemoved);)t=t.parent}updateDescendantsSize(){let t=0;for(const n of this._children){const r=n.updateDescendantsSize();n.isRemoved||(t+=r)}return this.size+=t,this.paddedSize}get isText(){return this.type===vs}get paddedSize(){return this.size+(this.isText?0:mKe)}isAncestorOf(t){return EKe(this,t)}get nextSibling(){const t=this.parent.findOffset(this),n=this.parent.children[t+1];if(n)return n}get prevSibling(){const t=this.parent.findOffset(this),n=this.parent.children[t-1];if(n)return n}splitText(t,n){if(t===0||t===this.size)return;const r=this.value.slice(0,t),i=this.value.slice(t);if(!i.length)return;this.value=r;const o=this.cloneText(t+n);return o.value=i,this.parent.insertAfterInternal(o,this),o}get children(){return this._children.filter(t=>!t.isRemoved)}get allChildren(){return[...this._children]}hasTextChild(){return this.children.length>0&&this.children.every(t=>t.isText)}append(...t){if(this.isText)throw new Y(W.ErrRefused,"Text node cannot have children");this._children.push(...t);for(const n of t)n.parent=this,n.updateAncestorsSize()}prepend(...t){if(this.isText)throw new Y(W.ErrRefused,"Text node cannot have children");this._children.unshift(...t);for(const n of t)n.parent=this}insertBefore(t,n){if(this.isText)throw new Y(W.ErrRefused,"Text node cannot have children");const r=this._children.indexOf(n);if(r===-1)throw new Y(W.ErrInvalidArgument,"child not found");this.insertAtInternal(t,r),t.updateAncestorsSize()}insertAfter(t,n){if(this.isText)throw new Y(W.ErrRefused,"Text node cannot have children");const r=this._children.indexOf(n);if(r===-1)throw new Y(W.ErrInvalidArgument,"child not found");this.insertAtInternal(t,r+1),t.updateAncestorsSize()}insertAt(t,n){if(this.isText)throw new Y(W.ErrRefused,"Text node cannot have children");this.insertAtInternal(t,n),t.updateAncestorsSize()}removeChild(t){if(this.isText)throw new Y(W.ErrRefused,"Text node cannot have children");const n=this._children.indexOf(t);if(n===-1)throw new Y(W.ErrInvalidArgument,"child not found");this._children.splice(n,1),t.parent=void 0}splitElement(t,n){const r=this.cloneElement(n);this.parent.insertAfterInternal(r,this),r.updateAncestorsSize();const i=this.children.slice(0,t),o=this.children.slice(t);this._children=i,r._children=o,this.size=this._children.reduce((a,s)=>a+s.paddedSize,0),r.size=r._children.reduce((a,s)=>a+s.paddedSize,0);for(const a of r._children)a.parent=r;return r}insertAfterInternal(t,n){if(this.isText)throw new Y(W.ErrRefused,"Text node cannot have children");const r=this._children.indexOf(n);if(r===-1)throw new Y(W.ErrInvalidArgument,"child not found");this.insertAtInternal(t,r+1)}insertAtInternal(t,n){if(this.isText)throw new Y(W.ErrRefused,"Text node cannot have children");this._children.splice(n,0,t),t.parent=this}findOffset(t){if(this.isText)throw new Y(W.ErrRefused,"Text node cannot have children");if(t.isRemoved){const n=this._children.indexOf(t);return this.allChildren.splice(0,n).filter(i=>!i.isRemoved).length}return this.children.indexOf(t)}findBranchOffset(t){if(this.isText)throw new Y(W.ErrRefused,"Text node cannot have children");let n=t;for(;n;){const r=this._children.indexOf(n);if(r!==-1)return r;n=n.parent}return-1}}function EKe(e,t){if(e===t)return!1;for(;t.parent;){if(t.parent===e)return!0;t=t.parent}return!1}var sn=(e=>(e.Start="Start",e.End="End",e.Text="Text",e))(sn||{});function NP(e,t,n,r){if(t>n)throw new Y(W.ErrInvalidArgument,`from is greater than to: ${t} > ${n}`);if(t>e.size)throw new Y(W.ErrInvalidArgument,`from is out of range: ${t} > ${e.size}`);if(n>e.size)throw new Y(W.ErrInvalidArgument,`to is out of range: ${n} > ${e.size}`);if(t===n)return;let i=0;for(const o of e.children){if(t-o.paddedSizeo.size;(o.isText||u)&&r([o,o.isText?"Text":"Start"],d),NP(o,Math.max(0,a),Math.min(s,o.size),r),d&&r([o,"End"],d)}i+=o.paddedSize}}function zP(e,t,n=0){for(const r of e.children)zP(r,t,n+1);t(e,n)}function y1(e,t,n=0){for(const r of e._children)y1(r,t,n+1);t(e,n)}function my(e,t,n=!0){if(t>e.size)throw new Y(W.ErrInvalidArgument,`index is out of range: ${t} > ${e.size}`);if(e.isText)return{node:e,offset:t};let r=0,i=0;for(const o of e.children){if(n&&o.isText&&o.size>=t-i)return my(o,t-i,n);if(t===i)return{node:e,offset:r};if(!n&&o.paddedSize===t-i)return{node:e,offset:r+1};if(o.paddedSize>t-i)return my(o,t-i-1,n);i+=o.paddedSize,r+=1}return{node:e,offset:r}}function HP(e){return e.isText||e.children.length===0?e:HP(e.children[0])}function CKe(e,t){if(e.sizee===t?0:e0)if(n.right)n.right.parent=n,n=n.right;else return n;else if(r<0)if(n.left)n.left.parent=n,n=n.left;else{let i=n.parent,o=n;for(;i&&o===i.left;)o=i,i=i.parent;return i}else return n}}lastEntry(){if(!this.root)return this.root;let t=this.root;for(;t.right;)t=t.right;return t}size(){return this.counter}isEmpty(){return this.counter===0}getInternal(t,n){for(;n;){const r=this.comparator(t,n.key);if(r===0)return n;r<0?n=n.left:r>0&&(n=n.right)}}putInternal(t,n,r){if(!r)return this.counter+=1,new SKe(t,n,!0);const i=this.comparator(t,r.key);return i<0?r.left=this.putInternal(t,n,r.left):i>0?r.right=this.putInternal(t,n,r.right):r.value=n,this.isRed(r.right)&&!this.isRed(r.left)&&(r=this.rotateLeft(r)),this.isRed(r.left)&&this.isRed(r.left.left)&&(r=this.rotateRight(r)),this.isRed(r.left)&&this.isRed(r.right)&&this.flipColors(r),r}removeInternal(t,n){if(this.comparator(n,t.key)<0)!this.isRed(t.left)&&!this.isRed(t.left.left)&&(t=this.moveRedLeft(t)),t.left=this.removeInternal(t.left,n);else{if(this.isRed(t.left)&&(t=this.rotateRight(t)),this.comparator(n,t.key)===0&&!t.right){this.counter-=1;return}if(!this.isRed(t.right)&&!this.isRed(t.right.left)&&(t=this.moveRedRight(t)),this.comparator(n,t.key)===0){this.counter-=1;const r=this.min(t.right);t.value=r.value,t.key=r.key,t.right=this.removeMin(t.right)}else t.right=this.removeInternal(t.right,n)}return this.fixUp(t)}min(t){return t.left?this.min(t.left):t}removeMin(t){if(t.left)return!this.isRed(t.left)&&!this.isRed(t.left.left)&&(t=this.moveRedLeft(t)),t.left=this.removeMin(t.left),this.fixUp(t)}fixUp(t){return this.isRed(t.right)&&(t=this.rotateLeft(t)),this.isRed(t.left)&&this.isRed(t.left.left)&&(t=this.rotateRight(t)),this.isRed(t.left)&&this.isRed(t.right)&&this.flipColors(t),t}moveRedLeft(t){return this.flipColors(t),this.isRed(t.right.left)&&(t.right=this.rotateRight(t.right),t=this.rotateLeft(t),this.flipColors(t)),t}moveRedRight(t){return this.flipColors(t),this.isRed(t.left.left)&&(t=this.rotateRight(t),this.flipColors(t)),t}isRed(t){return t&&t.isRed}rotateLeft(t){const n=t.right;return t.right=n.left,n.left=t,n.isRed=n.left.isRed,n.left.isRed=!0,n}rotateRight(t){const n=t.left;return t.left=n.right,n.right=t,n.isRed=n.right.isRed,n.right.isRed=!0,n}flipColors(t){t.isRed=!t.isRed,t.left.isRed=!t.left.isRed,t.right.isRed=!t.right.isRed}}class Xi{constructor(t,n){A(this,"parentID");A(this,"leftSiblingID");this.parentID=t,this.leftSiblingID=n}static of(t,n){return new Xi(t,n)}static fromTreePos(t){const{offset:n}=t;let{node:r}=t,i;return r.isText?(r.parent.children[0]===r&&n===0?i=r.parent:i=r,r=r.parent):n===0?i=r:i=r.children[n-1],Xi.of(r.id,Rn.of(i.getCreatedAt(),i.getOffset()+n))}getParentID(){return this.parentID}static fromStruct(t){return Xi.of(Rn.of(jr.fromStruct(t.parentID.createdAt),t.parentID.offset),Rn.of(jr.fromStruct(t.leftSiblingID.createdAt),t.leftSiblingID.offset))}toStruct(){return{parentID:{createdAt:this.getParentID().getCreatedAt().toStruct(),offset:this.getParentID().getOffset()},leftSiblingID:{createdAt:this.getLeftSiblingID().getCreatedAt().toStruct(),offset:this.getLeftSiblingID().getOffset()}}}toTreeNodePair(t){const n=this.getParentID(),r=this.getLeftSiblingID(),i=t.findFloorNode(n);let o=t.findFloorNode(r);if(!i||!o)throw new Y(W.ErrRefused,`cannot find node of CRDTTreePos(${n.toTestString()}, ${r.toTestString()})`);return!r.equals(n)&&r.getOffset()>0&&r.getOffset()===o.id.getOffset()&&o.insPrevID&&(o=t.findFloorNode(o.insPrevID)),[i,o]}getLeftSiblingID(){return this.leftSiblingID}equals(t){return this.getParentID().getCreatedAt().equals(t.getParentID().getCreatedAt())&&this.getParentID().getOffset()===t.getParentID().getOffset()&&this.getLeftSiblingID().getCreatedAt().equals(t.getLeftSiblingID().getCreatedAt())&&this.getLeftSiblingID().getOffset()===t.getLeftSiblingID().getOffset()}}class Rn{constructor(t,n){A(this,"createdAt");A(this,"offset");this.createdAt=t,this.offset=n}static of(t,n){return new Rn(t,n)}static fromStruct(t){return Rn.of(jr.fromStruct(t.createdAt),t.offset)}static createComparator(){return(t,n)=>{const r=t.getCreatedAt().compare(n.getCreatedAt());return r!==0?r:t.getOffset()>n.getOffset()?1:t.getOffset(){const o=i.deepcopy();return o.parent=n,o}),n.insPrevID=this.insPrevID,n.insNextID=this.insNextID,n}get value(){if(!this.isText)throw new Y(W.ErrInvalidType,`cannot get value of element node: ${this.type}`);return this._value}set value(n){if(!this.isText)throw new Y(W.ErrInvalidType,`cannot set value of element node: ${this.type}`);this._value=n,this.size=n.length}get isRemoved(){return!!this.removedAt}remove(n){const r=!this.removedAt;(!this.removedAt||this.removedAt.compare(n)>0)&&(this.removedAt=n),r&&this.updateAncestorsSize()}cloneText(n){return new Nr(Rn.of(this.id.getCreatedAt(),n),this.type,void 0,void 0,this.removedAt)}cloneElement(n){return new Nr(Rn.of(n(),0),this.type,void 0,void 0,this.removedAt)}split(n,r,i){const o=this.isText?this.splitText(r,this.id.getOffset()):this.splitElement(r,i);if(o){if(o.insPrevID=this.id,this.insNextID){const a=n.findFloorNode(this.insNextID);a.insPrevID=o.id,o.insNextID=this.insNextID}this.insNextID=o.id,n.registerNode(o)}return o}getCreatedAt(){return this.id.getCreatedAt()}getOffset(){return this.id.getOffset()}canDelete(n,r){return!this.getCreatedAt().after(r)&&(!this.removedAt||n.after(this.removedAt))}canStyle(n,r){return this.isText?!1:!this.getCreatedAt().after(r)&&(!this.removedAt||n.after(this.removedAt))}setAttrs(n,r){this.attrs||(this.attrs=new Is);const i=new Array;for(const[o,a]of Object.entries(n))i.push(this.attrs.set(o,a,r));return i}purge(n){this.attrs&&this.attrs.purge(n)}getGCPairs(){const n=[];if(!this.attrs)return n;for(const r of this.attrs)r.getRemovedAt()&&n.push({parent:this,child:r});return n}}function vy(e){var n;if(e.isText){const r=e;return{type:r.type,value:r.value}}const t={type:e.type,children:e.children.map(vy)};return e.attrs&&(t.attributes=zc((n=e.attrs)==null?void 0:n.toObject())),t}function _C(e){if(e.isText)return e.value;let t="";return e.attrs&&e.attrs.size()&&(t=" "+Array.from(e.attrs).filter(n=>!n.isRemoved()).sort((n,r)=>n.getKey().localeCompare(r.getKey())).map(n=>{const r=JSON.parse(n.getValue());return typeof r=="string"?`${n.getKey()}="${r}"`:`${n.getKey()}="${Oo(n.getValue())}"`}).join(" ")),`<${e.type}${t}>${e.children.map(n=>_C(n)).join("")}`}function UP(e){if(e.isText){const t=e;return{type:t.type,value:t.value,size:t.size,isRemoved:t.isRemoved}}return{type:e.type,children:e.children.map(UP),size:e.size,isRemoved:e.isRemoved}}class Pi extends Fh{constructor(n,r){super(r);A(this,"indexTree");A(this,"nodeMapByID");this.indexTree=new bKe(n),this.nodeMapByID=new jP(Rn.createComparator()),this.indexTree.traverseAll(i=>{this.nodeMapByID.put(i.id,i)})}static create(n,r){return new Pi(n,r)}findFloorNode(n){const r=this.nodeMapByID.floorEntry(n);if(!(!r||!r.key.getCreatedAt().equals(n.getCreatedAt())))return r.value}registerNode(n){this.nodeMapByID.put(n.id,n)}findNodesAndSplitText(n,r){const[i,o]=n.toTreeNodePair(this);let a=o;const s=i===a,u=a.parent&&!s?a.parent:i;if(a.isText&&a.split(this,n.getLeftSiblingID().getOffset()-a.id.getOffset()),r){const d=u.allChildren,h=s?0:d.indexOf(a)+1;for(let p=h;p{const E=v.getCreatedAt().getActorID(),w=o?o.has(E)?o.get(E):to:M0;if(v.canStyle(i,w)&&r){const C=g.get(E),b=v.getCreatedAt();(!C||b.after(C))&&g.set(E,b);const k=v.setAttrs(r,i),I=k.reduce((D,[,$])=>($&&(D[$.getKey()]=p[$.getKey()]),D),{}),B=v.parent,T=v.prevSibling||v.parent;Object.keys(I).length>0&&h.push({type:"style",from:this.toIndex(B,T),to:this.toIndex(v,v),fromPath:this.toPath(B,T),toPath:this.toPath(v,v),actor:i.getActorID(),value:I});for(const[D]of k)D&&m.push({parent:v,child:D})}}),[g,m,h]}removeStyle(n,r,i,o){const[a,s]=this.findNodesAndSplitText(n[0],i),[u,d]=this.findNodesAndSplitText(n[1],i),h=[],p=new Map,g=[];return this.traverseInPosRange(a,s,u,d,([m])=>{const v=m.getCreatedAt().getActorID(),E=o?o.has(v)?o.get(v):to:M0;if(m.canStyle(i,E)&&r){const w=p.get(v),C=m.getCreatedAt();(!w||C.after(w))&&p.set(v,C),m.attrs||(m.attrs=new Is);for(const I of r){const B=m.attrs.remove(I,i);for(const T of B)g.push({parent:m,child:T})}const b=m.parent,k=m.prevSibling||m.parent;h.push({actor:i.getActorID(),type:"removeStyle",from:this.toIndex(b,k),to:this.toIndex(m,m),fromPath:this.toPath(b,k),toPath:this.toPath(m,m),value:r})}}),[p,g,h]}edit(n,r,i,o,a,s){const[u,d]=this.findNodesAndSplitText(n[0],o),[h,p]=this.findNodesAndSplitText(n[1],o),g=this.toIndex(u,d),m=this.toPath(u,d),v=[],E=[],w=[],C=new Map;this.traverseInPosRange(u,d,h,p,([I,B],T)=>{if(B===sn.Start&&!T)for(const O of I.children)w.push(O);const D=I.getCreatedAt().getActorID(),$=s?s.has(D)?s.get(D):to:M0;if(I.canDelete(o,$)||v.includes(I.parent)){const O=C.get(D),H=I.getCreatedAt();(!O||H.after(O))&&C.set(D,H),(B===sn.Text||B===sn.Start)&&v.push(I),E.push([I,B])}});const b=this.makeDeletionChanges(E,o),k=[];for(const I of v)I.remove(o),I.isRemoved&&k.push({parent:this,child:I});for(const I of w)I.removedAt||u.append(I);if(i>0){let I=0,B=u,T=d;for(;I{u.isRemoved&&(D.remove(o),k.push({parent:this,child:D})),this.nodeMapByID.put(D.id,D)}),T.isRemoved||I.push(T);if(I.length){const T=I.map(D=>vy(D));b.length&&b[b.length-1].from===g?b[b.length-1].value=T:b.push({type:"content",from:g,to:g,fromPath:m,toPath:m,actor:o.getActorID(),value:T})}}return[b,k,C]}editT(n,r,i,o,a){const s=this.findPos(n[0]),u=this.findPos(n[1]);this.edit([s,u],r,i,o,a)}move(n,r,i){throw new Y(W.ErrUnimplemented,`not implemented: ${n}, ${r}, ${i}`)}purge(n){var o;(o=n.parent)==null||o.removeChild(n),this.nodeMapByID.remove(n.id);const r=n.insPrevID,i=n.insNextID;if(r){const a=this.findFloorNode(r);a.insNextID=i}if(i){const a=this.findFloorNode(i);a.insPrevID=r}n.insPrevID=void 0,n.insNextID=void 0}getGCPairs(){const n=[];return this.indexTree.traverse(r=>{r.getRemovedAt()&&n.push({parent:this,child:r});for(const i of r.getGCPairs())n.push(i)}),n}findPos(n,r=!0){const i=this.indexTree.findTreePos(n,r);return Xi.fromTreePos(i)}pathToPosRange(n){const r=this.pathToIndex(n);return[this.findPos(r),this.findPos(r+1)]}pathToPos(n){const r=this.indexTree.pathToIndex(n);return this.findPos(r)}getRoot(){return this.indexTree.getRoot()}getSize(){return this.indexTree.size}getNodeSize(){return this.nodeMapByID.size()}getIndexTree(){return this.indexTree}toXML(){return _C(this.indexTree.getRoot())}toJSON(){return JSON.stringify(this.getRootTreeNode())}toJSForTest(){return{createdAt:this.getCreatedAt().toTestString(),value:JSON.parse(this.toJSON()),type:"YORKIE_TREE"}}toJSInfoForTest(){const n=this.indexTree.getRoot(),r=(i,o=void 0,a=void 0,s=0)=>{var m,v,E,w;let u,d,h;const p=i.isText?{node:i,offset:0}:o&&a?this.toTreePos(o,a):null;p&&(u=this.indexTree.indexOf(p),d=this.indexTree.treePosToPath(p),h=Xi.fromTreePos(p).toStruct());const g={type:i.type,parent:o==null?void 0:o.id.toTestString(),size:i.size,id:i.id.toTestString(),removedAt:(m=i.removedAt)==null?void 0:m.toTestString(),insPrev:(v=i.insPrevID)==null?void 0:v.toTestString(),insNext:(E=i.insNextID)==null?void 0:E.toTestString(),value:i.isText?i.value:void 0,isRemoved:i.isRemoved,children:[],depth:s,attributes:i.attrs?zc((w=i.attrs)==null?void 0:w.toObject()):void 0,index:u,path:d,pos:h};for(let C=0;C0&&C===i[i.length-1].to?(i[i.length-1].to=b,i[i.length-1].toPath=this.toPath(w,m)):i.push({type:"content",from:C,to:b,fromPath:this.toPath(E,p),toPath:this.toPath(w,m),actor:r.getActorID()}))}return i.reverse()}findRightToken([n,r]){if(r===sn.Start){const u=n.allChildren;return u.length>0?[u[0],u[0].isText?sn.Text:sn.Start]:[n,sn.End]}const i=n.parent,o=i.allChildren,a=o.indexOf(n);if(i&&a===o.length-1)return[i,sn.End];const s=o[a+1];return[s,s.isText?sn.Text:sn.Start]}findLeftToken([n,r]){if(r===sn.End){const u=n.allChildren;if(u.length>0){const d=u[u.length-1];return[d,d.isText?sn.Text:sn.End]}return[n,sn.Start]}const i=n.parent,o=i.allChildren,a=o.indexOf(n);if(i&&a===0)return[i,sn.Start];const s=o[a-1];return[s,s.isText?sn.Text:sn.End]}}class Nh extends so{constructor(n,r,i,o,a,s,u){super(n,u);A(this,"fromPos");A(this,"toPos");A(this,"contents");A(this,"splitLevel");A(this,"maxCreatedAtMapByActor");this.fromPos=r,this.toPos=i,this.contents=o,this.splitLevel=a,this.maxCreatedAtMapByActor=s}static create(n,r,i,o,a,s,u){return new Nh(n,r,i,o,a,s,u)}execute(n){var u;const r=n.findByCreatedAt(this.getParentCreatedAt());if(!r)throw new Y(W.ErrInvalidArgument,`fail to find ${this.getParentCreatedAt()}`);if(!(r instanceof Pi))throw new Y(W.ErrInvalidArgument,"fail to execute, only Tree can execute edit");const i=this.getExecutedAt(),o=r,[a,s]=o.edit([this.fromPos,this.toPos],(u=this.contents)==null?void 0:u.map(d=>d.deepcopy()),this.splitLevel,i,(()=>{let d=i.getDelimiter();return this.contents!==void 0&&(d+=this.contents.length),()=>jr.of(i.getLamport(),++d,i.getActorID())})(),this.maxCreatedAtMapByActor);for(const d of s)n.registerGCPair(d);return{opInfos:a.map(({from:d,to:h,value:p,splitLevel:g,fromPath:m,toPath:v})=>({type:"tree-edit",path:n.createPath(this.getParentCreatedAt()),from:d,to:h,value:p,splitLevel:g,fromPath:m,toPath:v}))}}getEffectedCreatedAt(){return this.getParentCreatedAt()}toTestString(){const n=this.getParentCreatedAt().toTestString(),r=`${this.fromPos.getLeftSiblingID().getCreatedAt().toTestString()}/${this.fromPos.getLeftSiblingID().getOffset()}`,i=`${this.toPos.getLeftSiblingID().getCreatedAt().toTestString()}/${this.toPos.getLeftSiblingID().getOffset()}`,o=this.contents||[];return`${n}.EDIT(${r},${i},${o.map(a=>_C(a)).join("")})`}getFromPos(){return this.fromPos}getToPos(){return this.toPos}getContents(){return this.contents}getSplitLevel(){return this.splitLevel}getMaxCreatedAtMapByActor(){return this.maxCreatedAtMapByActor}}class Hc{constructor(t){A(this,"vector");this.vector=t||new Map}set(t,n){this.vector.set(t,n)}get(t){return this.vector.get(t)}maxLamport(){let t=BigInt(0);for(const[,n]of this)n>t&&(t=n);return t}max(t){const n=new Map;for(const[r,i]of t){const o=this.vector.get(r),a=o&&o>i?o:i;n.set(r,a)}for(const[r,i]of this){const o=t.get(r),a=o&&o>i?o:i;n.set(r,a)}return new Hc(n)}afterOrEqual(t){const n=this.vector.get(t.getActorID());return n===void 0?!1:n>=t.getLamport()}deepcopy(){const t=new Map;for(const[n,r]of this.vector)t.set(n,r);return new Hc(t)}filter(t){const n=new Map;for(const[r]of t){const i=this.vector.get(r);i!==void 0&&n.set(r,i)}return new Hc(n)}size(){return this.vector.size}*[Symbol.iterator](){for(const[t,n]of this.vector)yield[t,n]}}const AKe=new Hc(new Map);class as{constructor(t,n,r,i,o){A(this,"clientSeq");A(this,"serverSeq");A(this,"lamport");A(this,"actor");A(this,"versionVector");this.clientSeq=t,this.serverSeq=o,this.lamport=n,this.versionVector=i,this.actor=r}static of(t,n,r,i,o){return new as(t,n,r,i,o)}next(){const t=this.versionVector.deepcopy();return t.set(this.actor,this.lamport+1n),new as(this.clientSeq+1,this.lamport+1n,this.actor,t)}syncClocks(t){const n=t.lamport>this.lamport?t.lamport+1n:this.lamport+1n,r=this.versionVector.max(t.versionVector),i=new as(this.clientSeq,n,this.actor,r);return i.versionVector.set(this.actor,n),i}setClocks(t,n){const r=t>this.lamport?t:this.lamport+1n,i=this.versionVector.max(n);return i.set(this.actor,r),as.of(this.clientSeq,r,this.actor,i)}createTimeTicket(t){return jr.of(this.lamport,t,this.actor)}setActor(t){return new as(this.clientSeq,this.lamport,t,this.versionVector,this.serverSeq)}setVersionVector(t){return new as(this.clientSeq,this.lamport,this.actor,t,this.serverSeq)}getClientSeq(){return this.clientSeq}getServerSeq(){return this.serverSeq?this.serverSeq.toString():""}getLamport(){return this.lamport}getLamportAsString(){return this.lamport.toString()}getActorID(){return this.actor}getVersionVector(){return this.versionVector}toTestString(){return`${this.lamport.toString()}:${this.actor.slice(-2)}:${this.clientSeq}`}}const kKe=new as(0,0n,FC,AKe);class cd{constructor({id:t,operations:n,presenceChange:r,message:i}){A(this,"id");A(this,"operations");A(this,"presenceChange");A(this,"message");this.id=t,this.operations=n||[],this.presenceChange=r,this.message=i}static create({id:t,operations:n,presenceChange:r,message:i}){return new cd({id:t,operations:n,presenceChange:r,message:i})}getID(){return this.id}getMessage(){return this.message}hasOperations(){return this.operations.length>0}getOperations(){return this.operations}setActor(t){for(const n of this.operations)n.setActor(t);this.id=this.id.setActor(t)}hasPresenceChange(){return this.presenceChange!==void 0}getPresenceChange(){return this.presenceChange}execute(t,n,r){const i=[],o=[];for(const a of this.operations){const s=a.execute(t,r);if(!s)continue;const{opInfos:u,reverseOp:d}=s;i.push(...u),d&&o.unshift(d)}return this.presenceChange&&(this.presenceChange.type===Iu.Put?n.set(this.id.getActorID(),Gi(this.presenceChange.presence)):n.delete(this.id.getActorID())),{opInfos:i,reverseOps:o}}toTestString(){return`${this.operations.map(t=>t.toTestString()).join(",")}`}toStruct(){return{changeID:rn.bytesToHex(rn.toChangeID(this.getID()).toBinary()),message:this.getMessage(),operations:this.getOperations().map(t=>rn.bytesToHex(rn.toOperation(t).toBinary())),presenceChange:this.getPresenceChange()}}static fromStruct(t){const{changeID:n,operations:r,presenceChange:i,message:o}=t;return cd.create({id:rn.bytesToChangeID(rn.hexToBytes(n)),operations:r==null?void 0:r.map(a=>rn.bytesToOperation(rn.hexToBytes(a))),presenceChange:i,message:o})}}class E1{constructor(t,n,r,i,o,a,s){A(this,"documentKey");A(this,"checkpoint");A(this,"isRemoved");A(this,"changes");A(this,"snapshot");A(this,"minSyncedTicket");A(this,"versionVector");this.documentKey=t,this.checkpoint=n,this.isRemoved=r,this.changes=i,this.snapshot=a,this.minSyncedTicket=s,this.versionVector=o}static create(t,n,r,i,o,a,s){return new E1(t,n,r,i,o,a,s)}getDocumentKey(){return this.documentKey}getCheckpoint(){return this.checkpoint}getIsRemoved(){return this.isRemoved}getChanges(){return this.changes}hasChanges(){return this.changes.length>0}getChangeSize(){return this.changes.length}hasSnapshot(){return!!this.snapshot&&!!this.snapshot.length}getSnapshot(){return this.snapshot}getMinSyncedTicket(){return this.minSyncedTicket}getVersionVector(){return this.versionVector}}class jc{constructor(t,n){A(this,"serverSeq");A(this,"clientSeq");this.serverSeq=t,this.clientSeq=n}static of(t,n){return new jc(t,n)}increaseClientSeq(t){return t===0?this:new jc(this.serverSeq,this.clientSeq+t)}forward(t){if(this.equals(t))return this;const n=this.serverSeq>t.serverSeq?this.serverSeq:t.serverSeq,r=Math.max(this.clientSeq,t.clientSeq);return jc.of(n,r)}getServerSeqAsString(){return this.serverSeq.toString()}getClientSeq(){return this.clientSeq}getServerSeq(){return this.serverSeq}equals(t){return this.clientSeq===t.clientSeq&&this.serverSeq==t.serverSeq}toTestString(){return`serverSeq=${this.serverSeq}, clientSeq=${this.clientSeq}`}}const DKe=new jc(0n,0);class zo{constructor(t,n){A(this,"createdAt");A(this,"offset");this.createdAt=t,this.offset=n}static of(t,n){return new zo(t,n)}static fromStruct(t){return zo.of(jr.fromStruct(t.createdAt),t.offset)}getCreatedAt(){return this.createdAt}getOffset(){return this.offset}equals(t){return this.createdAt.compare(t.createdAt)===0&&this.offset===t.offset}hasSameCreatedAt(t){return this.createdAt.compare(t.createdAt)===0}split(t){return new zo(this.createdAt,this.offset+t)}toStruct(){return{createdAt:this.createdAt.toStruct(),offset:this.offset}}toTestString(){return`${this.createdAt.toTestString()}:${this.offset}`}toIDString(){return`${this.createdAt.toIDString()}:${this.offset}`}}const IKe=zo.of(to,0);class no{constructor(t,n){A(this,"id");A(this,"relativeOffset");this.id=t,this.relativeOffset=n}static of(t,n){return new no(t,n)}static fromStruct(t){const n=zo.fromStruct(t.id);return no.of(n,t.relativeOffset)}getID(){return this.id}getRelativeOffset(){return this.relativeOffset}getAbsoluteID(){return zo.of(this.id.getCreatedAt(),this.id.getOffset()+this.relativeOffset)}toTestString(){return`${this.id.toTestString()}:${this.relativeOffset}`}toStruct(){return{id:this.id.toStruct(),relativeOffset:this.relativeOffset}}equals(t){return this.id.equals(t.id)?this.relativeOffset===t.relativeOffset:!1}}class yu extends RP{constructor(n,r,i){super(r);A(this,"id");A(this,"removedAt");A(this,"prev");A(this,"next");A(this,"insPrev");A(this,"insNext");this.id=n,this.removedAt=i}static create(n,r){return new yu(n,r)}static createComparator(){return(n,r)=>{const i=n.getCreatedAt().compare(r.getCreatedAt());return i!==0?i:n.getOffset()>r.getOffset()?1:n.getOffset()0&&n.getID().getOffset()==t.getOffset()){if(!n.hasInsPrev())return n;n=n.getInsPrev()}return n}findFloorNode(t){const n=this.treeByID.floorEntry(t);if(n&&!(!n.key.equals(t)&&!n.key.hasSameCreatedAt(t)))return n.value}findBetween(t,n){const r=[];let i=t;for(;i&&i!==n;)r.push(i),i=i.getNext();return r}splitNode(t,n){if(n>t.getContentLength())throw new Y(W.ErrInvalidArgument,"offset should be less than or equal to length");if(n===0)return t;if(n===t.getContentLength())return t.getNext();const r=t.split(n);this.treeByIndex.updateWeight(r),this.insertAfter(t,r);const i=t.getInsNext();return i&&i.setInsPrev(r),r.setInsPrev(t),r}deleteNodes(t,n,r){if(!t.length)return[[],new Map,new Map];const[i,o]=this.filterNodes(t,n,r),a=new Map,s=new Map,u=this.makeChanges(o,n);for(const d of i){const h=d.getCreatedAt().getActorID();(!a.has(h)||d.getID().getCreatedAt().after(a.get(h)))&&a.set(h,d.getID().getCreatedAt()),s.set(d.getID().toIDString(),d),d.remove(n)}return this.deleteIndexNodes(o),[u,a,s]}filterNodes(t,n,r){const i=!!r,o=[],a=[],[s,u]=this.findEdgesOfCandidates(t);a.push(s);for(const d of t){const h=d.getCreatedAt().getActorID(),p=i?r.has(h)?r.get(h):to:M0;d.canDelete(n,p)?o.push(d):a.push(d)}return a.push(u),[o,a]}findEdgesOfCandidates(t){return[t[0].getPrev(),t[t.length-1].getNext()]}makeChanges(t,n){const r=[];let i,o;for(let a=0;ae<0?Math.ceil(e):Math.floor(e);var Ko=(e=>(e[e.IntegerCnt=0]="IntegerCnt",e[e.LongCnt=1]="LongCnt",e))(Ko||{});class Kr extends Fh{constructor(n,r,i){super(i);A(this,"valueType");A(this,"value");switch(this.valueType=n,n){case 0:typeof r=="number"?r>Math.pow(2,31)-1||r<-Math.pow(2,31)?this.value=at.fromNumber(r).toInt():this.value=Tx(r):this.value=r.toInt();break;case 1:typeof r=="number"?this.value=at.fromNumber(r):this.value=r;break;default:throw new Y(W.ErrUnimplemented,`unimplemented type: ${n}`)}}static create(n,r,i){return new Kr(n,r,i)}static valueFromBytes(n,r){switch(n){case 0:return r[0]|r[1]<<8|r[2]<<16|r[3]<<24;case 1:return at.fromBytesLE(Array.from(r));default:throw new Y(W.ErrUnimplemented,`unimplemented type: ${n}`)}}toJSON(){return`${this.value}`}toSortedJSON(){return this.toJSON()}toJSForTest(){return{createdAt:this.getCreatedAt().toTestString(),value:this.value,type:"YORKIE_COUNTER"}}deepcopy(){const n=Kr.create(this.valueType,this.value,this.getCreatedAt());return n.setMovedAt(this.getMovedAt()),n}getType(){return this.valueType}static getCounterType(n){switch(typeof n){case"object":return n instanceof at?1:void 0;case"number":return n>Math.pow(2,31)-1||n<-Math.pow(2,31)?1:0;default:return}}static isSupport(n){return!!Kr.getCounterType(n)}static isInteger(n){return n%1===0}isNumericType(){const n=this.valueType;return n===0||n===1}getValueType(){return this.valueType}getValue(){return this.value}toBytes(){switch(this.valueType){case 0:{const n=this.value;return new Uint8Array([n&255,n>>8&255,n>>16&255,n>>24&255])}case 1:{const r=this.value.toBytesLE();return Uint8Array.from(r)}default:throw new Y(W.ErrUnimplemented,`unimplemented type: ${this.valueType}`)}}increase(n){function r(i){if(!i.isNumericType())throw new TypeError(`Unsupported type of value: ${typeof i.getValue()}`)}return r(this),r(n),this.valueType===1?this.value=this.value.add(n.getValue()):n.getType()===Cn.Long?this.value=this.value+n.getValue().toInt():this.value=at.fromNumber(this.value+Tx(n.getValue())).toInt(),this}}class hd extends so{constructor(n,r,i){super(n,i);A(this,"value");this.value=r}static create(n,r,i){return new hd(n,r,i)}execute(n){const r=n.findByCreatedAt(this.getParentCreatedAt());if(!r)throw new Y(W.ErrInvalidArgument,`fail to find ${this.getParentCreatedAt()}`);if(!(r instanceof Kr))throw new Y(W.ErrInvalidArgument,"fail to execute, only Counter can execute increase");const i=r,o=this.value.deepcopy();return i.increase(o),{opInfos:[{type:"increase",path:n.createPath(this.getParentCreatedAt()),value:o.getValue()}],reverseOp:this.toReverseOperation()}}toReverseOperation(){const n=this.value.deepcopy(),i=n.getType()===Cn.Long?n.getValue().multiply(-1):n.getValue()*-1;return hd.create(this.getParentCreatedAt(),Gt.of(i,n.getCreatedAt()))}getEffectedCreatedAt(){return this.getParentCreatedAt()}toTestString(){return`${this.getParentCreatedAt().toTestString()}.INCREASE.${this.value.toJSON()}`}getValue(){return this.value}}class ys extends so{constructor(n,r,i,o,a,s,u){super(n,u);A(this,"fromPos");A(this,"toPos");A(this,"maxCreatedAtMapByActor");A(this,"attributes");A(this,"attributesToRemove");this.fromPos=r,this.toPos=i,this.maxCreatedAtMapByActor=o,this.attributes=a,this.attributesToRemove=s}static create(n,r,i,o,a,s){return new ys(n,r,i,o,a,new Array,s)}static createTreeRemoveStyleOperation(n,r,i,o,a,s){return new ys(n,r,i,o,new Map,a,s)}execute(n){const r=n.findByCreatedAt(this.getParentCreatedAt());if(!r)throw new Y(W.ErrInvalidArgument,`fail to find ${this.getParentCreatedAt()}`);if(!(r instanceof Pi))throw new Y(W.ErrInvalidArgument,"fail to execute, only Tree can execute edit");const i=r;let o,a;if(this.attributes.size){const s={};[...this.attributes].forEach(([u,d])=>s[u]=d),[,a,o]=i.style([this.fromPos,this.toPos],s,this.getExecutedAt(),this.maxCreatedAtMapByActor)}else{const s=this.attributesToRemove;[,a,o]=i.removeStyle([this.fromPos,this.toPos],s,this.getExecutedAt(),this.maxCreatedAtMapByActor)}for(const s of a)n.registerGCPair(s);return{opInfos:o.map(({from:s,to:u,value:d,fromPath:h,toPath:p})=>({type:"tree-style",from:s,to:u,value:this.attributes.size?{attributes:d}:{attributesToRemove:d},fromPath:h,toPath:p,path:n.createPath(this.getParentCreatedAt())}))}}getEffectedCreatedAt(){return this.getParentCreatedAt()}toTestString(){const n=this.getParentCreatedAt().toTestString(),r=`${this.fromPos.getLeftSiblingID().getCreatedAt().toTestString()}:${this.fromPos.getLeftSiblingID().getOffset()}`,i=`${this.toPos.getLeftSiblingID().getCreatedAt().toTestString()}:${this.toPos.getLeftSiblingID().getOffset()}`;return`${n}.STYLE(${r},${i},${Object.entries(this.attributes||{}).map(([o,a])=>`${o}:"${a}"`).join(" ")})`}getFromPos(){return this.fromPos}getToPos(){return this.toPos}getAttributes(){return this.attributes}getAttributesToRemove(){return this.attributesToRemove}getMaxCreatedAtMapByActor(){return this.maxCreatedAtMapByActor}}function TKe(e){const t=new RC,n=t.data;for(const[r,i]of Object.entries(e))n[r]=JSON.stringify(i);return t}function PKe(e){if(e.type===Iu.Put)return new uh({type:Il.PUT,presence:TKe(e.presence)});if(e.type===Iu.Clear)return new uh({type:Il.CLEAR});throw new Y(W.ErrUnimplemented,"unimplemented type")}function BKe(e){return new BP({serverSeq:e.getServerSeq(),clientSeq:e.getClientSeq()})}function KP(e){return new m1({clientSeq:e.getClientSeq(),lamport:e.getLamport(),actorId:YC(e.getActorID()),versionVector:NC(e.getVersionVector())})}function Te(e){if(e)return new De({lamport:e.getLamport(),delimiter:e.getDelimiter(),actorId:YC(e.getActorID())})}function NC(e){if(!e)return;const t=new v1;for(const[n,r]of e)t.vector[n]=BigInt(r.toString());return t}function VP(e){switch(e){case Cn.Null:return Ve.NULL;case Cn.Boolean:return Ve.BOOLEAN;case Cn.Integer:return Ve.INTEGER;case Cn.Long:return Ve.LONG;case Cn.Double:return Ve.DOUBLE;case Cn.String:return Ve.STRING;case Cn.Bytes:return Ve.BYTES;case Cn.Date:return Ve.DATE;default:throw new Y(W.ErrInvalidType,`unsupported type: ${e}`)}}function GP(e){switch(e){case Ko.IntegerCnt:return Ve.INTEGER_CNT;case Ko.LongCnt:return Ve.LONG_CNT;default:throw new Y(W.ErrInvalidType,`unsupported type: ${e}`)}}function t2(e){if(e instanceof wr)return new ci({type:Ve.JSON_OBJECT,createdAt:Te(e.getCreatedAt()),value:oB(e)});if(e instanceof Ur)return new ci({type:Ve.JSON_ARRAY,createdAt:Te(e.getCreatedAt()),value:uVe(e)});if(e instanceof Ti)return new ci({type:Ve.TEXT,createdAt:Te(e.getCreatedAt())});if(e instanceof Gt)return new ci({type:VP(e.getType()),createdAt:Te(e.getCreatedAt()),value:e.toBytes()});if(e instanceof Kr)return new ci({type:GP(e.getType()),createdAt:Te(e.getCreatedAt()),value:e.toBytes()});if(e instanceof Pi)return new ci({type:Ve.TREE,createdAt:Te(e.getCreatedAt()),value:cVe(e)});throw new Y(W.ErrUnimplemented,"unimplemented element")}function MKe(e){return new ah({createdAt:Te(e.getCreatedAt()),offset:e.getOffset()})}function bp(e){return new Ds({createdAt:Te(e.getID().getCreatedAt()),offset:e.getID().getOffset(),relativeOffset:e.getRelativeOffset()})}function wp(e){return new Dl({parentId:$0(e.getParentID()),leftSiblingId:$0(e.getLeftSiblingID())})}function $0(e){return new mu({createdAt:Te(e.getCreatedAt()),offset:e.getOffset()})}function JP(e){const t=new $C;if(e instanceof Tl){const n=e,r=new Hg;r.parentCreatedAt=Te(n.getParentCreatedAt()),r.key=n.getKey(),r.value=t2(n.getValue()),r.executedAt=Te(n.getExecutedAt()),t.body.case="set",t.body.value=r}else if(e instanceof Lh){const n=e,r=new jg;r.parentCreatedAt=Te(n.getParentCreatedAt()),r.prevCreatedAt=Te(n.getPrevCreatedAt()),r.value=t2(n.getValue()),r.executedAt=Te(n.getExecutedAt()),t.body.case="add",t.body.value=r}else if(e instanceof au){const n=e,r=new Ug;r.parentCreatedAt=Te(n.getParentCreatedAt()),r.prevCreatedAt=Te(n.getPrevCreatedAt()),r.createdAt=Te(n.getCreatedAt()),r.executedAt=Te(n.getExecutedAt()),t.body.case="move",t.body.value=r}else if(e instanceof Tu){const n=e,r=new Kg;r.parentCreatedAt=Te(n.getParentCreatedAt()),r.createdAt=Te(n.getCreatedAt()),r.executedAt=Te(n.getExecutedAt()),t.body.case="remove",t.body.value=r}else if(e instanceof Oh){const n=e,r=new Vg;r.parentCreatedAt=Te(n.getParentCreatedAt()),r.from=bp(n.getFromPos()),r.to=bp(n.getToPos());const i=r.createdAtMapByActor;for(const[a,s]of n.getMaxCreatedAtMapByActor())i[a]=Te(s);r.content=n.getContent();const o=r.attributes;for(const[a,s]of n.getAttributes())o[a]=s;r.executedAt=Te(n.getExecutedAt()),t.body.case="edit",t.body.value=r}else if(e instanceof _h){const n=e,r=new Gg;r.parentCreatedAt=Te(n.getParentCreatedAt()),r.from=bp(n.getFromPos()),r.to=bp(n.getToPos());const i=r.createdAtMapByActor;for(const[a,s]of n.getMaxCreatedAtMapByActor())i[a]=Te(s);const o=r.attributes;for(const[a,s]of n.getAttributes())o[a]=s;r.executedAt=Te(n.getExecutedAt()),t.body.case="style",t.body.value=r}else if(e instanceof hd){const n=e,r=new Jg;r.parentCreatedAt=Te(n.getParentCreatedAt()),r.value=t2(n.getValue()),r.executedAt=Te(n.getExecutedAt()),t.body.case="increase",t.body.value=r}else if(e instanceof Nh){const n=e,r=new Wg,i=r.createdAtMapByActor;for(const[o,a]of n.getMaxCreatedAtMapByActor())i[o]=Te(a);r.parentCreatedAt=Te(n.getParentCreatedAt()),r.from=wp(n.getFromPos()),r.to=wp(n.getToPos()),r.contents=NKe(n.getContents()),r.splitLevel=n.getSplitLevel(),r.executedAt=Te(n.getExecutedAt()),t.body.case="treeEdit",t.body.value=r}else if(e instanceof ys){const n=e,r=new Yg;r.parentCreatedAt=Te(n.getParentCreatedAt()),r.from=wp(n.getFromPos()),r.to=wp(n.getToPos());const i=r.createdAtMapByActor;for(const[a,s]of n.getMaxCreatedAtMapByActor())i[a]=Te(s);const o=n.getAttributesToRemove();if(o.length>0)r.attributesToRemove=o;else{const a=r.attributes;for(const[s,u]of n.getAttributes())a[s]=u}r.executedAt=Te(n.getExecutedAt()),t.body.case="treeStyle",t.body.value=r}else throw new Y(W.ErrUnimplemented,"unimplemented operation");return t}function $Ke(e){const t=[];for(const n of e)t.push(JP(n));return t}function RKe(e){const t=new TP({id:KP(e.getID()),message:e.getMessage()});return e.hasOperations()&&(t.operations=$Ke(e.getOperations())),e.hasPresenceChange()&&(t.presenceChange=PKe(e.getPresenceChange())),t}function FKe(e){const t=[];for(const n of e)t.push(RKe(n));return t}function LKe(e){const t=[];for(const n of e)t.push(new PP({key:n.getStrKey(),element:HC(n.getValue())}));return t}function OKe(e){const t=[];for(const n of e)t.push(new nm({element:HC(n.getValue())}));return t}function _Ke(e){const t=[];for(const n of e){const r=new rm;r.id=MKe(n.getID()),r.value=n.getValue().getContent(),r.removedAt=Te(n.getRemovedAt());const i=r.attributes,o=n.getValue().getAttrs();for(const a of o){const s=new sd;s.value=a.getValue(),s.updatedAt=Te(a.getUpdatedAt()),i[a.getKey()]=s}t.push(r)}return t}function NKe(e){const t=[];if(!e||!e.length)return t;for(const n of e)t.push(new im({content:zC(n)}));return t}function zKe(e){const t={};for(const n of e)t[n.getKey()]=new sd({value:n.getValue(),updatedAt:Te(n.getUpdatedAt()),isRemoved:n.isRemoved()});return t}function zC(e){if(!e)return[];const t=[];return y1(e,(n,r)=>{const i=new sh({id:$0(n.id),type:n.type,removedAt:Te(n.removedAt),depth:r});n.isText&&(i.value=n.value),n.insPrevID&&(i.insPrevId=$0(n.insPrevID)),n.insNextID&&(i.insNextId=$0(n.insNextID)),n.attrs&&(i.attributes=zKe(n.attrs)),t.push(i)}),t}function HKe(e){const t=new Sr;return t.body.case="jsonObject",t.body.value=new qg({nodes:LKe(e.getRHT()),createdAt:Te(e.getCreatedAt()),movedAt:Te(e.getMovedAt()),removedAt:Te(e.getRemovedAt())}),t}function WP(e){const t=new Sr;return t.body.case="jsonArray",t.body.value=new Xg({nodes:OKe(e.getElements()),createdAt:Te(e.getCreatedAt()),movedAt:Te(e.getMovedAt()),removedAt:Te(e.getRemovedAt())}),t}function jKe(e){const t=new Sr;return t.body.case="primitive",t.body.value=new Zg({type:VP(e.getType()),value:e.toBytes(),createdAt:Te(e.getCreatedAt()),movedAt:Te(e.getMovedAt()),removedAt:Te(e.getRemovedAt())}),t}function UKe(e){const t=new Sr;return t.body.case="text",t.body.value=new Qg({nodes:_Ke(e.getRGATreeSplit()),createdAt:Te(e.getCreatedAt()),movedAt:Te(e.getMovedAt()),removedAt:Te(e.getRemovedAt())}),t}function KKe(e){const t=new Sr;return t.body.case="counter",t.body.value=new em({type:GP(e.getType()),value:e.toBytes(),createdAt:Te(e.getCreatedAt()),movedAt:Te(e.getMovedAt()),removedAt:Te(e.getRemovedAt())}),t}function YP(e){const t=new Sr;return t.body.case="tree",t.body.value=new tm({nodes:zC(e.getRoot()),createdAt:Te(e.getCreatedAt()),movedAt:Te(e.getMovedAt()),removedAt:Te(e.getRemovedAt())}),t}function HC(e){if(e instanceof wr)return HKe(e);if(e instanceof Ur)return WP(e);if(e instanceof Gt)return jKe(e);if(e instanceof Ti)return UKe(e);if(e instanceof Kr)return KKe(e);if(e instanceof Pi)return YP(e);throw new Y(W.ErrUnimplemented,"unimplemented element")}function VKe(e){return new Rs({documentKey:e.getDocumentKey(),checkpoint:BKe(e.getCheckpoint()),isRemoved:e.getIsRemoved(),changes:FKe(e.getChanges()),snapshot:e.getSnapshot(),versionVector:NC(e.getVersionVector()),minSyncedTicket:Te(e.getMinSyncedTicket())})}function Px(e){const t=e.findDetails(sKe);for(const n of t)if(n.metadata.code)return n.metadata.code;return""}function qP(e){return as.of(e.clientSeq,BigInt(e.lamport),JC(e.actorId),jC(e.versionVector),BigInt(e.serverSeq))}function jC(e){if(!e)return;const t=new Hc;return Object.entries(e.vector).forEach(([n,r])=>{t.set(n,BigInt(r.toString()))}),t}function Pe(e){if(e)return jr.of(BigInt(e.lamport),e.delimiter,JC(e.actorId))}function UC(e){const t={};return Object.entries(e.data).forEach(([n,r])=>{t[n]=JSON.parse(r)}),t}function GKe(e){const t=e.type;if(t===Il.PUT){const n=UC(e.presence);return{type:Iu.Put,presence:n}}if(t===Il.CLEAR)return{type:Iu.Clear};throw new Y(W.ErrInvalidType,`unsupported type: ${t}`)}function JKe(e){const t=new Map;return Object.entries(e).forEach(([n,r])=>{t.set(n,UC(r))}),t}function XP(e){switch(e){case Ve.NULL:return Cn.Null;case Ve.BOOLEAN:return Cn.Boolean;case Ve.INTEGER:return Cn.Integer;case Ve.LONG:return Cn.Long;case Ve.DOUBLE:return Cn.Double;case Ve.STRING:return Cn.String;case Ve.BYTES:return Cn.Bytes;case Ve.DATE:return Cn.Date}throw new Y(W.ErrUnimplemented,`unimplemented value type: ${e}`)}function sm(e){switch(e){case Ve.INTEGER_CNT:return Ko.IntegerCnt;case Ve.LONG_CNT:return Ko.LongCnt}throw new Y(W.ErrUnimplemented,`unimplemented value type: ${e}`)}function n2(e){switch(e.type){case Ve.JSON_OBJECT:return e.value?iB(e.value):wr.create(Pe(e.createdAt));case Ve.JSON_ARRAY:return e.value?sVe(e.value):Ur.create(Pe(e.createdAt));case Ve.TEXT:return Ti.create(dd.create(),Pe(e.createdAt));case Ve.TREE:return lVe(e.value);case Ve.NULL:case Ve.BOOLEAN:case Ve.INTEGER:case Ve.LONG:case Ve.DOUBLE:case Ve.STRING:case Ve.BYTES:case Ve.DATE:return Gt.of(Gt.valueFromBytes(XP(e.type),e.value),Pe(e.createdAt));case Ve.INTEGER_CNT:case Ve.LONG_CNT:return Kr.create(sm(e.type),Kr.valueFromBytes(sm(e.type),e.value),Pe(e.createdAt))}}function Sp(e){return no.of(zo.of(Pe(e.createdAt),e.offset),e.relativeOffset)}function ZP(e){return zo.of(Pe(e.createdAt),e.offset)}function WKe(e){const t=hh.create(e.value);Object.entries(e.attributes).forEach(([r,i])=>{t.setAttr(r,i.value,Pe(i.updatedAt))});const n=yu.create(ZP(e.id),t);return n.remove(Pe(e.removedAt)),n}function dc(e){return Xi.of(R0(e.parentId),R0(e.leftSiblingId))}function R0(e){return Rn.of(Pe(e.createdAt),e.offset)}function YKe(e){if(!e.length)return;const t=[];return e.forEach(n=>{const r=KC(n.content);t.push(r)}),t}function KC(e){if(e.length===0)return;const t=[];for(const i of e)t.push(XKe(i));const n=t[t.length-1],r=new Map;r.set(e[t.length-1].depth,t[t.length-1]);for(let i=t.length-2;i>=0;i--)r.get(e[i].depth-1).prepend(t[i]),r.set(e[i].depth,t[i]);return n.updateDescendantsSize(),Pi.create(n,to).getRoot()}function qKe(e){const t=Is.create();for(const[n,r]of Object.entries(e))t.setInternal(n,r.value,Pe(r.updatedAt),r.isRemoved);return t}function XKe(e){const t=R0(e.id),n=Nr.create(t,e.type),r=Object.entries(e.attributes);return n.isText?n.value=e.value:r.length&&(n.attrs=qKe(e.attributes)),e.insPrevId&&(n.insPrevID=R0(e.insPrevId)),e.insNextId&&(n.insNextID=R0(e.insNextId)),n.removedAt=Pe(e.removedAt),n}function QP(e){if(e.body.case==="set"){const t=e.body.value;return Tl.create(t.key,n2(t.value),Pe(t.parentCreatedAt),Pe(t.executedAt))}else if(e.body.case==="add"){const t=e.body.value;return Lh.create(Pe(t.parentCreatedAt),Pe(t.prevCreatedAt),n2(t.value),Pe(t.executedAt))}else if(e.body.case==="move"){const t=e.body.value;return au.create(Pe(t.parentCreatedAt),Pe(t.prevCreatedAt),Pe(t.createdAt),Pe(t.executedAt))}else if(e.body.case==="remove"){const t=e.body.value;return Tu.create(Pe(t.parentCreatedAt),Pe(t.createdAt),Pe(t.executedAt))}else if(e.body.case==="edit"){const t=e.body.value,n=new Map;Object.entries(t.createdAtMapByActor).forEach(([i,o])=>{n.set(i,Pe(o))});const r=new Map;return Object.entries(t.attributes).forEach(([i,o])=>{r.set(i,o)}),Oh.create(Pe(t.parentCreatedAt),Sp(t.from),Sp(t.to),n,t.content,r,Pe(t.executedAt))}else if(e.body.case==="style"){const t=e.body.value,n=new Map;Object.entries(t.createdAtMapByActor).forEach(([i,o])=>{n.set(i,Pe(o))});const r=new Map;return Object.entries(t.attributes).forEach(([i,o])=>{r.set(i,o)}),_h.create(Pe(t.parentCreatedAt),Sp(t.from),Sp(t.to),n,r,Pe(t.executedAt))}else{if(e.body.case==="select")return;if(e.body.case==="increase"){const t=e.body.value;return hd.create(Pe(t.parentCreatedAt),n2(t.value),Pe(t.executedAt))}else if(e.body.case==="treeEdit"){const t=e.body.value,n=new Map;return Object.entries(t.createdAtMapByActor).forEach(([r,i])=>{n.set(r,Pe(i))}),Nh.create(Pe(t.parentCreatedAt),dc(t.from),dc(t.to),YKe(t.contents),t.splitLevel,n,Pe(t.executedAt))}else if(e.body.case==="treeStyle"){const t=e.body.value,n=new Map,r=t.attributesToRemove,i=new Map;return t!=null&&t.createdAtMapByActor&&Object.entries(t.createdAtMapByActor).forEach(([o,a])=>{i.set(o,Pe(a))}),(r==null?void 0:r.length)>0?ys.createTreeRemoveStyleOperation(Pe(t.parentCreatedAt),dc(t.from),dc(t.to),i,r,Pe(t.executedAt)):(Object.entries(t.attributes).forEach(([o,a])=>{n.set(o,a)}),ys.create(Pe(t.parentCreatedAt),dc(t.from),dc(t.to),i,n,Pe(t.executedAt)))}else throw new Y(W.ErrUnimplemented,"unimplemented operation")}}function ZKe(e){const t=[];for(const n of e){const r=QP(n);r&&t.push(r)}return t}function eB(e){const t=[];for(const n of e)t.push(cd.create({id:qP(n.id),operations:ZKe(n.operations),presenceChange:n.presenceChange?GKe(n.presenceChange):void 0,message:n.message}));return t}function QKe(e){return jc.of(BigInt(e.serverSeq),e.clientSeq)}function eVe(e){return E1.create(e.documentKey,QKe(e.checkpoint),e.isRemoved,eB(e.changes),jC(e.versionVector),e.snapshot,Pe(e.minSyncedTicket))}function tB(e){const t=new lh;for(const r of e.nodes){const i=VC(r.element);t.set(r.key,i,i.getPositionedAt())}const n=new wr(Pe(e.createdAt),t);return n.setMovedAt(Pe(e.movedAt)),n.setRemovedAt(Pe(e.removedAt)),n}function nB(e){const t=new dh;for(const r of e.nodes)t.insert(VC(r.element));const n=new Ur(Pe(e.createdAt),t);return n.setMovedAt(Pe(e.movedAt)),n.setRemovedAt(Pe(e.removedAt)),n}function tVe(e){const t=Gt.of(Gt.valueFromBytes(XP(e.type),e.value),Pe(e.createdAt));return t.setMovedAt(Pe(e.movedAt)),t.setRemovedAt(Pe(e.removedAt)),t}function nVe(e){const t=new dd;let n=t.getHead();for(const i of e.nodes){const o=t.insertAfter(n,WKe(i));i.insPrevId&&o.setInsPrev(t.findNode(ZP(i.insPrevId))),n=o}const r=new Ti(t,Pe(e.createdAt));return r.setMovedAt(Pe(e.movedAt)),r.setRemovedAt(Pe(e.removedAt)),r}function rVe(e){const t=Kr.create(sm(e.type),Kr.valueFromBytes(sm(e.type),e.value),Pe(e.createdAt));return t.setMovedAt(Pe(e.movedAt)),t.setRemovedAt(Pe(e.removedAt)),t}function rB(e){const t=KC(e.nodes);return Pi.create(t,Pe(e.createdAt))}function VC(e){if(e.body.case==="jsonObject")return tB(e.body.value);if(e.body.case==="jsonArray")return nB(e.body.value);if(e.body.case==="primitive")return tVe(e.body.value);if(e.body.case==="text")return nVe(e.body.value);if(e.body.case==="counter")return rVe(e.body.value);if(e.body.case==="tree")return rB(e.body.value);throw new Y(W.ErrUnimplemented,"unimplemented element")}function iVe(e){if(!e)return{root:wr.create(to),presences:new Map};const t=G3.fromBinary(e);return{root:VC(t.root),presences:JKe(t.presences)}}function oVe(e){const t=NC(e);return GC(t.toBinary())}function aVe(e){const t=WC(e),n=v1.fromBinary(t);return jC(n)}function iB(e){if(!e)throw new Y(W.ErrInvalidArgument,"bytes is empty");const t=Sr.fromBinary(e);return tB(t.body.value)}function oB(e){return HC(e).toBinary()}function sVe(e){if(!e)throw new Y(W.ErrInvalidArgument,"bytes is empty");const t=Sr.fromBinary(e);return nB(t.body.value)}function uVe(e){return WP(e).toBinary()}function lVe(e){if(!e)throw new Y(W.ErrInvalidArgument,"bytes is empty");const t=Sr.fromBinary(e);return rB(t.body.value)}function cVe(e){return YP(e).toBinary()}function GC(e){return e?Array.from(e).map(t=>t.toString(16).padStart(2,"0")).join(""):""}function JC(e){return GC(e)}function WC(e){return new Uint8Array(e.match(/.{1,2}/g).map(t=>parseInt(t,16)))}function YC(e){return WC(e)}function dVe(e){const t=m1.fromBinary(e);return qP(t)}function hVe(e){const t=$C.fromBinary(e);return QP(t)}const rn={fromPresence:UC,toChangePack:VKe,fromChangePack:eVe,fromChanges:eB,toTreeNodes:zC,fromTreeNodes:KC,objectToBytes:oB,bytesToObject:iB,bytesToSnapshot:iVe,bytesToHex:GC,hexToBytes:WC,toHexString:JC,toUint8Array:YC,toOperation:JP,toChangeID:KP,PbChangeID:m1,bytesToChangeID:dVe,bytesToOperation:hVe,versionVectorToHex:oVe,hexToVersionVector:aVe};var or=(e=>(e[e.Trivial=0]="Trivial",e[e.Debug=1]="Debug",e[e.Info=2]="Info",e[e.Warn=3]="Warn",e[e.Error=4]="Error",e[e.Fatal=5]="Fatal",e))(or||{});let tl=3;function aB(e){tl=e}const $e={trivial:(...e)=>{tl>0||typeof console<"u"&&console.log("YORKIE T:",...e)},debug:(...e)=>{tl>1||typeof console<"u"&&console.log("YORKIE D:",...e)},info:(...e)=>{tl>2||typeof console<"u"&&console.log("YORKIE I:",...e)},warn:(...e)=>{tl>3||typeof console<"u"&&(typeof console.warn<"u"?console.warn("YORKIE W:",...e):console.log("YORKIE W:",...e))},error:(...e)=>{tl>4||typeof console<"u"&&(typeof console.error<"u"?console.error("YORKIE E:",...e):console.log("YORKIE E:",...e))},fatal:(...e)=>{typeof console<"u"&&(typeof console.error<"u"?console.error("YORKIE F:",...e):console.log("YORKIE F:",...e))},isEnabled:e=>tl<=e};function sB(){return"xxxxxxxx-xxxx-4xxxy-xxxx-xxxxxxxxxxx".replace(/[xy]/g,e=>{const t=Math.random()*16|0;return(e==="x"?t:t&3|8).toString(16)})}class fVe{constructor(t,n,r,i,o){A(this,"reconnectStreamDelay");A(this,"doc");A(this,"docID");A(this,"syncMode");A(this,"remoteChangeEventReceived");A(this,"watchStream");A(this,"watchLoopTimerID");A(this,"watchAbortController");A(this,"unsubscribeBroadcastEvent");this.reconnectStreamDelay=t,this.doc=n,this.docID=r,this.syncMode=i,this.remoteChangeEventReceived=!1,this.unsubscribeBroadcastEvent=o}changeSyncMode(t){this.syncMode=t}needRealtimeSync(){return this.syncMode===Yp.RealtimeSyncOff?!1:this.syncMode===Yp.RealtimePushOnly?this.doc.hasLocalChanges():this.syncMode!==Yp.Manual&&(this.doc.hasLocalChanges()||this.remoteChangeEventReceived)}async runWatchLoop(t){const n=async()=>{if(this.watchStream)return Promise.resolve();this.watchLoopTimerID&&(clearTimeout(this.watchLoopTimerID),this.watchLoopTimerID=void 0);try{[this.watchStream,this.watchAbortController]=await t(()=>{this.watchStream=void 0,this.watchAbortController=void 0,this.watchLoopTimerID=setTimeout(n,this.reconnectStreamDelay)})}catch{}};await n()}cancelWatchStream(){this.watchStream&&this.watchAbortController&&(this.watchAbortController.abort(),this.watchStream=void 0,this.watchAbortController=void 0),clearTimeout(this.watchLoopTimerID),this.watchLoopTimerID=void 0}}const r2=()=>{};class pVe{constructor(t){A(this,"finalized",!1);A(this,"observers",[]);A(this,"finalError");try{t(this)}catch(n){this.error(n)}}next(t){this.forEachObserver(n=>{n.next(t)})}error(t){this.forEachObserver(n=>{n.error(t)}),this.close(t)}complete(){this.forEachObserver(t=>{t.complete()}),this.close()}subscribe(t,n,r){let i;if(!t)throw new Y(W.ErrInvalidArgument,"missing observer");if(this.finalized)throw new Y(W.ErrRefused,"observable is finalized due to previous error");typeof t=="object"?i=t:i={next:t,error:n,complete:r},i.next===void 0&&(i.next=r2),i.error===void 0&&(i.error=r2),i.complete===void 0&&(i.complete=r2);const o=sB(),a=this.unsubscribeOne.bind(this,o);if(this.observers.push({subscriptionID:o,observer:i}),this.finalized)try{this.finalError?i.error(this.finalError):i.complete()}catch(s){$e.warn(s)}return a}unsubscribeOne(t){var n;this.observers=(n=this.observers)==null?void 0:n.filter(r=>r.subscriptionID!==t)}forEachObserver(t){if(!this.finalized)for(let n=0;nt}}class Tc{constructor(t,n,r,i){A(this,"id");A(this,"delimiter");A(this,"message");A(this,"root");A(this,"operations");A(this,"presenceChange");A(this,"previousPresence");A(this,"reversePresenceKeys");this.id=t,this.delimiter=$P,this.root=n,this.operations=[],this.previousPresence=Gi(r),this.presenceChange=void 0,this.reversePresenceKeys=new Set,this.message=i}static create(t,n,r,i){return new Tc(t,n,r,i)}push(t){this.operations.push(t)}registerElement(t,n){this.root.registerElement(t,n)}registerRemovedElement(t){this.root.registerRemovedElement(t)}registerGCPair(t){this.root.registerGCPair(t)}getChange(){return cd.create({id:this.id,operations:this.operations,presenceChange:this.presenceChange,message:this.message})}hasChange(){return this.operations.length>0||this.presenceChange!==void 0}setPresenceChange(t){this.presenceChange=t}setReversePresence(t,n){for(const r of Object.keys(t))n!=null&&n.addToHistory?this.reversePresenceKeys.add(r):this.reversePresenceKeys.delete(r)}getReversePresence(){if(this.reversePresenceKeys.size===0)return;const t={};for(const n of this.reversePresenceKeys)t[n]=this.previousPresence[n];return t}issueTimeTicket(){return this.delimiter+=1,this.id.createTimeTicket(this.delimiter)}getLastTimeTicket(){return this.id.createTimeTicket(this.delimiter)}}class fh{constructor(t){A(this,"rootObject");A(this,"elementPairMapByCreatedAt");A(this,"gcElementSetByCreatedAt");A(this,"gcPairMap");this.rootObject=t,this.elementPairMapByCreatedAt=new Map,this.gcElementSetByCreatedAt=new Set,this.gcPairMap=new Map,this.registerElement(t,void 0),t.getDescendants(n=>{if(n.getRemovedAt()&&this.registerRemovedElement(n),n instanceof Ti||n instanceof Pi)for(const r of n.getGCPairs())this.registerGCPair(r);return!1})}static create(){return new fh(wr.create(to))}findByCreatedAt(t){const n=this.elementPairMapByCreatedAt.get(t.toIDString());if(n)return n.element}findElementPairByCreatedAt(t){return this.elementPairMapByCreatedAt.get(t.toIDString())}createSubPaths(t){let n=this.elementPairMapByCreatedAt.get(t.toIDString());if(!n)return[];const r=[];for(;n.parent;){const i=n.element.getCreatedAt(),o=n.parent.subPathOf(i);if(o===void 0)throw new Y(W.ErrInvalidArgument,`cant find the given element: ${i.toIDString()}`);r.unshift(o),n=this.elementPairMapByCreatedAt.get(n.parent.getCreatedAt().toIDString())}return r.unshift("$"),r}createPath(t){return this.createSubPaths(t).join(".")}registerElement(t,n){this.elementPairMapByCreatedAt.set(t.getCreatedAt().toIDString(),{parent:n,element:t}),t instanceof vu&&t.getDescendants((r,i)=>(this.registerElement(r,i),!1))}deregisterElement(t){let n=0;const r=i=>{const o=i.getCreatedAt().toIDString();this.elementPairMapByCreatedAt.delete(o),this.gcElementSetByCreatedAt.delete(o),n++};return r(t),t instanceof vu&&t.getDescendants(i=>(r(i),!1)),n}registerRemovedElement(t){this.gcElementSetByCreatedAt.add(t.getCreatedAt().toIDString())}registerGCPair(t){if(this.gcPairMap.get(t.child.toIDString())){this.gcPairMap.delete(t.child.toIDString());return}this.gcPairMap.set(t.child.toIDString(),t)}getElementMapSize(){return this.elementPairMapByCreatedAt.size}getGarbageElementSetSize(){const t=new Set;for(const n of this.gcElementSetByCreatedAt){t.add(n);const r=this.elementPairMapByCreatedAt.get(n);r.element instanceof vu&&r.element.getDescendants(i=>(t.add(i.getCreatedAt().toIDString()),!1))}return t.size}getObject(){return this.rootObject}getGarbageLen(){return this.getGarbageElementSetSize()+this.gcPairMap.size}deepcopy(){return new fh(this.rootObject.deepcopy())}garbageCollect(t){let n=0;for(const r of this.gcElementSetByCreatedAt){const i=this.elementPairMapByCreatedAt.get(r),o=i.element.getRemovedAt();o&&(t!=null&&t.afterOrEqual(o))&&(i.parent.purge(i.element),n+=this.deregisterElement(i.element))}for(const[,r]of this.gcPairMap){const i=r.child.getRemovedAt();i&&(t!=null&&t.afterOrEqual(i))&&(r.parent.purge(r.child),this.gcPairMap.delete(r.child.toIDString()),n+=1)}return n}toJSON(){return this.rootObject.toJSON()}toSortedJSON(){return this.rootObject.toSortedJSON()}getStats(){return{elements:this.getElementMapSize(),gcPairs:this.gcPairMap.size,gcElements:this.getGarbageElementSetSize()}}}function uB(e,t){const n=new ph(e);return new Proxy(t,n.getHandlers())}class ph{constructor(t){A(this,"context");A(this,"handlers");this.context=t,this.handlers={set:(n,r,i)=>($e.isEnabled(or.Trivial)&&$e.trivial(`obj[${r}]=${JSON.stringify(i)}`),ph.setInternal(t,n,r,i),!0),get:(n,r)=>($e.isEnabled(or.Trivial)&&$e.trivial(`obj[${r}]`),r==="getID"?()=>n.getCreatedAt():r==="toJSON"||r==="toString"?()=>n.toJSON():r==="toJS"?()=>n.toJS():r==="toJSForTest"?()=>n.toJSForTest():nl(t,n.get(r))),ownKeys:n=>n.getKeys(),getOwnPropertyDescriptor:()=>({enumerable:!0,configurable:!0}),deleteProperty:(n,r)=>($e.isEnabled(or.Trivial)&&$e.trivial(`obj[${r}]`),ph.deleteInternal(t,n,r),!0)}}static setInternal(t,n,r,i){if(r.includes("."))throw new Y(W.ErrInvalidObjectKey,"key must not contain the '.'.");const o=t.issueTimeTicket(),a=um(t,i,o),s=n.set(r,a,o);t.registerElement(a,n),s&&t.registerRemovedElement(s),t.push(Tl.create(r,a.deepcopy(),n.getCreatedAt(),o))}static buildObjectMembers(t,n){const r={};for(const[i,o]of Object.entries(n)){if(i.includes("."))throw new Y(W.ErrInvalidObjectKey,"key must not contain the '.'.");const a=t.issueTimeTicket(),s=um(t,o,a);r[i]=s}return r}static deleteInternal(t,n,r){const i=t.issueTimeTicket(),o=n.deleteByKey(r,i);o&&(t.push(Tu.create(n.getCreatedAt(),o.getCreatedAt(),i)),t.registerRemovedElement(o))}getHandlers(){return this.handlers}}function mVe(e,t){const n=new qt(e,t);return new Proxy(t,n.getHandlers())}function vVe(e){return typeof e=="string"||e instanceof String?!isNaN(e):!1}function yVe(e){return["concat","entries","every","filter","find","findIndex","forEach","join","keys","map","reduce","reduceRight","slice","some","toLocaleString","toString","values"].includes(e)}class qt{constructor(t,n){A(this,"context");A(this,"handlers");A(this,"array");this.context=t,this.array=n,this.handlers={get:(r,i,o)=>i==="getID"?()=>r.getCreatedAt():i==="getElementByID"?a=>{const s=r.getByID(a);if(!(!s||s.isRemoved()))return Xs(t,s)}:i==="getElementByIndex"?a=>{const s=r.get(a);return Xs(t,s)}:i==="getLast"?()=>Xs(t,r.getLast()):i==="deleteByID"?a=>{const s=qt.deleteInternalByID(t,r,a);return Xs(t,s)}:i==="insertAfter"?(a,s)=>{const u=qt.insertAfterInternal(t,r,a,s);return Xs(t,u)}:i==="insertBefore"?(a,s)=>{const u=qt.insertBeforeInternal(t,r,a,s);return Xs(t,u)}:i==="moveBefore"?(a,s)=>{qt.moveBeforeInternal(t,r,a,s)}:i==="moveAfter"?(a,s)=>{qt.moveAfterInternal(t,r,a,s)}:i==="moveFront"?a=>{qt.moveFrontInternal(t,r,a)}:i==="moveLast"?a=>{qt.moveLastInternal(t,r,a)}:vVe(i)?nl(t,r.get(Number(i))):i==="push"?a=>qt.pushInternal(t,r,a):i==="splice"?(a,s,...u)=>qt.splice(t,r,a,s,...u):i==="length"?r.length:typeof i=="symbol"&&i===Symbol.iterator?qt.iteratorInternal.bind(this,t,r):i==="includes"?(a,s)=>qt.includes(t,r,a,s):i==="indexOf"?(a,s)=>qt.indexOf(t,r,a,s):i==="lastIndexOf"?(a,s)=>qt.lastIndexOf(t,r,a,s):i==="toJSForTest"?()=>r.toJSForTest():i==="toTestString"?()=>qt.toTestString(r):typeof i=="string"&&yVe(i)?(...a)=>{const s=Array.from(r).map(u=>nl(t,u));return Array.prototype[i].apply(s,a)}:Reflect.get(r,i,o),deleteProperty:(r,i)=>($e.isEnabled(or.Trivial)&&$e.trivial(`array[${i}]`),qt.deleteInternalByIndex(t,r,Number.parseInt(i)),!0)}}static*iteratorInternal(t,n){for(const r of n)yield Xs(t,r)}static buildArrayElements(t,n){const r=[];for(const i of n){const o=t.issueTimeTicket(),a=um(t,i,o);r.push(a)}return r}static pushInternal(t,n,r){return qt.insertAfterInternal(t,n,n.getLastCreatedAt(),r),n.length}static moveBeforeInternal(t,n,r,i){const o=t.issueTimeTicket(),a=n.getPrevCreatedAt(r);n.moveAfter(a,i,o),t.push(au.create(n.getCreatedAt(),a,i,o))}static moveAfterInternal(t,n,r,i){const o=t.issueTimeTicket();n.moveAfter(r,i,o),t.push(au.create(n.getCreatedAt(),r,i,o))}static moveFrontInternal(t,n,r){const i=t.issueTimeTicket(),o=n.getHead();n.moveAfter(o.getCreatedAt(),r,i),t.push(au.create(n.getCreatedAt(),o.getCreatedAt(),r,i))}static moveLastInternal(t,n,r){const i=t.issueTimeTicket(),o=n.getLastCreatedAt();n.moveAfter(o,r,i),t.push(au.create(n.getCreatedAt(),o,r,i))}static insertAfterInternal(t,n,r,i){const o=t.issueTimeTicket(),a=um(t,i,o);return n.insertAfter(r,a),t.registerElement(a,n),t.push(Lh.create(n.getCreatedAt(),r,a.deepcopy(),o)),a}static insertBeforeInternal(t,n,r,i){return qt.insertAfterInternal(t,n,n.getPrevCreatedAt(r),i)}static deleteInternalByIndex(t,n,r){const i=t.issueTimeTicket(),o=n.deleteByIndex(r,i);if(o)return t.push(Tu.create(n.getCreatedAt(),o.getCreatedAt(),i)),t.registerRemovedElement(o),o}static deleteInternalByID(t,n,r){const i=t.issueTimeTicket(),o=n.delete(r,i);return t.push(Tu.create(n.getCreatedAt(),o.getCreatedAt(),i)),t.registerRemovedElement(o),o}static splice(t,n,r,i,...o){const a=n.length,s=r>=0?Math.min(r,a):Math.max(a+r,0),u=i===void 0?a:i<0?s:Math.min(s+i,a),d=[];for(let h=s;h=o)return!1;if(Gt.isSupport(r))return Array.from(n).map(d=>nl(t,d)).includes(r,a);for(let u=a;u=o)return-1;if(Gt.isSupport(r))return Array.from(n).map(d=>nl(t,d)).indexOf(r,a);for(let u=a;u=o?o-1:i<0?i+o:i;if(a<0)return-1;if(Gt.isSupport(r))return Array.from(n).map(d=>nl(t,d)).lastIndexOf(r,a);for(let u=a;u>0;u--)if(((s=n.get(u))==null?void 0:s.getID())===r.getID())return u;return-1}static toTestString(t){return t.toTestString()}getHandlers(){return this.handlers}}class C1{constructor(t,n){A(this,"context");A(this,"text");this.context=t,this.text=n}initialize(t,n){this.context=t,this.text=n}getID(){return this.text.getID()}edit(t,n,r,i){if(!this.context||!this.text)throw new Y(W.ErrNotInitialized,"Text is not initialized yet");if(t>n)throw new Y(W.ErrInvalidArgument,"from should be less than or equal to to");const o=this.text.indexRangeToPosRange(t,n);$e.isEnabled(or.Debug)&&$e.debug(`EDIT: f:${t}->${o[0].toTestString()}, t:${n}->${o[1].toTestString()} c:${r}`);const a=i?ud(i):void 0,s=this.context.issueTimeTicket(),[u,,d,h]=this.text.edit(o,r,s,a);for(const p of d)this.context.registerGCPair(p);return this.context.push(new Oh(this.text.getCreatedAt(),o[0],o[1],u,r,a?new Map(Object.entries(a)):new Map,s)),this.text.findIndexesFromRange(h)}delete(t,n){return this.edit(t,n,"")}empty(){return this.edit(0,this.length,"")}setStyle(t,n,r){if(!this.context||!this.text)throw new Y(W.ErrNotInitialized,"Text is not initialized yet");if(t>n)throw new Y(W.ErrInvalidArgument,"from should be less than or equal to to");const i=this.text.indexRangeToPosRange(t,n);$e.isEnabled(or.Debug)&&$e.debug(`STYL: f:${t}->${i[0].toTestString()}, t:${n}->${i[1].toTestString()} a:${JSON.stringify(r)}`);const o=ud(r),a=this.context.issueTimeTicket(),[s,u]=this.text.setStyle(i,o,a);for(const d of u)this.context.registerGCPair(d);return this.context.push(new _h(this.text.getCreatedAt(),i[0],i[1],s,new Map(Object.entries(o)),a)),!0}indexRangeToPosRange(t){if(!this.context||!this.text)throw new Y(W.ErrNotInitialized,"Text is not initialized yet");const n=this.text.indexRangeToPosRange(t[0],t[1]);return[n[0].toStruct(),n[1].toStruct()]}posRangeToIndexRange(t){if(!this.context||!this.text)throw new Y(W.ErrNotInitialized,"Text is not initialized yet");const n=this.text.findIndexesFromRange([no.fromStruct(t[0]),no.fromStruct(t[1])]);return[n[0],n[1]]}toTestString(){if(!this.context||!this.text)throw new Y(W.ErrNotInitialized,"Text is not initialized yet");return this.text.toTestString()}values(){if(!this.context||!this.text)throw new Y(W.ErrNotInitialized,"Text is not initialized yet");return this.text.values()}get length(){return this.text.length}getTreeByIndex(){return this.text.getTreeByIndex()}getTreeByID(){return this.text.getTreeByID()}toString(){if(!this.context||!this.text)throw new Y(W.ErrNotInitialized,"Text is not initialized yet");return this.text.toString()}toJSON(){if(!this.context||!this.text)throw new Y(W.ErrNotInitialized,"Text is not initialized yet");return this.text.toJSON()}toJSForTest(){if(!this.context||!this.text)throw new Y(W.ErrNotInitialized,"Text is not initialized yet");return this.text.toJSForTest()}createRangeForTest(t,n){if(!this.context||!this.text)throw new Y(W.ErrNotInitialized,"Text is not initialized yet");return this.text.indexRangeToPosRange(t,n)}}class b1{constructor(t,n){A(this,"valueType");A(this,"value");A(this,"context");A(this,"counter");this.valueType=t,this.value=n}initialize(t,n){this.valueType=n.getValueType(),this.context=t,this.counter=n,this.value=n.getValue()}getID(){return this.counter.getID()}getValue(){return this.value}getValueType(){return this.valueType}increase(t){if(!this.context||!this.counter)throw new Y(W.ErrNotInitialized,"Counter is not initialized yet");const n=this.context.issueTimeTicket(),r=Gt.of(t,n);if(!r.isNumericType())throw new TypeError(`Unsupported type of value: ${typeof r.getValue()}`);return this.counter.increase(r),this.context.push(hd.create(this.counter.getCreatedAt(),r,n)),this}toJSForTest(){if(!this.context||!this.counter)throw new Y(W.ErrNotInitialized,"Counter is not initialized yet");return this.counter.toJSForTest()}}function qC(e,t,n){const{type:r}=e,i=n.issueTimeTicket();if(r===vs){lB(e);const{value:o}=e,a=Nr.create(Rn.of(i,0),r,o);t.append(a)}else{const{children:o=[]}=e,{attributes:a}=e;let s;if(typeof a=="object"&&!MP(a)){const d=ud(a);s=new Is;for(const[h,p]of Object.entries(d))s.set(h,p,i)}const u=Nr.create(Rn.of(i,0),r,void 0,s);t.append(u);for(const d of o)qC(d,u,n)}}function EVe(e,t){const{type:n}=t,r=e.issueTimeTicket();let i;if(t.type===vs){const{value:o}=t;i=Nr.create(Rn.of(r,0),n,o)}else if(t){const{children:o=[]}=t,{attributes:a}=t;let s;if(typeof a=="object"&&!MP(a)){const u=ud(a);s=new Is;for(const[d,h]of Object.entries(u))s.set(d,h,r)}i=Nr.create(Rn.of(e.issueTimeTicket(),0),n,void 0,s);for(const u of o)qC(u,i,e)}return i}function lB(e){if(!e.value.length)throw new Y(W.ErrInvalidArgument,"text node cannot have empty value");return!0}function Bx(e){if(!e.length)return!0;if(e[0].type===vs)for(const n of e){const{type:r}=n;if(r!==vs)throw new Y(W.ErrInvalidArgument,"element node and text node cannot be passed together");lB(n)}else for(const n of e){const{type:r}=n;if(r===vs)throw new Y(W.ErrInvalidArgument,"element node and text node cannot be passed together")}return!0}class w1{constructor(t){A(this,"initialRoot");A(this,"context");A(this,"tree");this.initialRoot=t}initialize(t,n){this.context=t,this.tree=n}getID(){return this.tree.getID()}buildRoot(t){if(!this.initialRoot)return Nr.create(Rn.of(t.issueTimeTicket(),0),vKe);const n=Nr.create(Rn.of(t.issueTimeTicket(),0),this.initialRoot.type);for(const r of this.initialRoot.children)qC(r,n,t);return n}getSize(){if(!this.context||!this.tree)throw new Y(W.ErrNotInitialized,"Tree is not initialized yet");return this.tree.getSize()}getNodeSize(){if(!this.context||!this.tree)throw new Y(W.ErrNotInitialized,"Tree is not initialized yet");return this.tree.getNodeSize()}getIndexTree(){if(!this.context||!this.tree)throw new Y(W.ErrNotInitialized,"Tree is not initialized yet");return this.tree.getIndexTree()}styleByPath(t,n){if(!this.context||!this.tree)throw new Y(W.ErrNotInitialized,"Tree is not initialized yet");if(!t.length)throw new Y(W.ErrInvalidArgument,"path should not be empty");const[r,i]=this.tree.pathToPosRange(t),o=this.context.issueTimeTicket(),a=n?ud(n):void 0,[s]=this.tree.style([r,i],a,o);this.context.push(ys.create(this.tree.getCreatedAt(),r,i,s,a?new Map(Object.entries(a)):new Map,o))}style(t,n,r){if(!this.context||!this.tree)throw new Y(W.ErrNotInitialized,"Tree is not initialized yet");if(t>n)throw new Y(W.ErrInvalidArgument,"from should be less than or equal to to");const i=this.tree.findPos(t),o=this.tree.findPos(n),a=this.context.issueTimeTicket(),s=r?ud(r):void 0,[u,d]=this.tree.style([i,o],s,a);for(const h of d)this.context.registerGCPair(h);this.context.push(ys.create(this.tree.getCreatedAt(),i,o,u,s?new Map(Object.entries(s)):new Map,a))}removeStyle(t,n,r){if(!this.context||!this.tree)throw new Y(W.ErrNotInitialized,"Tree is not initialized yet");if(t>n)throw new Y(W.ErrInvalidArgument,"from should be less than or equal to to");const i=this.tree.findPos(t),o=this.tree.findPos(n),a=this.context.issueTimeTicket(),[s,u]=this.tree.removeStyle([i,o],r,a);for(const d of u)this.context.registerGCPair(d);this.context.push(ys.createTreeRemoveStyleOperation(this.tree.getCreatedAt(),i,o,s,r,a))}editInternal(t,n,r,i=0){var d;if(r.length!==0&&r[0]&&(Bx(r),r[0].type!==vs))for(const h of r){const{children:p=[]}=h;Bx(p)}const o=this.context.getLastTimeTicket();let a=new Array;if(((d=r[0])==null?void 0:d.type)===vs){let h="";for(const p of r){const{value:g}=p;h+=g}a.push(Nr.create(Rn.of(this.context.issueTimeTicket(),0),vs,h))}else a=r.map(h=>h&&EVe(this.context,h)).filter(h=>h);const[,s,u]=this.tree.edit([t,n],a.length?a.map(h=>h==null?void 0:h.deepcopy()):void 0,i,o,()=>this.context.issueTimeTicket());for(const h of s)this.context.registerGCPair(h);return this.context.push(Nh.create(this.tree.getCreatedAt(),t,n,a.length?a:void 0,i,u,o)),!0}editByPath(t,n,r,i=0){if(!this.context||!this.tree)throw new Y(W.ErrNotInitialized,"Tree is not initialized yet");if(t.length!==n.length)throw new Y(W.ErrInvalidArgument,"path length should be equal");if(!t.length||!n.length)throw new Y(W.ErrInvalidArgument,"path should not be empty");const o=this.tree.pathToPos(t),a=this.tree.pathToPos(n);return this.editInternal(o,a,r?[r]:[],i)}editBulkByPath(t,n,r,i=0){if(!this.context||!this.tree)throw new Y(W.ErrNotInitialized,"Tree is not initialized yet");if(t.length!==n.length)throw new Y(W.ErrInvalidArgument,"path length should be equal");if(!t.length||!n.length)throw new Y(W.ErrInvalidArgument,"path should not be empty");const o=this.tree.pathToPos(t),a=this.tree.pathToPos(n);return this.editInternal(o,a,r,i)}edit(t,n,r,i=0){if(!this.context||!this.tree)throw new Y(W.ErrNotInitialized,"Tree is not initialized yet");if(t>n)throw new Y(W.ErrInvalidArgument,"from should be less than or equal to to");const o=this.tree.findPos(t),a=this.tree.findPos(n);return this.editInternal(o,a,r?[r]:[],i)}editBulk(t,n,r,i=0){if(!this.context||!this.tree)throw new Y(W.ErrNotInitialized,"Tree is not initialized yet");if(t>n)throw new Y(W.ErrInvalidArgument,"from should be less than or equal to to");const o=this.tree.findPos(t),a=this.tree.findPos(n);return this.editInternal(o,a,r,i)}toXML(){if(!this.context||!this.tree)throw new Y(W.ErrNotInitialized,"Tree is not initialized yet");return this.tree.toXML()}toJSON(){if(!this.context||!this.tree)throw new Y(W.ErrNotInitialized,"Tree is not initialized yet");return this.tree.toJSON()}toJSForTest(){if(!this.context||!this.tree)throw new Y(W.ErrNotInitialized,"Tree is not initialized yet");return this.tree.toJSForTest()}toJSInfoForTest(){if(!this.context||!this.tree)throw new Y(W.ErrNotInitialized,"Tree is not initialized yet");return this.tree.toJSInfoForTest()}getRootTreeNode(){if(!this.context||!this.tree)throw new Y(W.ErrNotInitialized,"Tree is not initialized yet");return this.tree.getRootTreeNode()}indexToPath(t){if(!this.context||!this.tree)throw new Y(W.ErrNotInitialized,"Tree is not initialized yet");return this.tree.indexToPath(t)}pathToIndex(t){if(!this.context||!this.tree)throw new Y(W.ErrNotInitialized,"Tree is not initialized yet");return this.tree.pathToIndex(t)}pathRangeToPosRange(t){if(!this.context||!this.tree)throw new Y(W.ErrNotInitialized,"Tree is not initialized yet");const n=[this.tree.pathToIndex(t[0]),this.tree.pathToIndex(t[1])],r=this.tree.indexRangeToPosRange(n);return[r[0].toStruct(),r[1].toStruct()]}indexRangeToPosRange(t){if(!this.context||!this.tree)throw new Y(W.ErrNotInitialized,"Tree is not initialized yet");return this.tree.indexRangeToPosStructRange(t)}posRangeToIndexRange(t){if(!this.context||!this.tree)throw new Y(W.ErrNotInitialized,"Tree is not initialized yet");const n=[Xi.fromStruct(t[0]),Xi.fromStruct(t[1])];return this.tree.posRangeToIndexRange(n)}posRangeToPathRange(t){if(!this.context||!this.tree)throw new Y(W.ErrNotInitialized,"Tree is not initialized yet");const n=[Xi.fromStruct(t[0]),Xi.fromStruct(t[1])];return this.tree.posRangeToPathRange(n)}}function Mx(e,t){return uB(e,t)}function Xs(e,t){if(t){if(t instanceof Gt)return t;if(t instanceof wr)return uB(e,t);if(t instanceof Ur)return mVe(e,t);if(t instanceof Ti)return new C1(e,t);if(t instanceof Kr){const n=new b1(Ko.IntegerCnt,0);return n.initialize(e,t),n}else if(t instanceof Pi){const n=new w1;return n.initialize(e,t),n}}else return;throw new TypeError(`Unsupported type of element: ${typeof t}`)}function nl(e,t){const n=Xs(e,t);return n instanceof Gt?n.getValue():n}function um(e,t,n){let r;if(Gt.isSupport(t))r=Gt.of(t,n);else if(Array.isArray(t))r=Ur.create(n,qt.buildArrayElements(e,t));else if(typeof t=="object")t instanceof C1?(r=Ti.create(dd.create(),n),t.initialize(e,r)):t instanceof b1?(r=Kr.create(t.getValueType(),t.getValue(),n),t.initialize(e,r)):t instanceof w1?(r=Pi.create(t.buildRoot(e),n),t.initialize(e,r)):r=wr.create(n,ph.buildObjectMembers(e,t));else throw new TypeError(`Unsupported type of value: ${typeof t}`);return r}const $x=50;class CVe{constructor(){A(this,"undoStack",[]);A(this,"redoStack",[])}hasUndo(){return this.undoStack.length>0}hasRedo(){return this.redoStack.length>0}pushUndo(t){this.undoStack.length>=$x&&this.undoStack.shift(),this.undoStack.push(t)}popUndo(){return this.undoStack.pop()}pushRedo(t){this.redoStack.length>=$x&&this.redoStack.shift(),this.redoStack.push(t)}popRedo(){return this.redoStack.pop()}clearRedo(){this.redoStack=[]}getUndoStackForTest(){return this.undoStack}getRedoStackForTest(){return this.redoStack}}const bVe="yorkie-devtools-panel",wVe="yorkie-devtools-sdk";let fc="disconnected";const Rx=new Map,Wp=new Map;typeof window<"u"&&(window.transactionEventsByDocKey=Wp);function xp(e,t){(t!=null&&t.force||fc!=="disconnected")&&window.postMessage({source:wVe,...e},"*")}function SVe(e){if(!e.isEnableDevtools()||typeof window>"u"||Rx.has(e.getKey()))return;Wp.set(e.getKey(),[]);const t=e.subscribe("all",n=>{n.some(r=>r.type!==Un.StatusChanged&&r.type!==Un.Snapshot&&r.type!==Un.LocalChange&&r.type!==Un.RemoteChange&&r.type!==Un.Initialized&&r.type!==Un.Watched&&r.type!==Un.Unwatched&&r.type!==Un.PresenceChanged)||(Wp.get(e.getKey()).push(n),fc==="synced"&&xp({msg:"doc::sync::partial",docKey:e.getKey(),event:n}))});Rx.set(e.getKey(),[t]),xp({msg:"refresh-devtools"},{force:!0}),window.addEventListener("message",n=>{var i;if(((i=n.data)==null?void 0:i.source)!==bVe)return;switch(n.data.msg){case"devtools::connect":if(fc!=="disconnected")break;fc="connected",xp({msg:"doc::available",docKey:e.getKey()}),$e.info(`[YD] Devtools connected. Doc: ${e.getKey()}`);break;case"devtools::disconnect":fc="disconnected",$e.info(`[YD] Devtools disconnected. Doc: ${e.getKey()}`);break;case"devtools::subscribe":fc="synced",xp({msg:"doc::sync::full",docKey:e.getKey(),events:Wp.get(e.getKey())}),$e.info(`[YD] Devtools subscribed. Doc: ${e.getKey()}`);break}})}var Zs=(e=>(e.Detached="detached",e.Attached="attached",e.Removed="removed",e))(Zs||{}),Un=(e=>(e.StatusChanged="status-changed",e.ConnectionChanged="connection-changed",e.SyncStatusChanged="sync-status-changed",e.Snapshot="snapshot",e.LocalChange="local-change",e.RemoteChange="remote-change",e.Initialized="initialized",e.Watched="watched",e.Unwatched="unwatched",e.PresenceChanged="presence-changed",e.Broadcast="broadcast",e.LocalBroadcast="local-broadcast",e))(Un||{}),yy=(e=>(e.Connected="connected",e.Disconnected="disconnected",e))(yy||{}),Ey=(e=>(e.Synced="synced",e.SyncFailed="sync-failed",e))(Ey||{});class XC{constructor(t,n){A(this,"key");A(this,"status");A(this,"opts");A(this,"changeID");A(this,"checkpoint");A(this,"localChanges");A(this,"root");A(this,"clone");A(this,"eventStream");A(this,"eventStreamObserver");A(this,"onlineClients");A(this,"presences");A(this,"history");A(this,"internalHistory");A(this,"isUpdating");this.opts=n||{},this.key=t,this.status="detached",this.root=fh.create(),this.changeID=kKe,this.checkpoint=DKe,this.localChanges=[],this.eventStream=gVe(r=>{this.eventStreamObserver=r}),this.onlineClients=new Set,this.presences=new Map,this.isUpdating=!1,this.internalHistory=new CVe,this.history={canUndo:this.canUndo.bind(this),canRedo:this.canRedo.bind(this),undo:this.undo.bind(this),redo:this.redo.bind(this)},SVe(this)}update(t,n){if(this.getStatus()==="removed")throw new Y(W.ErrDocumentRemoved,`${this.key} is removed`);this.ensureClone();const r=this.changeID.getActorID(),i=Tc.create(this.changeID.next(),this.clone.root,this.clone.presences.get(r)||{},n);try{const o=Mx(i,this.clone.root.getObject());this.presences.has(r)||this.clone.presences.set(r,{}),this.isUpdating=!0,t(o,new e2(i,this.clone.presences.get(r)))}catch(o){throw this.clone=void 0,o}finally{this.isUpdating=!1}if(i.hasChange()){$e.isEnabled(or.Trivial)&&$e.trivial(`trying to update a local change: ${this.toJSON()}`);const o=i.getChange(),{opInfos:a,reverseOps:s}=o.execute(this.root,this.presences,xt.Local),u=i.getReversePresence();u&&s.push({type:"presence",value:u}),this.localChanges.push(o),s.length>0&&this.internalHistory.pushUndo(s),a.length>0&&this.internalHistory.clearRedo(),this.changeID=o.getID();const d=[];a.length>0&&d.push({type:"local-change",source:xt.Local,value:{message:o.getMessage()||"",operations:a,actor:r,clientSeq:o.getID().getClientSeq(),serverSeq:o.getID().getServerSeq()},rawChange:this.isEnableDevtools()?o.toStruct():void 0}),o.hasPresenceChange()&&d.push({type:"presence-changed",source:xt.Local,value:{clientID:r,presence:this.getPresence(r)}}),this.publish(d),$e.isEnabled(or.Trivial)&&$e.trivial(`after update a local change: ${this.toJSON()}`)}}subscribe(t,n,r,i){if(typeof t=="string"){if(typeof n!="function")throw new Y(W.ErrInvalidArgument,"Second argument must be a callback function");if(t==="presence"){const s=n;return this.eventStream.subscribe(u=>{for(const d of u)d.type!=="initialized"&&d.type!=="watched"&&d.type!=="unwatched"&&d.type!=="presence-changed"||s(d)},r,i)}if(t==="my-presence"){const s=n;return this.eventStream.subscribe(u=>{for(const d of u)d.type!=="initialized"&&d.type!=="presence-changed"||d.type==="presence-changed"&&d.value.clientID!==this.changeID.getActorID()||s(d)},r,i)}if(t==="others"){const s=n;return this.eventStream.subscribe(u=>{for(const d of u)d.type!=="watched"&&d.type!=="unwatched"&&d.type!=="presence-changed"||d.value.clientID!==this.changeID.getActorID()&&s(d)},r,i)}if(t==="connection"){const s=n;return this.eventStream.subscribe(u=>{for(const d of u)d.type==="connection-changed"&&s(d)},r,i)}if(t==="status"){const s=n;return this.eventStream.subscribe(u=>{for(const d of u)d.type==="status-changed"&&s(d)},r,i)}if(t==="sync"){const s=n;return this.eventStream.subscribe(u=>{for(const d of u)d.type==="sync-status-changed"&&s(d)},r,i)}if(t==="local-broadcast"){const s=n;return this.eventStream.subscribe(u=>{for(const d of u)d.type==="local-broadcast"&&s(d)},r)}if(t==="broadcast"){const s=n;return this.eventStream.subscribe(u=>{for(const d of u)d.type==="broadcast"&&s(d)},r)}if(t==="all"){const s=n;return this.eventStream.subscribe(s,r,i)}const o=t,a=n;return this.eventStream.subscribe(s=>{for(const u of s){if(u.type!=="local-change"&&u.type!=="remote-change")continue;const d=[];for(const h of u.value.operations)this.isSameElementOrChildOf(h.path,o)&&d.push(h);d.length&&a({...u,value:{...u.value,operations:d}})}},r,i)}if(typeof t=="function"){const o=t,a=n,s=r;return this.eventStream.subscribe(u=>{for(const d of u)d.type!=="snapshot"&&d.type!=="local-change"&&d.type!=="remote-change"||o(d)},a,s)}throw new Y(W.ErrInvalidArgument,`"${t}" is not a valid`)}publish(t){this.eventStreamObserver&&this.eventStreamObserver.next(t)}isSameElementOrChildOf(t,n){if(n===t)return!0;const r=t.split(".");return n.split(".").every((o,a)=>o===r[a])}removePushedLocalChanges(t){for(;this.localChanges.length&&!(this.localChanges[0].getID().getClientSeq()>t);)this.localChanges.shift()}applyChangePack(t){const n=t.hasSnapshot();n?this.applySnapshot(t.getCheckpoint().getServerSeq(),t.getVersionVector(),t.getSnapshot(),t.getCheckpoint().getClientSeq()):(this.applyChanges(t.getChanges(),xt.Remote),this.removePushedLocalChanges(t.getCheckpoint().getClientSeq())),this.checkpoint=this.checkpoint.forward(t.getCheckpoint()),n||this.garbageCollect(t.getVersionVector()),n||this.filterVersionVector(t.getVersionVector()),t.getIsRemoved()&&this.applyStatus("removed"),$e.isEnabled(or.Trivial)&&$e.trivial(`${this.root.toJSON()}`)}getCheckpoint(){return this.checkpoint}getChangeID(){return this.changeID}hasLocalChanges(){return this.localChanges.length>0}ensureClone(){this.clone||(this.clone={root:this.root.deepcopy(),presences:Gi(this.presences)})}createChangePack(){const t=Array.from(this.localChanges),n=this.checkpoint.increaseClientSeq(t.length);return E1.create(this.key,n,!1,t,this.getVersionVector())}setActor(t){for(const n of this.localChanges)n.setActor(t);this.changeID=this.changeID.setActor(t)}isEnableDevtools(){return!!this.opts.enableDevtools}getKey(){return this.key}getStatus(){return this.status}getCloneRoot(){if(this.clone)return this.clone.root.getObject()}getRoot(){this.ensureClone();const t=Tc.create(this.changeID.next(),this.clone.root,this.clone.presences.get(this.changeID.getActorID())||{});return Mx(t,this.clone.root.getObject())}garbageCollect(t){return this.opts.disableGC?0:(this.clone&&this.clone.root.garbageCollect(t),this.root.garbageCollect(t))}getRootObject(){return this.root.getObject()}getGarbageLen(){return this.root.getGarbageLen()}getGarbageLenFromClone(){return this.clone.root.getGarbageLen()}toJSON(){return this.root.toJSON()}toSortedJSON(){return this.root.toSortedJSON()}getStats(){return this.root.getStats()}toJSForTest(){return{...this.getRoot().toJSForTest(),key:"root"}}applySnapshot(t,n,r,i=-1){const{root:o,presences:a}=rn.bytesToSnapshot(r);this.root=new fh(o),this.presences=a,this.changeID=this.changeID.setClocks(t,n),this.clone=void 0,this.removePushedLocalChanges(i),this.applyChanges(this.localChanges,xt.Local),this.publish([{type:"snapshot",source:xt.Remote,value:{serverSeq:t.toString(),snapshot:this.isEnableDevtools()?rn.bytesToHex(r):void 0,snapshotVector:rn.versionVectorToHex(n)}}])}applyChanges(t,n){$e.isEnabled(or.Debug)&&$e.debug(`trying to apply ${t.length} remote changes.elements:${this.root.getElementMapSize()}, removeds:${this.root.getGarbageElementSetSize()}`),$e.isEnabled(or.Trivial)&&$e.trivial(t.map(r=>`${r.getID().toTestString()} ${r.toTestString()}`).join(` `));for(const r of t)this.applyChange(r,n);$e.isEnabled(or.Debug)&&$e.debug(`after appling ${t.length} remote changes.elements:${this.root.getElementMapSize()}, removeds:${this.root.getGarbageElementSetSize()}`)}applyChange(t,n){this.ensureClone(),t.execute(this.clone.root,this.clone.presences,n);const r=[],i=t.getID().getActorID();if(t.hasPresenceChange()&&this.onlineClients.has(i)){const a=t.getPresenceChange();switch(a.type){case Iu.Put:r.push(this.presences.has(i)?{type:"presence-changed",source:n,value:{clientID:i,presence:a.presence}}:{type:"watched",source:xt.Remote,value:{clientID:i,presence:a.presence}});break;case Iu.Clear:r.push({type:"unwatched",source:xt.Remote,value:{clientID:i,presence:this.getPresence(i)}}),this.removeOnlineClient(i);break}}const{opInfos:o}=t.execute(this.root,this.presences,n);if(this.changeID=this.changeID.syncClocks(t.getID()),o.length>0){const a=this.isEnableDevtools()?t.toStruct():void 0;r.push(n===xt.Remote?{type:"remote-change",source:n,value:{actor:i,clientSeq:t.getID().getClientSeq(),serverSeq:t.getID().getServerSeq(),message:t.getMessage()||"",operations:o},rawChange:a}:{type:"local-change",source:n,value:{actor:i,clientSeq:t.getID().getClientSeq(),serverSeq:t.getID().getServerSeq(),message:t.getMessage()||"",operations:o},rawChange:a})}r.length>0&&this.publish(r)}applyWatchStream(t){if(t.body.case==="initialization"){const n=t.body.value.clientIds,r=new Set;for(const i of n)i!==this.changeID.getActorID()&&r.add(i);this.setOnlineClients(r),this.publish([{type:"initialized",source:xt.Local,value:this.getPresences()}]);return}if(t.body.case==="event"){const{type:n,publisher:r}=t.body.value,i=[];if(n===ml.DOCUMENT_WATCHED){if(this.onlineClients.has(r)&&this.hasPresence(r))return;this.addOnlineClient(r),this.hasPresence(r)&&i.push({type:"watched",source:xt.Remote,value:{clientID:r,presence:this.getPresence(r)}})}else if(n===ml.DOCUMENT_UNWATCHED){const o=this.getPresence(r);this.removeOnlineClient(r),o&&i.push({type:"unwatched",source:xt.Remote,value:{clientID:r,presence:o}})}else if(n===ml.DOCUMENT_BROADCAST&&t.body.value.body){const{topic:o,payload:a}=t.body.value.body,s=new TextDecoder;i.push({type:"broadcast",value:{clientID:r,topic:o,payload:JSON.parse(s.decode(a))}})}i.length>0&&this.publish(i)}}applyStatus(t){this.status=t,t==="detached"&&this.setActor(FC),this.publish([{source:t==="removed"?xt.Remote:xt.Local,type:"status-changed",value:t==="attached"?{status:t,actorID:this.changeID.getActorID()}:{status:t}}])}applyDocEvent(t){if(t.type==="status-changed"){this.applyStatus(t.value.status),t.value.status==="attached"&&this.setActor(t.value.actorID);return}if(t.type==="snapshot"){const{snapshot:n,serverSeq:r,snapshotVector:i}=t.value;if(!n)return;this.applySnapshot(BigInt(r),rn.hexToVersionVector(i),rn.hexToBytes(n));return}if(t.type==="local-change"||t.type==="remote-change"){if(!t.rawChange)return;const n=cd.fromStruct(t.rawChange);this.applyChange(n,t.source)}if(t.type==="initialized"){const n=new Set;for(const{clientID:r,presence:i}of t.value)n.add(r),this.presences.set(r,i);this.setOnlineClients(n);return}if(t.type==="watched"){const{clientID:n,presence:r}=t.value;this.addOnlineClient(n),this.presences.set(n,r);return}if(t.type==="unwatched"){const{clientID:n}=t.value;this.removeOnlineClient(n),this.presences.delete(n)}if(t.type==="presence-changed"){const{clientID:n,presence:r}=t.value;this.presences.set(n,r)}}applyTransactionEvent(t){for(const n of t)this.applyDocEvent(n)}getValueByPath(t){if(!t.startsWith("$"))throw new Y(W.ErrInvalidArgument,'path must start with "$"');const n=t.split(".");n.shift();let r=this.getRoot();for(const i of n)if(r=r[i],r===void 0)return;return r}setOnlineClients(t){this.onlineClients=t}resetOnlineClients(){this.onlineClients=new Set}addOnlineClient(t){this.onlineClients.add(t)}removeOnlineClient(t){this.onlineClients.delete(t)}hasPresence(t){return this.presences.has(t)}getMyPresence(){if(this.status!=="attached")return{};const t=this.presences.get(this.changeID.getActorID());return t?Gi(t):{}}getPresence(t){if(t===this.changeID.getActorID())return this.getMyPresence();if(!this.onlineClients.has(t))return;const n=this.presences.get(t);return n?Gi(n):void 0}getPresenceForTest(t){const n=this.presences.get(t);return n?Gi(n):void 0}getPresences(){const t=[];t.push({clientID:this.changeID.getActorID(),presence:Gi(this.getMyPresence())});for(const n of this.onlineClients)this.presences.has(n)&&t.push({clientID:n,presence:Gi(this.presences.get(n))});return t}getSelfForTest(){return{clientID:this.getChangeID().getActorID(),presence:this.getMyPresence()}}getOthersForTest(){const t=this.getChangeID().getActorID();return this.getPresences().filter(n=>n.clientID!==t).sort((n,r)=>n.clientID>r.clientID?1:-1)}canUndo(){return this.internalHistory.hasUndo()&&!this.isUpdating}filterVersionVector(t){const r=this.changeID.getVersionVector().filter(t);this.changeID=this.changeID.setVersionVector(r)}canRedo(){return this.internalHistory.hasRedo()&&!this.isUpdating}undo(){if(this.isUpdating)throw new Y(W.ErrRefused,"Undo is not allowed during an update");const t=this.internalHistory.popUndo();if(t===void 0)throw new Y(W.ErrRefused,"There is no operation to be undone");this.ensureClone();const n=Tc.create(this.changeID.next(),this.clone.root,this.clone.presences.get(this.changeID.getActorID())||{});for(const d of t){if(!(d instanceof so)){new e2(n,Gi(this.clone.presences.get(this.changeID.getActorID()))).set(d.value,{addToHistory:!0});continue}const h=n.issueTimeTicket();d.setExecutedAt(h),n.push(d)}const r=n.getChange();r.execute(this.clone.root,this.clone.presences,xt.UndoRedo);const{opInfos:i,reverseOps:o}=r.execute(this.root,this.presences,xt.UndoRedo),a=n.getReversePresence();if(a&&o.push({type:"presence",value:a}),o.length>0&&this.internalHistory.pushRedo(o),!r.hasPresenceChange()&&i.length===0)return;this.localChanges.push(r),this.changeID=r.getID();const s=this.changeID.getActorID(),u=[];i.length>0&&u.push({type:"local-change",source:xt.UndoRedo,value:{message:r.getMessage()||"",operations:i,actor:s,clientSeq:r.getID().getClientSeq(),serverSeq:r.getID().getServerSeq()},rawChange:this.isEnableDevtools()?r.toStruct():void 0}),r.hasPresenceChange()&&u.push({type:"presence-changed",source:xt.UndoRedo,value:{clientID:s,presence:this.getPresence(s)}}),this.publish(u)}redo(){if(this.isUpdating)throw new Y(W.ErrRefused,"Redo is not allowed during an update");const t=this.internalHistory.popRedo();if(t===void 0)throw new Y(W.ErrRefused,"There is no operation to be redone");this.ensureClone();const n=Tc.create(this.changeID.next(),this.clone.root,this.clone.presences.get(this.changeID.getActorID())||{});for(const d of t){if(!(d instanceof so)){new e2(n,Gi(this.clone.presences.get(this.changeID.getActorID()))).set(d.value,{addToHistory:!0});continue}const h=n.issueTimeTicket();d.setExecutedAt(h),n.push(d)}const r=n.getChange();r.execute(this.clone.root,this.clone.presences,xt.UndoRedo);const{opInfos:i,reverseOps:o}=r.execute(this.root,this.presences,xt.UndoRedo),a=n.getReversePresence();if(a&&o.push({type:"presence",value:a}),o.length>0&&this.internalHistory.pushUndo(o),!r.hasPresenceChange()&&i.length===0)return;this.localChanges.push(r),this.changeID=r.getID();const s=this.changeID.getActorID(),u=[];i.length>0&&u.push({type:"local-change",source:xt.UndoRedo,value:{message:r.getMessage()||"",operations:i,actor:s,clientSeq:r.getID().getClientSeq(),serverSeq:r.getID().getServerSeq()},rawChange:this.isEnableDevtools()?r.toStruct():void 0}),r.hasPresenceChange()&&u.push({type:"presence-changed",source:xt.UndoRedo,value:{clientID:s,presence:this.getPresence(s)}}),this.publish(u)}getUndoStackForTest(){return this.internalHistory.getUndoStackForTest()}getRedoStackForTest(){return this.internalHistory.getRedoStackForTest()}broadcast(t,n,r){const i={type:"local-broadcast",value:{topic:t,payload:n},options:r};this.publish([i])}getVersionVector(){return this.changeID.getVersionVector()}}function xVe(e,t){return n=>async r=>(e&&r.header.set("x-api-key",e),t&&r.header.set("authorization",t),await n(r))}const AVe="yorkie-js-sdk",kVe="0.5.4",DVe="Yorkie JS SDK",IVe="./src/yorkie.ts",TVe={access:"public",main:"./dist/yorkie-js-sdk.js",typings:"./dist/yorkie-js-sdk.d.ts"},PVe=["dist"],BVe={build:"tsc && vite build","build:proto":"npx buf generate","build:docs":"typedoc","build:ghpages":"mkdir -p ghpages/examples && cp -r docs ghpages/api-reference && find ../../examples -name 'dist' -type d -exec sh -c 'cp -r {} ghpages/examples/$(basename $(dirname {}))' \\;",dev:"vite build -c vite.preview.ts && vite preview",test:"vitest run","test:watch":"vitest","test:bench":"vitest bench","test:ci":"vitest run --coverage","test:yorkie.dev":"TEST_RPC_ADDR=https://api.yorkie.dev vitest run --coverage",prepare:"pnpm build"},MVe={node:">=18.0.0",npm:">=7.1.0"},$Ve={type:"git",url:"git+https://github.com/yorkie-team/yorkie-js-sdk.git"},RVe={name:"hackerwins",email:"susukang98@gmail.com"},FVe="Apache-2.0",LVe={url:"https://github.com/yorkie-team/yorkie-js-sdk/issues"},OVe="https://github.com/yorkie-team/yorkie-js-sdk#readme",_Ve={"@buf/googleapis_googleapis.bufbuild_es":"^1.4.0-20240524201209-f0e53af8f2fc.3","@bufbuild/buf":"^1.28.1","@bufbuild/protoc-gen-es":"^1.6.0","@connectrpc/protoc-gen-connect-es":"^1.4.0","@types/google-protobuf":"^3.15.5","@types/long":"^4.0.1","@typescript-eslint/eslint-plugin":"^6.21.0","@typescript-eslint/parser":"^6.21.0","@vitest/coverage-istanbul":"^0.34.5","@vitest/coverage-v8":"^0.34.5","eslint-plugin-tsdoc":"^0.2.16",prettier:"^2.7.1","ts-node":"^10.9.1",typedoc:"^0.25.13",typescript:"^5.3.3","typescript-transform-paths":"^3.3.1",vite:"^5.0.12","vite-plugin-commonjs":"^0.10.1","vite-plugin-dts":"^3.9.1","vite-tsconfig-paths":"^4.2.1",vitest:"^0.34.5"},NVe={"@bufbuild/protobuf":"^1.6.0","@connectrpc/connect":"^1.4.0","@connectrpc/connect-web":"^1.4.0",long:"^5.2.0"},Fx={name:AVe,version:kVe,description:DVe,main:IVe,publishConfig:TVe,files:PVe,scripts:BVe,engines:MVe,repository:$Ve,author:RVe,license:FVe,bugs:LVe,homepage:OVe,devDependencies:_Ve,dependencies:NVe};function zVe(){return e=>async t=>(t.header.set("x-yorkie-user-agent",Fx.name+"/"+Fx.version),await e(t))}const HVe=e=>{try{if(JSON.stringify(e)===void 0)return!1}catch{return!1}return!0};var Yp=(e=>(e.Manual="manual",e.Realtime="realtime",e.RealtimePushOnly="realtime-pushonly",e.RealtimeSyncOff="realtime-syncoff",e))(Yp||{});const Ap={syncLoopDuration:50,retrySyncLoopDelay:1e3,reconnectStreamDelay:1e3},i2={maxRetries:1/0,initialRetryInterval:1e3,maxBackoff:2e4};class ZC{constructor(t,n){A(this,"id");A(this,"key");A(this,"status");A(this,"attachmentMap");A(this,"apiKey");A(this,"conditions");A(this,"syncLoopDuration");A(this,"reconnectStreamDelay");A(this,"retrySyncLoopDelay");A(this,"rpcClient");A(this,"taskQueue");A(this,"processing",!1);n=n||Ap,this.key=n.key?n.key:sB(),this.status="deactivated",this.attachmentMap=new Map,this.apiKey=n.apiKey||"",this.conditions={SyncLoop:!1,WatchLoop:!1},this.syncLoopDuration=n.syncLoopDuration||Ap.syncLoopDuration,this.reconnectStreamDelay=n.reconnectStreamDelay||Ap.reconnectStreamDelay,this.retrySyncLoopDelay=n.retrySyncLoopDelay||Ap.retrySyncLoopDelay,this.rpcClient=OUe(aKe,oKe({baseUrl:t,interceptors:[xVe(n.apiKey,n.token),zVe()]})),this.taskQueue=[]}activate(){return this.isActive()?Promise.resolve():this.enqueueTask(async()=>this.rpcClient.activateClient({clientKey:this.key},{headers:{"x-shard-key":this.apiKey}}).then(t=>{this.id=t.clientId,this.status="activated",this.runSyncLoop(),$e.info(`[AC] c:"${this.getKey()}" activated, id:"${this.id}"`)}).catch(t=>{throw $e.error(`[AC] c:"${this.getKey()}" err :`,t),this.handleConnectError(t),t}))}deactivate(){return this.status==="deactivated"?Promise.resolve():this.enqueueTask(async()=>this.rpcClient.deactivateClient({clientId:this.id},{headers:{"x-shard-key":this.apiKey}}).then(()=>{this.deactivateInternal(),$e.info(`[DC] c"${this.getKey()}" deactivated`)}).catch(t=>{throw $e.error(`[DC] c:"${this.getKey()}" err :`,t),this.handleConnectError(t),t}))}attach(t,n={}){if(!this.isActive())throw new Y(W.ErrClientNotActivated,`${this.key} is not active`);if(t.getStatus()!==Zs.Detached)throw new Y(W.ErrDocumentNotDetached,`${t.getKey()} is not detached`);t.setActor(this.id),t.update((o,a)=>a.set(n.initialPresence||{}));const r=t.subscribe("local-broadcast",async o=>{var h;const{topic:a,payload:s}=o.value,u=(h=o.options)==null?void 0:h.error,d=o.options;try{await this.broadcast(t.getKey(),a,s,d)}catch(p){p instanceof Error&&(u==null||u(p))}}),i=n.syncMode??"realtime";return this.enqueueTask(async()=>this.rpcClient.attachDocument({clientId:this.id,changePack:rn.toChangePack(t.createChangePack())},{headers:{"x-shard-key":`${this.apiKey}/${t.getKey()}`}}).then(async o=>{const a=rn.fromChangePack(o.changePack);if(t.applyChangePack(a),t.getStatus()===Zs.Removed)return t;t.applyStatus(Zs.Attached),this.attachmentMap.set(t.getKey(),new fVe(this.reconnectStreamDelay,t,o.documentId,i,r)),i!=="manual"&&await this.runWatchLoop(t.getKey()),$e.info(`[AD] c:"${this.getKey()}" attaches d:"${t.getKey()}"`);const s=t.getRootObject();if(n.initialRoot){const u=n.initialRoot;t.update(d=>{for(const[h,p]of Object.entries(u))if(!s.has(h)){const g=h;d[g]=p}})}return t}).catch(o=>{throw $e.error(`[AD] c:"${this.getKey()}" err :`,o),this.handleConnectError(o),o}))}detach(t,n={}){if(!this.isActive())throw new Y(W.ErrClientNotActivated,`${this.key} is not active`);const r=this.attachmentMap.get(t.getKey());if(!r)throw new Y(W.ErrDocumentNotAttached,`${t.getKey()} is not attached`);return t.update((i,o)=>o.clear()),this.enqueueTask(async()=>this.rpcClient.detachDocument({clientId:this.id,documentId:r.docID,changePack:rn.toChangePack(t.createChangePack()),removeIfNotAttached:n.removeIfNotAttached??!1},{headers:{"x-shard-key":`${this.apiKey}/${t.getKey()}`}}).then(i=>{const o=rn.fromChangePack(i.changePack);return t.applyChangePack(o),t.getStatus()!==Zs.Removed&&t.applyStatus(Zs.Detached),this.detachInternal(t.getKey()),$e.info(`[DD] c:"${this.getKey()}" detaches d:"${t.getKey()}"`),t}).catch(i=>{throw $e.error(`[DD] c:"${this.getKey()}" err :`,i),this.handleConnectError(i),i}))}async changeSyncMode(t,n){if(!this.isActive())throw new Y(W.ErrClientNotActivated,`${this.key} is not active`);const r=this.attachmentMap.get(t.getKey());if(!r)throw new Y(W.ErrDocumentNotAttached,`${t.getKey()} is not attached`);const i=r.syncMode;return i===n?t:(r.changeSyncMode(n),n==="manual"?(r.cancelWatchStream(),t):(n==="realtime"&&(r.remoteChangeEventReceived=!0),i==="manual"&&await this.runWatchLoop(t.getKey()),t))}sync(t){if(!this.isActive())throw new Y(W.ErrClientNotActivated,`${this.key} is not active`);if(t){const n=this.attachmentMap.get(t.getKey());if(!n)throw new Y(W.ErrDocumentNotAttached,`${t.getKey()} is not attached`);return this.enqueueTask(async()=>this.syncInternal(n,"realtime").catch(r=>{throw $e.error(`[SY] c:"${this.getKey()}" err :`,r),this.handleConnectError(r),r}))}return this.enqueueTask(async()=>{const n=[];for(const[,r]of this.attachmentMap)n.push(this.syncInternal(r,r.syncMode));return Promise.all(n).catch(r=>{throw $e.error(`[SY] c:"${this.getKey()}" err :`,r),this.handleConnectError(r),r})})}remove(t){if(!this.isActive())throw new Y(W.ErrClientNotActivated,`${this.key} is not active`);const n=this.attachmentMap.get(t.getKey());if(!n)throw new Y(W.ErrDocumentNotAttached,`${t.getKey()} is not attached`);t.setActor(this.id);const r=rn.toChangePack(t.createChangePack());return r.isRemoved=!0,this.enqueueTask(async()=>this.rpcClient.removeDocument({clientId:this.id,documentId:n.docID,changePack:r},{headers:{"x-shard-key":`${this.apiKey}/${t.getKey()}`}}).then(i=>{const o=rn.fromChangePack(i.changePack);t.applyChangePack(o),this.detachInternal(t.getKey()),$e.info(`[RD] c:"${this.getKey()}" removes d:"${t.getKey()}"`)}).catch(i=>{throw $e.error(`[RD] c:"${this.getKey()}" err :`,i),this.handleConnectError(i),i}))}getID(){return this.id}getKey(){return this.key}isActive(){return this.status==="activated"}getStatus(){return this.status}getCondition(t){return this.conditions[t]}broadcast(t,n,r,i){if(!this.isActive())throw new Y(W.ErrClientNotActivated,`${this.key} is not active`);const o=this.attachmentMap.get(t);if(!o)throw new Y(W.ErrDocumentNotAttached,`${t} is not attached`);if(!HVe(r))throw new Y(W.ErrInvalidArgument,"payload is not serializable");const a=(i==null?void 0:i.maxRetries)??i2.maxRetries,s=i2.maxBackoff;let u=0;const d=p=>Math.min(i2.initialRetryInterval*2**p,s),h=async()=>this.enqueueTask(async()=>this.rpcClient.broadcast({clientId:this.id,documentId:o.docID,topic:n,payload:new TextEncoder().encode(JSON.stringify(r))},{headers:{"x-shard-key":`${this.apiKey}/${t}`}}).then(()=>{$e.info(`[BC] c:"${this.getKey()}" broadcasts d:"${t}" t:"${n}"`)}).catch(p=>{if($e.error(`[BC] c:"${this.getKey()}" err:`,p),this.handleConnectError(p))if(uh(),d(u-1)),$e.info(`[BC] c:"${this.getKey()}" retry attempt ${u}/${a}`);else throw $e.error(`[BC] c:"${this.getKey()}" exceeded maximum retry attempts`),p;else throw p}));return h()}runSyncLoop(){const t=()=>{if(!this.isActive()){$e.debug(`[SL] c:"${this.getKey()}" exit sync loop`),this.conditions.SyncLoop=!1;return}const n=[];for(const[,r]of this.attachmentMap)r.needRealtimeSync()&&(r.remoteChangeEventReceived=!1,n.push(this.syncInternal(r,r.syncMode)));Promise.all(n).then(()=>setTimeout(t,this.syncLoopDuration)).catch(r=>{$e.error(`[SL] c:"${this.getKey()}" sync failed:`,r),this.handleConnectError(r)?setTimeout(t,this.retrySyncLoopDelay):this.conditions.SyncLoop=!1})};$e.debug(`[SL] c:"${this.getKey()}" run sync loop`),this.conditions.SyncLoop=!0,t()}async runWatchLoop(t){const n=this.attachmentMap.get(t);if(!n)throw new Y(W.ErrDocumentNotAttached,`${t} is not attached`);return this.conditions.WatchLoop=!0,n.runWatchLoop(r=>{if(!this.isActive())return this.conditions.WatchLoop=!1,Promise.reject(new Y(W.ErrClientNotActivated,`${this.key} is not active`));const i=new AbortController,o=this.rpcClient.watchDocument({clientId:this.id,documentId:n.docID},{headers:{"x-shard-key":`${this.apiKey}/${t}`},signal:i.signal});return n.doc.publish([{type:Un.ConnectionChanged,value:yy.Connected}]),$e.info(`[WD] c:"${this.getKey()}" watches d:"${t}"`),new Promise((a,s)=>{(async()=>{try{for await(const d of o)this.handleWatchDocumentsResponse(n,d),d.body.case==="initialization"&&a([o,i])}catch(d){n.doc.resetOnlineClients(),n.doc.publish([{type:Un.Initialized,source:xt.Local,value:n.doc.getPresences()}]),n.doc.publish([{type:Un.ConnectionChanged,value:yy.Disconnected}]),$e.debug(`[WD] c:"${this.getKey()}" unwatches`),this.handleConnectError(d)?r():this.conditions.WatchLoop=!1,s(d)}})()})})}handleWatchDocumentsResponse(t,n){if(n.body.case==="event"&&n.body.value.type===ml.DOCUMENT_CHANGED){t.remoteChangeEventReceived=!0;return}t.doc.applyWatchStream(n)}deactivateInternal(){this.status="deactivated";for(const[t,n]of this.attachmentMap)this.detachInternal(t),n.doc.applyStatus(Zs.Detached)}detachInternal(t){const n=this.attachmentMap.get(t);n&&(n.cancelWatchStream(),n.unsubscribeBroadcastEvent(),this.attachmentMap.delete(t))}syncInternal(t,n){const{doc:r,docID:i}=t,o=r.createChangePack();return this.rpcClient.pushPullChanges({clientId:this.id,documentId:i,changePack:rn.toChangePack(o),pushOnly:n==="realtime-pushonly"},{headers:{"x-shard-key":`${this.apiKey}/${r.getKey()}`}}).then(a=>{const s=rn.fromChangePack(a.changePack);if(s.hasChanges()&&(t.syncMode==="realtime-pushonly"||t.syncMode==="realtime-syncoff"))return r;r.applyChangePack(s),t.doc.publish([{type:Un.SyncStatusChanged,value:Ey.Synced}]),r.getStatus()===Zs.Removed&&this.detachInternal(r.getKey());const u=r.getKey(),d=s.getChangeSize();return $e.info(`[PP] c:"${this.getKey()}" sync d:"${u}", push:${o.getChangeSize()} pull:${d} cp:${s.getCheckpoint().toTestString()}`),r}).catch(a=>{throw r.publish([{type:Un.SyncStatusChanged,value:Ey.SyncFailed}]),$e.error(`[PP] c:"${this.getKey()}" err :`,a),a})}handleConnectError(t){return t instanceof fn?t.code===vt.Canceled||t.code===vt.Unknown||t.code===vt.ResourceExhausted||t.code===vt.Unavailable?!0:((Px(t)===W.ErrClientNotActivated||Px(t)===W.ErrClientNotFound)&&this.deactivateInternal(),!1):!1}enqueueTask(t){return new Promise((n,r)=>{this.taskQueue.push(()=>t().then(n).catch(r)),this.processing||this.processNext()})}async processNext(){if(this.taskQueue.length===0){this.processing=!1;return}try{this.processing=!0,await this.taskQueue.shift()()}catch{$e.error(`[TQ] c:"${this.getKey()}" process failed, id:"${this.id}"`)}this.processNext()}}Ko.IntegerCnt,Ko.LongCnt;typeof globalThis<"u"&&(globalThis.yorkie={Client:ZC,Document:XC,Primitive:Gt,Text:C1,Counter:b1,Tree:w1,LogLevel:or,setLogLevel:aB,IntType:Ko.IntegerCnt,LongType:Ko.LongCnt});var Cy={exports:{}};(function(e,t){(function(n,r){{var i=r();e&&e.exports&&(t=e.exports=i),t.randomColor=i}})(hc,function(){var n=null,r={};C();var i=[],o=function(D){if(D=D||{},D.seed!==void 0&&D.seed!==null&&D.seed===parseInt(D.seed,10))n=D.seed;else if(typeof D.seed=="string")n=B(D.seed);else{if(D.seed!==void 0&&D.seed!==null)throw new TypeError("The seed value must be an integer or string");n=null}var $,O,H;if(D.count!==null&&D.count!==void 0){for(var K=D.count,Z=[],X=0;XZ.length;){var pe=o(D);n!==null&&(D.seed=n),Z.push(pe)}return D.count=K,Z}return $=a(D),O=s($,D),H=u($,O,D),d([$,O,H],D)};function a(D){if(i.length>0){var $=T(D.hue),O=v($),H=($[1]-$[0])/i.length,K=parseInt((O-$[0])/H);i[K]===!0?K=(K+2)%i.length:i[K]=!0;var Z=($[0]+K*H)%359,X=($[0]+(K+1)*H)%359;return $=[Z,X],O=v($),O<0&&(O=360+O),O}else{var $=p(D.hue);return O=v($),O<0&&(O=360+O),O}}function s(D,$){if($.hue==="monochrome")return 0;if($.luminosity==="random")return v([0,100]);var O=g(D),H=O[0],K=O[1];switch($.luminosity){case"bright":H=55;break;case"dark":H=K-10;break;case"light":K=55;break}return v([H,K])}function u(D,$,O){var H=h(D,$),K=100;switch(O.luminosity){case"dark":K=H+20;break;case"light":H=(K+H)/2;break;case"random":H=0,K=100;break}return v([H,K])}function d(D,$){switch($.format){case"hsvArray":return D;case"hslArray":return I(D);case"hsl":var O=I(D);return"hsl("+O[0]+", "+O[1]+"%, "+O[2]+"%)";case"hsla":var H=I(D),X=$.alpha||Math.random();return"hsla("+H[0]+", "+H[1]+"%, "+H[2]+"%, "+X+")";case"rgbArray":return b(D);case"rgb":var K=b(D);return"rgb("+K.join(", ")+")";case"rgba":var Z=b(D),X=$.alpha||Math.random();return"rgba("+Z.join(", ")+", "+X+")";default:return E(D)}}function h(D,$){for(var O=m(D).lowerBounds,H=0;H=K&&$<=X){var me=(pe-Z)/(X-K),Ce=Z-me*K;return me*$+Ce}}return 0}function p(D){if(typeof parseInt(D)=="number"){var $=parseInt(D);if($<360&&$>0)return[$,$]}if(typeof D=="string"){if(r[D]){var O=r[D];if(O.hueRange)return O.hueRange}else if(D.match(/^#?([0-9A-F]{3}|[0-9A-F]{6})$/i)){var H=k(D)[0];return[H,H]}}return[0,360]}function g(D){return m(D).saturationRange}function m(D){D>=334&&D<=360&&(D-=360);for(var $ in r){var O=r[$];if(O.hueRange&&D>=O.hueRange[0]&&D<=O.hueRange[1])return r[$]}return"Color not found"}function v(D){if(n===null){var $=.618033988749895,O=Math.random();return O+=$,O%=1,Math.floor(D[0]+O*(D[1]+1-D[0]))}else{var H=D[1]||1,K=D[0]||0;n=(n*9301+49297)%233280;var Z=n/233280;return Math.floor(K+Z*(H-K))}}function E(D){var $=b(D);function O(K){var Z=K.toString(16);return Z.length==1?"0"+Z:Z}var H="#"+O($[0])+O($[1])+O($[2]);return H}function w(D,$,O){var H=O[0][0],K=O[O.length-1][0],Z=O[O.length-1][1],X=O[0][1];r[D]={hueRange:$,lowerBounds:O,saturationRange:[H,K],brightnessRange:[Z,X]}}function C(){w("monochrome",null,[[0,0],[100,0]]),w("red",[-26,18],[[20,100],[30,92],[40,89],[50,85],[60,78],[70,70],[80,60],[90,55],[100,50]]),w("orange",[18,46],[[20,100],[30,93],[40,88],[50,86],[60,85],[70,70],[100,70]]),w("yellow",[46,62],[[25,100],[40,94],[50,89],[60,86],[70,84],[80,82],[90,80],[100,75]]),w("green",[62,178],[[30,100],[40,90],[50,85],[60,81],[70,74],[80,64],[90,50],[100,40]]),w("blue",[178,257],[[20,100],[30,86],[40,80],[50,74],[60,60],[70,52],[80,44],[90,39],[100,35]]),w("purple",[257,282],[[20,100],[30,87],[40,79],[50,70],[60,65],[70,59],[80,52],[90,45],[100,42]]),w("pink",[282,334],[[20,100],[30,90],[40,86],[60,84],[80,80],[90,75],[100,73]])}function b(D){var $=D[0];$===0&&($=1),$===360&&($=359),$=$/360;var O=D[1]/100,H=D[2]/100,K=Math.floor($*6),Z=$*6-K,X=H*(1-O),pe=H*(1-Z*O),me=H*(1-(1-Z)*O),Ce=256,J=256,U=256;switch(K){case 0:Ce=H,J=me,U=X;break;case 1:Ce=pe,J=H,U=X;break;case 2:Ce=X,J=H,U=me;break;case 3:Ce=X,J=pe,U=H;break;case 4:Ce=me,J=X,U=H;break;case 5:Ce=H,J=X,U=pe;break}var ne=[Math.floor(Ce*255),Math.floor(J*255),Math.floor(U*255)];return ne}function k(D){D=D.replace(/^#/,""),D=D.length===3?D.replace(/(.)/g,"$1$1"):D;var $=parseInt(D.substr(0,2),16)/255,O=parseInt(D.substr(2,2),16)/255,H=parseInt(D.substr(4,2),16)/255,K=Math.max($,O,H),Z=K-Math.min($,O,H),X=K?Z/K:0;switch(K){case $:return[60*((O-H)/Z%6)||0,X,K];case O:return[60*((H-$)/Z+2)||0,X,K];case H:return[60*(($-O)/Z+4)||0,X,K]}}function I(D){var $=D[0],O=D[1]/100,H=D[2]/100,K=(2-O)*H;return[$,Math.round(O*H/(K<1?K:2-K)*1e4)/100,K/2*100]}function B(D){for(var $=0,O=0;O!==D.length&&!($>=Number.MAX_SAFE_INTEGER);O++)$+=D.charCodeAt(O);return $}function T(D){if(isNaN(D)){if(typeof D=="string"){if(r[D]){var O=r[D];if(O.hueRange)return O.hueRange}else if(D.match(/^#?([0-9A-F]{3}|[0-9A-F]{6})$/i)){var H=k(D)[0];return m(H).hueRange}}}else{var $=parseInt(D);if($<360&&$>0)return m(D).hueRange}return[0,360]}return o})})(Cy,Cy.exports);var jVe=Cy.exports;const UVe=gh(jVe),Lx=e=>{e=1831565813+(e|=0)|0;let t=Math.imul(e^e>>>15,1|e);return t=t+Math.imul(t^t>>>7,61|t)^t,((t^t>>>14)>>>0)/4294967296};class KVe{constructor(t){this.dictionaries=void 0,this.length=void 0,this.separator=void 0,this.style=void 0,this.seed=void 0;const{length:n,separator:r,dictionaries:i,style:o,seed:a}=t;this.dictionaries=i,this.separator=r,this.length=n,this.style=o,this.seed=a}generate(){if(!this.dictionaries)throw new Error('Cannot find any dictionary. Please provide at least one, or leave the "dictionary" field empty in the config object');if(this.length<=0)throw new Error("Invalid length provided");if(this.length>this.dictionaries.length)throw new Error(`The length cannot be bigger than the number of dictionaries. Length provided: ${this.length}. Number of dictionaries provided: ${this.dictionaries.length}`);let t=this.seed;return this.dictionaries.slice(0,this.length).reduce((n,r)=>{let i;t?(i=(a=>{if(typeof a=="string"){const s=a.split("").map(d=>d.charCodeAt(0)).reduce((d,h)=>d+h,1),u=Math.floor(Number(s));return Lx(u)}return Lx(a)})(t),t=4294967296*i):i=Math.random();let o=r[Math.floor(i*r.length)]||"";if(this.style==="lowerCase")o=o.toLowerCase();else if(this.style==="capital"){const[a,...s]=o.split("");o=a.toUpperCase()+s.join("")}else this.style==="upperCase"&&(o=o.toUpperCase());return n?`${n}${this.separator}${o}`:`${o}`},"")}}const Ox={separator:"_",dictionaries:[]},VVe=e=>{const t=[...e&&e.dictionaries||Ox.dictionaries],n={...Ox,...e,length:e&&e.length||t.length,dictionaries:t};if(!e||!e.dictionaries||!e.dictionaries.length)throw new Error('A "dictionaries" array must be provided. This is a breaking change introduced starting from Unique Name Generator v4. Read more about the breaking change here: https://github.com/andreasonny83/unique-names-generator#migration-guide');return new KVe(n).generate()};var GVe=["Aaren","Aarika","Abagael","Abagail","Abbe","Abbey","Abbi","Abbie","Abby","Abbye","Abigael","Abigail","Abigale","Abra","Ada","Adah","Adaline","Adan","Adara","Adda","Addi","Addia","Addie","Addy","Adel","Adela","Adelaida","Adelaide","Adele","Adelheid","Adelice","Adelina","Adelind","Adeline","Adella","Adelle","Adena","Adey","Adi","Adiana","Adina","Adora","Adore","Adoree","Adorne","Adrea","Adria","Adriaens","Adrian","Adriana","Adriane","Adrianna","Adrianne","Adriena","Adrienne","Aeriel","Aeriela","Aeriell","Afton","Ag","Agace","Agata","Agatha","Agathe","Aggi","Aggie","Aggy","Agna","Agnella","Agnes","Agnese","Agnesse","Agneta","Agnola","Agretha","Aida","Aidan","Aigneis","Aila","Aile","Ailee","Aileen","Ailene","Ailey","Aili","Ailina","Ailis","Ailsun","Ailyn","Aime","Aimee","Aimil","Aindrea","Ainslee","Ainsley","Ainslie","Ajay","Alaine","Alameda","Alana","Alanah","Alane","Alanna","Alayne","Alberta","Albertina","Albertine","Albina","Alecia","Aleda","Aleece","Aleen","Alejandra","Alejandrina","Alena","Alene","Alessandra","Aleta","Alethea","Alex","Alexa","Alexandra","Alexandrina","Alexi","Alexia","Alexina","Alexine","Alexis","Alfi","Alfie","Alfreda","Alfy","Ali","Alia","Alica","Alice","Alicea","Alicia","Alida","Alidia","Alie","Alika","Alikee","Alina","Aline","Alis","Alisa","Alisha","Alison","Alissa","Alisun","Alix","Aliza","Alla","Alleen","Allegra","Allene","Alli","Allianora","Allie","Allina","Allis","Allison","Allissa","Allix","Allsun","Allx","Ally","Allyce","Allyn","Allys","Allyson","Alma","Almeda","Almeria","Almeta","Almira","Almire","Aloise","Aloisia","Aloysia","Alta","Althea","Alvera","Alverta","Alvina","Alvinia","Alvira","Alyce","Alyda","Alys","Alysa","Alyse","Alysia","Alyson","Alyss","Alyssa","Amabel","Amabelle","Amalea","Amalee","Amaleta","Amalia","Amalie","Amalita","Amalle","Amanda","Amandi","Amandie","Amandy","Amara","Amargo","Amata","Amber","Amberly","Ambur","Ame","Amelia","Amelie","Amelina","Ameline","Amelita","Ami","Amie","Amii","Amil","Amitie","Amity","Ammamaria","Amy","Amye","Ana","Anabal","Anabel","Anabella","Anabelle","Analiese","Analise","Anallese","Anallise","Anastasia","Anastasie","Anastassia","Anatola","Andee","Andeee","Anderea","Andi","Andie","Andra","Andrea","Andreana","Andree","Andrei","Andria","Andriana","Andriette","Andromache","Andy","Anestassia","Anet","Anett","Anetta","Anette","Ange","Angel","Angela","Angele","Angelia","Angelica","Angelika","Angelina","Angeline","Angelique","Angelita","Angelle","Angie","Angil","Angy","Ania","Anica","Anissa","Anita","Anitra","Anjanette","Anjela","Ann","Ann-marie","Anna","Anna-diana","Anna-diane","Anna-maria","Annabal","Annabel","Annabela","Annabell","Annabella","Annabelle","Annadiana","Annadiane","Annalee","Annaliese","Annalise","Annamaria","Annamarie","Anne","Anne-corinne","Anne-marie","Annecorinne","Anneliese","Annelise","Annemarie","Annetta","Annette","Anni","Annice","Annie","Annis","Annissa","Annmaria","Annmarie","Annnora","Annora","Anny","Anselma","Ansley","Anstice","Anthe","Anthea","Anthia","Anthiathia","Antoinette","Antonella","Antonetta","Antonia","Antonie","Antonietta","Antonina","Anya","Appolonia","April","Aprilette","Ara","Arabel","Arabela","Arabele","Arabella","Arabelle","Arda","Ardath","Ardeen","Ardelia","Ardelis","Ardella","Ardelle","Arden","Ardene","Ardenia","Ardine","Ardis","Ardisj","Ardith","Ardra","Ardyce","Ardys","Ardyth","Aretha","Ariadne","Ariana","Aridatha","Ariel","Ariela","Ariella","Arielle","Arlana","Arlee","Arleen","Arlen","Arlena","Arlene","Arleta","Arlette","Arleyne","Arlie","Arliene","Arlina","Arlinda","Arline","Arluene","Arly","Arlyn","Arlyne","Aryn","Ashely","Ashia","Ashien","Ashil","Ashla","Ashlan","Ashlee","Ashleigh","Ashlen","Ashley","Ashli","Ashlie","Ashly","Asia","Astra","Astrid","Astrix","Atalanta","Athena","Athene","Atlanta","Atlante","Auberta","Aubine","Aubree","Aubrette","Aubrey","Aubrie","Aubry","Audi","Audie","Audra","Audre","Audrey","Audrie","Audry","Audrye","Audy","Augusta","Auguste","Augustina","Augustine","Aundrea","Aura","Aurea","Aurel","Aurelea","Aurelia","Aurelie","Auria","Aurie","Aurilia","Aurlie","Auroora","Aurora","Aurore","Austin","Austina","Austine","Ava","Aveline","Averil","Averyl","Avie","Avis","Aviva","Avivah","Avril","Avrit","Ayn","Bab","Babara","Babb","Babbette","Babbie","Babette","Babita","Babs","Bambi","Bambie","Bamby","Barb","Barbabra","Barbara","Barbara-anne","Barbaraanne","Barbe","Barbee","Barbette","Barbey","Barbi","Barbie","Barbra","Barby","Bari","Barrie","Barry","Basia","Bathsheba","Batsheva","Bea","Beatrice","Beatrisa","Beatrix","Beatriz","Bebe","Becca","Becka","Becki","Beckie","Becky","Bee","Beilul","Beitris","Bekki","Bel","Belia","Belicia","Belinda","Belita","Bell","Bella","Bellanca","Belle","Bellina","Belva","Belvia","Bendite","Benedetta","Benedicta","Benedikta","Benetta","Benita","Benni","Bennie","Benny","Benoite","Berenice","Beret","Berget","Berna","Bernadene","Bernadette","Bernadina","Bernadine","Bernardina","Bernardine","Bernelle","Bernete","Bernetta","Bernette","Berni","Bernice","Bernie","Bernita","Berny","Berri","Berrie","Berry","Bert","Berta","Berte","Bertha","Berthe","Berti","Bertie","Bertina","Bertine","Berty","Beryl","Beryle","Bess","Bessie","Bessy","Beth","Bethanne","Bethany","Bethena","Bethina","Betsey","Betsy","Betta","Bette","Bette-ann","Betteann","Betteanne","Betti","Bettina","Bettine","Betty","Bettye","Beulah","Bev","Beverie","Beverlee","Beverley","Beverlie","Beverly","Bevvy","Bianca","Bianka","Bibbie","Bibby","Bibbye","Bibi","Biddie","Biddy","Bidget","Bili","Bill","Billi","Billie","Billy","Billye","Binni","Binnie","Binny","Bird","Birdie","Birgit","Birgitta","Blair","Blaire","Blake","Blakelee","Blakeley","Blanca","Blanch","Blancha","Blanche","Blinni","Blinnie","Blinny","Bliss","Blisse","Blithe","Blondell","Blondelle","Blondie","Blondy","Blythe","Bobbe","Bobbee","Bobbette","Bobbi","Bobbie","Bobby","Bobbye","Bobette","Bobina","Bobine","Bobinette","Bonita","Bonnee","Bonni","Bonnibelle","Bonnie","Bonny","Brana","Brandais","Brande","Brandea","Brandi","Brandice","Brandie","Brandise","Brandy","Breanne","Brear","Bree","Breena","Bren","Brena","Brenda","Brenn","Brenna","Brett","Bria","Briana","Brianna","Brianne","Bride","Bridget","Bridgette","Bridie","Brier","Brietta","Brigid","Brigida","Brigit","Brigitta","Brigitte","Brina","Briney","Brinn","Brinna","Briny","Brit","Brita","Britney","Britni","Britt","Britta","Brittan","Brittaney","Brittani","Brittany","Britte","Britteny","Brittne","Brittney","Brittni","Brook","Brooke","Brooks","Brunhilda","Brunhilde","Bryana","Bryn","Bryna","Brynn","Brynna","Brynne","Buffy","Bunni","Bunnie","Bunny","Cacilia","Cacilie","Cahra","Cairistiona","Caitlin","Caitrin","Cal","Calida","Calla","Calley","Calli","Callida","Callie","Cally","Calypso","Cam","Camala","Camel","Camella","Camellia","Cami","Camila","Camile","Camilla","Camille","Cammi","Cammie","Cammy","Candace","Candi","Candice","Candida","Candide","Candie","Candis","Candra","Candy","Caprice","Cara","Caralie","Caren","Carena","Caresa","Caressa","Caresse","Carey","Cari","Caria","Carie","Caril","Carilyn","Carin","Carina","Carine","Cariotta","Carissa","Carita","Caritta","Carla","Carlee","Carleen","Carlen","Carlene","Carley","Carlie","Carlin","Carlina","Carline","Carlita","Carlota","Carlotta","Carly","Carlye","Carlyn","Carlynn","Carlynne","Carma","Carmel","Carmela","Carmelia","Carmelina","Carmelita","Carmella","Carmelle","Carmen","Carmencita","Carmina","Carmine","Carmita","Carmon","Caro","Carol","Carol-jean","Carola","Carolan","Carolann","Carole","Carolee","Carolin","Carolina","Caroline","Caroljean","Carolyn","Carolyne","Carolynn","Caron","Carree","Carri","Carrie","Carrissa","Carroll","Carry","Cary","Caryl","Caryn","Casandra","Casey","Casi","Casie","Cass","Cassandra","Cassandre","Cassandry","Cassaundra","Cassey","Cassi","Cassie","Cassondra","Cassy","Catarina","Cate","Caterina","Catha","Catharina","Catharine","Cathe","Cathee","Catherin","Catherina","Catherine","Cathi","Cathie","Cathleen","Cathlene","Cathrin","Cathrine","Cathryn","Cathy","Cathyleen","Cati","Catie","Catina","Catlaina","Catlee","Catlin","Catrina","Catriona","Caty","Caye","Cayla","Cecelia","Cecil","Cecile","Ceciley","Cecilia","Cecilla","Cecily","Ceil","Cele","Celene","Celesta","Celeste","Celestia","Celestina","Celestine","Celestyn","Celestyna","Celia","Celie","Celina","Celinda","Celine","Celinka","Celisse","Celka","Celle","Cesya","Chad","Chanda","Chandal","Chandra","Channa","Chantal","Chantalle","Charil","Charin","Charis","Charissa","Charisse","Charita","Charity","Charla","Charlean","Charleen","Charlena","Charlene","Charline","Charlot","Charlotta","Charlotte","Charmain","Charmaine","Charmane","Charmian","Charmine","Charmion","Charo","Charyl","Chastity","Chelsae","Chelsea","Chelsey","Chelsie","Chelsy","Cher","Chere","Cherey","Cheri","Cherianne","Cherice","Cherida","Cherie","Cherilyn","Cherilynn","Cherin","Cherise","Cherish","Cherlyn","Cherri","Cherrita","Cherry","Chery","Cherye","Cheryl","Cheslie","Chiarra","Chickie","Chicky","Chiquia","Chiquita","Chlo","Chloe","Chloette","Chloris","Chris","Chrissie","Chrissy","Christa","Christabel","Christabella","Christal","Christalle","Christan","Christean","Christel","Christen","Christi","Christian","Christiana","Christiane","Christie","Christin","Christina","Christine","Christy","Christye","Christyna","Chrysa","Chrysler","Chrystal","Chryste","Chrystel","Cicely","Cicily","Ciel","Cilka","Cinda","Cindee","Cindelyn","Cinderella","Cindi","Cindie","Cindra","Cindy","Cinnamon","Cissiee","Cissy","Clair","Claire","Clara","Clarabelle","Clare","Claresta","Clareta","Claretta","Clarette","Clarey","Clari","Claribel","Clarice","Clarie","Clarinda","Clarine","Clarissa","Clarisse","Clarita","Clary","Claude","Claudelle","Claudetta","Claudette","Claudia","Claudie","Claudina","Claudine","Clea","Clem","Clemence","Clementia","Clementina","Clementine","Clemmie","Clemmy","Cleo","Cleopatra","Clerissa","Clio","Clo","Cloe","Cloris","Clotilda","Clovis","Codee","Codi","Codie","Cody","Coleen","Colene","Coletta","Colette","Colleen","Collen","Collete","Collette","Collie","Colline","Colly","Con","Concettina","Conchita","Concordia","Conni","Connie","Conny","Consolata","Constance","Constancia","Constancy","Constanta","Constantia","Constantina","Constantine","Consuela","Consuelo","Cookie","Cora","Corabel","Corabella","Corabelle","Coral","Coralie","Coraline","Coralyn","Cordelia","Cordelie","Cordey","Cordi","Cordie","Cordula","Cordy","Coreen","Corella","Corenda","Corene","Coretta","Corette","Corey","Cori","Corie","Corilla","Corina","Corine","Corinna","Corinne","Coriss","Corissa","Corliss","Corly","Cornela","Cornelia","Cornelle","Cornie","Corny","Correna","Correy","Corri","Corrianne","Corrie","Corrina","Corrine","Corrinne","Corry","Cortney","Cory","Cosetta","Cosette","Costanza","Courtenay","Courtnay","Courtney","Crin","Cris","Crissie","Crissy","Crista","Cristabel","Cristal","Cristen","Cristi","Cristie","Cristin","Cristina","Cristine","Cristionna","Cristy","Crysta","Crystal","Crystie","Cthrine","Cyb","Cybil","Cybill","Cymbre","Cynde","Cyndi","Cyndia","Cyndie","Cyndy","Cynthea","Cynthia","Cynthie","Cynthy","Dacey","Dacia","Dacie","Dacy","Dael","Daffi","Daffie","Daffy","Dagmar","Dahlia","Daile","Daisey","Daisi","Daisie","Daisy","Dale","Dalenna","Dalia","Dalila","Dallas","Daloris","Damara","Damaris","Damita","Dana","Danell","Danella","Danette","Dani","Dania","Danica","Danice","Daniela","Daniele","Daniella","Danielle","Danika","Danila","Danit","Danita","Danna","Danni","Dannie","Danny","Dannye","Danya","Danyelle","Danyette","Daphene","Daphna","Daphne","Dara","Darb","Darbie","Darby","Darcee","Darcey","Darci","Darcie","Darcy","Darda","Dareen","Darell","Darelle","Dari","Daria","Darice","Darla","Darleen","Darlene","Darline","Darlleen","Daron","Darrelle","Darryl","Darsey","Darsie","Darya","Daryl","Daryn","Dasha","Dasi","Dasie","Dasya","Datha","Daune","Daveen","Daveta","Davida","Davina","Davine","Davita","Dawn","Dawna","Dayle","Dayna","Ddene","De","Deana","Deane","Deanna","Deanne","Deb","Debbi","Debbie","Debby","Debee","Debera","Debi","Debor","Debora","Deborah","Debra","Dede","Dedie","Dedra","Dee","Deeann","Deeanne","Deedee","Deena","Deerdre","Deeyn","Dehlia","Deidre","Deina","Deirdre","Del","Dela","Delcina","Delcine","Delia","Delila","Delilah","Delinda","Dell","Della","Delly","Delora","Delores","Deloria","Deloris","Delphine","Delphinia","Demeter","Demetra","Demetria","Demetris","Dena","Deni","Denice","Denise","Denna","Denni","Dennie","Denny","Deny","Denys","Denyse","Deonne","Desdemona","Desirae","Desiree","Desiri","Deva","Devan","Devi","Devin","Devina","Devinne","Devon","Devondra","Devonna","Devonne","Devora","Di","Diahann","Dian","Diana","Diandra","Diane","Diane-marie","Dianemarie","Diann","Dianna","Dianne","Diannne","Didi","Dido","Diena","Dierdre","Dina","Dinah","Dinnie","Dinny","Dion","Dione","Dionis","Dionne","Dita","Dix","Dixie","Dniren","Dode","Dodi","Dodie","Dody","Doe","Doll","Dolley","Dolli","Dollie","Dolly","Dolores","Dolorita","Doloritas","Domeniga","Dominga","Domini","Dominica","Dominique","Dona","Donella","Donelle","Donetta","Donia","Donica","Donielle","Donna","Donnamarie","Donni","Donnie","Donny","Dora","Doralia","Doralin","Doralyn","Doralynn","Doralynne","Dore","Doreen","Dorelia","Dorella","Dorelle","Dorena","Dorene","Doretta","Dorette","Dorey","Dori","Doria","Dorian","Dorice","Dorie","Dorine","Doris","Dorisa","Dorise","Dorita","Doro","Dorolice","Dorolisa","Dorotea","Doroteya","Dorothea","Dorothee","Dorothy","Dorree","Dorri","Dorrie","Dorris","Dorry","Dorthea","Dorthy","Dory","Dosi","Dot","Doti","Dotti","Dottie","Dotty","Dre","Dreddy","Dredi","Drona","Dru","Druci","Drucie","Drucill","Drucy","Drusi","Drusie","Drusilla","Drusy","Dulce","Dulcea","Dulci","Dulcia","Dulciana","Dulcie","Dulcine","Dulcinea","Dulcy","Dulsea","Dusty","Dyan","Dyana","Dyane","Dyann","Dyanna","Dyanne","Dyna","Dynah","Eachelle","Eada","Eadie","Eadith","Ealasaid","Eartha","Easter","Eba","Ebba","Ebonee","Ebony","Eda","Eddi","Eddie","Eddy","Ede","Edee","Edeline","Eden","Edi","Edie","Edin","Edita","Edith","Editha","Edithe","Ediva","Edna","Edwina","Edy","Edyth","Edythe","Effie","Eileen","Eilis","Eimile","Eirena","Ekaterina","Elaina","Elaine","Elana","Elane","Elayne","Elberta","Elbertina","Elbertine","Eleanor","Eleanora","Eleanore","Electra","Eleen","Elena","Elene","Eleni","Elenore","Eleonora","Eleonore","Elfie","Elfreda","Elfrida","Elfrieda","Elga","Elianora","Elianore","Elicia","Elie","Elinor","Elinore","Elisa","Elisabet","Elisabeth","Elisabetta","Elise","Elisha","Elissa","Elita","Eliza","Elizabet","Elizabeth","Elka","Elke","Ella","Elladine","Elle","Ellen","Ellene","Ellette","Elli","Ellie","Ellissa","Elly","Ellyn","Ellynn","Elmira","Elna","Elnora","Elnore","Eloisa","Eloise","Elonore","Elora","Elsa","Elsbeth","Else","Elset","Elsey","Elsi","Elsie","Elsinore","Elspeth","Elsy","Elva","Elvera","Elvina","Elvira","Elwira","Elyn","Elyse","Elysee","Elysha","Elysia","Elyssa","Em","Ema","Emalee","Emalia","Emelda","Emelia","Emelina","Emeline","Emelita","Emelyne","Emera","Emilee","Emili","Emilia","Emilie","Emiline","Emily","Emlyn","Emlynn","Emlynne","Emma","Emmalee","Emmaline","Emmalyn","Emmalynn","Emmalynne","Emmeline","Emmey","Emmi","Emmie","Emmy","Emmye","Emogene","Emyle","Emylee","Engracia","Enid","Enrica","Enrichetta","Enrika","Enriqueta","Eolanda","Eolande","Eran","Erda","Erena","Erica","Ericha","Ericka","Erika","Erin","Erina","Erinn","Erinna","Erma","Ermengarde","Ermentrude","Ermina","Erminia","Erminie","Erna","Ernaline","Ernesta","Ernestine","Ertha","Eryn","Esma","Esmaria","Esme","Esmeralda","Essa","Essie","Essy","Esta","Estel","Estele","Estell","Estella","Estelle","Ester","Esther","Estrella","Estrellita","Ethel","Ethelda","Ethelin","Ethelind","Etheline","Ethelyn","Ethyl","Etta","Etti","Ettie","Etty","Eudora","Eugenia","Eugenie","Eugine","Eula","Eulalie","Eunice","Euphemia","Eustacia","Eva","Evaleen","Evangelia","Evangelin","Evangelina","Evangeline","Evania","Evanne","Eve","Eveleen","Evelina","Eveline","Evelyn","Evey","Evie","Evita","Evonne","Evvie","Evvy","Evy","Eyde","Eydie","Ezmeralda","Fae","Faina","Faith","Fallon","Fan","Fanchette","Fanchon","Fancie","Fancy","Fanechka","Fania","Fanni","Fannie","Fanny","Fanya","Fara","Farah","Farand","Farica","Farra","Farrah","Farrand","Faun","Faunie","Faustina","Faustine","Fawn","Fawne","Fawnia","Fay","Faydra","Faye","Fayette","Fayina","Fayre","Fayth","Faythe","Federica","Fedora","Felecia","Felicdad","Felice","Felicia","Felicity","Felicle","Felipa","Felisha","Felita","Feliza","Fenelia","Feodora","Ferdinanda","Ferdinande","Fern","Fernanda","Fernande","Fernandina","Ferne","Fey","Fiann","Fianna","Fidela","Fidelia","Fidelity","Fifi","Fifine","Filia","Filide","Filippa","Fina","Fiona","Fionna","Fionnula","Fiorenze","Fleur","Fleurette","Flo","Flor","Flora","Florance","Flore","Florella","Florence","Florencia","Florentia","Florenza","Florette","Flori","Floria","Florida","Florie","Florina","Florinda","Floris","Florri","Florrie","Florry","Flory","Flossi","Flossie","Flossy","Flss","Fran","Francene","Frances","Francesca","Francine","Francisca","Franciska","Francoise","Francyne","Frank","Frankie","Franky","Franni","Frannie","Franny","Frayda","Fred","Freda","Freddi","Freddie","Freddy","Fredelia","Frederica","Fredericka","Frederique","Fredi","Fredia","Fredra","Fredrika","Freida","Frieda","Friederike","Fulvia","Gabbey","Gabbi","Gabbie","Gabey","Gabi","Gabie","Gabriel","Gabriela","Gabriell","Gabriella","Gabrielle","Gabriellia","Gabrila","Gaby","Gae","Gael","Gail","Gale","Galina","Garland","Garnet","Garnette","Gates","Gavra","Gavrielle","Gay","Gaye","Gayel","Gayla","Gayle","Gayleen","Gaylene","Gaynor","Gelya","Gena","Gene","Geneva","Genevieve","Genevra","Genia","Genna","Genni","Gennie","Gennifer","Genny","Genovera","Genvieve","George","Georgeanna","Georgeanne","Georgena","Georgeta","Georgetta","Georgette","Georgia","Georgiana","Georgianna","Georgianne","Georgie","Georgina","Georgine","Geralda","Geraldine","Gerda","Gerhardine","Geri","Gerianna","Gerianne","Gerladina","Germain","Germaine","Germana","Gerri","Gerrie","Gerrilee","Gerry","Gert","Gerta","Gerti","Gertie","Gertrud","Gertruda","Gertrude","Gertrudis","Gerty","Giacinta","Giana","Gianina","Gianna","Gigi","Gilberta","Gilberte","Gilbertina","Gilbertine","Gilda","Gilemette","Gill","Gillan","Gilli","Gillian","Gillie","Gilligan","Gilly","Gina","Ginelle","Ginevra","Ginger","Ginni","Ginnie","Ginnifer","Ginny","Giorgia","Giovanna","Gipsy","Giralda","Gisela","Gisele","Gisella","Giselle","Giuditta","Giulia","Giulietta","Giustina","Gizela","Glad","Gladi","Gladys","Gleda","Glen","Glenda","Glenine","Glenn","Glenna","Glennie","Glennis","Glori","Gloria","Gloriana","Gloriane","Glory","Glyn","Glynda","Glynis","Glynnis","Gnni","Godiva","Golda","Goldarina","Goldi","Goldia","Goldie","Goldina","Goldy","Grace","Gracia","Gracie","Grata","Gratia","Gratiana","Gray","Grayce","Grazia","Greer","Greta","Gretal","Gretchen","Grete","Gretel","Grethel","Gretna","Gretta","Grier","Griselda","Grissel","Guendolen","Guenevere","Guenna","Guglielma","Gui","Guillema","Guillemette","Guinevere","Guinna","Gunilla","Gus","Gusella","Gussi","Gussie","Gussy","Gusta","Gusti","Gustie","Gusty","Gwen","Gwendolen","Gwendolin","Gwendolyn","Gweneth","Gwenette","Gwenneth","Gwenni","Gwennie","Gwenny","Gwenora","Gwenore","Gwyn","Gwyneth","Gwynne","Gypsy","Hadria","Hailee","Haily","Haleigh","Halette","Haley","Hali","Halie","Halimeda","Halley","Halli","Hallie","Hally","Hana","Hanna","Hannah","Hanni","Hannie","Hannis","Hanny","Happy","Harlene","Harley","Harli","Harlie","Harmonia","Harmonie","Harmony","Harri","Harrie","Harriet","Harriett","Harrietta","Harriette","Harriot","Harriott","Hatti","Hattie","Hatty","Hayley","Hazel","Heath","Heather","Heda","Hedda","Heddi","Heddie","Hedi","Hedvig","Hedvige","Hedwig","Hedwiga","Hedy","Heida","Heidi","Heidie","Helaina","Helaine","Helen","Helen-elizabeth","Helena","Helene","Helenka","Helga","Helge","Helli","Heloise","Helsa","Helyn","Hendrika","Henka","Henrie","Henrieta","Henrietta","Henriette","Henryetta","Hephzibah","Hermia","Hermina","Hermine","Herminia","Hermione","Herta","Hertha","Hester","Hesther","Hestia","Hetti","Hettie","Hetty","Hilary","Hilda","Hildagard","Hildagarde","Hilde","Hildegaard","Hildegarde","Hildy","Hillary","Hilliary","Hinda","Holli","Hollie","Holly","Holly-anne","Hollyanne","Honey","Honor","Honoria","Hope","Horatia","Hortense","Hortensia","Hulda","Hyacinth","Hyacintha","Hyacinthe","Hyacinthia","Hyacinthie","Hynda","Ianthe","Ibbie","Ibby","Ida","Idalia","Idalina","Idaline","Idell","Idelle","Idette","Ileana","Ileane","Ilene","Ilise","Ilka","Illa","Ilsa","Ilse","Ilysa","Ilyse","Ilyssa","Imelda","Imogen","Imogene","Imojean","Ina","Indira","Ines","Inesita","Inessa","Inez","Inga","Ingaberg","Ingaborg","Inge","Ingeberg","Ingeborg","Inger","Ingrid","Ingunna","Inna","Iolande","Iolanthe","Iona","Iormina","Ira","Irena","Irene","Irina","Iris","Irita","Irma","Isa","Isabel","Isabelita","Isabella","Isabelle","Isadora","Isahella","Iseabal","Isidora","Isis","Isobel","Issi","Issie","Issy","Ivett","Ivette","Ivie","Ivonne","Ivory","Ivy","Izabel","Jacenta","Jacinda","Jacinta","Jacintha","Jacinthe","Jackelyn","Jacki","Jackie","Jacklin","Jacklyn","Jackquelin","Jackqueline","Jacky","Jaclin","Jaclyn","Jacquelin","Jacqueline","Jacquelyn","Jacquelynn","Jacquenetta","Jacquenette","Jacquetta","Jacquette","Jacqui","Jacquie","Jacynth","Jada","Jade","Jaime","Jaimie","Jaine","Jami","Jamie","Jamima","Jammie","Jan","Jana","Janaya","Janaye","Jandy","Jane","Janean","Janeczka","Janeen","Janel","Janela","Janella","Janelle","Janene","Janenna","Janessa","Janet","Janeta","Janetta","Janette","Janeva","Janey","Jania","Janice","Janie","Janifer","Janina","Janine","Janis","Janith","Janka","Janna","Jannel","Jannelle","Janot","Jany","Jaquelin","Jaquelyn","Jaquenetta","Jaquenette","Jaquith","Jasmin","Jasmina","Jasmine","Jayme","Jaymee","Jayne","Jaynell","Jazmin","Jean","Jeana","Jeane","Jeanelle","Jeanette","Jeanie","Jeanine","Jeanna","Jeanne","Jeannette","Jeannie","Jeannine","Jehanna","Jelene","Jemie","Jemima","Jemimah","Jemmie","Jemmy","Jen","Jena","Jenda","Jenelle","Jeni","Jenica","Jeniece","Jenifer","Jeniffer","Jenilee","Jenine","Jenn","Jenna","Jennee","Jennette","Jenni","Jennica","Jennie","Jennifer","Jennilee","Jennine","Jenny","Jeralee","Jere","Jeri","Jermaine","Jerrie","Jerrilee","Jerrilyn","Jerrine","Jerry","Jerrylee","Jess","Jessa","Jessalin","Jessalyn","Jessamine","Jessamyn","Jesse","Jesselyn","Jessi","Jessica","Jessie","Jessika","Jessy","Jewel","Jewell","Jewelle","Jill","Jillana","Jillane","Jillayne","Jilleen","Jillene","Jilli","Jillian","Jillie","Jilly","Jinny","Jo","Jo-ann","Jo-anne","Joan","Joana","Joane","Joanie","Joann","Joanna","Joanne","Joannes","Jobey","Jobi","Jobie","Jobina","Joby","Jobye","Jobyna","Jocelin","Joceline","Jocelyn","Jocelyne","Jodee","Jodi","Jodie","Jody","Joeann","Joela","Joelie","Joell","Joella","Joelle","Joellen","Joelly","Joellyn","Joelynn","Joete","Joey","Johanna","Johannah","Johna","Johnath","Johnette","Johnna","Joice","Jojo","Jolee","Joleen","Jolene","Joletta","Joli","Jolie","Joline","Joly","Jolyn","Jolynn","Jonell","Joni","Jonie","Jonis","Jordain","Jordan","Jordana","Jordanna","Jorey","Jori","Jorie","Jorrie","Jorry","Joscelin","Josee","Josefa","Josefina","Josepha","Josephina","Josephine","Josey","Josi","Josie","Josselyn","Josy","Jourdan","Joy","Joya","Joyan","Joyann","Joyce","Joycelin","Joye","Jsandye","Juana","Juanita","Judi","Judie","Judith","Juditha","Judy","Judye","Juieta","Julee","Juli","Julia","Juliana","Juliane","Juliann","Julianna","Julianne","Julie","Julienne","Juliet","Julieta","Julietta","Juliette","Julina","Juline","Julissa","Julita","June","Junette","Junia","Junie","Junina","Justina","Justine","Justinn","Jyoti","Kacey","Kacie","Kacy","Kaela","Kai","Kaia","Kaila","Kaile","Kailey","Kaitlin","Kaitlyn","Kaitlynn","Kaja","Kakalina","Kala","Kaleena","Kali","Kalie","Kalila","Kalina","Kalinda","Kalindi","Kalli","Kally","Kameko","Kamila","Kamilah","Kamillah","Kandace","Kandy","Kania","Kanya","Kara","Kara-lynn","Karalee","Karalynn","Kare","Karee","Karel","Karen","Karena","Kari","Karia","Karie","Karil","Karilynn","Karin","Karina","Karine","Kariotta","Karisa","Karissa","Karita","Karla","Karlee","Karleen","Karlen","Karlene","Karlie","Karlotta","Karlotte","Karly","Karlyn","Karmen","Karna","Karol","Karola","Karole","Karolina","Karoline","Karoly","Karon","Karrah","Karrie","Karry","Kary","Karyl","Karylin","Karyn","Kasey","Kass","Kassandra","Kassey","Kassi","Kassia","Kassie","Kat","Kata","Katalin","Kate","Katee","Katerina","Katerine","Katey","Kath","Katha","Katharina","Katharine","Katharyn","Kathe","Katherina","Katherine","Katheryn","Kathi","Kathie","Kathleen","Kathlin","Kathrine","Kathryn","Kathryne","Kathy","Kathye","Kati","Katie","Katina","Katine","Katinka","Katleen","Katlin","Katrina","Katrine","Katrinka","Katti","Kattie","Katuscha","Katusha","Katy","Katya","Kay","Kaycee","Kaye","Kayla","Kayle","Kaylee","Kayley","Kaylil","Kaylyn","Keeley","Keelia","Keely","Kelcey","Kelci","Kelcie","Kelcy","Kelila","Kellen","Kelley","Kelli","Kellia","Kellie","Kellina","Kellsie","Kelly","Kellyann","Kelsey","Kelsi","Kelsy","Kendra","Kendre","Kenna","Keri","Keriann","Kerianne","Kerri","Kerrie","Kerrill","Kerrin","Kerry","Kerstin","Kesley","Keslie","Kessia","Kessiah","Ketti","Kettie","Ketty","Kevina","Kevyn","Ki","Kiah","Kial","Kiele","Kiersten","Kikelia","Kiley","Kim","Kimberlee","Kimberley","Kimberli","Kimberly","Kimberlyn","Kimbra","Kimmi","Kimmie","Kimmy","Kinna","Kip","Kipp","Kippie","Kippy","Kira","Kirbee","Kirbie","Kirby","Kiri","Kirsten","Kirsteni","Kirsti","Kirstin","Kirstyn","Kissee","Kissiah","Kissie","Kit","Kitti","Kittie","Kitty","Kizzee","Kizzie","Klara","Klarika","Klarrisa","Konstance","Konstanze","Koo","Kora","Koral","Koralle","Kordula","Kore","Korella","Koren","Koressa","Kori","Korie","Korney","Korrie","Korry","Kris","Krissie","Krissy","Krista","Kristal","Kristan","Kriste","Kristel","Kristen","Kristi","Kristien","Kristin","Kristina","Kristine","Kristy","Kristyn","Krysta","Krystal","Krystalle","Krystle","Krystyna","Kyla","Kyle","Kylen","Kylie","Kylila","Kylynn","Kym","Kynthia","Kyrstin","Lacee","Lacey","Lacie","Lacy","Ladonna","Laetitia","Laina","Lainey","Lana","Lanae","Lane","Lanette","Laney","Lani","Lanie","Lanita","Lanna","Lanni","Lanny","Lara","Laraine","Lari","Larina","Larine","Larisa","Larissa","Lark","Laryssa","Latashia","Latia","Latisha","Latrena","Latrina","Laura","Lauraine","Laural","Lauralee","Laure","Lauree","Laureen","Laurel","Laurella","Lauren","Laurena","Laurene","Lauretta","Laurette","Lauri","Laurianne","Laurice","Laurie","Lauryn","Lavena","Laverna","Laverne","Lavina","Lavinia","Lavinie","Layla","Layne","Layney","Lea","Leah","Leandra","Leann","Leanna","Leanor","Leanora","Lebbie","Leda","Lee","Leeann","Leeanne","Leela","Leelah","Leena","Leesa","Leese","Legra","Leia","Leigh","Leigha","Leila","Leilah","Leisha","Lela","Lelah","Leland","Lelia","Lena","Lenee","Lenette","Lenka","Lenna","Lenora","Lenore","Leodora","Leoine","Leola","Leoline","Leona","Leonanie","Leone","Leonelle","Leonie","Leonora","Leonore","Leontine","Leontyne","Leora","Leshia","Lesley","Lesli","Leslie","Lesly","Lesya","Leta","Lethia","Leticia","Letisha","Letitia","Letizia","Letta","Letti","Lettie","Letty","Lexi","Lexie","Lexine","Lexis","Lexy","Leyla","Lezlie","Lia","Lian","Liana","Liane","Lianna","Lianne","Lib","Libbey","Libbi","Libbie","Libby","Licha","Lida","Lidia","Liesa","Lil","Lila","Lilah","Lilas","Lilia","Lilian","Liliane","Lilias","Lilith","Lilla","Lilli","Lillian","Lillis","Lilllie","Lilly","Lily","Lilyan","Lin","Lina","Lind","Linda","Lindi","Lindie","Lindsay","Lindsey","Lindsy","Lindy","Linea","Linell","Linet","Linette","Linn","Linnea","Linnell","Linnet","Linnie","Linzy","Lira","Lisa","Lisabeth","Lisbeth","Lise","Lisetta","Lisette","Lisha","Lishe","Lissa","Lissi","Lissie","Lissy","Lita","Liuka","Liv","Liva","Livia","Livvie","Livvy","Livvyy","Livy","Liz","Liza","Lizabeth","Lizbeth","Lizette","Lizzie","Lizzy","Loella","Lois","Loise","Lola","Loleta","Lolita","Lolly","Lona","Lonee","Loni","Lonna","Lonni","Lonnie","Lora","Lorain","Loraine","Loralee","Loralie","Loralyn","Loree","Loreen","Lorelei","Lorelle","Loren","Lorena","Lorene","Lorenza","Loretta","Lorette","Lori","Loria","Lorianna","Lorianne","Lorie","Lorilee","Lorilyn","Lorinda","Lorine","Lorita","Lorna","Lorne","Lorraine","Lorrayne","Lorri","Lorrie","Lorrin","Lorry","Lory","Lotta","Lotte","Lotti","Lottie","Lotty","Lou","Louella","Louisa","Louise","Louisette","Loutitia","Lu","Luce","Luci","Lucia","Luciana","Lucie","Lucienne","Lucila","Lucilia","Lucille","Lucina","Lucinda","Lucine","Lucita","Lucky","Lucretia","Lucy","Ludovika","Luella","Luelle","Luisa","Luise","Lula","Lulita","Lulu","Lura","Lurette","Lurleen","Lurlene","Lurline","Lusa","Luz","Lyda","Lydia","Lydie","Lyn","Lynda","Lynde","Lyndel","Lyndell","Lyndsay","Lyndsey","Lyndsie","Lyndy","Lynea","Lynelle","Lynett","Lynette","Lynn","Lynna","Lynne","Lynnea","Lynnell","Lynnelle","Lynnet","Lynnett","Lynnette","Lynsey","Lyssa","Mab","Mabel","Mabelle","Mable","Mada","Madalena","Madalyn","Maddalena","Maddi","Maddie","Maddy","Madel","Madelaine","Madeleine","Madelena","Madelene","Madelin","Madelina","Madeline","Madella","Madelle","Madelon","Madelyn","Madge","Madlen","Madlin","Madonna","Mady","Mae","Maegan","Mag","Magda","Magdaia","Magdalen","Magdalena","Magdalene","Maggee","Maggi","Maggie","Maggy","Mahala","Mahalia","Maia","Maible","Maiga","Maighdiln","Mair","Maire","Maisey","Maisie","Maitilde","Mala","Malanie","Malena","Malia","Malina","Malinda","Malinde","Malissa","Malissia","Mallissa","Mallorie","Mallory","Malorie","Malory","Malva","Malvina","Malynda","Mame","Mamie","Manda","Mandi","Mandie","Mandy","Manon","Manya","Mara","Marabel","Marcela","Marcelia","Marcella","Marcelle","Marcellina","Marcelline","Marchelle","Marci","Marcia","Marcie","Marcile","Marcille","Marcy","Mareah","Maren","Marena","Maressa","Marga","Margalit","Margalo","Margaret","Margareta","Margarete","Margaretha","Margarethe","Margaretta","Margarette","Margarita","Margaux","Marge","Margeaux","Margery","Marget","Margette","Margi","Margie","Margit","Margo","Margot","Margret","Marguerite","Margy","Mari","Maria","Mariam","Marian","Mariana","Mariann","Marianna","Marianne","Maribel","Maribelle","Maribeth","Marice","Maridel","Marie","Marie-ann","Marie-jeanne","Marieann","Mariejeanne","Mariel","Mariele","Marielle","Mariellen","Marietta","Mariette","Marigold","Marijo","Marika","Marilee","Marilin","Marillin","Marilyn","Marin","Marina","Marinna","Marion","Mariquilla","Maris","Marisa","Mariska","Marissa","Marita","Maritsa","Mariya","Marj","Marja","Marje","Marji","Marjie","Marjorie","Marjory","Marjy","Marketa","Marla","Marlane","Marleah","Marlee","Marleen","Marlena","Marlene","Marley","Marlie","Marline","Marlo","Marlyn","Marna","Marne","Marney","Marni","Marnia","Marnie","Marquita","Marrilee","Marris","Marrissa","Marsha","Marsiella","Marta","Martelle","Martguerita","Martha","Marthe","Marthena","Marti","Martica","Martie","Martina","Martita","Marty","Martynne","Mary","Marya","Maryann","Maryanna","Maryanne","Marybelle","Marybeth","Maryellen","Maryjane","Maryjo","Maryl","Marylee","Marylin","Marylinda","Marylou","Marylynne","Maryrose","Marys","Marysa","Masha","Matelda","Mathilda","Mathilde","Matilda","Matilde","Matti","Mattie","Matty","Maud","Maude","Maudie","Maura","Maure","Maureen","Maureene","Maurene","Maurine","Maurise","Maurita","Maurizia","Mavis","Mavra","Max","Maxi","Maxie","Maxine","Maxy","May","Maybelle","Maye","Mead","Meade","Meagan","Meaghan","Meara","Mechelle","Meg","Megan","Megen","Meggi","Meggie","Meggy","Meghan","Meghann","Mehetabel","Mei","Mel","Mela","Melamie","Melania","Melanie","Melantha","Melany","Melba","Melesa","Melessa","Melicent","Melina","Melinda","Melinde","Melisa","Melisande","Melisandra","Melisenda","Melisent","Melissa","Melisse","Melita","Melitta","Mella","Melli","Mellicent","Mellie","Mellisa","Mellisent","Melloney","Melly","Melodee","Melodie","Melody","Melonie","Melony","Melosa","Melva","Mercedes","Merci","Mercie","Mercy","Meredith","Meredithe","Meridel","Meridith","Meriel","Merilee","Merilyn","Meris","Merissa","Merl","Merla","Merle","Merlina","Merline","Merna","Merola","Merralee","Merridie","Merrie","Merrielle","Merrile","Merrilee","Merrili","Merrill","Merrily","Merry","Mersey","Meryl","Meta","Mia","Micaela","Michaela","Michaelina","Michaeline","Michaella","Michal","Michel","Michele","Michelina","Micheline","Michell","Michelle","Micki","Mickie","Micky","Midge","Mignon","Mignonne","Miguela","Miguelita","Mikaela","Mil","Mildred","Mildrid","Milena","Milicent","Milissent","Milka","Milli","Millicent","Millie","Millisent","Milly","Milzie","Mimi","Min","Mina","Minda","Mindy","Minerva","Minetta","Minette","Minna","Minnaminnie","Minne","Minni","Minnie","Minnnie","Minny","Minta","Miquela","Mira","Mirabel","Mirabella","Mirabelle","Miran","Miranda","Mireielle","Mireille","Mirella","Mirelle","Miriam","Mirilla","Mirna","Misha","Missie","Missy","Misti","Misty","Mitzi","Modesta","Modestia","Modestine","Modesty","Moina","Moira","Moll","Mollee","Molli","Mollie","Molly","Mommy","Mona","Monah","Monica","Monika","Monique","Mora","Moreen","Morena","Morgan","Morgana","Morganica","Morganne","Morgen","Moria","Morissa","Morna","Moselle","Moyna","Moyra","Mozelle","Muffin","Mufi","Mufinella","Muire","Mureil","Murial","Muriel","Murielle","Myra","Myrah","Myranda","Myriam","Myrilla","Myrle","Myrlene","Myrna","Myrta","Myrtia","Myrtice","Myrtie","Myrtle","Nada","Nadean","Nadeen","Nadia","Nadine","Nadiya","Nady","Nadya","Nalani","Nan","Nana","Nananne","Nance","Nancee","Nancey","Nanci","Nancie","Nancy","Nanete","Nanette","Nani","Nanice","Nanine","Nannette","Nanni","Nannie","Nanny","Nanon","Naoma","Naomi","Nara","Nari","Nariko","Nat","Nata","Natala","Natalee","Natalie","Natalina","Nataline","Natalya","Natasha","Natassia","Nathalia","Nathalie","Natividad","Natka","Natty","Neala","Neda","Nedda","Nedi","Neely","Neila","Neile","Neilla","Neille","Nelia","Nelie","Nell","Nelle","Nelli","Nellie","Nelly","Nerissa","Nerita","Nert","Nerta","Nerte","Nerti","Nertie","Nerty","Nessa","Nessi","Nessie","Nessy","Nesta","Netta","Netti","Nettie","Nettle","Netty","Nevsa","Neysa","Nichol","Nichole","Nicholle","Nicki","Nickie","Nicky","Nicol","Nicola","Nicole","Nicolea","Nicolette","Nicoli","Nicolina","Nicoline","Nicolle","Nikaniki","Nike","Niki","Nikki","Nikkie","Nikoletta","Nikolia","Nina","Ninetta","Ninette","Ninnetta","Ninnette","Ninon","Nissa","Nisse","Nissie","Nissy","Nita","Nixie","Noami","Noel","Noelani","Noell","Noella","Noelle","Noellyn","Noelyn","Noemi","Nola","Nolana","Nolie","Nollie","Nomi","Nona","Nonah","Noni","Nonie","Nonna","Nonnah","Nora","Norah","Norean","Noreen","Norene","Norina","Norine","Norma","Norri","Norrie","Norry","Novelia","Nydia","Nyssa","Octavia","Odele","Odelia","Odelinda","Odella","Odelle","Odessa","Odetta","Odette","Odilia","Odille","Ofelia","Ofella","Ofilia","Ola","Olenka","Olga","Olia","Olimpia","Olive","Olivette","Olivia","Olivie","Oliy","Ollie","Olly","Olva","Olwen","Olympe","Olympia","Olympie","Ondrea","Oneida","Onida","Oona","Opal","Opalina","Opaline","Ophelia","Ophelie","Ora","Oralee","Oralia","Oralie","Oralla","Oralle","Orel","Orelee","Orelia","Orelie","Orella","Orelle","Oriana","Orly","Orsa","Orsola","Ortensia","Otha","Othelia","Othella","Othilia","Othilie","Ottilie","Page","Paige","Paloma","Pam","Pamela","Pamelina","Pamella","Pammi","Pammie","Pammy","Pandora","Pansie","Pansy","Paola","Paolina","Papagena","Pat","Patience","Patrica","Patrice","Patricia","Patrizia","Patsy","Patti","Pattie","Patty","Paula","Paule","Pauletta","Paulette","Pauli","Paulie","Paulina","Pauline","Paulita","Pauly","Pavia","Pavla","Pearl","Pearla","Pearle","Pearline","Peg","Pegeen","Peggi","Peggie","Peggy","Pen","Penelopa","Penelope","Penni","Pennie","Penny","Pepi","Pepita","Peri","Peria","Perl","Perla","Perle","Perri","Perrine","Perry","Persis","Pet","Peta","Petra","Petrina","Petronella","Petronia","Petronilla","Petronille","Petunia","Phaedra","Phaidra","Phebe","Phedra","Phelia","Phil","Philipa","Philippa","Philippe","Philippine","Philis","Phillida","Phillie","Phillis","Philly","Philomena","Phoebe","Phylis","Phyllida","Phyllis","Phyllys","Phylys","Pia","Pier","Pierette","Pierrette","Pietra","Piper","Pippa","Pippy","Polly","Pollyanna","Pooh","Poppy","Portia","Pris","Prisca","Priscella","Priscilla","Prissie","Pru","Prudence","Prudi","Prudy","Prue","Queenie","Quentin","Querida","Quinn","Quinta","Quintana","Quintilla","Quintina","Rachael","Rachel","Rachele","Rachelle","Rae","Raeann","Raf","Rafa","Rafaela","Rafaelia","Rafaelita","Rahal","Rahel","Raina","Raine","Rakel","Ralina","Ramona","Ramonda","Rana","Randa","Randee","Randene","Randi","Randie","Randy","Ranee","Rani","Rania","Ranice","Ranique","Ranna","Raphaela","Raquel","Raquela","Rasia","Rasla","Raven","Ray","Raychel","Raye","Rayna","Raynell","Rayshell","Rea","Reba","Rebbecca","Rebe","Rebeca","Rebecca","Rebecka","Rebeka","Rebekah","Rebekkah","Ree","Reeba","Reena","Reeta","Reeva","Regan","Reggi","Reggie","Regina","Regine","Reiko","Reina","Reine","Remy","Rena","Renae","Renata","Renate","Rene","Renee","Renell","Renelle","Renie","Rennie","Reta","Retha","Revkah","Rey","Reyna","Rhea","Rheba","Rheta","Rhetta","Rhiamon","Rhianna","Rhianon","Rhoda","Rhodia","Rhodie","Rhody","Rhona","Rhonda","Riane","Riannon","Rianon","Rica","Ricca","Rici","Ricki","Rickie","Ricky","Riki","Rikki","Rina","Risa","Rita","Riva","Rivalee","Rivi","Rivkah","Rivy","Roana","Roanna","Roanne","Robbi","Robbie","Robbin","Robby","Robbyn","Robena","Robenia","Roberta","Robin","Robina","Robinet","Robinett","Robinetta","Robinette","Robinia","Roby","Robyn","Roch","Rochell","Rochella","Rochelle","Rochette","Roda","Rodi","Rodie","Rodina","Rois","Romola","Romona","Romonda","Romy","Rona","Ronalda","Ronda","Ronica","Ronna","Ronni","Ronnica","Ronnie","Ronny","Roobbie","Rora","Rori","Rorie","Rory","Ros","Rosa","Rosabel","Rosabella","Rosabelle","Rosaleen","Rosalia","Rosalie","Rosalind","Rosalinda","Rosalinde","Rosaline","Rosalyn","Rosalynd","Rosamond","Rosamund","Rosana","Rosanna","Rosanne","Rose","Roseann","Roseanna","Roseanne","Roselia","Roselin","Roseline","Rosella","Roselle","Rosemaria","Rosemarie","Rosemary","Rosemonde","Rosene","Rosetta","Rosette","Roshelle","Rosie","Rosina","Rosita","Roslyn","Rosmunda","Rosy","Row","Rowe","Rowena","Roxana","Roxane","Roxanna","Roxanne","Roxi","Roxie","Roxine","Roxy","Roz","Rozalie","Rozalin","Rozamond","Rozanna","Rozanne","Roze","Rozele","Rozella","Rozelle","Rozina","Rubetta","Rubi","Rubia","Rubie","Rubina","Ruby","Ruperta","Ruth","Ruthann","Ruthanne","Ruthe","Ruthi","Ruthie","Ruthy","Ryann","Rycca","Saba","Sabina","Sabine","Sabra","Sabrina","Sacha","Sada","Sadella","Sadie","Sadye","Saidee","Sal","Salaidh","Sallee","Salli","Sallie","Sally","Sallyann","Sallyanne","Saloma","Salome","Salomi","Sam","Samantha","Samara","Samaria","Sammy","Sande","Sandi","Sandie","Sandra","Sandy","Sandye","Sapphira","Sapphire","Sara","Sara-ann","Saraann","Sarah","Sarajane","Saree","Sarena","Sarene","Sarette","Sari","Sarina","Sarine","Sarita","Sascha","Sasha","Sashenka","Saudra","Saundra","Savina","Sayre","Scarlet","Scarlett","Sean","Seana","Seka","Sela","Selena","Selene","Selestina","Selia","Selie","Selina","Selinda","Seline","Sella","Selle","Selma","Sena","Sephira","Serena","Serene","Shae","Shaina","Shaine","Shalna","Shalne","Shana","Shanda","Shandee","Shandeigh","Shandie","Shandra","Shandy","Shane","Shani","Shanie","Shanna","Shannah","Shannen","Shannon","Shanon","Shanta","Shantee","Shara","Sharai","Shari","Sharia","Sharity","Sharl","Sharla","Sharleen","Sharlene","Sharline","Sharon","Sharona","Sharron","Sharyl","Shaun","Shauna","Shawn","Shawna","Shawnee","Shay","Shayla","Shaylah","Shaylyn","Shaylynn","Shayna","Shayne","Shea","Sheba","Sheela","Sheelagh","Sheelah","Sheena","Sheeree","Sheila","Sheila-kathryn","Sheilah","Shel","Shela","Shelagh","Shelba","Shelbi","Shelby","Shelia","Shell","Shelley","Shelli","Shellie","Shelly","Shena","Sher","Sheree","Sheri","Sherie","Sherill","Sherilyn","Sherline","Sherri","Sherrie","Sherry","Sherye","Sheryl","Shina","Shir","Shirl","Shirlee","Shirleen","Shirlene","Shirley","Shirline","Shoshana","Shoshanna","Siana","Sianna","Sib","Sibbie","Sibby","Sibeal","Sibel","Sibella","Sibelle","Sibilla","Sibley","Sibyl","Sibylla","Sibylle","Sidoney","Sidonia","Sidonnie","Sigrid","Sile","Sileas","Silva","Silvana","Silvia","Silvie","Simona","Simone","Simonette","Simonne","Sindee","Siobhan","Sioux","Siouxie","Sisely","Sisile","Sissie","Sissy","Siusan","Sofia","Sofie","Sondra","Sonia","Sonja","Sonni","Sonnie","Sonnnie","Sonny","Sonya","Sophey","Sophi","Sophia","Sophie","Sophronia","Sorcha","Sosanna","Stace","Stacee","Stacey","Staci","Stacia","Stacie","Stacy","Stafani","Star","Starla","Starlene","Starlin","Starr","Stefa","Stefania","Stefanie","Steffane","Steffi","Steffie","Stella","Stepha","Stephana","Stephani","Stephanie","Stephannie","Stephenie","Stephi","Stephie","Stephine","Stesha","Stevana","Stevena","Stoddard","Storm","Stormi","Stormie","Stormy","Sue","Suellen","Sukey","Suki","Sula","Sunny","Sunshine","Susan","Susana","Susanetta","Susann","Susanna","Susannah","Susanne","Susette","Susi","Susie","Susy","Suzann","Suzanna","Suzanne","Suzette","Suzi","Suzie","Suzy","Sybil","Sybila","Sybilla","Sybille","Sybyl","Sydel","Sydelle","Sydney","Sylvia","Tabatha","Tabbatha","Tabbi","Tabbie","Tabbitha","Tabby","Tabina","Tabitha","Taffy","Talia","Tallia","Tallie","Tallou","Tallulah","Tally","Talya","Talyah","Tamar","Tamara","Tamarah","Tamarra","Tamera","Tami","Tamiko","Tamma","Tammara","Tammi","Tammie","Tammy","Tamqrah","Tamra","Tana","Tandi","Tandie","Tandy","Tanhya","Tani","Tania","Tanitansy","Tansy","Tanya","Tara","Tarah","Tarra","Tarrah","Taryn","Tasha","Tasia","Tate","Tatiana","Tatiania","Tatum","Tawnya","Tawsha","Ted","Tedda","Teddi","Teddie","Teddy","Tedi","Tedra","Teena","Teirtza","Teodora","Tera","Teresa","Terese","Teresina","Teresita","Teressa","Teri","Teriann","Terra","Terri","Terrie","Terrijo","Terry","Terrye","Tersina","Terza","Tess","Tessa","Tessi","Tessie","Tessy","Thalia","Thea","Theadora","Theda","Thekla","Thelma","Theo","Theodora","Theodosia","Theresa","Therese","Theresina","Theresita","Theressa","Therine","Thia","Thomasa","Thomasin","Thomasina","Thomasine","Tiena","Tierney","Tiertza","Tiff","Tiffani","Tiffanie","Tiffany","Tiffi","Tiffie","Tiffy","Tilda","Tildi","Tildie","Tildy","Tillie","Tilly","Tim","Timi","Timmi","Timmie","Timmy","Timothea","Tina","Tine","Tiphani","Tiphanie","Tiphany","Tish","Tisha","Tobe","Tobey","Tobi","Toby","Tobye","Toinette","Toma","Tomasina","Tomasine","Tomi","Tommi","Tommie","Tommy","Toni","Tonia","Tonie","Tony","Tonya","Tonye","Tootsie","Torey","Tori","Torie","Torrie","Tory","Tova","Tove","Tracee","Tracey","Traci","Tracie","Tracy","Trenna","Tresa","Trescha","Tressa","Tricia","Trina","Trish","Trisha","Trista","Trix","Trixi","Trixie","Trixy","Truda","Trude","Trudey","Trudi","Trudie","Trudy","Trula","Tuesday","Twila","Twyla","Tybi","Tybie","Tyne","Ula","Ulla","Ulrica","Ulrika","Ulrikaumeko","Ulrike","Umeko","Una","Ursa","Ursala","Ursola","Ursula","Ursulina","Ursuline","Uta","Val","Valaree","Valaria","Vale","Valeda","Valencia","Valene","Valenka","Valentia","Valentina","Valentine","Valera","Valeria","Valerie","Valery","Valerye","Valida","Valina","Valli","Vallie","Vally","Valma","Valry","Van","Vanda","Vanessa","Vania","Vanna","Vanni","Vannie","Vanny","Vanya","Veda","Velma","Velvet","Venita","Venus","Vera","Veradis","Vere","Verena","Verene","Veriee","Verile","Verina","Verine","Verla","Verna","Vernice","Veronica","Veronika","Veronike","Veronique","Vevay","Vi","Vicki","Vickie","Vicky","Victoria","Vida","Viki","Vikki","Vikky","Vilhelmina","Vilma","Vin","Vina","Vinita","Vinni","Vinnie","Vinny","Viola","Violante","Viole","Violet","Violetta","Violette","Virgie","Virgina","Virginia","Virginie","Vita","Vitia","Vitoria","Vittoria","Viv","Viva","Vivi","Vivia","Vivian","Viviana","Vivianna","Vivianne","Vivie","Vivien","Viviene","Vivienne","Viviyan","Vivyan","Vivyanne","Vonni","Vonnie","Vonny","Vyky","Wallie","Wallis","Walliw","Wally","Waly","Wanda","Wandie","Wandis","Waneta","Wanids","Wenda","Wendeline","Wendi","Wendie","Wendy","Wendye","Wenona","Wenonah","Whitney","Wileen","Wilhelmina","Wilhelmine","Wilie","Willa","Willabella","Willamina","Willetta","Willette","Willi","Willie","Willow","Willy","Willyt","Wilma","Wilmette","Wilona","Wilone","Wilow","Windy","Wini","Winifred","Winna","Winnah","Winne","Winni","Winnie","Winnifred","Winny","Winona","Winonah","Wren","Wrennie","Wylma","Wynn","Wynne","Wynnie","Wynny","Xaviera","Xena","Xenia","Xylia","Xylina","Yalonda","Yasmeen","Yasmin","Yelena","Yetta","Yettie","Yetty","Yevette","Ynes","Ynez","Yoko","Yolanda","Yolande","Yolane","Yolanthe","Yoshi","Yoshiko","Yovonnda","Ysabel","Yvette","Yvonne","Zabrina","Zahara","Zandra","Zaneta","Zara","Zarah","Zaria","Zarla","Zea","Zelda","Zelma","Zena","Zenia","Zia","Zilvia","Zita","Zitella","Zoe","Zola","Zonda","Zondra","Zonnya","Zora","Zorah","Zorana","Zorina","Zorine","Zsazsa","Zulema","Zuzana"],lm={exports:{}};/** * @license diff --git a/examples/react-tldraw/index.html b/examples/react-tldraw/index.html index d9090bec6..9ef1a897c 100644 --- a/examples/react-tldraw/index.html +++ b/examples/react-tldraw/index.html @@ -4,7 +4,7 @@ react-tldraw - + diff --git a/examples/react-todomvc/assets/index-q-5ISMOx.js b/examples/react-todomvc/assets/index-B-Ld1ayL.js similarity index 99% rename from examples/react-todomvc/assets/index-q-5ISMOx.js rename to examples/react-todomvc/assets/index-B-Ld1ayL.js index c9d572ef6..51c783ce7 100644 --- a/examples/react-todomvc/assets/index-q-5ISMOx.js +++ b/examples/react-todomvc/assets/index-B-Ld1ayL.js @@ -58,7 +58,7 @@ Error generating stack: `+s.message+` * limitations under the License. * * SPDX-License-Identifier: Apache-2.0 - */var wt=null;try{wt=new WebAssembly.Instance(new WebAssembly.Module(new Uint8Array([0,97,115,109,1,0,0,0,1,13,2,96,0,1,127,96,4,127,127,127,127,1,127,3,7,6,0,1,1,1,1,1,6,6,1,127,1,65,0,11,7,50,6,3,109,117,108,0,1,5,100,105,118,95,115,0,2,5,100,105,118,95,117,0,3,5,114,101,109,95,115,0,4,5,114,101,109,95,117,0,5,8,103,101,116,95,104,105,103,104,0,0,10,191,1,6,4,0,35,0,11,36,1,1,126,32,0,173,32,1,173,66,32,134,132,32,2,173,32,3,173,66,32,134,132,126,34,4,66,32,135,167,36,0,32,4,167,11,36,1,1,126,32,0,173,32,1,173,66,32,134,132,32,2,173,32,3,173,66,32,134,132,127,34,4,66,32,135,167,36,0,32,4,167,11,36,1,1,126,32,0,173,32,1,173,66,32,134,132,32,2,173,32,3,173,66,32,134,132,128,34,4,66,32,135,167,36,0,32,4,167,11,36,1,1,126,32,0,173,32,1,173,66,32,134,132,32,2,173,32,3,173,66,32,134,132,129,34,4,66,32,135,167,36,0,32,4,167,11,36,1,1,126,32,0,173,32,1,173,66,32,134,132,32,2,173,32,3,173,66,32,134,132,130,34,4,66,32,135,167,36,0,32,4,167,11])),{}).exports}catch{}function q(n,e,t){this.low=n|0,this.high=e|0,this.unsigned=!!t}q.prototype.__isLong__;Object.defineProperty(q.prototype,"__isLong__",{value:!0});function Re(n){return(n&&n.__isLong__)===!0}function Yh(n){var e=Math.clz32(n&-n);return n?31-e:e}q.isLong=Re;var Qh={},Xh={};function Ci(n,e){var t,r,i;return e?(n>>>=0,(i=0<=n&&n<256)&&(r=Xh[n],r)?r:(t=W(n,0,!0),i&&(Xh[n]=t),t)):(n|=0,(i=-128<=n&&n<128)&&(r=Qh[n],r)?r:(t=W(n,n<0?-1:0,!1),i&&(Qh[n]=t),t))}q.fromInt=Ci;function St(n,e){if(isNaN(n))return e?hr:Ot;if(e){if(n<0)return hr;if(n>=ty)return iy}else{if(n<=-eg)return je;if(n+1>=eg)return ry}return n<0?St(-n,e).neg():W(n%ds|0,n/ds|0,e)}q.fromNumber=St;function W(n,e,t){return new q(n,e,t)}q.fromBits=W;var hl=Math.pow;function _f(n,e,t){if(n.length===0)throw Error("empty string");if(typeof e=="number"?(t=e,e=!1):e=!!e,n==="NaN"||n==="Infinity"||n==="+Infinity"||n==="-Infinity")return e?hr:Ot;if(t=t||10,t<2||360)throw Error("interior hyphen");if(r===0)return _f(n.substring(1),e,t).neg();for(var i=St(hl(t,8)),s=Ot,o=0;o>>0:this.low};C.toNumber=function(){return this.unsigned?(this.high>>>0)*ds+(this.low>>>0):this.high*ds+(this.low>>>0)};C.toString=function(e){if(e=e||10,e<2||36>>0,d=c.toString(e);if(o=l,o.isZero())return d+a;for(;d.length<6;)d="0"+d;a=""+d+a}};C.getHighBits=function(){return this.high};C.getHighBitsUnsigned=function(){return this.high>>>0};C.getLowBits=function(){return this.low};C.getLowBitsUnsigned=function(){return this.low>>>0};C.getNumBitsAbs=function(){if(this.isNegative())return this.eq(je)?64:this.neg().getNumBitsAbs();for(var e=this.high!=0?this.high:this.low,t=31;t>0&&!(e&1<=0};C.isOdd=function(){return(this.low&1)===1};C.isEven=function(){return(this.low&1)===0};C.equals=function(e){return Re(e)||(e=$t(e)),this.unsigned!==e.unsigned&&this.high>>>31===1&&e.high>>>31===1?!1:this.high===e.high&&this.low===e.low};C.eq=C.equals;C.notEquals=function(e){return!this.eq(e)};C.neq=C.notEquals;C.ne=C.notEquals;C.lessThan=function(e){return this.comp(e)<0};C.lt=C.lessThan;C.lessThanOrEqual=function(e){return this.comp(e)<=0};C.lte=C.lessThanOrEqual;C.le=C.lessThanOrEqual;C.greaterThan=function(e){return this.comp(e)>0};C.gt=C.greaterThan;C.greaterThanOrEqual=function(e){return this.comp(e)>=0};C.gte=C.greaterThanOrEqual;C.ge=C.greaterThanOrEqual;C.compare=function(e){if(Re(e)||(e=$t(e)),this.eq(e))return 0;var t=this.isNegative(),r=e.isNegative();return t&&!r?-1:!t&&r?1:this.unsigned?e.high>>>0>this.high>>>0||e.high===this.high&&e.low>>>0>this.low>>>0?-1:1:this.sub(e).isNegative()?-1:1};C.comp=C.compare;C.negate=function(){return!this.unsigned&&this.eq(je)?je:this.not().add(qi)};C.neg=C.negate;C.add=function(e){Re(e)||(e=$t(e));var t=this.high>>>16,r=this.high&65535,i=this.low>>>16,s=this.low&65535,o=e.high>>>16,a=e.high&65535,l=e.low>>>16,c=e.low&65535,d=0,h=0,p=0,m=0;return m+=s+c,p+=m>>>16,m&=65535,p+=i+l,h+=p>>>16,p&=65535,h+=r+a,d+=h>>>16,h&=65535,d+=t+o,d&=65535,W(p<<16|m,d<<16|h,this.unsigned)};C.subtract=function(e){return Re(e)||(e=$t(e)),this.add(e.neg())};C.sub=C.subtract;C.multiply=function(e){if(this.isZero())return this;if(Re(e)||(e=$t(e)),wt){var t=wt.mul(this.low,this.high,e.low,e.high);return W(t,wt.get_high(),this.unsigned)}if(e.isZero())return this.unsigned?hr:Ot;if(this.eq(je))return e.isOdd()?je:Ot;if(e.eq(je))return this.isOdd()?je:Ot;if(this.isNegative())return e.isNegative()?this.neg().mul(e.neg()):this.neg().mul(e).neg();if(e.isNegative())return this.mul(e.neg()).neg();if(this.lt(tg)&&e.lt(tg))return St(this.toNumber()*e.toNumber(),this.unsigned);var r=this.high>>>16,i=this.high&65535,s=this.low>>>16,o=this.low&65535,a=e.high>>>16,l=e.high&65535,c=e.low>>>16,d=e.low&65535,h=0,p=0,m=0,w=0;return w+=o*d,m+=w>>>16,w&=65535,m+=s*d,p+=m>>>16,m&=65535,m+=o*c,p+=m>>>16,m&=65535,p+=i*d,h+=p>>>16,p&=65535,p+=s*c,h+=p>>>16,p&=65535,p+=o*l,h+=p>>>16,p&=65535,h+=r*d+i*c+s*l+o*a,h&=65535,W(m<<16|w,h<<16|p,this.unsigned)};C.mul=C.multiply;C.divide=function(e){if(Re(e)||(e=$t(e)),e.isZero())throw Error("division by zero");if(wt){if(!this.unsigned&&this.high===-2147483648&&e.low===-1&&e.high===-1)return this;var t=(this.unsigned?wt.div_u:wt.div_s)(this.low,this.high,e.low,e.high);return W(t,wt.get_high(),this.unsigned)}if(this.isZero())return this.unsigned?hr:Ot;var r,i,s;if(this.unsigned){if(e.unsigned||(e=e.toUnsigned()),e.gt(this))return hr;if(e.gt(this.shru(1)))return ny;s=hr}else{if(this.eq(je)){if(e.eq(qi)||e.eq(jc))return je;if(e.eq(je))return qi;var o=this.shr(1);return r=o.div(e).shl(1),r.eq(Ot)?e.isNegative()?qi:jc:(i=this.sub(e.mul(r)),s=r.add(i.div(e)),s)}else if(e.eq(je))return this.unsigned?hr:Ot;if(this.isNegative())return e.isNegative()?this.neg().div(e.neg()):this.neg().div(e).neg();if(e.isNegative())return this.div(e.neg()).neg();s=Ot}for(i=this;i.gte(e);){r=Math.max(1,Math.floor(i.toNumber()/e.toNumber()));for(var a=Math.ceil(Math.log(r)/Math.LN2),l=a<=48?1:hl(2,a-48),c=St(r),d=c.mul(e);d.isNegative()||d.gt(i);)r-=l,c=St(r,this.unsigned),d=c.mul(e);c.isZero()&&(c=qi),s=s.add(c),i=i.sub(d)}return s};C.div=C.divide;C.modulo=function(e){if(Re(e)||(e=$t(e)),wt){var t=(this.unsigned?wt.rem_u:wt.rem_s)(this.low,this.high,e.low,e.high);return W(t,wt.get_high(),this.unsigned)}return this.sub(this.div(e).mul(e))};C.mod=C.modulo;C.rem=C.modulo;C.not=function(){return W(~this.low,~this.high,this.unsigned)};C.countLeadingZeros=function(){return this.high?Math.clz32(this.high):Math.clz32(this.low)+32};C.clz=C.countLeadingZeros;C.countTrailingZeros=function(){return this.low?Yh(this.low):Yh(this.high)+32};C.ctz=C.countTrailingZeros;C.and=function(e){return Re(e)||(e=$t(e)),W(this.low&e.low,this.high&e.high,this.unsigned)};C.or=function(e){return Re(e)||(e=$t(e)),W(this.low|e.low,this.high|e.high,this.unsigned)};C.xor=function(e){return Re(e)||(e=$t(e)),W(this.low^e.low,this.high^e.high,this.unsigned)};C.shiftLeft=function(e){return Re(e)&&(e=e.toInt()),(e&=63)===0?this:e<32?W(this.low<>>32-e,this.unsigned):W(0,this.low<>>e|this.high<<32-e,this.high>>e,this.unsigned):W(this.high>>e-32,this.high>=0?0:-1,this.unsigned)};C.shr=C.shiftRight;C.shiftRightUnsigned=function(e){return Re(e)&&(e=e.toInt()),(e&=63)===0?this:e<32?W(this.low>>>e|this.high<<32-e,this.high>>>e,this.unsigned):e===32?W(this.high,0,this.unsigned):W(this.high>>>e-32,0,this.unsigned)};C.shru=C.shiftRightUnsigned;C.shr_u=C.shiftRightUnsigned;C.rotateLeft=function(e){var t;return Re(e)&&(e=e.toInt()),(e&=63)===0?this:e===32?W(this.high,this.low,this.unsigned):e<32?(t=32-e,W(this.low<>>t,this.high<>>t,this.unsigned)):(e-=32,t=32-e,W(this.high<>>t,this.low<>>t,this.unsigned))};C.rotl=C.rotateLeft;C.rotateRight=function(e){var t;return Re(e)&&(e=e.toInt()),(e&=63)===0?this:e===32?W(this.high,this.low,this.unsigned):e<32?(t=32-e,W(this.high<>>e,this.low<>>e,this.unsigned)):(e-=32,t=32-e,W(this.low<>>e,this.high<>>e,this.unsigned))};C.rotr=C.rotateRight;C.toSigned=function(){return this.unsigned?W(this.low,this.high,!1):this};C.toUnsigned=function(){return this.unsigned?this:W(this.low,this.high,!0)};C.toBytes=function(e){return e?this.toBytesLE():this.toBytesBE()};C.toBytesLE=function(){var e=this.high,t=this.low;return[t&255,t>>>8&255,t>>>16&255,t>>>24,e&255,e>>>8&255,e>>>16&255,e>>>24]};C.toBytesBE=function(){var e=this.high,t=this.low;return[e>>>24,e>>>16&255,e>>>8&255,e&255,t>>>24,t>>>16&255,t>>>8&255,t&255]};q.fromBytes=function(e,t,r){return r?q.fromBytesLE(e,t):q.fromBytesBE(e,t)};q.fromBytesLE=function(e,t){return new q(e[0]|e[1]<<8|e[2]<<16|e[3]<<24,e[4]|e[5]<<8|e[6]<<16|e[7]<<24,t)};q.fromBytesBE=function(e,t){return new q(e[4]<<24|e[5]<<16|e[6]<<8|e[7],e[0]<<24|e[1]<<16|e[2]<<8|e[3],t)};var ve=(n=>(n[n.Null=0]="Null",n[n.Boolean=1]="Boolean",n[n.Integer=2]="Integer",n[n.Long=3]="Long",n[n.Double=4]="Double",n[n.String=5]="String",n[n.Bytes=6]="Bytes",n[n.Date=7]="Date",n))(ve||{});class ie extends No{constructor(t,r){super(r);u(this,"valueType");u(this,"value");this.valueType=ie.getPrimitiveType(t),this.value=t===void 0?null:t}static of(t,r){return new ie(t,r)}static valueFromBytes(t,r){switch(t){case 0:return null;case 1:return!!r[0];case 2:return r[0]|r[1]<<8|r[2]<<16|r[3]<<24;case 4:{const i=new DataView(r.buffer);return r.forEach(function(s,o){i.setUint8(o,s)}),i.getFloat64(0,!0)}case 5:return new TextDecoder("utf-8").decode(r);case 3:return q.fromBytesLE(Array.from(r));case 6:return r;case 7:return new Date(q.fromBytesLE(Array.from(r),!0).toNumber());default:throw new k(S.ErrUnimplemented,`unimplemented type: ${t}`)}}toJSON(){return this.valueType===5?`"${en(this.value)}"`:`${this.value}`}toSortedJSON(){return this.toJSON()}toJSForTest(){return{createdAt:this.getCreatedAt().toTestString(),value:this.value,type:"YORKIE_PRIMITIVE"}}deepcopy(){const t=ie.of(this.value,this.getCreatedAt());return t.setMovedAt(this.getMovedAt()),t.setRemovedAt(this.getRemovedAt()),t}getType(){return this.valueType}static getPrimitiveType(t){switch(typeof t){case"undefined":return 0;case"boolean":return 1;case"number":return this.isInteger(t)?2:4;case"string":return 5;case"object":if(t===null)return 0;if(t instanceof q)return 3;if(t instanceof Uint8Array)return 6;if(t instanceof Date)return 7}}static isSupport(t){return ie.getPrimitiveType(t)!==void 0}static isInteger(t){return t%1===0}isNumericType(){const t=this.valueType;return t===2||t===3||t===4}getValue(){return this.value}toBytes(){switch(this.valueType){case 0:return new Uint8Array;case 1:return this.value?new Uint8Array([1]):new Uint8Array([0]);case 2:{const t=this.value;return new Uint8Array([t&255,t>>8&255,t>>16&255,t>>24&255])}case 4:{const t=this.value,r=new Uint8Array(8);return new DataView(r.buffer).setFloat64(0,t,!0),r}case 5:return new TextEncoder().encode(this.value);case 3:{const r=this.value.toBytesLE();return Uint8Array.from(r)}case 6:return this.value;case 7:{const t=this.value,r=q.fromNumber(t.getTime(),!0).toBytesLE();return Uint8Array.from(r)}default:throw new k(S.ErrUnimplemented,`unimplemented type: ${this.valueType}`)}}}class gl extends ey{constructor(t){super(t);u(this,"prev");u(this,"next");this.value=t}static createAfter(t,r){const i=new gl(r),s=t.next;return t.next=i,i.prev=t,i.next=s,s&&(s.prev=i),i}remove(t){return this.value.remove(t)}getCreatedAt(){return this.value.getCreatedAt()}getPositionedAt(){return this.value.getPositionedAt()}release(){this.prev&&(this.prev.next=this.next),this.next&&(this.next.prev=this.prev),this.prev=void 0,this.next=void 0}getLength(){return this.value.isRemoved()?0:1}getPrev(){return this.prev}getNext(){return this.next}getValue(){return this.value}isRemoved(){return this.value.isRemoved()}}class wo{constructor(){u(this,"dummyHead");u(this,"last");u(this,"nodeMapByIndex");u(this,"nodeMapByCreatedAt");const e=ie.of(0,bt);e.setRemovedAt(bt),this.dummyHead=new gl(e),this.last=this.dummyHead,this.nodeMapByIndex=new vo,this.nodeMapByCreatedAt=new Map,this.nodeMapByIndex.insert(this.dummyHead),this.nodeMapByCreatedAt.set(this.dummyHead.getCreatedAt().toIDString(),this.dummyHead)}static create(){return new wo}get length(){return this.nodeMapByIndex.length}findNextBeforeExecutedAt(e,t){let r=this.nodeMapByCreatedAt.get(e.toIDString());if(!r)throw new k(S.ErrInvalidArgument,`cant find the given node: ${e.toIDString()}`);for(;r.getNext()&&r.getNext().getPositionedAt().after(t);)r=r.getNext();return r}release(e){this.last===e&&(this.last=e.getPrev()),e.release(),this.nodeMapByIndex.delete(e),this.nodeMapByCreatedAt.delete(e.getValue().getCreatedAt().toIDString())}insertAfter(e,t,r=t.getCreatedAt()){const i=this.findNextBeforeExecutedAt(e,r),s=gl.createAfter(i,t);i===this.last&&(this.last=s),this.nodeMapByIndex.insertAfter(i,s),this.nodeMapByCreatedAt.set(s.getCreatedAt().toIDString(),s)}moveAfter(e,t,r){const i=this.nodeMapByCreatedAt.get(e.toIDString());if(!i)throw new k(S.ErrInvalidArgument,`cant find the given node: ${e.toIDString()}`);const s=this.nodeMapByCreatedAt.get(t.toIDString());if(!s)throw new k(S.ErrInvalidArgument,`cant find the given node: ${t.toIDString()}`);i!==s&&(!s.getValue().getMovedAt()||r.after(s.getValue().getMovedAt()))&&(this.release(s),this.insertAfter(i.getCreatedAt(),s.getValue(),r),s.getValue().setMovedAt(r))}insert(e){this.insertAfter(this.last.getCreatedAt(),e)}getByID(e){return this.nodeMapByCreatedAt.get(e.toIDString())}subPathOf(e){const t=this.nodeMapByCreatedAt.get(e.toIDString());if(t)return String(this.nodeMapByIndex.indexOf(t))}purge(e){const t=this.nodeMapByCreatedAt.get(e.getCreatedAt().toIDString());if(!t)throw new k(S.ErrInvalidArgument,`fail to find the given createdAt: ${e.getCreatedAt().toIDString()}`);this.release(t)}getByIndex(e){if(e>=this.length)return;const[t,r]=this.nodeMapByIndex.find(e);let i=t;if(e===0&&t===this.dummyHead||r>0)do i&&(i=i.getNext());while(i&&i.isRemoved());return i}getPrevCreatedAt(e){let t=this.nodeMapByCreatedAt.get(e.toIDString());do t=t.getPrev();while(this.dummyHead!==t&&t.isRemoved());return t.getValue().getCreatedAt()}delete(e,t){const r=this.nodeMapByCreatedAt.get(e.toIDString()),i=r.isRemoved();return r.remove(t)&&!i&&this.nodeMapByIndex.splayNode(r),r.getValue()}deleteByIndex(e,t){const r=this.getByIndex(e);if(r)return r.remove(t)&&this.nodeMapByIndex.splayNode(r),r.getValue()}getHead(){return this.dummyHead.getValue()}getLast(){return this.last.getValue()}getLastCreatedAt(){return this.last.getCreatedAt()}toTestString(){const e=[];for(const t of this){const r=`${t.getCreatedAt().toIDString()}:${t.getValue().toJSON()}`;t.isRemoved()?e.push(`{${r}}`):e.push(`[${r}]`)}return e.join("")}*[Symbol.iterator](){let e=this.dummyHead.getNext();for(;e;)yield e,e=e.getNext()}}class tt extends Wr{constructor(t,r){super(t);u(this,"elements");this.elements=r}static create(t,r){if(!r)return new tt(t,wo.create());const i=wo.create();for(const s of r)i.insertAfter(i.getLastCreatedAt(),s.deepcopy());return new tt(t,i)}subPathOf(t){return this.elements.subPathOf(t)}purge(t){this.elements.purge(t)}insertAfter(t,r){this.elements.insertAfter(t,r)}moveAfter(t,r,i){this.elements.moveAfter(t,r,i)}get(t){const r=this.elements.getByIndex(t);return r==null?void 0:r.getValue()}getByID(t){const r=this.elements.getByID(t);return r==null?void 0:r.getValue()}getHead(){return this.elements.getHead()}getLast(){return this.elements.getLast()}getPrevCreatedAt(t){return this.elements.getPrevCreatedAt(t)}delete(t,r){return this.elements.delete(t,r)}deleteByIndex(t,r){return this.elements.deleteByIndex(t,r)}getLastCreatedAt(){return this.elements.getLastCreatedAt()}get length(){return this.elements.length}*[Symbol.iterator](){for(const t of this.elements)t.isRemoved()||(yield t.getValue())}toTestString(){return this.elements.toTestString()}getDescendants(t){for(const r of this.elements){const i=r.getValue();if(t(i,this))return;i instanceof Wr&&i.getDescendants(t)}}toJSON(){const t=[];for(const r of this)t.push(r.toJSON());return`[${t.join(",")}]`}toJS(){return JSON.parse(this.toJSON())}toJSForTest(){const t={};for(let r=0;r({...m,value:m.value?{attributes:Xi(m.value.getAttributes()),content:m.value.getContent()}:{attributes:void 0,content:""},type:"content"}));return[c,p,d,[l,l]]}setStyle(t,r,i,s){const[,o]=this.rgaTreeSplit.findNodeWithSplit(t[1],i),[,a]=this.rgaTreeSplit.findNodeWithSplit(t[0],i),l=[],c=this.rgaTreeSplit.findBetween(a,o),d=new Map,h=[];for(const m of c){const w=m.getCreatedAt().getActorID(),I=s!=null&&s.size?s.has(w)?s.get(w):bt:Ws;if(m.canStyle(i,I)){const O=d.get(w),y=m.getCreatedAt();(!O||y.after(O))&&d.set(w,y),h.push(m)}}const p=[];for(const m of h){if(m.isRemoved())continue;const[w,I]=this.rgaTreeSplit.findIndexesFromRange(m.createPosRange());l.push({type:"style",actor:i.getActorID(),from:w,to:I,value:{attributes:Xi(r)}});for(const[O,y]of Object.entries(r)){const[g]=m.getValue().setAttr(O,y,i);g!==void 0&&p.push({parent:m.getValue(),child:g})}}return[d,p,l]}indexRangeToPosRange(t,r){const i=this.rgaTreeSplit.indexToPos(t);return t===r?[i,i]:[i,this.rgaTreeSplit.indexToPos(r)]}get length(){return this.rgaTreeSplit.length}getTreeByIndex(){return this.rgaTreeSplit.getTreeByIndex()}getTreeByID(){return this.rgaTreeSplit.getTreeByID()}toJSON(){const t=[];for(const r of this.rgaTreeSplit)r.isRemoved()||t.push(r.getValue().toJSON());return`[${t.join(",")}]`}toSortedJSON(){return this.toJSON()}toJSForTest(){return{createdAt:this.getCreatedAt().toTestString(),value:JSON.parse(this.toJSON()),type:"YORKIE_TEXT"}}toString(){return this.rgaTreeSplit.toString()}values(){const t=[];for(const r of this.rgaTreeSplit)if(!r.isRemoved()){const i=r.getValue();t.push({attributes:Xi(i.getAttributes()),content:i.getContent()})}return t}getRGATreeSplit(){return this.rgaTreeSplit}toTestString(){return this.rgaTreeSplit.toTestString()}deepcopy(){const t=new It(this.rgaTreeSplit.deepcopy(),this.getCreatedAt());return t.remove(this.getRemovedAt()),t}findIndexesFromRange(t){return this.rgaTreeSplit.findIndexesFromRange(t)}getGCPairs(){const t=[];for(const r of this.rgaTreeSplit){r.getRemovedAt()&&t.push({parent:this.rgaTreeSplit,child:r});for(const i of r.getValue().getGCPairs())t.push(i)}return t}}class Do extends Jt{constructor(t,r,i,s,o,a,l){super(t,l);u(this,"fromPos");u(this,"toPos");u(this,"maxCreatedAtMapByActor");u(this,"content");u(this,"attributes");this.fromPos=r,this.toPos=i,this.maxCreatedAtMapByActor=s,this.content=o,this.attributes=a}static create(t,r,i,s,o,a,l){return new Do(t,r,i,s,o,a,l)}execute(t){const r=t.findByCreatedAt(this.getParentCreatedAt());if(!r)throw new k(S.ErrInvalidArgument,`fail to find ${this.getParentCreatedAt()}`);if(!(r instanceof It))throw new k(S.ErrInvalidArgument,"fail to execute, only Text can execute edit");const i=r,[,s,o]=i.edit([this.fromPos,this.toPos],this.content,this.getExecutedAt(),Object.fromEntries(this.attributes),this.maxCreatedAtMapByActor);for(const a of o)t.registerGCPair(a);return{opInfos:s.map(({from:a,to:l,value:c})=>({type:"edit",from:a,to:l,value:c,path:t.createPath(this.getParentCreatedAt())}))}}getEffectedCreatedAt(){return this.getParentCreatedAt()}toTestString(){const t=this.getParentCreatedAt().toTestString(),r=this.fromPos.toTestString(),i=this.toPos.toTestString(),s=this.content;return`${t}.EDIT(${r},${i},${s})`}getFromPos(){return this.fromPos}getToPos(){return this.toPos}getContent(){return this.content}getAttributes(){return this.attributes||new Map}getMaxCreatedAtMapByActor(){return this.maxCreatedAtMapByActor}}class Oo extends Jt{constructor(t,r,i,s,o,a){super(t,a);u(this,"fromPos");u(this,"toPos");u(this,"maxCreatedAtMapByActor");u(this,"attributes");this.fromPos=r,this.toPos=i,this.maxCreatedAtMapByActor=s,this.attributes=o}static create(t,r,i,s,o,a){return new Oo(t,r,i,s,o,a)}execute(t){const r=t.findByCreatedAt(this.getParentCreatedAt());if(!r)throw new k(S.ErrInvalidArgument,`fail to find ${this.getParentCreatedAt()}`);if(!(r instanceof It))throw new k(S.ErrInvalidArgument,"fail to execute, only Text can execute edit");const i=r,[,s,o]=i.setStyle([this.fromPos,this.toPos],this.attributes?Object.fromEntries(this.attributes):{},this.getExecutedAt(),this.maxCreatedAtMapByActor);for(const a of s)t.registerGCPair(a);return{opInfos:o.map(({from:a,to:l,value:c})=>({type:"style",from:a,to:l,value:c,path:t.createPath(this.getParentCreatedAt())}))}}getEffectedCreatedAt(){return this.getParentCreatedAt()}toTestString(){const t=this.getParentCreatedAt().toTestString(),r=this.fromPos.toTestString(),i=this.toPos.toTestString(),s=this.attributes;return`${t}.STYL(${r},${i},${JSON.stringify(s)})`}getFromPos(){return this.fromPos}getToPos(){return this.toPos}getAttributes(){return this.attributes}getMaxCreatedAtMapByActor(){return this.maxCreatedAtMapByActor}}const z1=2,U1="root",mr="text";function Ds(n,e){let t=0;const r=n.children;for(let i=0;i0)throw new k(S.ErrRefused,"Text node cannot have children")}updateAncestorsSize(){let e=this.parent;const t=this.isRemoved?-1:1;for(;e&&(e.size+=this.paddedSize*t,!e.isRemoved);)e=e.parent}updateDescendantsSize(){let e=0;for(const t of this._children){const r=t.updateDescendantsSize();t.isRemoved||(e+=r)}return this.size+=e,this.paddedSize}get isText(){return this.type===mr}get paddedSize(){return this.size+(this.isText?0:z1)}isAncestorOf(e){return V1(this,e)}get nextSibling(){const e=this.parent.findOffset(this),t=this.parent.children[e+1];if(t)return t}get prevSibling(){const e=this.parent.findOffset(this),t=this.parent.children[e-1];if(t)return t}splitText(e,t){if(e===0||e===this.size)return;const r=this.value.slice(0,e),i=this.value.slice(e);if(!i.length)return;this.value=r;const s=this.cloneText(e+t);return s.value=i,this.parent.insertAfterInternal(s,this),s}get children(){return this._children.filter(e=>!e.isRemoved)}get allChildren(){return[...this._children]}hasTextChild(){return this.children.length>0&&this.children.every(e=>e.isText)}append(...e){if(this.isText)throw new k(S.ErrRefused,"Text node cannot have children");this._children.push(...e);for(const t of e)t.parent=this,t.updateAncestorsSize()}prepend(...e){if(this.isText)throw new k(S.ErrRefused,"Text node cannot have children");this._children.unshift(...e);for(const t of e)t.parent=this}insertBefore(e,t){if(this.isText)throw new k(S.ErrRefused,"Text node cannot have children");const r=this._children.indexOf(t);if(r===-1)throw new k(S.ErrInvalidArgument,"child not found");this.insertAtInternal(e,r),e.updateAncestorsSize()}insertAfter(e,t){if(this.isText)throw new k(S.ErrRefused,"Text node cannot have children");const r=this._children.indexOf(t);if(r===-1)throw new k(S.ErrInvalidArgument,"child not found");this.insertAtInternal(e,r+1),e.updateAncestorsSize()}insertAt(e,t){if(this.isText)throw new k(S.ErrRefused,"Text node cannot have children");this.insertAtInternal(e,t),e.updateAncestorsSize()}removeChild(e){if(this.isText)throw new k(S.ErrRefused,"Text node cannot have children");const t=this._children.indexOf(e);if(t===-1)throw new k(S.ErrInvalidArgument,"child not found");this._children.splice(t,1),e.parent=void 0}splitElement(e,t){const r=this.cloneElement(t);this.parent.insertAfterInternal(r,this),r.updateAncestorsSize();const i=this.children.slice(0,e),s=this.children.slice(e);this._children=i,r._children=s,this.size=this._children.reduce((o,a)=>o+a.paddedSize,0),r.size=r._children.reduce((o,a)=>o+a.paddedSize,0);for(const o of r._children)o.parent=r;return r}insertAfterInternal(e,t){if(this.isText)throw new k(S.ErrRefused,"Text node cannot have children");const r=this._children.indexOf(t);if(r===-1)throw new k(S.ErrInvalidArgument,"child not found");this.insertAtInternal(e,r+1)}insertAtInternal(e,t){if(this.isText)throw new k(S.ErrRefused,"Text node cannot have children");this._children.splice(t,0,e),e.parent=this}findOffset(e){if(this.isText)throw new k(S.ErrRefused,"Text node cannot have children");if(e.isRemoved){const t=this._children.indexOf(e);return this.allChildren.splice(0,t).filter(i=>!i.isRemoved).length}return this.children.indexOf(e)}findBranchOffset(e){if(this.isText)throw new k(S.ErrRefused,"Text node cannot have children");let t=e;for(;t;){const r=this._children.indexOf(t);if(r!==-1)return r;t=t.parent}return-1}}function V1(n,e){if(n===e)return!1;for(;e.parent;){if(e.parent===n)return!0;e=e.parent}return!1}var ge=(n=>(n.Start="Start",n.End="End",n.Text="Text",n))(ge||{});function sy(n,e,t,r){if(e>t)throw new k(S.ErrInvalidArgument,`from is greater than to: ${e} > ${t}`);if(e>n.size)throw new k(S.ErrInvalidArgument,`from is out of range: ${e} > ${n.size}`);if(t>n.size)throw new k(S.ErrInvalidArgument,`to is out of range: ${t} > ${n.size}`);if(e===t)return;let i=0;for(const s of n.children){if(e-s.paddedSizes.size;(s.isText||l)&&r([s,s.isText?"Text":"Start"],c),sy(s,Math.max(0,o),Math.min(a,s.size),r),c&&r([s,"End"],c)}i+=s.paddedSize}}function oy(n,e,t=0){for(const r of n.children)oy(r,e,t+1);e(n,t)}function Fl(n,e,t=0){for(const r of n._children)Fl(r,e,t+1);e(n,t)}function Vc(n,e,t=!0){if(e>n.size)throw new k(S.ErrInvalidArgument,`index is out of range: ${e} > ${n.size}`);if(n.isText)return{node:n,offset:e};let r=0,i=0;for(const s of n.children){if(t&&s.isText&&s.size>=e-i)return Vc(s,e-i,t);if(e===i)return{node:n,offset:r};if(!t&&s.paddedSize===e-i)return{node:n,offset:r+1};if(s.paddedSize>e-i)return Vc(s,e-i-1,t);i+=s.paddedSize,r+=1}return{node:n,offset:r}}function ay(n){return n.isText||n.children.length===0?n:ay(n.children[0])}function q1(n,e){if(n.sizen===e?0:n0)if(t.right)t.right.parent=t,t=t.right;else return t;else if(r<0)if(t.left)t.left.parent=t,t=t.left;else{let i=t.parent,s=t;for(;i&&s===i.left;)s=i,i=i.parent;return i}else return t}}lastEntry(){if(!this.root)return this.root;let e=this.root;for(;e.right;)e=e.right;return e}size(){return this.counter}isEmpty(){return this.counter===0}getInternal(e,t){for(;t;){const r=this.comparator(e,t.key);if(r===0)return t;r<0?t=t.left:r>0&&(t=t.right)}}putInternal(e,t,r){if(!r)return this.counter+=1,new H1(e,t,!0);const i=this.comparator(e,r.key);return i<0?r.left=this.putInternal(e,t,r.left):i>0?r.right=this.putInternal(e,t,r.right):r.value=t,this.isRed(r.right)&&!this.isRed(r.left)&&(r=this.rotateLeft(r)),this.isRed(r.left)&&this.isRed(r.left.left)&&(r=this.rotateRight(r)),this.isRed(r.left)&&this.isRed(r.right)&&this.flipColors(r),r}removeInternal(e,t){if(this.comparator(t,e.key)<0)!this.isRed(e.left)&&!this.isRed(e.left.left)&&(e=this.moveRedLeft(e)),e.left=this.removeInternal(e.left,t);else{if(this.isRed(e.left)&&(e=this.rotateRight(e)),this.comparator(t,e.key)===0&&!e.right){this.counter-=1;return}if(!this.isRed(e.right)&&!this.isRed(e.right.left)&&(e=this.moveRedRight(e)),this.comparator(t,e.key)===0){this.counter-=1;const r=this.min(e.right);e.value=r.value,e.key=r.key,e.right=this.removeMin(e.right)}else e.right=this.removeInternal(e.right,t)}return this.fixUp(e)}min(e){return e.left?this.min(e.left):e}removeMin(e){if(e.left)return!this.isRed(e.left)&&!this.isRed(e.left.left)&&(e=this.moveRedLeft(e)),e.left=this.removeMin(e.left),this.fixUp(e)}fixUp(e){return this.isRed(e.right)&&(e=this.rotateLeft(e)),this.isRed(e.left)&&this.isRed(e.left.left)&&(e=this.rotateRight(e)),this.isRed(e.left)&&this.isRed(e.right)&&this.flipColors(e),e}moveRedLeft(e){return this.flipColors(e),this.isRed(e.right.left)&&(e.right=this.rotateRight(e.right),e=this.rotateLeft(e),this.flipColors(e)),e}moveRedRight(e){return this.flipColors(e),this.isRed(e.left.left)&&(e=this.rotateRight(e),this.flipColors(e)),e}isRed(e){return e&&e.isRed}rotateLeft(e){const t=e.right;return e.right=t.left,t.left=e,t.isRed=t.left.isRed,t.left.isRed=!0,t}rotateRight(e){const t=e.left;return e.left=t.right,t.right=e,t.isRed=t.right.isRed,t.right.isRed=!0,t}flipColors(e){e.isRed=!e.isRed,e.left.isRed=!e.left.isRed,e.right.isRed=!e.right.isRed}}class Rt{constructor(e,t){u(this,"parentID");u(this,"leftSiblingID");this.parentID=e,this.leftSiblingID=t}static of(e,t){return new Rt(e,t)}static fromTreePos(e){const{offset:t}=e;let{node:r}=e,i;return r.isText?(r.parent.children[0]===r&&t===0?i=r.parent:i=r,r=r.parent):t===0?i=r:i=r.children[t-1],Rt.of(r.id,Ee.of(i.getCreatedAt(),i.getOffset()+t))}getParentID(){return this.parentID}static fromStruct(e){return Rt.of(Ee.of(et.fromStruct(e.parentID.createdAt),e.parentID.offset),Ee.of(et.fromStruct(e.leftSiblingID.createdAt),e.leftSiblingID.offset))}toStruct(){return{parentID:{createdAt:this.getParentID().getCreatedAt().toStruct(),offset:this.getParentID().getOffset()},leftSiblingID:{createdAt:this.getLeftSiblingID().getCreatedAt().toStruct(),offset:this.getLeftSiblingID().getOffset()}}}toTreeNodePair(e){const t=this.getParentID(),r=this.getLeftSiblingID(),i=e.findFloorNode(t);let s=e.findFloorNode(r);if(!i||!s)throw new k(S.ErrRefused,`cannot find node of CRDTTreePos(${t.toTestString()}, ${r.toTestString()})`);return!r.equals(t)&&r.getOffset()>0&&r.getOffset()===s.id.getOffset()&&s.insPrevID&&(s=e.findFloorNode(s.insPrevID)),[i,s]}getLeftSiblingID(){return this.leftSiblingID}equals(e){return this.getParentID().getCreatedAt().equals(e.getParentID().getCreatedAt())&&this.getParentID().getOffset()===e.getParentID().getOffset()&&this.getLeftSiblingID().getCreatedAt().equals(e.getLeftSiblingID().getCreatedAt())&&this.getLeftSiblingID().getOffset()===e.getLeftSiblingID().getOffset()}}class Ee{constructor(e,t){u(this,"createdAt");u(this,"offset");this.createdAt=e,this.offset=t}static of(e,t){return new Ee(e,t)}static fromStruct(e){return Ee.of(et.fromStruct(e.createdAt),e.offset)}static createComparator(){return(e,t)=>{const r=e.getCreatedAt().compare(t.getCreatedAt());return r!==0?r:e.getOffset()>t.getOffset()?1:e.getOffset(){const s=i.deepcopy();return s.parent=t,s}),t.insPrevID=this.insPrevID,t.insNextID=this.insNextID,t}get value(){if(!this.isText)throw new k(S.ErrInvalidType,`cannot get value of element node: ${this.type}`);return this._value}set value(t){if(!this.isText)throw new k(S.ErrInvalidType,`cannot set value of element node: ${this.type}`);this._value=t,this.size=t.length}get isRemoved(){return!!this.removedAt}remove(t){const r=!this.removedAt;(!this.removedAt||this.removedAt.compare(t)>0)&&(this.removedAt=t),r&&this.updateAncestorsSize()}cloneText(t){return new Xe(Ee.of(this.id.getCreatedAt(),t),this.type,void 0,void 0,this.removedAt)}cloneElement(t){return new Xe(Ee.of(t(),0),this.type,void 0,void 0,this.removedAt)}split(t,r,i){const s=this.isText?this.splitText(r,this.id.getOffset()):this.splitElement(r,i);if(s){if(s.insPrevID=this.id,this.insNextID){const o=t.findFloorNode(this.insNextID);o.insPrevID=s.id,s.insNextID=this.insNextID}this.insNextID=s.id,t.registerNode(s)}return s}getCreatedAt(){return this.id.getCreatedAt()}getOffset(){return this.id.getOffset()}canDelete(t,r){return!this.getCreatedAt().after(r)&&(!this.removedAt||t.after(this.removedAt))}canStyle(t,r){return this.isText?!1:!this.getCreatedAt().after(r)&&(!this.removedAt||t.after(this.removedAt))}setAttrs(t,r){this.attrs||(this.attrs=new Tr);const i=new Array;for(const[s,o]of Object.entries(t))i.push(this.attrs.set(s,o,r));return i}purge(t){this.attrs&&this.attrs.purge(t)}getGCPairs(){const t=[];if(!this.attrs)return t;for(const r of this.attrs)r.getRemovedAt()&&t.push({parent:this,child:r});return t}}function qc(n){var t;if(n.isText){const r=n;return{type:r.type,value:r.value}}const e={type:n.type,children:n.children.map(qc)};return n.attrs&&(e.attributes=Xi((t=n.attrs)==null?void 0:t.toObject())),e}function Gf(n){if(n.isText)return n.value;let e="";return n.attrs&&n.attrs.size()&&(e=" "+Array.from(n.attrs).filter(t=>!t.isRemoved()).sort((t,r)=>t.getKey().localeCompare(r.getKey())).map(t=>{const r=JSON.parse(t.getValue());return typeof r=="string"?`${t.getKey()}="${r}"`:`${t.getKey()}="${en(t.getValue())}"`}).join(" ")),`<${n.type}${e}>${n.children.map(t=>Gf(t)).join("")}`}function uy(n){if(n.isText){const e=n;return{type:e.type,value:e.value,size:e.size,isRemoved:e.isRemoved}}return{type:n.type,children:n.children.map(uy),size:n.size,isRemoved:n.isRemoved}}class Et extends No{constructor(t,r){super(r);u(this,"indexTree");u(this,"nodeMapByID");this.indexTree=new K1(t),this.nodeMapByID=new ly(Ee.createComparator()),this.indexTree.traverseAll(i=>{this.nodeMapByID.put(i.id,i)})}static create(t,r){return new Et(t,r)}findFloorNode(t){const r=this.nodeMapByID.floorEntry(t);if(!(!r||!r.key.getCreatedAt().equals(t.getCreatedAt())))return r.value}registerNode(t){this.nodeMapByID.put(t.id,t)}findNodesAndSplitText(t,r){const[i,s]=t.toTreeNodePair(this);let o=s;const a=i===o,l=o.parent&&!a?o.parent:i;if(o.isText&&o.split(this,t.getLeftSiblingID().getOffset()-o.id.getOffset()),r){const c=l.allChildren,d=a?0:c.indexOf(o)+1;for(let h=d;h{const I=w.getCreatedAt().getActorID(),O=s?s.has(I)?s.get(I):bt:Ws;if(w.canStyle(i,O)&&r){const y=p.get(I),g=w.getCreatedAt();(!y||g.after(y))&&p.set(I,g);const v=w.setAttrs(r,i),T=v.reduce((P,[,B])=>(B&&(P[B.getKey()]=h[B.getKey()]),P),{}),x=w.parent,N=w.prevSibling||w.parent;Object.keys(T).length>0&&d.push({type:"style",from:this.toIndex(x,N),to:this.toIndex(w,w),fromPath:this.toPath(x,N),toPath:this.toPath(w,w),actor:i.getActorID(),value:T});for(const[P]of v)P&&m.push({parent:w,child:P})}}),[p,m,d]}removeStyle(t,r,i,s){const[o,a]=this.findNodesAndSplitText(t[0],i),[l,c]=this.findNodesAndSplitText(t[1],i),d=[],h=new Map,p=[];return this.traverseInPosRange(o,a,l,c,([m])=>{const w=m.getCreatedAt().getActorID(),I=s?s.has(w)?s.get(w):bt:Ws;if(m.canStyle(i,I)&&r){const O=h.get(w),y=m.getCreatedAt();(!O||y.after(O))&&h.set(w,y),m.attrs||(m.attrs=new Tr);for(const T of r){const x=m.attrs.remove(T,i);for(const N of x)p.push({parent:m,child:N})}const g=m.parent,v=m.prevSibling||m.parent;d.push({actor:i.getActorID(),type:"removeStyle",from:this.toIndex(g,v),to:this.toIndex(m,m),fromPath:this.toPath(g,v),toPath:this.toPath(m,m),value:r})}}),[h,p,d]}edit(t,r,i,s,o,a){const[l,c]=this.findNodesAndSplitText(t[0],s),[d,h]=this.findNodesAndSplitText(t[1],s),p=this.toIndex(l,c),m=this.toPath(l,c),w=[],I=[],O=[],y=new Map;this.traverseInPosRange(l,c,d,h,([T,x],N)=>{if(x===ge.Start&&!N)for(const H of T.children)O.push(H);const P=T.getCreatedAt().getActorID(),B=a?a.has(P)?a.get(P):bt:Ws;if(T.canDelete(s,B)||w.includes(T.parent)){const H=y.get(P),U=T.getCreatedAt();(!H||U.after(H))&&y.set(P,U),(x===ge.Text||x===ge.Start)&&w.push(T),I.push([T,x])}});const g=this.makeDeletionChanges(I,s),v=[];for(const T of w)T.remove(s),T.isRemoved&&v.push({parent:this,child:T});for(const T of O)T.removedAt||l.append(T);if(i>0){let T=0,x=l,N=c;for(;T{l.isRemoved&&(P.remove(s),v.push({parent:this,child:P})),this.nodeMapByID.put(P.id,P)}),N.isRemoved||T.push(N);if(T.length){const N=T.map(P=>qc(P));g.length&&g[g.length-1].from===p?g[g.length-1].value=N:g.push({type:"content",from:p,to:p,fromPath:m,toPath:m,actor:s.getActorID(),value:N})}}return[g,v,y]}editT(t,r,i,s,o){const a=this.findPos(t[0]),l=this.findPos(t[1]);this.edit([a,l],r,i,s,o)}move(t,r,i){throw new k(S.ErrUnimplemented,`not implemented: ${t}, ${r}, ${i}`)}purge(t){var s;(s=t.parent)==null||s.removeChild(t),this.nodeMapByID.remove(t.id);const r=t.insPrevID,i=t.insNextID;if(r){const o=this.findFloorNode(r);o.insNextID=i}if(i){const o=this.findFloorNode(i);o.insPrevID=r}t.insPrevID=void 0,t.insNextID=void 0}getGCPairs(){const t=[];return this.indexTree.traverse(r=>{r.getRemovedAt()&&t.push({parent:this,child:r});for(const i of r.getGCPairs())t.push(i)}),t}findPos(t,r=!0){const i=this.indexTree.findTreePos(t,r);return Rt.fromTreePos(i)}pathToPosRange(t){const r=this.pathToIndex(t);return[this.findPos(r),this.findPos(r+1)]}pathToPos(t){const r=this.indexTree.pathToIndex(t);return this.findPos(r)}getRoot(){return this.indexTree.getRoot()}getSize(){return this.indexTree.size}getNodeSize(){return this.nodeMapByID.size()}getIndexTree(){return this.indexTree}toXML(){return Gf(this.indexTree.getRoot())}toJSON(){return JSON.stringify(this.getRootTreeNode())}toJSForTest(){return{createdAt:this.getCreatedAt().toTestString(),value:JSON.parse(this.toJSON()),type:"YORKIE_TREE"}}toJSInfoForTest(){const t=this.indexTree.getRoot(),r=(i,s=void 0,o=void 0,a=0)=>{var m,w,I,O;let l,c,d;const h=i.isText?{node:i,offset:0}:s&&o?this.toTreePos(s,o):null;h&&(l=this.indexTree.indexOf(h),c=this.indexTree.treePosToPath(h),d=Rt.fromTreePos(h).toStruct());const p={type:i.type,parent:s==null?void 0:s.id.toTestString(),size:i.size,id:i.id.toTestString(),removedAt:(m=i.removedAt)==null?void 0:m.toTestString(),insPrev:(w=i.insPrevID)==null?void 0:w.toTestString(),insNext:(I=i.insNextID)==null?void 0:I.toTestString(),value:i.isText?i.value:void 0,isRemoved:i.isRemoved,children:[],depth:a,attributes:i.attrs?Xi((O=i.attrs)==null?void 0:O.toObject()):void 0,index:l,path:c,pos:d};for(let y=0;y0&&y===i[i.length-1].to?(i[i.length-1].to=g,i[i.length-1].toPath=this.toPath(O,m)):i.push({type:"content",from:y,to:g,fromPath:this.toPath(I,h),toPath:this.toPath(O,m),actor:r.getActorID()}))}return i.reverse()}findRightToken([t,r]){if(r===ge.Start){const l=t.allChildren;return l.length>0?[l[0],l[0].isText?ge.Text:ge.Start]:[t,ge.End]}const i=t.parent,s=i.allChildren,o=s.indexOf(t);if(i&&o===s.length-1)return[i,ge.End];const a=s[o+1];return[a,a.isText?ge.Text:ge.Start]}findLeftToken([t,r]){if(r===ge.End){const l=t.allChildren;if(l.length>0){const c=l[l.length-1];return[c,c.isText?ge.Text:ge.End]}return[t,ge.Start]}const i=t.parent,s=i.allChildren,o=s.indexOf(t);if(i&&o===0)return[i,ge.Start];const a=s[o-1];return[a,a.isText?ge.Text:ge.End]}}class Ro extends Jt{constructor(t,r,i,s,o,a,l){super(t,l);u(this,"fromPos");u(this,"toPos");u(this,"contents");u(this,"splitLevel");u(this,"maxCreatedAtMapByActor");this.fromPos=r,this.toPos=i,this.contents=s,this.splitLevel=o,this.maxCreatedAtMapByActor=a}static create(t,r,i,s,o,a,l){return new Ro(t,r,i,s,o,a,l)}execute(t){var l;const r=t.findByCreatedAt(this.getParentCreatedAt());if(!r)throw new k(S.ErrInvalidArgument,`fail to find ${this.getParentCreatedAt()}`);if(!(r instanceof Et))throw new k(S.ErrInvalidArgument,"fail to execute, only Tree can execute edit");const i=this.getExecutedAt(),s=r,[o,a]=s.edit([this.fromPos,this.toPos],(l=this.contents)==null?void 0:l.map(c=>c.deepcopy()),this.splitLevel,i,(()=>{let c=i.getDelimiter();return this.contents!==void 0&&(c+=this.contents.length),()=>et.of(i.getLamport(),++c,i.getActorID())})(),this.maxCreatedAtMapByActor);for(const c of a)t.registerGCPair(c);return{opInfos:o.map(({from:c,to:d,value:h,splitLevel:p,fromPath:m,toPath:w})=>({type:"tree-edit",path:t.createPath(this.getParentCreatedAt()),from:c,to:d,value:h,splitLevel:p,fromPath:m,toPath:w}))}}getEffectedCreatedAt(){return this.getParentCreatedAt()}toTestString(){const t=this.getParentCreatedAt().toTestString(),r=`${this.fromPos.getLeftSiblingID().getCreatedAt().toTestString()}/${this.fromPos.getLeftSiblingID().getOffset()}`,i=`${this.toPos.getLeftSiblingID().getCreatedAt().toTestString()}/${this.toPos.getLeftSiblingID().getOffset()}`,s=this.contents||[];return`${t}.EDIT(${r},${i},${s.map(o=>Gf(o)).join("")})`}getFromPos(){return this.fromPos}getToPos(){return this.toPos}getContents(){return this.contents}getSplitLevel(){return this.splitLevel}getMaxCreatedAtMapByActor(){return this.maxCreatedAtMapByActor}}class Zi{constructor(e){u(this,"vector");this.vector=e||new Map}set(e,t){this.vector.set(e,t)}get(e){return this.vector.get(e)}maxLamport(){let e=BigInt(0);for(const[,t]of this)t>e&&(e=t);return e}max(e){const t=new Map;for(const[r,i]of e){const s=this.vector.get(r),o=s&&s>i?s:i;t.set(r,o)}for(const[r,i]of this){const s=e.get(r),o=s&&s>i?s:i;t.set(r,o)}return new Zi(t)}afterOrEqual(e){const t=this.vector.get(e.getActorID());return t===void 0?!1:t>=e.getLamport()}deepcopy(){const e=new Map;for(const[t,r]of this.vector)e.set(t,r);return new Zi(e)}filter(e){const t=new Map;for(const[r]of e){const i=this.vector.get(r);i!==void 0&&t.set(r,i)}return new Zi(t)}size(){return this.vector.size}*[Symbol.iterator](){for(const[e,t]of this.vector)yield[e,t]}}const G1=new Zi(new Map);class ar{constructor(e,t,r,i,s){u(this,"clientSeq");u(this,"serverSeq");u(this,"lamport");u(this,"actor");u(this,"versionVector");this.clientSeq=e,this.serverSeq=s,this.lamport=t,this.versionVector=i,this.actor=r}static of(e,t,r,i,s){return new ar(e,t,r,i,s)}next(){const e=this.versionVector.deepcopy();return e.set(this.actor,this.lamport+1n),new ar(this.clientSeq+1,this.lamport+1n,this.actor,e)}syncClocks(e){const t=e.lamport>this.lamport?e.lamport+1n:this.lamport+1n,r=this.versionVector.max(e.versionVector),i=new ar(this.clientSeq,t,this.actor,r);return i.versionVector.set(this.actor,t),i}setClocks(e,t){const r=e>this.lamport?e:this.lamport+1n,i=this.versionVector.max(t);return i.set(this.actor,r),ar.of(this.clientSeq,r,this.actor,i)}createTimeTicket(e){return et.of(this.lamport,e,this.actor)}setActor(e){return new ar(this.clientSeq,this.lamport,e,this.versionVector,this.serverSeq)}setVersionVector(e){return new ar(this.clientSeq,this.lamport,this.actor,e,this.serverSeq)}getClientSeq(){return this.clientSeq}getServerSeq(){return this.serverSeq?this.serverSeq.toString():""}getLamport(){return this.lamport}getLamportAsString(){return this.lamport.toString()}getActorID(){return this.actor}getVersionVector(){return this.versionVector}toTestString(){return`${this.lamport.toString()}:${this.actor.slice(-2)}:${this.clientSeq}`}}const Y1=new ar(0,0n,Wf,G1);class hs{constructor({id:e,operations:t,presenceChange:r,message:i}){u(this,"id");u(this,"operations");u(this,"presenceChange");u(this,"message");this.id=e,this.operations=t||[],this.presenceChange=r,this.message=i}static create({id:e,operations:t,presenceChange:r,message:i}){return new hs({id:e,operations:t,presenceChange:r,message:i})}getID(){return this.id}getMessage(){return this.message}hasOperations(){return this.operations.length>0}getOperations(){return this.operations}setActor(e){for(const t of this.operations)t.setActor(e);this.id=this.id.setActor(e)}hasPresenceChange(){return this.presenceChange!==void 0}getPresenceChange(){return this.presenceChange}execute(e,t,r){const i=[],s=[];for(const o of this.operations){const a=o.execute(e,r);if(!a)continue;const{opInfos:l,reverseOp:c}=a;i.push(...l),c&&s.unshift(c)}return this.presenceChange&&(this.presenceChange.type===Qr.Put?t.set(this.id.getActorID(),Nt(this.presenceChange.presence)):t.delete(this.id.getActorID())),{opInfos:i,reverseOps:s}}toTestString(){return`${this.operations.map(e=>e.toTestString()).join(",")}`}toStruct(){return{changeID:fe.bytesToHex(fe.toChangeID(this.getID()).toBinary()),message:this.getMessage(),operations:this.getOperations().map(e=>fe.bytesToHex(fe.toOperation(e).toBinary())),presenceChange:this.getPresenceChange()}}static fromStruct(e){const{changeID:t,operations:r,presenceChange:i,message:s}=e;return hs.create({id:fe.bytesToChangeID(fe.hexToBytes(t)),operations:r==null?void 0:r.map(o=>fe.bytesToOperation(fe.hexToBytes(o))),presenceChange:i,message:s})}}class Ml{constructor(e,t,r,i,s,o,a){u(this,"documentKey");u(this,"checkpoint");u(this,"isRemoved");u(this,"changes");u(this,"snapshot");u(this,"minSyncedTicket");u(this,"versionVector");this.documentKey=e,this.checkpoint=t,this.isRemoved=r,this.changes=i,this.snapshot=o,this.minSyncedTicket=a,this.versionVector=s}static create(e,t,r,i,s,o,a){return new Ml(e,t,r,i,s,o,a)}getDocumentKey(){return this.documentKey}getCheckpoint(){return this.checkpoint}getIsRemoved(){return this.isRemoved}getChanges(){return this.changes}hasChanges(){return this.changes.length>0}getChangeSize(){return this.changes.length}hasSnapshot(){return!!this.snapshot&&!!this.snapshot.length}getSnapshot(){return this.snapshot}getMinSyncedTicket(){return this.minSyncedTicket}getVersionVector(){return this.versionVector}}class es{constructor(e,t){u(this,"serverSeq");u(this,"clientSeq");this.serverSeq=e,this.clientSeq=t}static of(e,t){return new es(e,t)}increaseClientSeq(e){return e===0?this:new es(this.serverSeq,this.clientSeq+e)}forward(e){if(this.equals(e))return this;const t=this.serverSeq>e.serverSeq?this.serverSeq:e.serverSeq,r=Math.max(this.clientSeq,e.clientSeq);return es.of(t,r)}getServerSeqAsString(){return this.serverSeq.toString()}getClientSeq(){return this.clientSeq}getServerSeq(){return this.serverSeq}equals(e){return this.clientSeq===e.clientSeq&&this.serverSeq==e.serverSeq}toTestString(){return`serverSeq=${this.serverSeq}, clientSeq=${this.clientSeq}`}}const Q1=new es(0n,0);class rn{constructor(e,t){u(this,"createdAt");u(this,"offset");this.createdAt=e,this.offset=t}static of(e,t){return new rn(e,t)}static fromStruct(e){return rn.of(et.fromStruct(e.createdAt),e.offset)}getCreatedAt(){return this.createdAt}getOffset(){return this.offset}equals(e){return this.createdAt.compare(e.createdAt)===0&&this.offset===e.offset}hasSameCreatedAt(e){return this.createdAt.compare(e.createdAt)===0}split(e){return new rn(this.createdAt,this.offset+e)}toStruct(){return{createdAt:this.createdAt.toStruct(),offset:this.offset}}toTestString(){return`${this.createdAt.toTestString()}:${this.offset}`}toIDString(){return`${this.createdAt.toIDString()}:${this.offset}`}}const X1=rn.of(bt,0);class Ft{constructor(e,t){u(this,"id");u(this,"relativeOffset");this.id=e,this.relativeOffset=t}static of(e,t){return new Ft(e,t)}static fromStruct(e){const t=rn.fromStruct(e.id);return Ft.of(t,e.relativeOffset)}getID(){return this.id}getRelativeOffset(){return this.relativeOffset}getAbsoluteID(){return rn.of(this.id.getCreatedAt(),this.id.getOffset()+this.relativeOffset)}toTestString(){return`${this.id.toTestString()}:${this.relativeOffset}`}toStruct(){return{id:this.id.toStruct(),relativeOffset:this.relativeOffset}}equals(e){return this.id.equals(e.id)?this.relativeOffset===e.relativeOffset:!1}}class Hr extends ey{constructor(t,r,i){super(r);u(this,"id");u(this,"removedAt");u(this,"prev");u(this,"next");u(this,"insPrev");u(this,"insNext");this.id=t,this.removedAt=i}static create(t,r){return new Hr(t,r)}static createComparator(){return(t,r)=>{const i=t.getCreatedAt().compare(r.getCreatedAt());return i!==0?i:t.getOffset()>r.getOffset()?1:t.getOffset()0&&t.getID().getOffset()==e.getOffset()){if(!t.hasInsPrev())return t;t=t.getInsPrev()}return t}findFloorNode(e){const t=this.treeByID.floorEntry(e);if(t&&!(!t.key.equals(e)&&!t.key.hasSameCreatedAt(e)))return t.value}findBetween(e,t){const r=[];let i=e;for(;i&&i!==t;)r.push(i),i=i.getNext();return r}splitNode(e,t){if(t>e.getContentLength())throw new k(S.ErrInvalidArgument,"offset should be less than or equal to length");if(t===0)return e;if(t===e.getContentLength())return e.getNext();const r=e.split(t);this.treeByIndex.updateWeight(r),this.insertAfter(e,r);const i=e.getInsNext();return i&&i.setInsPrev(r),r.setInsPrev(e),r}deleteNodes(e,t,r){if(!e.length)return[[],new Map,new Map];const[i,s]=this.filterNodes(e,t,r),o=new Map,a=new Map,l=this.makeChanges(s,t);for(const c of i){const d=c.getCreatedAt().getActorID();(!o.has(d)||c.getID().getCreatedAt().after(o.get(d)))&&o.set(d,c.getID().getCreatedAt()),a.set(c.getID().toIDString(),c),c.remove(t)}return this.deleteIndexNodes(s),[l,o,a]}filterNodes(e,t,r){const i=!!r,s=[],o=[],[a,l]=this.findEdgesOfCandidates(e);o.push(a);for(const c of e){const d=c.getCreatedAt().getActorID(),h=i?r.has(d)?r.get(d):bt:Ws;c.canDelete(t,h)?s.push(c):o.push(c)}return o.push(l),[s,o]}findEdgesOfCandidates(e){return[e[0].getPrev(),e[e.length-1].getNext()]}makeChanges(e,t){const r=[];let i,s;for(let o=0;on<0?Math.ceil(n):Math.floor(n);var sn=(n=>(n[n.IntegerCnt=0]="IntegerCnt",n[n.LongCnt=1]="LongCnt",n))(sn||{});class nt extends No{constructor(t,r,i){super(i);u(this,"valueType");u(this,"value");switch(this.valueType=t,t){case 0:typeof r=="number"?r>Math.pow(2,31)-1||r<-Math.pow(2,31)?this.value=q.fromNumber(r).toInt():this.value=ng(r):this.value=r.toInt();break;case 1:typeof r=="number"?this.value=q.fromNumber(r):this.value=r;break;default:throw new k(S.ErrUnimplemented,`unimplemented type: ${t}`)}}static create(t,r,i){return new nt(t,r,i)}static valueFromBytes(t,r){switch(t){case 0:return r[0]|r[1]<<8|r[2]<<16|r[3]<<24;case 1:return q.fromBytesLE(Array.from(r));default:throw new k(S.ErrUnimplemented,`unimplemented type: ${t}`)}}toJSON(){return`${this.value}`}toSortedJSON(){return this.toJSON()}toJSForTest(){return{createdAt:this.getCreatedAt().toTestString(),value:this.value,type:"YORKIE_COUNTER"}}deepcopy(){const t=nt.create(this.valueType,this.value,this.getCreatedAt());return t.setMovedAt(this.getMovedAt()),t}getType(){return this.valueType}static getCounterType(t){switch(typeof t){case"object":return t instanceof q?1:void 0;case"number":return t>Math.pow(2,31)-1||t<-Math.pow(2,31)?1:0;default:return}}static isSupport(t){return!!nt.getCounterType(t)}static isInteger(t){return t%1===0}isNumericType(){const t=this.valueType;return t===0||t===1}getValueType(){return this.valueType}getValue(){return this.value}toBytes(){switch(this.valueType){case 0:{const t=this.value;return new Uint8Array([t&255,t>>8&255,t>>16&255,t>>24&255])}case 1:{const r=this.value.toBytesLE();return Uint8Array.from(r)}default:throw new k(S.ErrUnimplemented,`unimplemented type: ${this.valueType}`)}}increase(t){function r(i){if(!i.isNumericType())throw new TypeError(`Unsupported type of value: ${typeof i.getValue()}`)}return r(this),r(t),this.valueType===1?this.value=this.value.add(t.getValue()):t.getType()===ve.Long?this.value=this.value+t.getValue().toInt():this.value=q.fromNumber(this.value+ng(t.getValue())).toInt(),this}}class ms extends Jt{constructor(t,r,i){super(t,i);u(this,"value");this.value=r}static create(t,r,i){return new ms(t,r,i)}execute(t){const r=t.findByCreatedAt(this.getParentCreatedAt());if(!r)throw new k(S.ErrInvalidArgument,`fail to find ${this.getParentCreatedAt()}`);if(!(r instanceof nt))throw new k(S.ErrInvalidArgument,"fail to execute, only Counter can execute increase");const i=r,s=this.value.deepcopy();return i.increase(s),{opInfos:[{type:"increase",path:t.createPath(this.getParentCreatedAt()),value:s.getValue()}],reverseOp:this.toReverseOperation()}}toReverseOperation(){const t=this.value.deepcopy(),i=t.getType()===ve.Long?t.getValue().multiply(-1):t.getValue()*-1;return ms.create(this.getParentCreatedAt(),ie.of(i,t.getCreatedAt()))}getEffectedCreatedAt(){return this.getParentCreatedAt()}toTestString(){return`${this.getParentCreatedAt().toTestString()}.INCREASE.${this.value.toJSON()}`}getValue(){return this.value}}class pr extends Jt{constructor(t,r,i,s,o,a,l){super(t,l);u(this,"fromPos");u(this,"toPos");u(this,"maxCreatedAtMapByActor");u(this,"attributes");u(this,"attributesToRemove");this.fromPos=r,this.toPos=i,this.maxCreatedAtMapByActor=s,this.attributes=o,this.attributesToRemove=a}static create(t,r,i,s,o,a){return new pr(t,r,i,s,o,new Array,a)}static createTreeRemoveStyleOperation(t,r,i,s,o,a){return new pr(t,r,i,s,new Map,o,a)}execute(t){const r=t.findByCreatedAt(this.getParentCreatedAt());if(!r)throw new k(S.ErrInvalidArgument,`fail to find ${this.getParentCreatedAt()}`);if(!(r instanceof Et))throw new k(S.ErrInvalidArgument,"fail to execute, only Tree can execute edit");const i=r;let s,o;if(this.attributes.size){const a={};[...this.attributes].forEach(([l,c])=>a[l]=c),[,o,s]=i.style([this.fromPos,this.toPos],a,this.getExecutedAt(),this.maxCreatedAtMapByActor)}else{const a=this.attributesToRemove;[,o,s]=i.removeStyle([this.fromPos,this.toPos],a,this.getExecutedAt(),this.maxCreatedAtMapByActor)}for(const a of o)t.registerGCPair(a);return{opInfos:s.map(({from:a,to:l,value:c,fromPath:d,toPath:h})=>({type:"tree-style",from:a,to:l,value:this.attributes.size?{attributes:c}:{attributesToRemove:c},fromPath:d,toPath:h,path:t.createPath(this.getParentCreatedAt())}))}}getEffectedCreatedAt(){return this.getParentCreatedAt()}toTestString(){const t=this.getParentCreatedAt().toTestString(),r=`${this.fromPos.getLeftSiblingID().getCreatedAt().toTestString()}:${this.fromPos.getLeftSiblingID().getOffset()}`,i=`${this.toPos.getLeftSiblingID().getCreatedAt().toTestString()}:${this.toPos.getLeftSiblingID().getOffset()}`;return`${t}.STYLE(${r},${i},${Object.entries(this.attributes||{}).map(([s,o])=>`${s}:"${o}"`).join(" ")})`}getFromPos(){return this.fromPos}getToPos(){return this.toPos}getAttributes(){return this.attributes}getAttributesToRemove(){return this.attributesToRemove}getMaxCreatedAtMapByActor(){return this.maxCreatedAtMapByActor}}function Z1(n){const e=new Kf,t=e.data;for(const[r,i]of Object.entries(n))t[r]=JSON.stringify(i);return e}function eS(n){if(n.type===Qr.Put)return new po({type:Ai.PUT,presence:Z1(n.presence)});if(n.type===Qr.Clear)return new po({type:Ai.CLEAR});throw new k(S.ErrUnimplemented,"unimplemented type")}function tS(n){return new Qp({serverSeq:n.getServerSeq(),clientSeq:n.getClientSeq()})}function cy(n){return new Bl({clientSeq:n.getClientSeq(),lamport:n.getLamport(),actorId:od(n.getActorID()),versionVector:Yf(n.getVersionVector())})}function F(n){if(n)return new b({lamport:n.getLamport(),delimiter:n.getDelimiter(),actorId:od(n.getActorID())})}function Yf(n){if(!n)return;const e=new bl;for(const[t,r]of n)e.vector[t]=BigInt(r.toString());return e}function fy(n){switch(n){case ve.Null:return $.NULL;case ve.Boolean:return $.BOOLEAN;case ve.Integer:return $.INTEGER;case ve.Long:return $.LONG;case ve.Double:return $.DOUBLE;case ve.String:return $.STRING;case ve.Bytes:return $.BYTES;case ve.Date:return $.DATE;default:throw new k(S.ErrInvalidType,`unsupported type: ${n}`)}}function dy(n){switch(n){case sn.IntegerCnt:return $.INTEGER_CNT;case sn.LongCnt:return $.LONG_CNT;default:throw new k(S.ErrInvalidType,`unsupported type: ${n}`)}}function ku(n){if(n instanceof We)return new lt({type:$.JSON_OBJECT,createdAt:F(n.getCreatedAt()),value:Ey(n)});if(n instanceof tt)return new lt({type:$.JSON_ARRAY,createdAt:F(n.getCreatedAt()),value:RS(n)});if(n instanceof It)return new lt({type:$.TEXT,createdAt:F(n.getCreatedAt())});if(n instanceof ie)return new lt({type:fy(n.getType()),createdAt:F(n.getCreatedAt()),value:n.toBytes()});if(n instanceof nt)return new lt({type:dy(n.getType()),createdAt:F(n.getCreatedAt()),value:n.toBytes()});if(n instanceof Et)return new lt({type:$.TREE,createdAt:F(n.getCreatedAt()),value:BS(n)});throw new k(S.ErrUnimplemented,"unimplemented element")}function nS(n){return new go({createdAt:F(n.getCreatedAt()),offset:n.getOffset()})}function Zo(n){return new kr({createdAt:F(n.getID().getCreatedAt()),offset:n.getID().getOffset(),relativeOffset:n.getRelativeOffset()})}function ea(n){return new Ti({parentId:Hs(n.getParentID()),leftSiblingId:Hs(n.getLeftSiblingID())})}function Hs(n){return new Kr({createdAt:F(n.getCreatedAt()),offset:n.getOffset()})}function hy(n){const e=new qf;if(n instanceof Ii){const t=n,r=new Ga;r.parentCreatedAt=F(t.getParentCreatedAt()),r.key=t.getKey(),r.value=ku(t.getValue()),r.executedAt=F(t.getExecutedAt()),e.body.case="set",e.body.value=r}else if(n instanceof Po){const t=n,r=new Ya;r.parentCreatedAt=F(t.getParentCreatedAt()),r.prevCreatedAt=F(t.getPrevCreatedAt()),r.value=ku(t.getValue()),r.executedAt=F(t.getExecutedAt()),e.body.case="add",e.body.value=r}else if(n instanceof br){const t=n,r=new Qa;r.parentCreatedAt=F(t.getParentCreatedAt()),r.prevCreatedAt=F(t.getPrevCreatedAt()),r.createdAt=F(t.getCreatedAt()),r.executedAt=F(t.getExecutedAt()),e.body.case="move",e.body.value=r}else if(n instanceof Xr){const t=n,r=new Xa;r.parentCreatedAt=F(t.getParentCreatedAt()),r.createdAt=F(t.getCreatedAt()),r.executedAt=F(t.getExecutedAt()),e.body.case="remove",e.body.value=r}else if(n instanceof Do){const t=n,r=new Za;r.parentCreatedAt=F(t.getParentCreatedAt()),r.from=Zo(t.getFromPos()),r.to=Zo(t.getToPos());const i=r.createdAtMapByActor;for(const[o,a]of t.getMaxCreatedAtMapByActor())i[o]=F(a);r.content=t.getContent();const s=r.attributes;for(const[o,a]of t.getAttributes())s[o]=a;r.executedAt=F(t.getExecutedAt()),e.body.case="edit",e.body.value=r}else if(n instanceof Oo){const t=n,r=new el;r.parentCreatedAt=F(t.getParentCreatedAt()),r.from=Zo(t.getFromPos()),r.to=Zo(t.getToPos());const i=r.createdAtMapByActor;for(const[o,a]of t.getMaxCreatedAtMapByActor())i[o]=F(a);const s=r.attributes;for(const[o,a]of t.getAttributes())s[o]=a;r.executedAt=F(t.getExecutedAt()),e.body.case="style",e.body.value=r}else if(n instanceof ms){const t=n,r=new tl;r.parentCreatedAt=F(t.getParentCreatedAt()),r.value=ku(t.getValue()),r.executedAt=F(t.getExecutedAt()),e.body.case="increase",e.body.value=r}else if(n instanceof Ro){const t=n,r=new nl,i=r.createdAtMapByActor;for(const[s,o]of t.getMaxCreatedAtMapByActor())i[s]=F(o);r.parentCreatedAt=F(t.getParentCreatedAt()),r.from=ea(t.getFromPos()),r.to=ea(t.getToPos()),r.contents=uS(t.getContents()),r.splitLevel=t.getSplitLevel(),r.executedAt=F(t.getExecutedAt()),e.body.case="treeEdit",e.body.value=r}else if(n instanceof pr){const t=n,r=new rl;r.parentCreatedAt=F(t.getParentCreatedAt()),r.from=ea(t.getFromPos()),r.to=ea(t.getToPos());const i=r.createdAtMapByActor;for(const[o,a]of t.getMaxCreatedAtMapByActor())i[o]=F(a);const s=t.getAttributesToRemove();if(s.length>0)r.attributesToRemove=s;else{const o=r.attributes;for(const[a,l]of t.getAttributes())o[a]=l}r.executedAt=F(t.getExecutedAt()),e.body.case="treeStyle",e.body.value=r}else throw new k(S.ErrUnimplemented,"unimplemented operation");return e}function rS(n){const e=[];for(const t of n)e.push(hy(t));return e}function iS(n){const e=new Gp({id:cy(n.getID()),message:n.getMessage()});return n.hasOperations()&&(e.operations=rS(n.getOperations())),n.hasPresenceChange()&&(e.presenceChange=eS(n.getPresenceChange())),e}function sS(n){const e=[];for(const t of n)e.push(iS(t));return e}function oS(n){const e=[];for(const t of n)e.push(new Yp({key:t.getStrKey(),element:Xf(t.getValue())}));return e}function aS(n){const e=[];for(const t of n)e.push(new cl({element:Xf(t.getValue())}));return e}function lS(n){const e=[];for(const t of n){const r=new fl;r.id=nS(t.getID()),r.value=t.getValue().getContent(),r.removedAt=F(t.getRemovedAt());const i=r.attributes,s=t.getValue().getAttrs();for(const o of s){const a=new cs;a.value=o.getValue(),a.updatedAt=F(o.getUpdatedAt()),i[o.getKey()]=a}e.push(r)}return e}function uS(n){const e=[];if(!n||!n.length)return e;for(const t of n)e.push(new dl({content:Qf(t)}));return e}function cS(n){const e={};for(const t of n)e[t.getKey()]=new cs({value:t.getValue(),updatedAt:F(t.getUpdatedAt()),isRemoved:t.isRemoved()});return e}function Qf(n){if(!n)return[];const e=[];return Fl(n,(t,r)=>{const i=new mo({id:Hs(t.id),type:t.type,removedAt:F(t.removedAt),depth:r});t.isText&&(i.value=t.value),t.insPrevID&&(i.insPrevId=Hs(t.insPrevID)),t.insNextID&&(i.insNextId=Hs(t.insNextID)),t.attrs&&(i.attributes=cS(t.attrs)),e.push(i)}),e}function fS(n){const e=new He;return e.body.case="jsonObject",e.body.value=new il({nodes:oS(n.getRHT()),createdAt:F(n.getCreatedAt()),movedAt:F(n.getMovedAt()),removedAt:F(n.getRemovedAt())}),e}function gy(n){const e=new He;return e.body.case="jsonArray",e.body.value=new sl({nodes:aS(n.getElements()),createdAt:F(n.getCreatedAt()),movedAt:F(n.getMovedAt()),removedAt:F(n.getRemovedAt())}),e}function dS(n){const e=new He;return e.body.case="primitive",e.body.value=new ol({type:fy(n.getType()),value:n.toBytes(),createdAt:F(n.getCreatedAt()),movedAt:F(n.getMovedAt()),removedAt:F(n.getRemovedAt())}),e}function hS(n){const e=new He;return e.body.case="text",e.body.value=new al({nodes:lS(n.getRGATreeSplit()),createdAt:F(n.getCreatedAt()),movedAt:F(n.getMovedAt()),removedAt:F(n.getRemovedAt())}),e}function gS(n){const e=new He;return e.body.case="counter",e.body.value=new ll({type:dy(n.getType()),value:n.toBytes(),createdAt:F(n.getCreatedAt()),movedAt:F(n.getMovedAt()),removedAt:F(n.getRemovedAt())}),e}function my(n){const e=new He;return e.body.case="tree",e.body.value=new ul({nodes:Qf(n.getRoot()),createdAt:F(n.getCreatedAt()),movedAt:F(n.getMovedAt()),removedAt:F(n.getRemovedAt())}),e}function Xf(n){if(n instanceof We)return fS(n);if(n instanceof tt)return gy(n);if(n instanceof ie)return dS(n);if(n instanceof It)return hS(n);if(n instanceof nt)return gS(n);if(n instanceof Et)return my(n);throw new k(S.ErrUnimplemented,"unimplemented element")}function mS(n){return new Ir({documentKey:n.getDocumentKey(),checkpoint:tS(n.getCheckpoint()),isRemoved:n.getIsRemoved(),changes:sS(n.getChanges()),snapshot:n.getSnapshot(),versionVector:Yf(n.getVersionVector()),minSyncedTicket:F(n.getMinSyncedTicket())})}function rg(n){const e=n.findDetails(O1);for(const t of e)if(t.metadata.code)return t.metadata.code;return""}function py(n){return ar.of(n.clientSeq,BigInt(n.lamport),id(n.actorId),Zf(n.versionVector),BigInt(n.serverSeq))}function Zf(n){if(!n)return;const e=new Zi;return Object.entries(n.vector).forEach(([t,r])=>{e.set(t,BigInt(r.toString()))}),e}function M(n){if(n)return et.of(BigInt(n.lamport),n.delimiter,id(n.actorId))}function ed(n){const e={};return Object.entries(n.data).forEach(([t,r])=>{e[t]=JSON.parse(r)}),e}function pS(n){const e=n.type;if(e===Ai.PUT){const t=ed(n.presence);return{type:Qr.Put,presence:t}}if(e===Ai.CLEAR)return{type:Qr.Clear};throw new k(S.ErrInvalidType,`unsupported type: ${e}`)}function yS(n){const e=new Map;return Object.entries(n).forEach(([t,r])=>{e.set(t,ed(r))}),e}function yy(n){switch(n){case $.NULL:return ve.Null;case $.BOOLEAN:return ve.Boolean;case $.INTEGER:return ve.Integer;case $.LONG:return ve.Long;case $.DOUBLE:return ve.Double;case $.STRING:return ve.String;case $.BYTES:return ve.Bytes;case $.DATE:return ve.Date}throw new k(S.ErrUnimplemented,`unimplemented value type: ${n}`)}function ml(n){switch(n){case $.INTEGER_CNT:return sn.IntegerCnt;case $.LONG_CNT:return sn.LongCnt}throw new k(S.ErrUnimplemented,`unimplemented value type: ${n}`)}function Tu(n){switch(n.type){case $.JSON_OBJECT:return n.value?Iy(n.value):We.create(M(n.createdAt));case $.JSON_ARRAY:return n.value?OS(n.value):tt.create(M(n.createdAt));case $.TEXT:return It.create(gs.create(),M(n.createdAt));case $.TREE:return LS(n.value);case $.NULL:case $.BOOLEAN:case $.INTEGER:case $.LONG:case $.DOUBLE:case $.STRING:case $.BYTES:case $.DATE:return ie.of(ie.valueFromBytes(yy(n.type),n.value),M(n.createdAt));case $.INTEGER_CNT:case $.LONG_CNT:return nt.create(ml(n.type),nt.valueFromBytes(ml(n.type),n.value),M(n.createdAt))}}function ta(n){return Ft.of(rn.of(M(n.createdAt),n.offset),n.relativeOffset)}function vy(n){return rn.of(M(n.createdAt),n.offset)}function vS(n){const e=So.create(n.value);Object.entries(n.attributes).forEach(([r,i])=>{e.setAttr(r,i.value,M(i.updatedAt))});const t=Hr.create(vy(n.id),e);return t.remove(M(n.removedAt)),t}function Di(n){return Rt.of(_s(n.parentId),_s(n.leftSiblingId))}function _s(n){return Ee.of(M(n.createdAt),n.offset)}function wS(n){if(!n.length)return;const e=[];return n.forEach(t=>{const r=td(t.content);e.push(r)}),e}function td(n){if(n.length===0)return;const e=[];for(const i of n)e.push(kS(i));const t=e[e.length-1],r=new Map;r.set(n[e.length-1].depth,e[e.length-1]);for(let i=e.length-2;i>=0;i--)r.get(n[i].depth-1).prepend(e[i]),r.set(n[i].depth,e[i]);return t.updateDescendantsSize(),Et.create(t,bt).getRoot()}function SS(n){const e=Tr.create();for(const[t,r]of Object.entries(n))e.setInternal(t,r.value,M(r.updatedAt),r.isRemoved);return e}function kS(n){const e=_s(n.id),t=Xe.create(e,n.type),r=Object.entries(n.attributes);return t.isText?t.value=n.value:r.length&&(t.attrs=SS(n.attributes)),n.insPrevId&&(t.insPrevID=_s(n.insPrevId)),n.insNextId&&(t.insNextID=_s(n.insNextId)),t.removedAt=M(n.removedAt),t}function wy(n){if(n.body.case==="set"){const e=n.body.value;return Ii.create(e.key,Tu(e.value),M(e.parentCreatedAt),M(e.executedAt))}else if(n.body.case==="add"){const e=n.body.value;return Po.create(M(e.parentCreatedAt),M(e.prevCreatedAt),Tu(e.value),M(e.executedAt))}else if(n.body.case==="move"){const e=n.body.value;return br.create(M(e.parentCreatedAt),M(e.prevCreatedAt),M(e.createdAt),M(e.executedAt))}else if(n.body.case==="remove"){const e=n.body.value;return Xr.create(M(e.parentCreatedAt),M(e.createdAt),M(e.executedAt))}else if(n.body.case==="edit"){const e=n.body.value,t=new Map;Object.entries(e.createdAtMapByActor).forEach(([i,s])=>{t.set(i,M(s))});const r=new Map;return Object.entries(e.attributes).forEach(([i,s])=>{r.set(i,s)}),Do.create(M(e.parentCreatedAt),ta(e.from),ta(e.to),t,e.content,r,M(e.executedAt))}else if(n.body.case==="style"){const e=n.body.value,t=new Map;Object.entries(e.createdAtMapByActor).forEach(([i,s])=>{t.set(i,M(s))});const r=new Map;return Object.entries(e.attributes).forEach(([i,s])=>{r.set(i,s)}),Oo.create(M(e.parentCreatedAt),ta(e.from),ta(e.to),t,r,M(e.executedAt))}else{if(n.body.case==="select")return;if(n.body.case==="increase"){const e=n.body.value;return ms.create(M(e.parentCreatedAt),Tu(e.value),M(e.executedAt))}else if(n.body.case==="treeEdit"){const e=n.body.value,t=new Map;return Object.entries(e.createdAtMapByActor).forEach(([r,i])=>{t.set(r,M(i))}),Ro.create(M(e.parentCreatedAt),Di(e.from),Di(e.to),wS(e.contents),e.splitLevel,t,M(e.executedAt))}else if(n.body.case==="treeStyle"){const e=n.body.value,t=new Map,r=e.attributesToRemove,i=new Map;return e!=null&&e.createdAtMapByActor&&Object.entries(e.createdAtMapByActor).forEach(([s,o])=>{i.set(s,M(o))}),(r==null?void 0:r.length)>0?pr.createTreeRemoveStyleOperation(M(e.parentCreatedAt),Di(e.from),Di(e.to),i,r,M(e.executedAt)):(Object.entries(e.attributes).forEach(([s,o])=>{t.set(s,o)}),pr.create(M(e.parentCreatedAt),Di(e.from),Di(e.to),i,t,M(e.executedAt)))}else throw new k(S.ErrUnimplemented,"unimplemented operation")}}function TS(n){const e=[];for(const t of n){const r=wy(t);r&&e.push(r)}return e}function Sy(n){const e=[];for(const t of n)e.push(hs.create({id:py(t.id),operations:TS(t.operations),presenceChange:t.presenceChange?pS(t.presenceChange):void 0,message:t.message}));return e}function AS(n){return es.of(BigInt(n.serverSeq),n.clientSeq)}function IS(n){return Ml.create(n.documentKey,AS(n.checkpoint),n.isRemoved,Sy(n.changes),Zf(n.versionVector),n.snapshot,M(n.minSyncedTicket))}function ky(n){const e=new yo;for(const r of n.nodes){const i=nd(r.element);e.set(r.key,i,i.getPositionedAt())}const t=new We(M(n.createdAt),e);return t.setMovedAt(M(n.movedAt)),t.setRemovedAt(M(n.removedAt)),t}function Ty(n){const e=new wo;for(const r of n.nodes)e.insert(nd(r.element));const t=new tt(M(n.createdAt),e);return t.setMovedAt(M(n.movedAt)),t.setRemovedAt(M(n.removedAt)),t}function ES(n){const e=ie.of(ie.valueFromBytes(yy(n.type),n.value),M(n.createdAt));return e.setMovedAt(M(n.movedAt)),e.setRemovedAt(M(n.removedAt)),e}function xS(n){const e=new gs;let t=e.getHead();for(const i of n.nodes){const s=e.insertAfter(t,vS(i));i.insPrevId&&s.setInsPrev(e.findNode(vy(i.insPrevId))),t=s}const r=new It(e,M(n.createdAt));return r.setMovedAt(M(n.movedAt)),r.setRemovedAt(M(n.removedAt)),r}function CS(n){const e=nt.create(ml(n.type),nt.valueFromBytes(ml(n.type),n.value),M(n.createdAt));return e.setMovedAt(M(n.movedAt)),e.setRemovedAt(M(n.removedAt)),e}function Ay(n){const e=td(n.nodes);return Et.create(e,M(n.createdAt))}function nd(n){if(n.body.case==="jsonObject")return ky(n.body.value);if(n.body.case==="jsonArray")return Ty(n.body.value);if(n.body.case==="primitive")return ES(n.body.value);if(n.body.case==="text")return xS(n.body.value);if(n.body.case==="counter")return CS(n.body.value);if(n.body.case==="tree")return Ay(n.body.value);throw new k(S.ErrUnimplemented,"unimplemented element")}function NS(n){if(!n)return{root:We.create(bt),presences:new Map};const e=wc.fromBinary(n);return{root:nd(e.root),presences:yS(e.presences)}}function PS(n){const e=Yf(n);return rd(e.toBinary())}function DS(n){const e=sd(n),t=bl.fromBinary(e);return Zf(t)}function Iy(n){if(!n)throw new k(S.ErrInvalidArgument,"bytes is empty");const e=He.fromBinary(n);return ky(e.body.value)}function Ey(n){return Xf(n).toBinary()}function OS(n){if(!n)throw new k(S.ErrInvalidArgument,"bytes is empty");const e=He.fromBinary(n);return Ty(e.body.value)}function RS(n){return gy(n).toBinary()}function LS(n){if(!n)throw new k(S.ErrInvalidArgument,"bytes is empty");const e=He.fromBinary(n);return Ay(e.body.value)}function BS(n){return my(n).toBinary()}function rd(n){return n?Array.from(n).map(e=>e.toString(16).padStart(2,"0")).join(""):""}function id(n){return rd(n)}function sd(n){return new Uint8Array(n.match(/.{1,2}/g).map(e=>parseInt(e,16)))}function od(n){return sd(n)}function bS(n){const e=Bl.fromBinary(n);return py(e)}function FS(n){const e=qf.fromBinary(n);return wy(e)}const fe={fromPresence:ed,toChangePack:mS,fromChangePack:IS,fromChanges:Sy,toTreeNodes:Qf,fromTreeNodes:td,objectToBytes:Ey,bytesToObject:Iy,bytesToSnapshot:NS,bytesToHex:rd,hexToBytes:sd,toHexString:id,toUint8Array:od,toOperation:hy,toChangeID:cy,PbChangeID:Bl,bytesToChangeID:bS,bytesToOperation:FS,versionVectorToHex:PS,hexToVersionVector:DS};var be=(n=>(n[n.Trivial=0]="Trivial",n[n.Debug=1]="Debug",n[n.Info=2]="Info",n[n.Warn=3]="Warn",n[n.Error=4]="Error",n[n.Fatal=5]="Fatal",n))(be||{});let oi=3;function xy(n){oi=n}const J={trivial:(...n)=>{oi>0||typeof console<"u"&&console.log("YORKIE T:",...n)},debug:(...n)=>{oi>1||typeof console<"u"&&console.log("YORKIE D:",...n)},info:(...n)=>{oi>2||typeof console<"u"&&console.log("YORKIE I:",...n)},warn:(...n)=>{oi>3||typeof console<"u"&&(typeof console.warn<"u"?console.warn("YORKIE W:",...n):console.log("YORKIE W:",...n))},error:(...n)=>{oi>4||typeof console<"u"&&(typeof console.error<"u"?console.error("YORKIE E:",...n):console.log("YORKIE E:",...n))},fatal:(...n)=>{typeof console<"u"&&(typeof console.error<"u"?console.error("YORKIE F:",...n):console.log("YORKIE F:",...n))},isEnabled:n=>oi<=n};function Cy(){return"xxxxxxxx-xxxx-4xxxy-xxxx-xxxxxxxxxxx".replace(/[xy]/g,n=>{const e=Math.random()*16|0;return(n==="x"?e:e&3|8).toString(16)})}class MS{constructor(e,t,r,i,s){u(this,"reconnectStreamDelay");u(this,"doc");u(this,"docID");u(this,"syncMode");u(this,"remoteChangeEventReceived");u(this,"watchStream");u(this,"watchLoopTimerID");u(this,"watchAbortController");u(this,"unsubscribeBroadcastEvent");this.reconnectStreamDelay=e,this.doc=t,this.docID=r,this.syncMode=i,this.remoteChangeEventReceived=!1,this.unsubscribeBroadcastEvent=s}changeSyncMode(e){this.syncMode=e}needRealtimeSync(){return this.syncMode===Ta.RealtimeSyncOff?!1:this.syncMode===Ta.RealtimePushOnly?this.doc.hasLocalChanges():this.syncMode!==Ta.Manual&&(this.doc.hasLocalChanges()||this.remoteChangeEventReceived)}async runWatchLoop(e){const t=async()=>{if(this.watchStream)return Promise.resolve();this.watchLoopTimerID&&(clearTimeout(this.watchLoopTimerID),this.watchLoopTimerID=void 0);try{[this.watchStream,this.watchAbortController]=await e(()=>{this.watchStream=void 0,this.watchAbortController=void 0,this.watchLoopTimerID=setTimeout(t,this.reconnectStreamDelay)})}catch{}};await t()}cancelWatchStream(){this.watchStream&&this.watchAbortController&&(this.watchAbortController.abort(),this.watchStream=void 0,this.watchAbortController=void 0),clearTimeout(this.watchLoopTimerID),this.watchLoopTimerID=void 0}}const Au=()=>{};class JS{constructor(e){u(this,"finalized",!1);u(this,"observers",[]);u(this,"finalError");try{e(this)}catch(t){this.error(t)}}next(e){this.forEachObserver(t=>{t.next(e)})}error(e){this.forEachObserver(t=>{t.error(e)}),this.close(e)}complete(){this.forEachObserver(e=>{e.complete()}),this.close()}subscribe(e,t,r){let i;if(!e)throw new k(S.ErrInvalidArgument,"missing observer");if(this.finalized)throw new k(S.ErrRefused,"observable is finalized due to previous error");typeof e=="object"?i=e:i={next:e,error:t,complete:r},i.next===void 0&&(i.next=Au),i.error===void 0&&(i.error=Au),i.complete===void 0&&(i.complete=Au);const s=Cy(),o=this.unsubscribeOne.bind(this,s);if(this.observers.push({subscriptionID:s,observer:i}),this.finalized)try{this.finalError?i.error(this.finalError):i.complete()}catch(a){J.warn(a)}return o}unsubscribeOne(e){var t;this.observers=(t=this.observers)==null?void 0:t.filter(r=>r.subscriptionID!==e)}forEachObserver(e){if(!this.finalized)for(let t=0;te}}class Ki{constructor(e,t,r,i){u(this,"id");u(this,"delimiter");u(this,"message");u(this,"root");u(this,"operations");u(this,"presenceChange");u(this,"previousPresence");u(this,"reversePresenceKeys");this.id=e,this.delimiter=Zp,this.root=t,this.operations=[],this.previousPresence=Nt(r),this.presenceChange=void 0,this.reversePresenceKeys=new Set,this.message=i}static create(e,t,r,i){return new Ki(e,t,r,i)}push(e){this.operations.push(e)}registerElement(e,t){this.root.registerElement(e,t)}registerRemovedElement(e){this.root.registerRemovedElement(e)}registerGCPair(e){this.root.registerGCPair(e)}getChange(){return hs.create({id:this.id,operations:this.operations,presenceChange:this.presenceChange,message:this.message})}hasChange(){return this.operations.length>0||this.presenceChange!==void 0}setPresenceChange(e){this.presenceChange=e}setReversePresence(e,t){for(const r of Object.keys(e))t!=null&&t.addToHistory?this.reversePresenceKeys.add(r):this.reversePresenceKeys.delete(r)}getReversePresence(){if(this.reversePresenceKeys.size===0)return;const e={};for(const t of this.reversePresenceKeys)e[t]=this.previousPresence[t];return e}issueTimeTicket(){return this.delimiter+=1,this.id.createTimeTicket(this.delimiter)}getLastTimeTicket(){return this.id.createTimeTicket(this.delimiter)}}class ko{constructor(e){u(this,"rootObject");u(this,"elementPairMapByCreatedAt");u(this,"gcElementSetByCreatedAt");u(this,"gcPairMap");this.rootObject=e,this.elementPairMapByCreatedAt=new Map,this.gcElementSetByCreatedAt=new Set,this.gcPairMap=new Map,this.registerElement(e,void 0),e.getDescendants(t=>{if(t.getRemovedAt()&&this.registerRemovedElement(t),t instanceof It||t instanceof Et)for(const r of t.getGCPairs())this.registerGCPair(r);return!1})}static create(){return new ko(We.create(bt))}findByCreatedAt(e){const t=this.elementPairMapByCreatedAt.get(e.toIDString());if(t)return t.element}findElementPairByCreatedAt(e){return this.elementPairMapByCreatedAt.get(e.toIDString())}createSubPaths(e){let t=this.elementPairMapByCreatedAt.get(e.toIDString());if(!t)return[];const r=[];for(;t.parent;){const i=t.element.getCreatedAt(),s=t.parent.subPathOf(i);if(s===void 0)throw new k(S.ErrInvalidArgument,`cant find the given element: ${i.toIDString()}`);r.unshift(s),t=this.elementPairMapByCreatedAt.get(t.parent.getCreatedAt().toIDString())}return r.unshift("$"),r}createPath(e){return this.createSubPaths(e).join(".")}registerElement(e,t){this.elementPairMapByCreatedAt.set(e.getCreatedAt().toIDString(),{parent:t,element:e}),e instanceof Wr&&e.getDescendants((r,i)=>(this.registerElement(r,i),!1))}deregisterElement(e){let t=0;const r=i=>{const s=i.getCreatedAt().toIDString();this.elementPairMapByCreatedAt.delete(s),this.gcElementSetByCreatedAt.delete(s),t++};return r(e),e instanceof Wr&&e.getDescendants(i=>(r(i),!1)),t}registerRemovedElement(e){this.gcElementSetByCreatedAt.add(e.getCreatedAt().toIDString())}registerGCPair(e){if(this.gcPairMap.get(e.child.toIDString())){this.gcPairMap.delete(e.child.toIDString());return}this.gcPairMap.set(e.child.toIDString(),e)}getElementMapSize(){return this.elementPairMapByCreatedAt.size}getGarbageElementSetSize(){const e=new Set;for(const t of this.gcElementSetByCreatedAt){e.add(t);const r=this.elementPairMapByCreatedAt.get(t);r.element instanceof Wr&&r.element.getDescendants(i=>(e.add(i.getCreatedAt().toIDString()),!1))}return e.size}getObject(){return this.rootObject}getGarbageLen(){return this.getGarbageElementSetSize()+this.gcPairMap.size}deepcopy(){return new ko(this.rootObject.deepcopy())}garbageCollect(e){let t=0;for(const r of this.gcElementSetByCreatedAt){const i=this.elementPairMapByCreatedAt.get(r),s=i.element.getRemovedAt();s&&(e!=null&&e.afterOrEqual(s))&&(i.parent.purge(i.element),t+=this.deregisterElement(i.element))}for(const[,r]of this.gcPairMap){const i=r.child.getRemovedAt();i&&(e!=null&&e.afterOrEqual(i))&&(r.parent.purge(r.child),this.gcPairMap.delete(r.child.toIDString()),t+=1)}return t}toJSON(){return this.rootObject.toJSON()}toSortedJSON(){return this.rootObject.toSortedJSON()}getStats(){return{elements:this.getElementMapSize(),gcPairs:this.gcPairMap.size,gcElements:this.getGarbageElementSetSize()}}}function Ny(n,e){const t=new To(n);return new Proxy(e,t.getHandlers())}class To{constructor(e){u(this,"context");u(this,"handlers");this.context=e,this.handlers={set:(t,r,i)=>(J.isEnabled(be.Trivial)&&J.trivial(`obj[${r}]=${JSON.stringify(i)}`),To.setInternal(e,t,r,i),!0),get:(t,r)=>(J.isEnabled(be.Trivial)&&J.trivial(`obj[${r}]`),r==="getID"?()=>t.getCreatedAt():r==="toJSON"||r==="toString"?()=>t.toJSON():r==="toJS"?()=>t.toJS():r==="toJSForTest"?()=>t.toJSForTest():ai(e,t.get(r))),ownKeys:t=>t.getKeys(),getOwnPropertyDescriptor:()=>({enumerable:!0,configurable:!0}),deleteProperty:(t,r)=>(J.isEnabled(be.Trivial)&&J.trivial(`obj[${r}]`),To.deleteInternal(e,t,r),!0)}}static setInternal(e,t,r,i){if(r.includes("."))throw new k(S.ErrInvalidObjectKey,"key must not contain the '.'.");const s=e.issueTimeTicket(),o=pl(e,i,s),a=t.set(r,o,s);e.registerElement(o,t),a&&e.registerRemovedElement(a),e.push(Ii.create(r,o.deepcopy(),t.getCreatedAt(),s))}static buildObjectMembers(e,t){const r={};for(const[i,s]of Object.entries(t)){if(i.includes("."))throw new k(S.ErrInvalidObjectKey,"key must not contain the '.'.");const o=e.issueTimeTicket(),a=pl(e,s,o);r[i]=a}return r}static deleteInternal(e,t,r){const i=e.issueTimeTicket(),s=t.deleteByKey(r,i);s&&(e.push(Xr.create(t.getCreatedAt(),s.getCreatedAt(),i)),e.registerRemovedElement(s))}getHandlers(){return this.handlers}}function zS(n,e){const t=new ae(n,e);return new Proxy(e,t.getHandlers())}function US(n){return typeof n=="string"||n instanceof String?!isNaN(n):!1}function jS(n){return["concat","entries","every","filter","find","findIndex","forEach","join","keys","map","reduce","reduceRight","slice","some","toLocaleString","toString","values"].includes(n)}class ae{constructor(e,t){u(this,"context");u(this,"handlers");u(this,"array");this.context=e,this.array=t,this.handlers={get:(r,i,s)=>i==="getID"?()=>r.getCreatedAt():i==="getElementByID"?o=>{const a=r.getByID(o);if(!(!a||a.isRemoved()))return Cr(e,a)}:i==="getElementByIndex"?o=>{const a=r.get(o);return Cr(e,a)}:i==="getLast"?()=>Cr(e,r.getLast()):i==="deleteByID"?o=>{const a=ae.deleteInternalByID(e,r,o);return Cr(e,a)}:i==="insertAfter"?(o,a)=>{const l=ae.insertAfterInternal(e,r,o,a);return Cr(e,l)}:i==="insertBefore"?(o,a)=>{const l=ae.insertBeforeInternal(e,r,o,a);return Cr(e,l)}:i==="moveBefore"?(o,a)=>{ae.moveBeforeInternal(e,r,o,a)}:i==="moveAfter"?(o,a)=>{ae.moveAfterInternal(e,r,o,a)}:i==="moveFront"?o=>{ae.moveFrontInternal(e,r,o)}:i==="moveLast"?o=>{ae.moveLastInternal(e,r,o)}:US(i)?ai(e,r.get(Number(i))):i==="push"?o=>ae.pushInternal(e,r,o):i==="splice"?(o,a,...l)=>ae.splice(e,r,o,a,...l):i==="length"?r.length:typeof i=="symbol"&&i===Symbol.iterator?ae.iteratorInternal.bind(this,e,r):i==="includes"?(o,a)=>ae.includes(e,r,o,a):i==="indexOf"?(o,a)=>ae.indexOf(e,r,o,a):i==="lastIndexOf"?(o,a)=>ae.lastIndexOf(e,r,o,a):i==="toJSForTest"?()=>r.toJSForTest():i==="toTestString"?()=>ae.toTestString(r):typeof i=="string"&&jS(i)?(...o)=>{const a=Array.from(r).map(l=>ai(e,l));return Array.prototype[i].apply(a,o)}:Reflect.get(r,i,s),deleteProperty:(r,i)=>(J.isEnabled(be.Trivial)&&J.trivial(`array[${i}]`),ae.deleteInternalByIndex(e,r,Number.parseInt(i)),!0)}}static*iteratorInternal(e,t){for(const r of t)yield Cr(e,r)}static buildArrayElements(e,t){const r=[];for(const i of t){const s=e.issueTimeTicket(),o=pl(e,i,s);r.push(o)}return r}static pushInternal(e,t,r){return ae.insertAfterInternal(e,t,t.getLastCreatedAt(),r),t.length}static moveBeforeInternal(e,t,r,i){const s=e.issueTimeTicket(),o=t.getPrevCreatedAt(r);t.moveAfter(o,i,s),e.push(br.create(t.getCreatedAt(),o,i,s))}static moveAfterInternal(e,t,r,i){const s=e.issueTimeTicket();t.moveAfter(r,i,s),e.push(br.create(t.getCreatedAt(),r,i,s))}static moveFrontInternal(e,t,r){const i=e.issueTimeTicket(),s=t.getHead();t.moveAfter(s.getCreatedAt(),r,i),e.push(br.create(t.getCreatedAt(),s.getCreatedAt(),r,i))}static moveLastInternal(e,t,r){const i=e.issueTimeTicket(),s=t.getLastCreatedAt();t.moveAfter(s,r,i),e.push(br.create(t.getCreatedAt(),s,r,i))}static insertAfterInternal(e,t,r,i){const s=e.issueTimeTicket(),o=pl(e,i,s);return t.insertAfter(r,o),e.registerElement(o,t),e.push(Po.create(t.getCreatedAt(),r,o.deepcopy(),s)),o}static insertBeforeInternal(e,t,r,i){return ae.insertAfterInternal(e,t,t.getPrevCreatedAt(r),i)}static deleteInternalByIndex(e,t,r){const i=e.issueTimeTicket(),s=t.deleteByIndex(r,i);if(s)return e.push(Xr.create(t.getCreatedAt(),s.getCreatedAt(),i)),e.registerRemovedElement(s),s}static deleteInternalByID(e,t,r){const i=e.issueTimeTicket(),s=t.delete(r,i);return e.push(Xr.create(t.getCreatedAt(),s.getCreatedAt(),i)),e.registerRemovedElement(s),s}static splice(e,t,r,i,...s){const o=t.length,a=r>=0?Math.min(r,o):Math.max(o+r,0),l=i===void 0?o:i<0?a:Math.min(a+i,o),c=[];for(let d=a;d=s)return!1;if(ie.isSupport(r))return Array.from(t).map(c=>ai(e,c)).includes(r,o);for(let l=o;l=s)return-1;if(ie.isSupport(r))return Array.from(t).map(c=>ai(e,c)).indexOf(r,o);for(let l=o;l=s?s-1:i<0?i+s:i;if(o<0)return-1;if(ie.isSupport(r))return Array.from(t).map(c=>ai(e,c)).lastIndexOf(r,o);for(let l=o;l>0;l--)if(((a=t.get(l))==null?void 0:a.getID())===r.getID())return l;return-1}static toTestString(e){return e.toTestString()}getHandlers(){return this.handlers}}class Jl{constructor(e,t){u(this,"context");u(this,"text");this.context=e,this.text=t}initialize(e,t){this.context=e,this.text=t}getID(){return this.text.getID()}edit(e,t,r,i){if(!this.context||!this.text)throw new k(S.ErrNotInitialized,"Text is not initialized yet");if(e>t)throw new k(S.ErrInvalidArgument,"from should be less than or equal to to");const s=this.text.indexRangeToPosRange(e,t);J.isEnabled(be.Debug)&&J.debug(`EDIT: f:${e}->${s[0].toTestString()}, t:${t}->${s[1].toTestString()} c:${r}`);const o=i?fs(i):void 0,a=this.context.issueTimeTicket(),[l,,c,d]=this.text.edit(s,r,a,o);for(const h of c)this.context.registerGCPair(h);return this.context.push(new Do(this.text.getCreatedAt(),s[0],s[1],l,r,o?new Map(Object.entries(o)):new Map,a)),this.text.findIndexesFromRange(d)}delete(e,t){return this.edit(e,t,"")}empty(){return this.edit(0,this.length,"")}setStyle(e,t,r){if(!this.context||!this.text)throw new k(S.ErrNotInitialized,"Text is not initialized yet");if(e>t)throw new k(S.ErrInvalidArgument,"from should be less than or equal to to");const i=this.text.indexRangeToPosRange(e,t);J.isEnabled(be.Debug)&&J.debug(`STYL: f:${e}->${i[0].toTestString()}, t:${t}->${i[1].toTestString()} a:${JSON.stringify(r)}`);const s=fs(r),o=this.context.issueTimeTicket(),[a,l]=this.text.setStyle(i,s,o);for(const c of l)this.context.registerGCPair(c);return this.context.push(new Oo(this.text.getCreatedAt(),i[0],i[1],a,new Map(Object.entries(s)),o)),!0}indexRangeToPosRange(e){if(!this.context||!this.text)throw new k(S.ErrNotInitialized,"Text is not initialized yet");const t=this.text.indexRangeToPosRange(e[0],e[1]);return[t[0].toStruct(),t[1].toStruct()]}posRangeToIndexRange(e){if(!this.context||!this.text)throw new k(S.ErrNotInitialized,"Text is not initialized yet");const t=this.text.findIndexesFromRange([Ft.fromStruct(e[0]),Ft.fromStruct(e[1])]);return[t[0],t[1]]}toTestString(){if(!this.context||!this.text)throw new k(S.ErrNotInitialized,"Text is not initialized yet");return this.text.toTestString()}values(){if(!this.context||!this.text)throw new k(S.ErrNotInitialized,"Text is not initialized yet");return this.text.values()}get length(){return this.text.length}getTreeByIndex(){return this.text.getTreeByIndex()}getTreeByID(){return this.text.getTreeByID()}toString(){if(!this.context||!this.text)throw new k(S.ErrNotInitialized,"Text is not initialized yet");return this.text.toString()}toJSON(){if(!this.context||!this.text)throw new k(S.ErrNotInitialized,"Text is not initialized yet");return this.text.toJSON()}toJSForTest(){if(!this.context||!this.text)throw new k(S.ErrNotInitialized,"Text is not initialized yet");return this.text.toJSForTest()}createRangeForTest(e,t){if(!this.context||!this.text)throw new k(S.ErrNotInitialized,"Text is not initialized yet");return this.text.indexRangeToPosRange(e,t)}}class $l{constructor(e,t){u(this,"valueType");u(this,"value");u(this,"context");u(this,"counter");this.valueType=e,this.value=t}initialize(e,t){this.valueType=t.getValueType(),this.context=e,this.counter=t,this.value=t.getValue()}getID(){return this.counter.getID()}getValue(){return this.value}getValueType(){return this.valueType}increase(e){if(!this.context||!this.counter)throw new k(S.ErrNotInitialized,"Counter is not initialized yet");const t=this.context.issueTimeTicket(),r=ie.of(e,t);if(!r.isNumericType())throw new TypeError(`Unsupported type of value: ${typeof r.getValue()}`);return this.counter.increase(r),this.context.push(ms.create(this.counter.getCreatedAt(),r,t)),this}toJSForTest(){if(!this.context||!this.counter)throw new k(S.ErrNotInitialized,"Counter is not initialized yet");return this.counter.toJSForTest()}}function ad(n,e,t){const{type:r}=n,i=t.issueTimeTicket();if(r===mr){Py(n);const{value:s}=n,o=Xe.create(Ee.of(i,0),r,s);e.append(o)}else{const{children:s=[]}=n,{attributes:o}=n;let a;if(typeof o=="object"&&!Xp(o)){const c=fs(o);a=new Tr;for(const[d,h]of Object.entries(c))a.set(d,h,i)}const l=Xe.create(Ee.of(i,0),r,void 0,a);e.append(l);for(const c of s)ad(c,l,t)}}function VS(n,e){const{type:t}=e,r=n.issueTimeTicket();let i;if(e.type===mr){const{value:s}=e;i=Xe.create(Ee.of(r,0),t,s)}else if(e){const{children:s=[]}=e,{attributes:o}=e;let a;if(typeof o=="object"&&!Xp(o)){const l=fs(o);a=new Tr;for(const[c,d]of Object.entries(l))a.set(c,d,r)}i=Xe.create(Ee.of(n.issueTimeTicket(),0),t,void 0,a);for(const l of s)ad(l,i,n)}return i}function Py(n){if(!n.value.length)throw new k(S.ErrInvalidArgument,"text node cannot have empty value");return!0}function ig(n){if(!n.length)return!0;if(n[0].type===mr)for(const t of n){const{type:r}=t;if(r!==mr)throw new k(S.ErrInvalidArgument,"element node and text node cannot be passed together");Py(t)}else for(const t of n){const{type:r}=t;if(r===mr)throw new k(S.ErrInvalidArgument,"element node and text node cannot be passed together")}return!0}class zl{constructor(e){u(this,"initialRoot");u(this,"context");u(this,"tree");this.initialRoot=e}initialize(e,t){this.context=e,this.tree=t}getID(){return this.tree.getID()}buildRoot(e){if(!this.initialRoot)return Xe.create(Ee.of(e.issueTimeTicket(),0),U1);const t=Xe.create(Ee.of(e.issueTimeTicket(),0),this.initialRoot.type);for(const r of this.initialRoot.children)ad(r,t,e);return t}getSize(){if(!this.context||!this.tree)throw new k(S.ErrNotInitialized,"Tree is not initialized yet");return this.tree.getSize()}getNodeSize(){if(!this.context||!this.tree)throw new k(S.ErrNotInitialized,"Tree is not initialized yet");return this.tree.getNodeSize()}getIndexTree(){if(!this.context||!this.tree)throw new k(S.ErrNotInitialized,"Tree is not initialized yet");return this.tree.getIndexTree()}styleByPath(e,t){if(!this.context||!this.tree)throw new k(S.ErrNotInitialized,"Tree is not initialized yet");if(!e.length)throw new k(S.ErrInvalidArgument,"path should not be empty");const[r,i]=this.tree.pathToPosRange(e),s=this.context.issueTimeTicket(),o=t?fs(t):void 0,[a]=this.tree.style([r,i],o,s);this.context.push(pr.create(this.tree.getCreatedAt(),r,i,a,o?new Map(Object.entries(o)):new Map,s))}style(e,t,r){if(!this.context||!this.tree)throw new k(S.ErrNotInitialized,"Tree is not initialized yet");if(e>t)throw new k(S.ErrInvalidArgument,"from should be less than or equal to to");const i=this.tree.findPos(e),s=this.tree.findPos(t),o=this.context.issueTimeTicket(),a=r?fs(r):void 0,[l,c]=this.tree.style([i,s],a,o);for(const d of c)this.context.registerGCPair(d);this.context.push(pr.create(this.tree.getCreatedAt(),i,s,l,a?new Map(Object.entries(a)):new Map,o))}removeStyle(e,t,r){if(!this.context||!this.tree)throw new k(S.ErrNotInitialized,"Tree is not initialized yet");if(e>t)throw new k(S.ErrInvalidArgument,"from should be less than or equal to to");const i=this.tree.findPos(e),s=this.tree.findPos(t),o=this.context.issueTimeTicket(),[a,l]=this.tree.removeStyle([i,s],r,o);for(const c of l)this.context.registerGCPair(c);this.context.push(pr.createTreeRemoveStyleOperation(this.tree.getCreatedAt(),i,s,a,r,o))}editInternal(e,t,r,i=0){var c;if(r.length!==0&&r[0]&&(ig(r),r[0].type!==mr))for(const d of r){const{children:h=[]}=d;ig(h)}const s=this.context.getLastTimeTicket();let o=new Array;if(((c=r[0])==null?void 0:c.type)===mr){let d="";for(const h of r){const{value:p}=h;d+=p}o.push(Xe.create(Ee.of(this.context.issueTimeTicket(),0),mr,d))}else o=r.map(d=>d&&VS(this.context,d)).filter(d=>d);const[,a,l]=this.tree.edit([e,t],o.length?o.map(d=>d==null?void 0:d.deepcopy()):void 0,i,s,()=>this.context.issueTimeTicket());for(const d of a)this.context.registerGCPair(d);return this.context.push(Ro.create(this.tree.getCreatedAt(),e,t,o.length?o:void 0,i,l,s)),!0}editByPath(e,t,r,i=0){if(!this.context||!this.tree)throw new k(S.ErrNotInitialized,"Tree is not initialized yet");if(e.length!==t.length)throw new k(S.ErrInvalidArgument,"path length should be equal");if(!e.length||!t.length)throw new k(S.ErrInvalidArgument,"path should not be empty");const s=this.tree.pathToPos(e),o=this.tree.pathToPos(t);return this.editInternal(s,o,r?[r]:[],i)}editBulkByPath(e,t,r,i=0){if(!this.context||!this.tree)throw new k(S.ErrNotInitialized,"Tree is not initialized yet");if(e.length!==t.length)throw new k(S.ErrInvalidArgument,"path length should be equal");if(!e.length||!t.length)throw new k(S.ErrInvalidArgument,"path should not be empty");const s=this.tree.pathToPos(e),o=this.tree.pathToPos(t);return this.editInternal(s,o,r,i)}edit(e,t,r,i=0){if(!this.context||!this.tree)throw new k(S.ErrNotInitialized,"Tree is not initialized yet");if(e>t)throw new k(S.ErrInvalidArgument,"from should be less than or equal to to");const s=this.tree.findPos(e),o=this.tree.findPos(t);return this.editInternal(s,o,r?[r]:[],i)}editBulk(e,t,r,i=0){if(!this.context||!this.tree)throw new k(S.ErrNotInitialized,"Tree is not initialized yet");if(e>t)throw new k(S.ErrInvalidArgument,"from should be less than or equal to to");const s=this.tree.findPos(e),o=this.tree.findPos(t);return this.editInternal(s,o,r,i)}toXML(){if(!this.context||!this.tree)throw new k(S.ErrNotInitialized,"Tree is not initialized yet");return this.tree.toXML()}toJSON(){if(!this.context||!this.tree)throw new k(S.ErrNotInitialized,"Tree is not initialized yet");return this.tree.toJSON()}toJSForTest(){if(!this.context||!this.tree)throw new k(S.ErrNotInitialized,"Tree is not initialized yet");return this.tree.toJSForTest()}toJSInfoForTest(){if(!this.context||!this.tree)throw new k(S.ErrNotInitialized,"Tree is not initialized yet");return this.tree.toJSInfoForTest()}getRootTreeNode(){if(!this.context||!this.tree)throw new k(S.ErrNotInitialized,"Tree is not initialized yet");return this.tree.getRootTreeNode()}indexToPath(e){if(!this.context||!this.tree)throw new k(S.ErrNotInitialized,"Tree is not initialized yet");return this.tree.indexToPath(e)}pathToIndex(e){if(!this.context||!this.tree)throw new k(S.ErrNotInitialized,"Tree is not initialized yet");return this.tree.pathToIndex(e)}pathRangeToPosRange(e){if(!this.context||!this.tree)throw new k(S.ErrNotInitialized,"Tree is not initialized yet");const t=[this.tree.pathToIndex(e[0]),this.tree.pathToIndex(e[1])],r=this.tree.indexRangeToPosRange(t);return[r[0].toStruct(),r[1].toStruct()]}indexRangeToPosRange(e){if(!this.context||!this.tree)throw new k(S.ErrNotInitialized,"Tree is not initialized yet");return this.tree.indexRangeToPosStructRange(e)}posRangeToIndexRange(e){if(!this.context||!this.tree)throw new k(S.ErrNotInitialized,"Tree is not initialized yet");const t=[Rt.fromStruct(e[0]),Rt.fromStruct(e[1])];return this.tree.posRangeToIndexRange(t)}posRangeToPathRange(e){if(!this.context||!this.tree)throw new k(S.ErrNotInitialized,"Tree is not initialized yet");const t=[Rt.fromStruct(e[0]),Rt.fromStruct(e[1])];return this.tree.posRangeToPathRange(t)}}function sg(n,e){return Ny(n,e)}function Cr(n,e){if(e){if(e instanceof ie)return e;if(e instanceof We)return Ny(n,e);if(e instanceof tt)return zS(n,e);if(e instanceof It)return new Jl(n,e);if(e instanceof nt){const t=new $l(sn.IntegerCnt,0);return t.initialize(n,e),t}else if(e instanceof Et){const t=new zl;return t.initialize(n,e),t}}else return;throw new TypeError(`Unsupported type of element: ${typeof e}`)}function ai(n,e){const t=Cr(n,e);return t instanceof ie?t.getValue():t}function pl(n,e,t){let r;if(ie.isSupport(e))r=ie.of(e,t);else if(Array.isArray(e))r=tt.create(t,ae.buildArrayElements(n,e));else if(typeof e=="object")e instanceof Jl?(r=It.create(gs.create(),t),e.initialize(n,r)):e instanceof $l?(r=nt.create(e.getValueType(),e.getValue(),t),e.initialize(n,r)):e instanceof zl?(r=Et.create(e.buildRoot(n),t),e.initialize(n,r)):r=We.create(t,To.buildObjectMembers(n,e));else throw new TypeError(`Unsupported type of value: ${typeof e}`);return r}const og=50;class qS{constructor(){u(this,"undoStack",[]);u(this,"redoStack",[])}hasUndo(){return this.undoStack.length>0}hasRedo(){return this.redoStack.length>0}pushUndo(e){this.undoStack.length>=og&&this.undoStack.shift(),this.undoStack.push(e)}popUndo(){return this.undoStack.pop()}pushRedo(e){this.redoStack.length>=og&&this.redoStack.shift(),this.redoStack.push(e)}popRedo(){return this.redoStack.pop()}clearRedo(){this.redoStack=[]}getUndoStackForTest(){return this.undoStack}getRedoStackForTest(){return this.redoStack}}const KS="yorkie-devtools-panel",WS="yorkie-devtools-sdk";let Oi="disconnected";const ag=new Map,ka=new Map;typeof window<"u"&&(window.transactionEventsByDocKey=ka);function na(n,e){(e!=null&&e.force||Oi!=="disconnected")&&window.postMessage({source:WS,...n},"*")}function HS(n){if(!n.isEnableDevtools()||typeof window>"u"||ag.has(n.getKey()))return;ka.set(n.getKey(),[]);const e=n.subscribe("all",t=>{t.some(r=>r.type!==$e.StatusChanged&&r.type!==$e.Snapshot&&r.type!==$e.LocalChange&&r.type!==$e.RemoteChange&&r.type!==$e.Initialized&&r.type!==$e.Watched&&r.type!==$e.Unwatched&&r.type!==$e.PresenceChanged)||(ka.get(n.getKey()).push(t),Oi==="synced"&&na({msg:"doc::sync::partial",docKey:n.getKey(),event:t}))});ag.set(n.getKey(),[e]),na({msg:"refresh-devtools"},{force:!0}),window.addEventListener("message",t=>{var i;if(((i=t.data)==null?void 0:i.source)!==KS)return;switch(t.data.msg){case"devtools::connect":if(Oi!=="disconnected")break;Oi="connected",na({msg:"doc::available",docKey:n.getKey()}),J.info(`[YD] Devtools connected. Doc: ${n.getKey()}`);break;case"devtools::disconnect":Oi="disconnected",J.info(`[YD] Devtools disconnected. Doc: ${n.getKey()}`);break;case"devtools::subscribe":Oi="synced",na({msg:"doc::sync::full",docKey:n.getKey(),events:ka.get(n.getKey())}),J.info(`[YD] Devtools subscribed. Doc: ${n.getKey()}`);break}})}var Nr=(n=>(n.Detached="detached",n.Attached="attached",n.Removed="removed",n))(Nr||{}),$e=(n=>(n.StatusChanged="status-changed",n.ConnectionChanged="connection-changed",n.SyncStatusChanged="sync-status-changed",n.Snapshot="snapshot",n.LocalChange="local-change",n.RemoteChange="remote-change",n.Initialized="initialized",n.Watched="watched",n.Unwatched="unwatched",n.PresenceChanged="presence-changed",n.Broadcast="broadcast",n.LocalBroadcast="local-broadcast",n))($e||{}),Kc=(n=>(n.Connected="connected",n.Disconnected="disconnected",n))(Kc||{}),Wc=(n=>(n.Synced="synced",n.SyncFailed="sync-failed",n))(Wc||{});class Dy{constructor(e,t){u(this,"key");u(this,"status");u(this,"opts");u(this,"changeID");u(this,"checkpoint");u(this,"localChanges");u(this,"root");u(this,"clone");u(this,"eventStream");u(this,"eventStreamObserver");u(this,"onlineClients");u(this,"presences");u(this,"history");u(this,"internalHistory");u(this,"isUpdating");this.opts=t||{},this.key=e,this.status="detached",this.root=ko.create(),this.changeID=Y1,this.checkpoint=Q1,this.localChanges=[],this.eventStream=$S(r=>{this.eventStreamObserver=r}),this.onlineClients=new Set,this.presences=new Map,this.isUpdating=!1,this.internalHistory=new qS,this.history={canUndo:this.canUndo.bind(this),canRedo:this.canRedo.bind(this),undo:this.undo.bind(this),redo:this.redo.bind(this)},HS(this)}update(e,t){if(this.getStatus()==="removed")throw new k(S.ErrDocumentRemoved,`${this.key} is removed`);this.ensureClone();const r=this.changeID.getActorID(),i=Ki.create(this.changeID.next(),this.clone.root,this.clone.presences.get(r)||{},t);try{const s=sg(i,this.clone.root.getObject());this.presences.has(r)||this.clone.presences.set(r,{}),this.isUpdating=!0,e(s,new Su(i,this.clone.presences.get(r)))}catch(s){throw this.clone=void 0,s}finally{this.isUpdating=!1}if(i.hasChange()){J.isEnabled(be.Trivial)&&J.trivial(`trying to update a local change: ${this.toJSON()}`);const s=i.getChange(),{opInfos:o,reverseOps:a}=s.execute(this.root,this.presences,Y.Local),l=i.getReversePresence();l&&a.push({type:"presence",value:l}),this.localChanges.push(s),a.length>0&&this.internalHistory.pushUndo(a),o.length>0&&this.internalHistory.clearRedo(),this.changeID=s.getID();const c=[];o.length>0&&c.push({type:"local-change",source:Y.Local,value:{message:s.getMessage()||"",operations:o,actor:r,clientSeq:s.getID().getClientSeq(),serverSeq:s.getID().getServerSeq()},rawChange:this.isEnableDevtools()?s.toStruct():void 0}),s.hasPresenceChange()&&c.push({type:"presence-changed",source:Y.Local,value:{clientID:r,presence:this.getPresence(r)}}),this.publish(c),J.isEnabled(be.Trivial)&&J.trivial(`after update a local change: ${this.toJSON()}`)}}subscribe(e,t,r,i){if(typeof e=="string"){if(typeof t!="function")throw new k(S.ErrInvalidArgument,"Second argument must be a callback function");if(e==="presence"){const a=t;return this.eventStream.subscribe(l=>{for(const c of l)c.type!=="initialized"&&c.type!=="watched"&&c.type!=="unwatched"&&c.type!=="presence-changed"||a(c)},r,i)}if(e==="my-presence"){const a=t;return this.eventStream.subscribe(l=>{for(const c of l)c.type!=="initialized"&&c.type!=="presence-changed"||c.type==="presence-changed"&&c.value.clientID!==this.changeID.getActorID()||a(c)},r,i)}if(e==="others"){const a=t;return this.eventStream.subscribe(l=>{for(const c of l)c.type!=="watched"&&c.type!=="unwatched"&&c.type!=="presence-changed"||c.value.clientID!==this.changeID.getActorID()&&a(c)},r,i)}if(e==="connection"){const a=t;return this.eventStream.subscribe(l=>{for(const c of l)c.type==="connection-changed"&&a(c)},r,i)}if(e==="status"){const a=t;return this.eventStream.subscribe(l=>{for(const c of l)c.type==="status-changed"&&a(c)},r,i)}if(e==="sync"){const a=t;return this.eventStream.subscribe(l=>{for(const c of l)c.type==="sync-status-changed"&&a(c)},r,i)}if(e==="local-broadcast"){const a=t;return this.eventStream.subscribe(l=>{for(const c of l)c.type==="local-broadcast"&&a(c)},r)}if(e==="broadcast"){const a=t;return this.eventStream.subscribe(l=>{for(const c of l)c.type==="broadcast"&&a(c)},r)}if(e==="all"){const a=t;return this.eventStream.subscribe(a,r,i)}const s=e,o=t;return this.eventStream.subscribe(a=>{for(const l of a){if(l.type!=="local-change"&&l.type!=="remote-change")continue;const c=[];for(const d of l.value.operations)this.isSameElementOrChildOf(d.path,s)&&c.push(d);c.length&&o({...l,value:{...l.value,operations:c}})}},r,i)}if(typeof e=="function"){const s=e,o=t,a=r;return this.eventStream.subscribe(l=>{for(const c of l)c.type!=="snapshot"&&c.type!=="local-change"&&c.type!=="remote-change"||s(c)},o,a)}throw new k(S.ErrInvalidArgument,`"${e}" is not a valid`)}publish(e){this.eventStreamObserver&&this.eventStreamObserver.next(e)}isSameElementOrChildOf(e,t){if(t===e)return!0;const r=e.split(".");return t.split(".").every((s,o)=>s===r[o])}applyChangePack(e){const t=e.hasSnapshot();for(t?this.applySnapshot(e.getCheckpoint().getServerSeq(),e.getVersionVector(),e.getSnapshot()):e.hasChanges()&&this.applyChanges(e.getChanges(),Y.Remote);this.localChanges.length&&!(this.localChanges[0].getID().getClientSeq()>e.getCheckpoint().getClientSeq());)this.localChanges.shift();t&&this.applyChanges(this.localChanges,Y.Remote),this.checkpoint=this.checkpoint.forward(e.getCheckpoint()),t||this.garbageCollect(e.getVersionVector()),t||this.filterVersionVector(e.getVersionVector()),e.getIsRemoved()&&this.applyStatus("removed"),J.isEnabled(be.Trivial)&&J.trivial(`${this.root.toJSON()}`)}getCheckpoint(){return this.checkpoint}getChangeID(){return this.changeID}hasLocalChanges(){return this.localChanges.length>0}ensureClone(){this.clone||(this.clone={root:this.root.deepcopy(),presences:Nt(this.presences)})}createChangePack(){const e=Array.from(this.localChanges),t=this.checkpoint.increaseClientSeq(e.length);return Ml.create(this.key,t,!1,e,this.getVersionVector())}setActor(e){for(const t of this.localChanges)t.setActor(e);this.changeID=this.changeID.setActor(e)}isEnableDevtools(){return!!this.opts.enableDevtools}getKey(){return this.key}getStatus(){return this.status}getCloneRoot(){if(this.clone)return this.clone.root.getObject()}getRoot(){this.ensureClone();const e=Ki.create(this.changeID.next(),this.clone.root,this.clone.presences.get(this.changeID.getActorID())||{});return sg(e,this.clone.root.getObject())}garbageCollect(e){return this.opts.disableGC?0:(this.clone&&this.clone.root.garbageCollect(e),this.root.garbageCollect(e))}getRootObject(){return this.root.getObject()}getGarbageLen(){return this.root.getGarbageLen()}getGarbageLenFromClone(){return this.clone.root.getGarbageLen()}toJSON(){return this.root.toJSON()}toSortedJSON(){return this.root.toSortedJSON()}getStats(){return this.root.getStats()}toJSForTest(){return{...this.getRoot().toJSForTest(),key:"root"}}applySnapshot(e,t,r){const{root:i,presences:s}=fe.bytesToSnapshot(r);this.root=new ko(i),this.presences=s,this.changeID=this.changeID.setClocks(e,t),this.clone=void 0,this.publish([{type:"snapshot",source:Y.Remote,value:{serverSeq:e.toString(),snapshot:this.isEnableDevtools()?fe.bytesToHex(r):void 0,snapshotVector:fe.versionVectorToHex(t)}}])}applyChanges(e,t){J.isEnabled(be.Debug)&&J.debug(`trying to apply ${e.length} remote changes.elements:${this.root.getElementMapSize()}, removeds:${this.root.getGarbageElementSetSize()}`),J.isEnabled(be.Trivial)&&J.trivial(e.map(r=>`${r.getID().toTestString()} ${r.toTestString()}`).join(` + */var wt=null;try{wt=new WebAssembly.Instance(new WebAssembly.Module(new Uint8Array([0,97,115,109,1,0,0,0,1,13,2,96,0,1,127,96,4,127,127,127,127,1,127,3,7,6,0,1,1,1,1,1,6,6,1,127,1,65,0,11,7,50,6,3,109,117,108,0,1,5,100,105,118,95,115,0,2,5,100,105,118,95,117,0,3,5,114,101,109,95,115,0,4,5,114,101,109,95,117,0,5,8,103,101,116,95,104,105,103,104,0,0,10,191,1,6,4,0,35,0,11,36,1,1,126,32,0,173,32,1,173,66,32,134,132,32,2,173,32,3,173,66,32,134,132,126,34,4,66,32,135,167,36,0,32,4,167,11,36,1,1,126,32,0,173,32,1,173,66,32,134,132,32,2,173,32,3,173,66,32,134,132,127,34,4,66,32,135,167,36,0,32,4,167,11,36,1,1,126,32,0,173,32,1,173,66,32,134,132,32,2,173,32,3,173,66,32,134,132,128,34,4,66,32,135,167,36,0,32,4,167,11,36,1,1,126,32,0,173,32,1,173,66,32,134,132,32,2,173,32,3,173,66,32,134,132,129,34,4,66,32,135,167,36,0,32,4,167,11,36,1,1,126,32,0,173,32,1,173,66,32,134,132,32,2,173,32,3,173,66,32,134,132,130,34,4,66,32,135,167,36,0,32,4,167,11])),{}).exports}catch{}function q(n,e,t){this.low=n|0,this.high=e|0,this.unsigned=!!t}q.prototype.__isLong__;Object.defineProperty(q.prototype,"__isLong__",{value:!0});function Re(n){return(n&&n.__isLong__)===!0}function Yh(n){var e=Math.clz32(n&-n);return n?31-e:e}q.isLong=Re;var Qh={},Xh={};function Ci(n,e){var t,r,i;return e?(n>>>=0,(i=0<=n&&n<256)&&(r=Xh[n],r)?r:(t=W(n,0,!0),i&&(Xh[n]=t),t)):(n|=0,(i=-128<=n&&n<128)&&(r=Qh[n],r)?r:(t=W(n,n<0?-1:0,!1),i&&(Qh[n]=t),t))}q.fromInt=Ci;function St(n,e){if(isNaN(n))return e?hr:Ot;if(e){if(n<0)return hr;if(n>=ty)return iy}else{if(n<=-eg)return je;if(n+1>=eg)return ry}return n<0?St(-n,e).neg():W(n%ds|0,n/ds|0,e)}q.fromNumber=St;function W(n,e,t){return new q(n,e,t)}q.fromBits=W;var hl=Math.pow;function _f(n,e,t){if(n.length===0)throw Error("empty string");if(typeof e=="number"?(t=e,e=!1):e=!!e,n==="NaN"||n==="Infinity"||n==="+Infinity"||n==="-Infinity")return e?hr:Ot;if(t=t||10,t<2||360)throw Error("interior hyphen");if(r===0)return _f(n.substring(1),e,t).neg();for(var i=St(hl(t,8)),s=Ot,o=0;o>>0:this.low};C.toNumber=function(){return this.unsigned?(this.high>>>0)*ds+(this.low>>>0):this.high*ds+(this.low>>>0)};C.toString=function(e){if(e=e||10,e<2||36>>0,d=c.toString(e);if(o=l,o.isZero())return d+a;for(;d.length<6;)d="0"+d;a=""+d+a}};C.getHighBits=function(){return this.high};C.getHighBitsUnsigned=function(){return this.high>>>0};C.getLowBits=function(){return this.low};C.getLowBitsUnsigned=function(){return this.low>>>0};C.getNumBitsAbs=function(){if(this.isNegative())return this.eq(je)?64:this.neg().getNumBitsAbs();for(var e=this.high!=0?this.high:this.low,t=31;t>0&&!(e&1<=0};C.isOdd=function(){return(this.low&1)===1};C.isEven=function(){return(this.low&1)===0};C.equals=function(e){return Re(e)||(e=$t(e)),this.unsigned!==e.unsigned&&this.high>>>31===1&&e.high>>>31===1?!1:this.high===e.high&&this.low===e.low};C.eq=C.equals;C.notEquals=function(e){return!this.eq(e)};C.neq=C.notEquals;C.ne=C.notEquals;C.lessThan=function(e){return this.comp(e)<0};C.lt=C.lessThan;C.lessThanOrEqual=function(e){return this.comp(e)<=0};C.lte=C.lessThanOrEqual;C.le=C.lessThanOrEqual;C.greaterThan=function(e){return this.comp(e)>0};C.gt=C.greaterThan;C.greaterThanOrEqual=function(e){return this.comp(e)>=0};C.gte=C.greaterThanOrEqual;C.ge=C.greaterThanOrEqual;C.compare=function(e){if(Re(e)||(e=$t(e)),this.eq(e))return 0;var t=this.isNegative(),r=e.isNegative();return t&&!r?-1:!t&&r?1:this.unsigned?e.high>>>0>this.high>>>0||e.high===this.high&&e.low>>>0>this.low>>>0?-1:1:this.sub(e).isNegative()?-1:1};C.comp=C.compare;C.negate=function(){return!this.unsigned&&this.eq(je)?je:this.not().add(qi)};C.neg=C.negate;C.add=function(e){Re(e)||(e=$t(e));var t=this.high>>>16,r=this.high&65535,i=this.low>>>16,s=this.low&65535,o=e.high>>>16,a=e.high&65535,l=e.low>>>16,c=e.low&65535,d=0,h=0,p=0,m=0;return m+=s+c,p+=m>>>16,m&=65535,p+=i+l,h+=p>>>16,p&=65535,h+=r+a,d+=h>>>16,h&=65535,d+=t+o,d&=65535,W(p<<16|m,d<<16|h,this.unsigned)};C.subtract=function(e){return Re(e)||(e=$t(e)),this.add(e.neg())};C.sub=C.subtract;C.multiply=function(e){if(this.isZero())return this;if(Re(e)||(e=$t(e)),wt){var t=wt.mul(this.low,this.high,e.low,e.high);return W(t,wt.get_high(),this.unsigned)}if(e.isZero())return this.unsigned?hr:Ot;if(this.eq(je))return e.isOdd()?je:Ot;if(e.eq(je))return this.isOdd()?je:Ot;if(this.isNegative())return e.isNegative()?this.neg().mul(e.neg()):this.neg().mul(e).neg();if(e.isNegative())return this.mul(e.neg()).neg();if(this.lt(tg)&&e.lt(tg))return St(this.toNumber()*e.toNumber(),this.unsigned);var r=this.high>>>16,i=this.high&65535,s=this.low>>>16,o=this.low&65535,a=e.high>>>16,l=e.high&65535,c=e.low>>>16,d=e.low&65535,h=0,p=0,m=0,w=0;return w+=o*d,m+=w>>>16,w&=65535,m+=s*d,p+=m>>>16,m&=65535,m+=o*c,p+=m>>>16,m&=65535,p+=i*d,h+=p>>>16,p&=65535,p+=s*c,h+=p>>>16,p&=65535,p+=o*l,h+=p>>>16,p&=65535,h+=r*d+i*c+s*l+o*a,h&=65535,W(m<<16|w,h<<16|p,this.unsigned)};C.mul=C.multiply;C.divide=function(e){if(Re(e)||(e=$t(e)),e.isZero())throw Error("division by zero");if(wt){if(!this.unsigned&&this.high===-2147483648&&e.low===-1&&e.high===-1)return this;var t=(this.unsigned?wt.div_u:wt.div_s)(this.low,this.high,e.low,e.high);return W(t,wt.get_high(),this.unsigned)}if(this.isZero())return this.unsigned?hr:Ot;var r,i,s;if(this.unsigned){if(e.unsigned||(e=e.toUnsigned()),e.gt(this))return hr;if(e.gt(this.shru(1)))return ny;s=hr}else{if(this.eq(je)){if(e.eq(qi)||e.eq(jc))return je;if(e.eq(je))return qi;var o=this.shr(1);return r=o.div(e).shl(1),r.eq(Ot)?e.isNegative()?qi:jc:(i=this.sub(e.mul(r)),s=r.add(i.div(e)),s)}else if(e.eq(je))return this.unsigned?hr:Ot;if(this.isNegative())return e.isNegative()?this.neg().div(e.neg()):this.neg().div(e).neg();if(e.isNegative())return this.div(e.neg()).neg();s=Ot}for(i=this;i.gte(e);){r=Math.max(1,Math.floor(i.toNumber()/e.toNumber()));for(var a=Math.ceil(Math.log(r)/Math.LN2),l=a<=48?1:hl(2,a-48),c=St(r),d=c.mul(e);d.isNegative()||d.gt(i);)r-=l,c=St(r,this.unsigned),d=c.mul(e);c.isZero()&&(c=qi),s=s.add(c),i=i.sub(d)}return s};C.div=C.divide;C.modulo=function(e){if(Re(e)||(e=$t(e)),wt){var t=(this.unsigned?wt.rem_u:wt.rem_s)(this.low,this.high,e.low,e.high);return W(t,wt.get_high(),this.unsigned)}return this.sub(this.div(e).mul(e))};C.mod=C.modulo;C.rem=C.modulo;C.not=function(){return W(~this.low,~this.high,this.unsigned)};C.countLeadingZeros=function(){return this.high?Math.clz32(this.high):Math.clz32(this.low)+32};C.clz=C.countLeadingZeros;C.countTrailingZeros=function(){return this.low?Yh(this.low):Yh(this.high)+32};C.ctz=C.countTrailingZeros;C.and=function(e){return Re(e)||(e=$t(e)),W(this.low&e.low,this.high&e.high,this.unsigned)};C.or=function(e){return Re(e)||(e=$t(e)),W(this.low|e.low,this.high|e.high,this.unsigned)};C.xor=function(e){return Re(e)||(e=$t(e)),W(this.low^e.low,this.high^e.high,this.unsigned)};C.shiftLeft=function(e){return Re(e)&&(e=e.toInt()),(e&=63)===0?this:e<32?W(this.low<>>32-e,this.unsigned):W(0,this.low<>>e|this.high<<32-e,this.high>>e,this.unsigned):W(this.high>>e-32,this.high>=0?0:-1,this.unsigned)};C.shr=C.shiftRight;C.shiftRightUnsigned=function(e){return Re(e)&&(e=e.toInt()),(e&=63)===0?this:e<32?W(this.low>>>e|this.high<<32-e,this.high>>>e,this.unsigned):e===32?W(this.high,0,this.unsigned):W(this.high>>>e-32,0,this.unsigned)};C.shru=C.shiftRightUnsigned;C.shr_u=C.shiftRightUnsigned;C.rotateLeft=function(e){var t;return Re(e)&&(e=e.toInt()),(e&=63)===0?this:e===32?W(this.high,this.low,this.unsigned):e<32?(t=32-e,W(this.low<>>t,this.high<>>t,this.unsigned)):(e-=32,t=32-e,W(this.high<>>t,this.low<>>t,this.unsigned))};C.rotl=C.rotateLeft;C.rotateRight=function(e){var t;return Re(e)&&(e=e.toInt()),(e&=63)===0?this:e===32?W(this.high,this.low,this.unsigned):e<32?(t=32-e,W(this.high<>>e,this.low<>>e,this.unsigned)):(e-=32,t=32-e,W(this.low<>>e,this.high<>>e,this.unsigned))};C.rotr=C.rotateRight;C.toSigned=function(){return this.unsigned?W(this.low,this.high,!1):this};C.toUnsigned=function(){return this.unsigned?this:W(this.low,this.high,!0)};C.toBytes=function(e){return e?this.toBytesLE():this.toBytesBE()};C.toBytesLE=function(){var e=this.high,t=this.low;return[t&255,t>>>8&255,t>>>16&255,t>>>24,e&255,e>>>8&255,e>>>16&255,e>>>24]};C.toBytesBE=function(){var e=this.high,t=this.low;return[e>>>24,e>>>16&255,e>>>8&255,e&255,t>>>24,t>>>16&255,t>>>8&255,t&255]};q.fromBytes=function(e,t,r){return r?q.fromBytesLE(e,t):q.fromBytesBE(e,t)};q.fromBytesLE=function(e,t){return new q(e[0]|e[1]<<8|e[2]<<16|e[3]<<24,e[4]|e[5]<<8|e[6]<<16|e[7]<<24,t)};q.fromBytesBE=function(e,t){return new q(e[4]<<24|e[5]<<16|e[6]<<8|e[7],e[0]<<24|e[1]<<16|e[2]<<8|e[3],t)};var ve=(n=>(n[n.Null=0]="Null",n[n.Boolean=1]="Boolean",n[n.Integer=2]="Integer",n[n.Long=3]="Long",n[n.Double=4]="Double",n[n.String=5]="String",n[n.Bytes=6]="Bytes",n[n.Date=7]="Date",n))(ve||{});class ie extends No{constructor(t,r){super(r);u(this,"valueType");u(this,"value");this.valueType=ie.getPrimitiveType(t),this.value=t===void 0?null:t}static of(t,r){return new ie(t,r)}static valueFromBytes(t,r){switch(t){case 0:return null;case 1:return!!r[0];case 2:return r[0]|r[1]<<8|r[2]<<16|r[3]<<24;case 4:{const i=new DataView(r.buffer);return r.forEach(function(s,o){i.setUint8(o,s)}),i.getFloat64(0,!0)}case 5:return new TextDecoder("utf-8").decode(r);case 3:return q.fromBytesLE(Array.from(r));case 6:return r;case 7:return new Date(q.fromBytesLE(Array.from(r),!0).toNumber());default:throw new k(S.ErrUnimplemented,`unimplemented type: ${t}`)}}toJSON(){return this.valueType===5?`"${en(this.value)}"`:`${this.value}`}toSortedJSON(){return this.toJSON()}toJSForTest(){return{createdAt:this.getCreatedAt().toTestString(),value:this.value,type:"YORKIE_PRIMITIVE"}}deepcopy(){const t=ie.of(this.value,this.getCreatedAt());return t.setMovedAt(this.getMovedAt()),t.setRemovedAt(this.getRemovedAt()),t}getType(){return this.valueType}static getPrimitiveType(t){switch(typeof t){case"undefined":return 0;case"boolean":return 1;case"number":return this.isInteger(t)?2:4;case"string":return 5;case"object":if(t===null)return 0;if(t instanceof q)return 3;if(t instanceof Uint8Array)return 6;if(t instanceof Date)return 7}}static isSupport(t){return ie.getPrimitiveType(t)!==void 0}static isInteger(t){return t%1===0}isNumericType(){const t=this.valueType;return t===2||t===3||t===4}getValue(){return this.value}toBytes(){switch(this.valueType){case 0:return new Uint8Array;case 1:return this.value?new Uint8Array([1]):new Uint8Array([0]);case 2:{const t=this.value;return new Uint8Array([t&255,t>>8&255,t>>16&255,t>>24&255])}case 4:{const t=this.value,r=new Uint8Array(8);return new DataView(r.buffer).setFloat64(0,t,!0),r}case 5:return new TextEncoder().encode(this.value);case 3:{const r=this.value.toBytesLE();return Uint8Array.from(r)}case 6:return this.value;case 7:{const t=this.value,r=q.fromNumber(t.getTime(),!0).toBytesLE();return Uint8Array.from(r)}default:throw new k(S.ErrUnimplemented,`unimplemented type: ${this.valueType}`)}}}class gl extends ey{constructor(t){super(t);u(this,"prev");u(this,"next");this.value=t}static createAfter(t,r){const i=new gl(r),s=t.next;return t.next=i,i.prev=t,i.next=s,s&&(s.prev=i),i}remove(t){return this.value.remove(t)}getCreatedAt(){return this.value.getCreatedAt()}getPositionedAt(){return this.value.getPositionedAt()}release(){this.prev&&(this.prev.next=this.next),this.next&&(this.next.prev=this.prev),this.prev=void 0,this.next=void 0}getLength(){return this.value.isRemoved()?0:1}getPrev(){return this.prev}getNext(){return this.next}getValue(){return this.value}isRemoved(){return this.value.isRemoved()}}class wo{constructor(){u(this,"dummyHead");u(this,"last");u(this,"nodeMapByIndex");u(this,"nodeMapByCreatedAt");const e=ie.of(0,bt);e.setRemovedAt(bt),this.dummyHead=new gl(e),this.last=this.dummyHead,this.nodeMapByIndex=new vo,this.nodeMapByCreatedAt=new Map,this.nodeMapByIndex.insert(this.dummyHead),this.nodeMapByCreatedAt.set(this.dummyHead.getCreatedAt().toIDString(),this.dummyHead)}static create(){return new wo}get length(){return this.nodeMapByIndex.length}findNextBeforeExecutedAt(e,t){let r=this.nodeMapByCreatedAt.get(e.toIDString());if(!r)throw new k(S.ErrInvalidArgument,`cant find the given node: ${e.toIDString()}`);for(;r.getNext()&&r.getNext().getPositionedAt().after(t);)r=r.getNext();return r}release(e){this.last===e&&(this.last=e.getPrev()),e.release(),this.nodeMapByIndex.delete(e),this.nodeMapByCreatedAt.delete(e.getValue().getCreatedAt().toIDString())}insertAfter(e,t,r=t.getCreatedAt()){const i=this.findNextBeforeExecutedAt(e,r),s=gl.createAfter(i,t);i===this.last&&(this.last=s),this.nodeMapByIndex.insertAfter(i,s),this.nodeMapByCreatedAt.set(s.getCreatedAt().toIDString(),s)}moveAfter(e,t,r){const i=this.nodeMapByCreatedAt.get(e.toIDString());if(!i)throw new k(S.ErrInvalidArgument,`cant find the given node: ${e.toIDString()}`);const s=this.nodeMapByCreatedAt.get(t.toIDString());if(!s)throw new k(S.ErrInvalidArgument,`cant find the given node: ${t.toIDString()}`);i!==s&&(!s.getValue().getMovedAt()||r.after(s.getValue().getMovedAt()))&&(this.release(s),this.insertAfter(i.getCreatedAt(),s.getValue(),r),s.getValue().setMovedAt(r))}insert(e){this.insertAfter(this.last.getCreatedAt(),e)}getByID(e){return this.nodeMapByCreatedAt.get(e.toIDString())}subPathOf(e){const t=this.nodeMapByCreatedAt.get(e.toIDString());if(t)return String(this.nodeMapByIndex.indexOf(t))}purge(e){const t=this.nodeMapByCreatedAt.get(e.getCreatedAt().toIDString());if(!t)throw new k(S.ErrInvalidArgument,`fail to find the given createdAt: ${e.getCreatedAt().toIDString()}`);this.release(t)}getByIndex(e){if(e>=this.length)return;const[t,r]=this.nodeMapByIndex.find(e);let i=t;if(e===0&&t===this.dummyHead||r>0)do i&&(i=i.getNext());while(i&&i.isRemoved());return i}getPrevCreatedAt(e){let t=this.nodeMapByCreatedAt.get(e.toIDString());do t=t.getPrev();while(this.dummyHead!==t&&t.isRemoved());return t.getValue().getCreatedAt()}delete(e,t){const r=this.nodeMapByCreatedAt.get(e.toIDString()),i=r.isRemoved();return r.remove(t)&&!i&&this.nodeMapByIndex.splayNode(r),r.getValue()}deleteByIndex(e,t){const r=this.getByIndex(e);if(r)return r.remove(t)&&this.nodeMapByIndex.splayNode(r),r.getValue()}getHead(){return this.dummyHead.getValue()}getLast(){return this.last.getValue()}getLastCreatedAt(){return this.last.getCreatedAt()}toTestString(){const e=[];for(const t of this){const r=`${t.getCreatedAt().toIDString()}:${t.getValue().toJSON()}`;t.isRemoved()?e.push(`{${r}}`):e.push(`[${r}]`)}return e.join("")}*[Symbol.iterator](){let e=this.dummyHead.getNext();for(;e;)yield e,e=e.getNext()}}class tt extends Wr{constructor(t,r){super(t);u(this,"elements");this.elements=r}static create(t,r){if(!r)return new tt(t,wo.create());const i=wo.create();for(const s of r)i.insertAfter(i.getLastCreatedAt(),s.deepcopy());return new tt(t,i)}subPathOf(t){return this.elements.subPathOf(t)}purge(t){this.elements.purge(t)}insertAfter(t,r){this.elements.insertAfter(t,r)}moveAfter(t,r,i){this.elements.moveAfter(t,r,i)}get(t){const r=this.elements.getByIndex(t);return r==null?void 0:r.getValue()}getByID(t){const r=this.elements.getByID(t);return r==null?void 0:r.getValue()}getHead(){return this.elements.getHead()}getLast(){return this.elements.getLast()}getPrevCreatedAt(t){return this.elements.getPrevCreatedAt(t)}delete(t,r){return this.elements.delete(t,r)}deleteByIndex(t,r){return this.elements.deleteByIndex(t,r)}getLastCreatedAt(){return this.elements.getLastCreatedAt()}get length(){return this.elements.length}*[Symbol.iterator](){for(const t of this.elements)t.isRemoved()||(yield t.getValue())}toTestString(){return this.elements.toTestString()}getDescendants(t){for(const r of this.elements){const i=r.getValue();if(t(i,this))return;i instanceof Wr&&i.getDescendants(t)}}toJSON(){const t=[];for(const r of this)t.push(r.toJSON());return`[${t.join(",")}]`}toJS(){return JSON.parse(this.toJSON())}toJSForTest(){const t={};for(let r=0;r({...m,value:m.value?{attributes:Xi(m.value.getAttributes()),content:m.value.getContent()}:{attributes:void 0,content:""},type:"content"}));return[c,p,d,[l,l]]}setStyle(t,r,i,s){const[,o]=this.rgaTreeSplit.findNodeWithSplit(t[1],i),[,a]=this.rgaTreeSplit.findNodeWithSplit(t[0],i),l=[],c=this.rgaTreeSplit.findBetween(a,o),d=new Map,h=[];for(const m of c){const w=m.getCreatedAt().getActorID(),I=s!=null&&s.size?s.has(w)?s.get(w):bt:Ws;if(m.canStyle(i,I)){const O=d.get(w),y=m.getCreatedAt();(!O||y.after(O))&&d.set(w,y),h.push(m)}}const p=[];for(const m of h){if(m.isRemoved())continue;const[w,I]=this.rgaTreeSplit.findIndexesFromRange(m.createPosRange());l.push({type:"style",actor:i.getActorID(),from:w,to:I,value:{attributes:Xi(r)}});for(const[O,y]of Object.entries(r)){const[g]=m.getValue().setAttr(O,y,i);g!==void 0&&p.push({parent:m.getValue(),child:g})}}return[d,p,l]}indexRangeToPosRange(t,r){const i=this.rgaTreeSplit.indexToPos(t);return t===r?[i,i]:[i,this.rgaTreeSplit.indexToPos(r)]}get length(){return this.rgaTreeSplit.length}getTreeByIndex(){return this.rgaTreeSplit.getTreeByIndex()}getTreeByID(){return this.rgaTreeSplit.getTreeByID()}toJSON(){const t=[];for(const r of this.rgaTreeSplit)r.isRemoved()||t.push(r.getValue().toJSON());return`[${t.join(",")}]`}toSortedJSON(){return this.toJSON()}toJSForTest(){return{createdAt:this.getCreatedAt().toTestString(),value:JSON.parse(this.toJSON()),type:"YORKIE_TEXT"}}toString(){return this.rgaTreeSplit.toString()}values(){const t=[];for(const r of this.rgaTreeSplit)if(!r.isRemoved()){const i=r.getValue();t.push({attributes:Xi(i.getAttributes()),content:i.getContent()})}return t}getRGATreeSplit(){return this.rgaTreeSplit}toTestString(){return this.rgaTreeSplit.toTestString()}deepcopy(){const t=new It(this.rgaTreeSplit.deepcopy(),this.getCreatedAt());return t.remove(this.getRemovedAt()),t}findIndexesFromRange(t){return this.rgaTreeSplit.findIndexesFromRange(t)}getGCPairs(){const t=[];for(const r of this.rgaTreeSplit){r.getRemovedAt()&&t.push({parent:this.rgaTreeSplit,child:r});for(const i of r.getValue().getGCPairs())t.push(i)}return t}}class Do extends Jt{constructor(t,r,i,s,o,a,l){super(t,l);u(this,"fromPos");u(this,"toPos");u(this,"maxCreatedAtMapByActor");u(this,"content");u(this,"attributes");this.fromPos=r,this.toPos=i,this.maxCreatedAtMapByActor=s,this.content=o,this.attributes=a}static create(t,r,i,s,o,a,l){return new Do(t,r,i,s,o,a,l)}execute(t){const r=t.findByCreatedAt(this.getParentCreatedAt());if(!r)throw new k(S.ErrInvalidArgument,`fail to find ${this.getParentCreatedAt()}`);if(!(r instanceof It))throw new k(S.ErrInvalidArgument,"fail to execute, only Text can execute edit");const i=r,[,s,o]=i.edit([this.fromPos,this.toPos],this.content,this.getExecutedAt(),Object.fromEntries(this.attributes),this.maxCreatedAtMapByActor);for(const a of o)t.registerGCPair(a);return{opInfos:s.map(({from:a,to:l,value:c})=>({type:"edit",from:a,to:l,value:c,path:t.createPath(this.getParentCreatedAt())}))}}getEffectedCreatedAt(){return this.getParentCreatedAt()}toTestString(){const t=this.getParentCreatedAt().toTestString(),r=this.fromPos.toTestString(),i=this.toPos.toTestString(),s=this.content;return`${t}.EDIT(${r},${i},${s})`}getFromPos(){return this.fromPos}getToPos(){return this.toPos}getContent(){return this.content}getAttributes(){return this.attributes||new Map}getMaxCreatedAtMapByActor(){return this.maxCreatedAtMapByActor}}class Oo extends Jt{constructor(t,r,i,s,o,a){super(t,a);u(this,"fromPos");u(this,"toPos");u(this,"maxCreatedAtMapByActor");u(this,"attributes");this.fromPos=r,this.toPos=i,this.maxCreatedAtMapByActor=s,this.attributes=o}static create(t,r,i,s,o,a){return new Oo(t,r,i,s,o,a)}execute(t){const r=t.findByCreatedAt(this.getParentCreatedAt());if(!r)throw new k(S.ErrInvalidArgument,`fail to find ${this.getParentCreatedAt()}`);if(!(r instanceof It))throw new k(S.ErrInvalidArgument,"fail to execute, only Text can execute edit");const i=r,[,s,o]=i.setStyle([this.fromPos,this.toPos],this.attributes?Object.fromEntries(this.attributes):{},this.getExecutedAt(),this.maxCreatedAtMapByActor);for(const a of s)t.registerGCPair(a);return{opInfos:o.map(({from:a,to:l,value:c})=>({type:"style",from:a,to:l,value:c,path:t.createPath(this.getParentCreatedAt())}))}}getEffectedCreatedAt(){return this.getParentCreatedAt()}toTestString(){const t=this.getParentCreatedAt().toTestString(),r=this.fromPos.toTestString(),i=this.toPos.toTestString(),s=this.attributes;return`${t}.STYL(${r},${i},${JSON.stringify(s)})`}getFromPos(){return this.fromPos}getToPos(){return this.toPos}getAttributes(){return this.attributes}getMaxCreatedAtMapByActor(){return this.maxCreatedAtMapByActor}}const z1=2,U1="root",mr="text";function Ds(n,e){let t=0;const r=n.children;for(let i=0;i0)throw new k(S.ErrRefused,"Text node cannot have children")}updateAncestorsSize(){let e=this.parent;const t=this.isRemoved?-1:1;for(;e&&(e.size+=this.paddedSize*t,!e.isRemoved);)e=e.parent}updateDescendantsSize(){let e=0;for(const t of this._children){const r=t.updateDescendantsSize();t.isRemoved||(e+=r)}return this.size+=e,this.paddedSize}get isText(){return this.type===mr}get paddedSize(){return this.size+(this.isText?0:z1)}isAncestorOf(e){return V1(this,e)}get nextSibling(){const e=this.parent.findOffset(this),t=this.parent.children[e+1];if(t)return t}get prevSibling(){const e=this.parent.findOffset(this),t=this.parent.children[e-1];if(t)return t}splitText(e,t){if(e===0||e===this.size)return;const r=this.value.slice(0,e),i=this.value.slice(e);if(!i.length)return;this.value=r;const s=this.cloneText(e+t);return s.value=i,this.parent.insertAfterInternal(s,this),s}get children(){return this._children.filter(e=>!e.isRemoved)}get allChildren(){return[...this._children]}hasTextChild(){return this.children.length>0&&this.children.every(e=>e.isText)}append(...e){if(this.isText)throw new k(S.ErrRefused,"Text node cannot have children");this._children.push(...e);for(const t of e)t.parent=this,t.updateAncestorsSize()}prepend(...e){if(this.isText)throw new k(S.ErrRefused,"Text node cannot have children");this._children.unshift(...e);for(const t of e)t.parent=this}insertBefore(e,t){if(this.isText)throw new k(S.ErrRefused,"Text node cannot have children");const r=this._children.indexOf(t);if(r===-1)throw new k(S.ErrInvalidArgument,"child not found");this.insertAtInternal(e,r),e.updateAncestorsSize()}insertAfter(e,t){if(this.isText)throw new k(S.ErrRefused,"Text node cannot have children");const r=this._children.indexOf(t);if(r===-1)throw new k(S.ErrInvalidArgument,"child not found");this.insertAtInternal(e,r+1),e.updateAncestorsSize()}insertAt(e,t){if(this.isText)throw new k(S.ErrRefused,"Text node cannot have children");this.insertAtInternal(e,t),e.updateAncestorsSize()}removeChild(e){if(this.isText)throw new k(S.ErrRefused,"Text node cannot have children");const t=this._children.indexOf(e);if(t===-1)throw new k(S.ErrInvalidArgument,"child not found");this._children.splice(t,1),e.parent=void 0}splitElement(e,t){const r=this.cloneElement(t);this.parent.insertAfterInternal(r,this),r.updateAncestorsSize();const i=this.children.slice(0,e),s=this.children.slice(e);this._children=i,r._children=s,this.size=this._children.reduce((o,a)=>o+a.paddedSize,0),r.size=r._children.reduce((o,a)=>o+a.paddedSize,0);for(const o of r._children)o.parent=r;return r}insertAfterInternal(e,t){if(this.isText)throw new k(S.ErrRefused,"Text node cannot have children");const r=this._children.indexOf(t);if(r===-1)throw new k(S.ErrInvalidArgument,"child not found");this.insertAtInternal(e,r+1)}insertAtInternal(e,t){if(this.isText)throw new k(S.ErrRefused,"Text node cannot have children");this._children.splice(t,0,e),e.parent=this}findOffset(e){if(this.isText)throw new k(S.ErrRefused,"Text node cannot have children");if(e.isRemoved){const t=this._children.indexOf(e);return this.allChildren.splice(0,t).filter(i=>!i.isRemoved).length}return this.children.indexOf(e)}findBranchOffset(e){if(this.isText)throw new k(S.ErrRefused,"Text node cannot have children");let t=e;for(;t;){const r=this._children.indexOf(t);if(r!==-1)return r;t=t.parent}return-1}}function V1(n,e){if(n===e)return!1;for(;e.parent;){if(e.parent===n)return!0;e=e.parent}return!1}var ge=(n=>(n.Start="Start",n.End="End",n.Text="Text",n))(ge||{});function sy(n,e,t,r){if(e>t)throw new k(S.ErrInvalidArgument,`from is greater than to: ${e} > ${t}`);if(e>n.size)throw new k(S.ErrInvalidArgument,`from is out of range: ${e} > ${n.size}`);if(t>n.size)throw new k(S.ErrInvalidArgument,`to is out of range: ${t} > ${n.size}`);if(e===t)return;let i=0;for(const s of n.children){if(e-s.paddedSizes.size;(s.isText||l)&&r([s,s.isText?"Text":"Start"],c),sy(s,Math.max(0,o),Math.min(a,s.size),r),c&&r([s,"End"],c)}i+=s.paddedSize}}function oy(n,e,t=0){for(const r of n.children)oy(r,e,t+1);e(n,t)}function Fl(n,e,t=0){for(const r of n._children)Fl(r,e,t+1);e(n,t)}function Vc(n,e,t=!0){if(e>n.size)throw new k(S.ErrInvalidArgument,`index is out of range: ${e} > ${n.size}`);if(n.isText)return{node:n,offset:e};let r=0,i=0;for(const s of n.children){if(t&&s.isText&&s.size>=e-i)return Vc(s,e-i,t);if(e===i)return{node:n,offset:r};if(!t&&s.paddedSize===e-i)return{node:n,offset:r+1};if(s.paddedSize>e-i)return Vc(s,e-i-1,t);i+=s.paddedSize,r+=1}return{node:n,offset:r}}function ay(n){return n.isText||n.children.length===0?n:ay(n.children[0])}function q1(n,e){if(n.sizen===e?0:n0)if(t.right)t.right.parent=t,t=t.right;else return t;else if(r<0)if(t.left)t.left.parent=t,t=t.left;else{let i=t.parent,s=t;for(;i&&s===i.left;)s=i,i=i.parent;return i}else return t}}lastEntry(){if(!this.root)return this.root;let e=this.root;for(;e.right;)e=e.right;return e}size(){return this.counter}isEmpty(){return this.counter===0}getInternal(e,t){for(;t;){const r=this.comparator(e,t.key);if(r===0)return t;r<0?t=t.left:r>0&&(t=t.right)}}putInternal(e,t,r){if(!r)return this.counter+=1,new H1(e,t,!0);const i=this.comparator(e,r.key);return i<0?r.left=this.putInternal(e,t,r.left):i>0?r.right=this.putInternal(e,t,r.right):r.value=t,this.isRed(r.right)&&!this.isRed(r.left)&&(r=this.rotateLeft(r)),this.isRed(r.left)&&this.isRed(r.left.left)&&(r=this.rotateRight(r)),this.isRed(r.left)&&this.isRed(r.right)&&this.flipColors(r),r}removeInternal(e,t){if(this.comparator(t,e.key)<0)!this.isRed(e.left)&&!this.isRed(e.left.left)&&(e=this.moveRedLeft(e)),e.left=this.removeInternal(e.left,t);else{if(this.isRed(e.left)&&(e=this.rotateRight(e)),this.comparator(t,e.key)===0&&!e.right){this.counter-=1;return}if(!this.isRed(e.right)&&!this.isRed(e.right.left)&&(e=this.moveRedRight(e)),this.comparator(t,e.key)===0){this.counter-=1;const r=this.min(e.right);e.value=r.value,e.key=r.key,e.right=this.removeMin(e.right)}else e.right=this.removeInternal(e.right,t)}return this.fixUp(e)}min(e){return e.left?this.min(e.left):e}removeMin(e){if(e.left)return!this.isRed(e.left)&&!this.isRed(e.left.left)&&(e=this.moveRedLeft(e)),e.left=this.removeMin(e.left),this.fixUp(e)}fixUp(e){return this.isRed(e.right)&&(e=this.rotateLeft(e)),this.isRed(e.left)&&this.isRed(e.left.left)&&(e=this.rotateRight(e)),this.isRed(e.left)&&this.isRed(e.right)&&this.flipColors(e),e}moveRedLeft(e){return this.flipColors(e),this.isRed(e.right.left)&&(e.right=this.rotateRight(e.right),e=this.rotateLeft(e),this.flipColors(e)),e}moveRedRight(e){return this.flipColors(e),this.isRed(e.left.left)&&(e=this.rotateRight(e),this.flipColors(e)),e}isRed(e){return e&&e.isRed}rotateLeft(e){const t=e.right;return e.right=t.left,t.left=e,t.isRed=t.left.isRed,t.left.isRed=!0,t}rotateRight(e){const t=e.left;return e.left=t.right,t.right=e,t.isRed=t.right.isRed,t.right.isRed=!0,t}flipColors(e){e.isRed=!e.isRed,e.left.isRed=!e.left.isRed,e.right.isRed=!e.right.isRed}}class Rt{constructor(e,t){u(this,"parentID");u(this,"leftSiblingID");this.parentID=e,this.leftSiblingID=t}static of(e,t){return new Rt(e,t)}static fromTreePos(e){const{offset:t}=e;let{node:r}=e,i;return r.isText?(r.parent.children[0]===r&&t===0?i=r.parent:i=r,r=r.parent):t===0?i=r:i=r.children[t-1],Rt.of(r.id,Ee.of(i.getCreatedAt(),i.getOffset()+t))}getParentID(){return this.parentID}static fromStruct(e){return Rt.of(Ee.of(et.fromStruct(e.parentID.createdAt),e.parentID.offset),Ee.of(et.fromStruct(e.leftSiblingID.createdAt),e.leftSiblingID.offset))}toStruct(){return{parentID:{createdAt:this.getParentID().getCreatedAt().toStruct(),offset:this.getParentID().getOffset()},leftSiblingID:{createdAt:this.getLeftSiblingID().getCreatedAt().toStruct(),offset:this.getLeftSiblingID().getOffset()}}}toTreeNodePair(e){const t=this.getParentID(),r=this.getLeftSiblingID(),i=e.findFloorNode(t);let s=e.findFloorNode(r);if(!i||!s)throw new k(S.ErrRefused,`cannot find node of CRDTTreePos(${t.toTestString()}, ${r.toTestString()})`);return!r.equals(t)&&r.getOffset()>0&&r.getOffset()===s.id.getOffset()&&s.insPrevID&&(s=e.findFloorNode(s.insPrevID)),[i,s]}getLeftSiblingID(){return this.leftSiblingID}equals(e){return this.getParentID().getCreatedAt().equals(e.getParentID().getCreatedAt())&&this.getParentID().getOffset()===e.getParentID().getOffset()&&this.getLeftSiblingID().getCreatedAt().equals(e.getLeftSiblingID().getCreatedAt())&&this.getLeftSiblingID().getOffset()===e.getLeftSiblingID().getOffset()}}class Ee{constructor(e,t){u(this,"createdAt");u(this,"offset");this.createdAt=e,this.offset=t}static of(e,t){return new Ee(e,t)}static fromStruct(e){return Ee.of(et.fromStruct(e.createdAt),e.offset)}static createComparator(){return(e,t)=>{const r=e.getCreatedAt().compare(t.getCreatedAt());return r!==0?r:e.getOffset()>t.getOffset()?1:e.getOffset(){const s=i.deepcopy();return s.parent=t,s}),t.insPrevID=this.insPrevID,t.insNextID=this.insNextID,t}get value(){if(!this.isText)throw new k(S.ErrInvalidType,`cannot get value of element node: ${this.type}`);return this._value}set value(t){if(!this.isText)throw new k(S.ErrInvalidType,`cannot set value of element node: ${this.type}`);this._value=t,this.size=t.length}get isRemoved(){return!!this.removedAt}remove(t){const r=!this.removedAt;(!this.removedAt||this.removedAt.compare(t)>0)&&(this.removedAt=t),r&&this.updateAncestorsSize()}cloneText(t){return new Xe(Ee.of(this.id.getCreatedAt(),t),this.type,void 0,void 0,this.removedAt)}cloneElement(t){return new Xe(Ee.of(t(),0),this.type,void 0,void 0,this.removedAt)}split(t,r,i){const s=this.isText?this.splitText(r,this.id.getOffset()):this.splitElement(r,i);if(s){if(s.insPrevID=this.id,this.insNextID){const o=t.findFloorNode(this.insNextID);o.insPrevID=s.id,s.insNextID=this.insNextID}this.insNextID=s.id,t.registerNode(s)}return s}getCreatedAt(){return this.id.getCreatedAt()}getOffset(){return this.id.getOffset()}canDelete(t,r){return!this.getCreatedAt().after(r)&&(!this.removedAt||t.after(this.removedAt))}canStyle(t,r){return this.isText?!1:!this.getCreatedAt().after(r)&&(!this.removedAt||t.after(this.removedAt))}setAttrs(t,r){this.attrs||(this.attrs=new Tr);const i=new Array;for(const[s,o]of Object.entries(t))i.push(this.attrs.set(s,o,r));return i}purge(t){this.attrs&&this.attrs.purge(t)}getGCPairs(){const t=[];if(!this.attrs)return t;for(const r of this.attrs)r.getRemovedAt()&&t.push({parent:this,child:r});return t}}function qc(n){var t;if(n.isText){const r=n;return{type:r.type,value:r.value}}const e={type:n.type,children:n.children.map(qc)};return n.attrs&&(e.attributes=Xi((t=n.attrs)==null?void 0:t.toObject())),e}function Gf(n){if(n.isText)return n.value;let e="";return n.attrs&&n.attrs.size()&&(e=" "+Array.from(n.attrs).filter(t=>!t.isRemoved()).sort((t,r)=>t.getKey().localeCompare(r.getKey())).map(t=>{const r=JSON.parse(t.getValue());return typeof r=="string"?`${t.getKey()}="${r}"`:`${t.getKey()}="${en(t.getValue())}"`}).join(" ")),`<${n.type}${e}>${n.children.map(t=>Gf(t)).join("")}`}function uy(n){if(n.isText){const e=n;return{type:e.type,value:e.value,size:e.size,isRemoved:e.isRemoved}}return{type:n.type,children:n.children.map(uy),size:n.size,isRemoved:n.isRemoved}}class Et extends No{constructor(t,r){super(r);u(this,"indexTree");u(this,"nodeMapByID");this.indexTree=new K1(t),this.nodeMapByID=new ly(Ee.createComparator()),this.indexTree.traverseAll(i=>{this.nodeMapByID.put(i.id,i)})}static create(t,r){return new Et(t,r)}findFloorNode(t){const r=this.nodeMapByID.floorEntry(t);if(!(!r||!r.key.getCreatedAt().equals(t.getCreatedAt())))return r.value}registerNode(t){this.nodeMapByID.put(t.id,t)}findNodesAndSplitText(t,r){const[i,s]=t.toTreeNodePair(this);let o=s;const a=i===o,l=o.parent&&!a?o.parent:i;if(o.isText&&o.split(this,t.getLeftSiblingID().getOffset()-o.id.getOffset()),r){const c=l.allChildren,d=a?0:c.indexOf(o)+1;for(let h=d;h{const I=w.getCreatedAt().getActorID(),O=s?s.has(I)?s.get(I):bt:Ws;if(w.canStyle(i,O)&&r){const y=p.get(I),g=w.getCreatedAt();(!y||g.after(y))&&p.set(I,g);const v=w.setAttrs(r,i),T=v.reduce((P,[,B])=>(B&&(P[B.getKey()]=h[B.getKey()]),P),{}),x=w.parent,N=w.prevSibling||w.parent;Object.keys(T).length>0&&d.push({type:"style",from:this.toIndex(x,N),to:this.toIndex(w,w),fromPath:this.toPath(x,N),toPath:this.toPath(w,w),actor:i.getActorID(),value:T});for(const[P]of v)P&&m.push({parent:w,child:P})}}),[p,m,d]}removeStyle(t,r,i,s){const[o,a]=this.findNodesAndSplitText(t[0],i),[l,c]=this.findNodesAndSplitText(t[1],i),d=[],h=new Map,p=[];return this.traverseInPosRange(o,a,l,c,([m])=>{const w=m.getCreatedAt().getActorID(),I=s?s.has(w)?s.get(w):bt:Ws;if(m.canStyle(i,I)&&r){const O=h.get(w),y=m.getCreatedAt();(!O||y.after(O))&&h.set(w,y),m.attrs||(m.attrs=new Tr);for(const T of r){const x=m.attrs.remove(T,i);for(const N of x)p.push({parent:m,child:N})}const g=m.parent,v=m.prevSibling||m.parent;d.push({actor:i.getActorID(),type:"removeStyle",from:this.toIndex(g,v),to:this.toIndex(m,m),fromPath:this.toPath(g,v),toPath:this.toPath(m,m),value:r})}}),[h,p,d]}edit(t,r,i,s,o,a){const[l,c]=this.findNodesAndSplitText(t[0],s),[d,h]=this.findNodesAndSplitText(t[1],s),p=this.toIndex(l,c),m=this.toPath(l,c),w=[],I=[],O=[],y=new Map;this.traverseInPosRange(l,c,d,h,([T,x],N)=>{if(x===ge.Start&&!N)for(const H of T.children)O.push(H);const P=T.getCreatedAt().getActorID(),B=a?a.has(P)?a.get(P):bt:Ws;if(T.canDelete(s,B)||w.includes(T.parent)){const H=y.get(P),U=T.getCreatedAt();(!H||U.after(H))&&y.set(P,U),(x===ge.Text||x===ge.Start)&&w.push(T),I.push([T,x])}});const g=this.makeDeletionChanges(I,s),v=[];for(const T of w)T.remove(s),T.isRemoved&&v.push({parent:this,child:T});for(const T of O)T.removedAt||l.append(T);if(i>0){let T=0,x=l,N=c;for(;T{l.isRemoved&&(P.remove(s),v.push({parent:this,child:P})),this.nodeMapByID.put(P.id,P)}),N.isRemoved||T.push(N);if(T.length){const N=T.map(P=>qc(P));g.length&&g[g.length-1].from===p?g[g.length-1].value=N:g.push({type:"content",from:p,to:p,fromPath:m,toPath:m,actor:s.getActorID(),value:N})}}return[g,v,y]}editT(t,r,i,s,o){const a=this.findPos(t[0]),l=this.findPos(t[1]);this.edit([a,l],r,i,s,o)}move(t,r,i){throw new k(S.ErrUnimplemented,`not implemented: ${t}, ${r}, ${i}`)}purge(t){var s;(s=t.parent)==null||s.removeChild(t),this.nodeMapByID.remove(t.id);const r=t.insPrevID,i=t.insNextID;if(r){const o=this.findFloorNode(r);o.insNextID=i}if(i){const o=this.findFloorNode(i);o.insPrevID=r}t.insPrevID=void 0,t.insNextID=void 0}getGCPairs(){const t=[];return this.indexTree.traverse(r=>{r.getRemovedAt()&&t.push({parent:this,child:r});for(const i of r.getGCPairs())t.push(i)}),t}findPos(t,r=!0){const i=this.indexTree.findTreePos(t,r);return Rt.fromTreePos(i)}pathToPosRange(t){const r=this.pathToIndex(t);return[this.findPos(r),this.findPos(r+1)]}pathToPos(t){const r=this.indexTree.pathToIndex(t);return this.findPos(r)}getRoot(){return this.indexTree.getRoot()}getSize(){return this.indexTree.size}getNodeSize(){return this.nodeMapByID.size()}getIndexTree(){return this.indexTree}toXML(){return Gf(this.indexTree.getRoot())}toJSON(){return JSON.stringify(this.getRootTreeNode())}toJSForTest(){return{createdAt:this.getCreatedAt().toTestString(),value:JSON.parse(this.toJSON()),type:"YORKIE_TREE"}}toJSInfoForTest(){const t=this.indexTree.getRoot(),r=(i,s=void 0,o=void 0,a=0)=>{var m,w,I,O;let l,c,d;const h=i.isText?{node:i,offset:0}:s&&o?this.toTreePos(s,o):null;h&&(l=this.indexTree.indexOf(h),c=this.indexTree.treePosToPath(h),d=Rt.fromTreePos(h).toStruct());const p={type:i.type,parent:s==null?void 0:s.id.toTestString(),size:i.size,id:i.id.toTestString(),removedAt:(m=i.removedAt)==null?void 0:m.toTestString(),insPrev:(w=i.insPrevID)==null?void 0:w.toTestString(),insNext:(I=i.insNextID)==null?void 0:I.toTestString(),value:i.isText?i.value:void 0,isRemoved:i.isRemoved,children:[],depth:a,attributes:i.attrs?Xi((O=i.attrs)==null?void 0:O.toObject()):void 0,index:l,path:c,pos:d};for(let y=0;y0&&y===i[i.length-1].to?(i[i.length-1].to=g,i[i.length-1].toPath=this.toPath(O,m)):i.push({type:"content",from:y,to:g,fromPath:this.toPath(I,h),toPath:this.toPath(O,m),actor:r.getActorID()}))}return i.reverse()}findRightToken([t,r]){if(r===ge.Start){const l=t.allChildren;return l.length>0?[l[0],l[0].isText?ge.Text:ge.Start]:[t,ge.End]}const i=t.parent,s=i.allChildren,o=s.indexOf(t);if(i&&o===s.length-1)return[i,ge.End];const a=s[o+1];return[a,a.isText?ge.Text:ge.Start]}findLeftToken([t,r]){if(r===ge.End){const l=t.allChildren;if(l.length>0){const c=l[l.length-1];return[c,c.isText?ge.Text:ge.End]}return[t,ge.Start]}const i=t.parent,s=i.allChildren,o=s.indexOf(t);if(i&&o===0)return[i,ge.Start];const a=s[o-1];return[a,a.isText?ge.Text:ge.End]}}class Ro extends Jt{constructor(t,r,i,s,o,a,l){super(t,l);u(this,"fromPos");u(this,"toPos");u(this,"contents");u(this,"splitLevel");u(this,"maxCreatedAtMapByActor");this.fromPos=r,this.toPos=i,this.contents=s,this.splitLevel=o,this.maxCreatedAtMapByActor=a}static create(t,r,i,s,o,a,l){return new Ro(t,r,i,s,o,a,l)}execute(t){var l;const r=t.findByCreatedAt(this.getParentCreatedAt());if(!r)throw new k(S.ErrInvalidArgument,`fail to find ${this.getParentCreatedAt()}`);if(!(r instanceof Et))throw new k(S.ErrInvalidArgument,"fail to execute, only Tree can execute edit");const i=this.getExecutedAt(),s=r,[o,a]=s.edit([this.fromPos,this.toPos],(l=this.contents)==null?void 0:l.map(c=>c.deepcopy()),this.splitLevel,i,(()=>{let c=i.getDelimiter();return this.contents!==void 0&&(c+=this.contents.length),()=>et.of(i.getLamport(),++c,i.getActorID())})(),this.maxCreatedAtMapByActor);for(const c of a)t.registerGCPair(c);return{opInfos:o.map(({from:c,to:d,value:h,splitLevel:p,fromPath:m,toPath:w})=>({type:"tree-edit",path:t.createPath(this.getParentCreatedAt()),from:c,to:d,value:h,splitLevel:p,fromPath:m,toPath:w}))}}getEffectedCreatedAt(){return this.getParentCreatedAt()}toTestString(){const t=this.getParentCreatedAt().toTestString(),r=`${this.fromPos.getLeftSiblingID().getCreatedAt().toTestString()}/${this.fromPos.getLeftSiblingID().getOffset()}`,i=`${this.toPos.getLeftSiblingID().getCreatedAt().toTestString()}/${this.toPos.getLeftSiblingID().getOffset()}`,s=this.contents||[];return`${t}.EDIT(${r},${i},${s.map(o=>Gf(o)).join("")})`}getFromPos(){return this.fromPos}getToPos(){return this.toPos}getContents(){return this.contents}getSplitLevel(){return this.splitLevel}getMaxCreatedAtMapByActor(){return this.maxCreatedAtMapByActor}}class Zi{constructor(e){u(this,"vector");this.vector=e||new Map}set(e,t){this.vector.set(e,t)}get(e){return this.vector.get(e)}maxLamport(){let e=BigInt(0);for(const[,t]of this)t>e&&(e=t);return e}max(e){const t=new Map;for(const[r,i]of e){const s=this.vector.get(r),o=s&&s>i?s:i;t.set(r,o)}for(const[r,i]of this){const s=e.get(r),o=s&&s>i?s:i;t.set(r,o)}return new Zi(t)}afterOrEqual(e){const t=this.vector.get(e.getActorID());return t===void 0?!1:t>=e.getLamport()}deepcopy(){const e=new Map;for(const[t,r]of this.vector)e.set(t,r);return new Zi(e)}filter(e){const t=new Map;for(const[r]of e){const i=this.vector.get(r);i!==void 0&&t.set(r,i)}return new Zi(t)}size(){return this.vector.size}*[Symbol.iterator](){for(const[e,t]of this.vector)yield[e,t]}}const G1=new Zi(new Map);class ar{constructor(e,t,r,i,s){u(this,"clientSeq");u(this,"serverSeq");u(this,"lamport");u(this,"actor");u(this,"versionVector");this.clientSeq=e,this.serverSeq=s,this.lamport=t,this.versionVector=i,this.actor=r}static of(e,t,r,i,s){return new ar(e,t,r,i,s)}next(){const e=this.versionVector.deepcopy();return e.set(this.actor,this.lamport+1n),new ar(this.clientSeq+1,this.lamport+1n,this.actor,e)}syncClocks(e){const t=e.lamport>this.lamport?e.lamport+1n:this.lamport+1n,r=this.versionVector.max(e.versionVector),i=new ar(this.clientSeq,t,this.actor,r);return i.versionVector.set(this.actor,t),i}setClocks(e,t){const r=e>this.lamport?e:this.lamport+1n,i=this.versionVector.max(t);return i.set(this.actor,r),ar.of(this.clientSeq,r,this.actor,i)}createTimeTicket(e){return et.of(this.lamport,e,this.actor)}setActor(e){return new ar(this.clientSeq,this.lamport,e,this.versionVector,this.serverSeq)}setVersionVector(e){return new ar(this.clientSeq,this.lamport,this.actor,e,this.serverSeq)}getClientSeq(){return this.clientSeq}getServerSeq(){return this.serverSeq?this.serverSeq.toString():""}getLamport(){return this.lamport}getLamportAsString(){return this.lamport.toString()}getActorID(){return this.actor}getVersionVector(){return this.versionVector}toTestString(){return`${this.lamport.toString()}:${this.actor.slice(-2)}:${this.clientSeq}`}}const Y1=new ar(0,0n,Wf,G1);class hs{constructor({id:e,operations:t,presenceChange:r,message:i}){u(this,"id");u(this,"operations");u(this,"presenceChange");u(this,"message");this.id=e,this.operations=t||[],this.presenceChange=r,this.message=i}static create({id:e,operations:t,presenceChange:r,message:i}){return new hs({id:e,operations:t,presenceChange:r,message:i})}getID(){return this.id}getMessage(){return this.message}hasOperations(){return this.operations.length>0}getOperations(){return this.operations}setActor(e){for(const t of this.operations)t.setActor(e);this.id=this.id.setActor(e)}hasPresenceChange(){return this.presenceChange!==void 0}getPresenceChange(){return this.presenceChange}execute(e,t,r){const i=[],s=[];for(const o of this.operations){const a=o.execute(e,r);if(!a)continue;const{opInfos:l,reverseOp:c}=a;i.push(...l),c&&s.unshift(c)}return this.presenceChange&&(this.presenceChange.type===Qr.Put?t.set(this.id.getActorID(),Nt(this.presenceChange.presence)):t.delete(this.id.getActorID())),{opInfos:i,reverseOps:s}}toTestString(){return`${this.operations.map(e=>e.toTestString()).join(",")}`}toStruct(){return{changeID:fe.bytesToHex(fe.toChangeID(this.getID()).toBinary()),message:this.getMessage(),operations:this.getOperations().map(e=>fe.bytesToHex(fe.toOperation(e).toBinary())),presenceChange:this.getPresenceChange()}}static fromStruct(e){const{changeID:t,operations:r,presenceChange:i,message:s}=e;return hs.create({id:fe.bytesToChangeID(fe.hexToBytes(t)),operations:r==null?void 0:r.map(o=>fe.bytesToOperation(fe.hexToBytes(o))),presenceChange:i,message:s})}}class Ml{constructor(e,t,r,i,s,o,a){u(this,"documentKey");u(this,"checkpoint");u(this,"isRemoved");u(this,"changes");u(this,"snapshot");u(this,"minSyncedTicket");u(this,"versionVector");this.documentKey=e,this.checkpoint=t,this.isRemoved=r,this.changes=i,this.snapshot=o,this.minSyncedTicket=a,this.versionVector=s}static create(e,t,r,i,s,o,a){return new Ml(e,t,r,i,s,o,a)}getDocumentKey(){return this.documentKey}getCheckpoint(){return this.checkpoint}getIsRemoved(){return this.isRemoved}getChanges(){return this.changes}hasChanges(){return this.changes.length>0}getChangeSize(){return this.changes.length}hasSnapshot(){return!!this.snapshot&&!!this.snapshot.length}getSnapshot(){return this.snapshot}getMinSyncedTicket(){return this.minSyncedTicket}getVersionVector(){return this.versionVector}}class es{constructor(e,t){u(this,"serverSeq");u(this,"clientSeq");this.serverSeq=e,this.clientSeq=t}static of(e,t){return new es(e,t)}increaseClientSeq(e){return e===0?this:new es(this.serverSeq,this.clientSeq+e)}forward(e){if(this.equals(e))return this;const t=this.serverSeq>e.serverSeq?this.serverSeq:e.serverSeq,r=Math.max(this.clientSeq,e.clientSeq);return es.of(t,r)}getServerSeqAsString(){return this.serverSeq.toString()}getClientSeq(){return this.clientSeq}getServerSeq(){return this.serverSeq}equals(e){return this.clientSeq===e.clientSeq&&this.serverSeq==e.serverSeq}toTestString(){return`serverSeq=${this.serverSeq}, clientSeq=${this.clientSeq}`}}const Q1=new es(0n,0);class rn{constructor(e,t){u(this,"createdAt");u(this,"offset");this.createdAt=e,this.offset=t}static of(e,t){return new rn(e,t)}static fromStruct(e){return rn.of(et.fromStruct(e.createdAt),e.offset)}getCreatedAt(){return this.createdAt}getOffset(){return this.offset}equals(e){return this.createdAt.compare(e.createdAt)===0&&this.offset===e.offset}hasSameCreatedAt(e){return this.createdAt.compare(e.createdAt)===0}split(e){return new rn(this.createdAt,this.offset+e)}toStruct(){return{createdAt:this.createdAt.toStruct(),offset:this.offset}}toTestString(){return`${this.createdAt.toTestString()}:${this.offset}`}toIDString(){return`${this.createdAt.toIDString()}:${this.offset}`}}const X1=rn.of(bt,0);class Ft{constructor(e,t){u(this,"id");u(this,"relativeOffset");this.id=e,this.relativeOffset=t}static of(e,t){return new Ft(e,t)}static fromStruct(e){const t=rn.fromStruct(e.id);return Ft.of(t,e.relativeOffset)}getID(){return this.id}getRelativeOffset(){return this.relativeOffset}getAbsoluteID(){return rn.of(this.id.getCreatedAt(),this.id.getOffset()+this.relativeOffset)}toTestString(){return`${this.id.toTestString()}:${this.relativeOffset}`}toStruct(){return{id:this.id.toStruct(),relativeOffset:this.relativeOffset}}equals(e){return this.id.equals(e.id)?this.relativeOffset===e.relativeOffset:!1}}class Hr extends ey{constructor(t,r,i){super(r);u(this,"id");u(this,"removedAt");u(this,"prev");u(this,"next");u(this,"insPrev");u(this,"insNext");this.id=t,this.removedAt=i}static create(t,r){return new Hr(t,r)}static createComparator(){return(t,r)=>{const i=t.getCreatedAt().compare(r.getCreatedAt());return i!==0?i:t.getOffset()>r.getOffset()?1:t.getOffset()0&&t.getID().getOffset()==e.getOffset()){if(!t.hasInsPrev())return t;t=t.getInsPrev()}return t}findFloorNode(e){const t=this.treeByID.floorEntry(e);if(t&&!(!t.key.equals(e)&&!t.key.hasSameCreatedAt(e)))return t.value}findBetween(e,t){const r=[];let i=e;for(;i&&i!==t;)r.push(i),i=i.getNext();return r}splitNode(e,t){if(t>e.getContentLength())throw new k(S.ErrInvalidArgument,"offset should be less than or equal to length");if(t===0)return e;if(t===e.getContentLength())return e.getNext();const r=e.split(t);this.treeByIndex.updateWeight(r),this.insertAfter(e,r);const i=e.getInsNext();return i&&i.setInsPrev(r),r.setInsPrev(e),r}deleteNodes(e,t,r){if(!e.length)return[[],new Map,new Map];const[i,s]=this.filterNodes(e,t,r),o=new Map,a=new Map,l=this.makeChanges(s,t);for(const c of i){const d=c.getCreatedAt().getActorID();(!o.has(d)||c.getID().getCreatedAt().after(o.get(d)))&&o.set(d,c.getID().getCreatedAt()),a.set(c.getID().toIDString(),c),c.remove(t)}return this.deleteIndexNodes(s),[l,o,a]}filterNodes(e,t,r){const i=!!r,s=[],o=[],[a,l]=this.findEdgesOfCandidates(e);o.push(a);for(const c of e){const d=c.getCreatedAt().getActorID(),h=i?r.has(d)?r.get(d):bt:Ws;c.canDelete(t,h)?s.push(c):o.push(c)}return o.push(l),[s,o]}findEdgesOfCandidates(e){return[e[0].getPrev(),e[e.length-1].getNext()]}makeChanges(e,t){const r=[];let i,s;for(let o=0;on<0?Math.ceil(n):Math.floor(n);var sn=(n=>(n[n.IntegerCnt=0]="IntegerCnt",n[n.LongCnt=1]="LongCnt",n))(sn||{});class nt extends No{constructor(t,r,i){super(i);u(this,"valueType");u(this,"value");switch(this.valueType=t,t){case 0:typeof r=="number"?r>Math.pow(2,31)-1||r<-Math.pow(2,31)?this.value=q.fromNumber(r).toInt():this.value=ng(r):this.value=r.toInt();break;case 1:typeof r=="number"?this.value=q.fromNumber(r):this.value=r;break;default:throw new k(S.ErrUnimplemented,`unimplemented type: ${t}`)}}static create(t,r,i){return new nt(t,r,i)}static valueFromBytes(t,r){switch(t){case 0:return r[0]|r[1]<<8|r[2]<<16|r[3]<<24;case 1:return q.fromBytesLE(Array.from(r));default:throw new k(S.ErrUnimplemented,`unimplemented type: ${t}`)}}toJSON(){return`${this.value}`}toSortedJSON(){return this.toJSON()}toJSForTest(){return{createdAt:this.getCreatedAt().toTestString(),value:this.value,type:"YORKIE_COUNTER"}}deepcopy(){const t=nt.create(this.valueType,this.value,this.getCreatedAt());return t.setMovedAt(this.getMovedAt()),t}getType(){return this.valueType}static getCounterType(t){switch(typeof t){case"object":return t instanceof q?1:void 0;case"number":return t>Math.pow(2,31)-1||t<-Math.pow(2,31)?1:0;default:return}}static isSupport(t){return!!nt.getCounterType(t)}static isInteger(t){return t%1===0}isNumericType(){const t=this.valueType;return t===0||t===1}getValueType(){return this.valueType}getValue(){return this.value}toBytes(){switch(this.valueType){case 0:{const t=this.value;return new Uint8Array([t&255,t>>8&255,t>>16&255,t>>24&255])}case 1:{const r=this.value.toBytesLE();return Uint8Array.from(r)}default:throw new k(S.ErrUnimplemented,`unimplemented type: ${this.valueType}`)}}increase(t){function r(i){if(!i.isNumericType())throw new TypeError(`Unsupported type of value: ${typeof i.getValue()}`)}return r(this),r(t),this.valueType===1?this.value=this.value.add(t.getValue()):t.getType()===ve.Long?this.value=this.value+t.getValue().toInt():this.value=q.fromNumber(this.value+ng(t.getValue())).toInt(),this}}class ms extends Jt{constructor(t,r,i){super(t,i);u(this,"value");this.value=r}static create(t,r,i){return new ms(t,r,i)}execute(t){const r=t.findByCreatedAt(this.getParentCreatedAt());if(!r)throw new k(S.ErrInvalidArgument,`fail to find ${this.getParentCreatedAt()}`);if(!(r instanceof nt))throw new k(S.ErrInvalidArgument,"fail to execute, only Counter can execute increase");const i=r,s=this.value.deepcopy();return i.increase(s),{opInfos:[{type:"increase",path:t.createPath(this.getParentCreatedAt()),value:s.getValue()}],reverseOp:this.toReverseOperation()}}toReverseOperation(){const t=this.value.deepcopy(),i=t.getType()===ve.Long?t.getValue().multiply(-1):t.getValue()*-1;return ms.create(this.getParentCreatedAt(),ie.of(i,t.getCreatedAt()))}getEffectedCreatedAt(){return this.getParentCreatedAt()}toTestString(){return`${this.getParentCreatedAt().toTestString()}.INCREASE.${this.value.toJSON()}`}getValue(){return this.value}}class pr extends Jt{constructor(t,r,i,s,o,a,l){super(t,l);u(this,"fromPos");u(this,"toPos");u(this,"maxCreatedAtMapByActor");u(this,"attributes");u(this,"attributesToRemove");this.fromPos=r,this.toPos=i,this.maxCreatedAtMapByActor=s,this.attributes=o,this.attributesToRemove=a}static create(t,r,i,s,o,a){return new pr(t,r,i,s,o,new Array,a)}static createTreeRemoveStyleOperation(t,r,i,s,o,a){return new pr(t,r,i,s,new Map,o,a)}execute(t){const r=t.findByCreatedAt(this.getParentCreatedAt());if(!r)throw new k(S.ErrInvalidArgument,`fail to find ${this.getParentCreatedAt()}`);if(!(r instanceof Et))throw new k(S.ErrInvalidArgument,"fail to execute, only Tree can execute edit");const i=r;let s,o;if(this.attributes.size){const a={};[...this.attributes].forEach(([l,c])=>a[l]=c),[,o,s]=i.style([this.fromPos,this.toPos],a,this.getExecutedAt(),this.maxCreatedAtMapByActor)}else{const a=this.attributesToRemove;[,o,s]=i.removeStyle([this.fromPos,this.toPos],a,this.getExecutedAt(),this.maxCreatedAtMapByActor)}for(const a of o)t.registerGCPair(a);return{opInfos:s.map(({from:a,to:l,value:c,fromPath:d,toPath:h})=>({type:"tree-style",from:a,to:l,value:this.attributes.size?{attributes:c}:{attributesToRemove:c},fromPath:d,toPath:h,path:t.createPath(this.getParentCreatedAt())}))}}getEffectedCreatedAt(){return this.getParentCreatedAt()}toTestString(){const t=this.getParentCreatedAt().toTestString(),r=`${this.fromPos.getLeftSiblingID().getCreatedAt().toTestString()}:${this.fromPos.getLeftSiblingID().getOffset()}`,i=`${this.toPos.getLeftSiblingID().getCreatedAt().toTestString()}:${this.toPos.getLeftSiblingID().getOffset()}`;return`${t}.STYLE(${r},${i},${Object.entries(this.attributes||{}).map(([s,o])=>`${s}:"${o}"`).join(" ")})`}getFromPos(){return this.fromPos}getToPos(){return this.toPos}getAttributes(){return this.attributes}getAttributesToRemove(){return this.attributesToRemove}getMaxCreatedAtMapByActor(){return this.maxCreatedAtMapByActor}}function Z1(n){const e=new Kf,t=e.data;for(const[r,i]of Object.entries(n))t[r]=JSON.stringify(i);return e}function eS(n){if(n.type===Qr.Put)return new po({type:Ai.PUT,presence:Z1(n.presence)});if(n.type===Qr.Clear)return new po({type:Ai.CLEAR});throw new k(S.ErrUnimplemented,"unimplemented type")}function tS(n){return new Qp({serverSeq:n.getServerSeq(),clientSeq:n.getClientSeq()})}function cy(n){return new Bl({clientSeq:n.getClientSeq(),lamport:n.getLamport(),actorId:od(n.getActorID()),versionVector:Yf(n.getVersionVector())})}function F(n){if(n)return new b({lamport:n.getLamport(),delimiter:n.getDelimiter(),actorId:od(n.getActorID())})}function Yf(n){if(!n)return;const e=new bl;for(const[t,r]of n)e.vector[t]=BigInt(r.toString());return e}function fy(n){switch(n){case ve.Null:return $.NULL;case ve.Boolean:return $.BOOLEAN;case ve.Integer:return $.INTEGER;case ve.Long:return $.LONG;case ve.Double:return $.DOUBLE;case ve.String:return $.STRING;case ve.Bytes:return $.BYTES;case ve.Date:return $.DATE;default:throw new k(S.ErrInvalidType,`unsupported type: ${n}`)}}function dy(n){switch(n){case sn.IntegerCnt:return $.INTEGER_CNT;case sn.LongCnt:return $.LONG_CNT;default:throw new k(S.ErrInvalidType,`unsupported type: ${n}`)}}function ku(n){if(n instanceof We)return new lt({type:$.JSON_OBJECT,createdAt:F(n.getCreatedAt()),value:Ey(n)});if(n instanceof tt)return new lt({type:$.JSON_ARRAY,createdAt:F(n.getCreatedAt()),value:RS(n)});if(n instanceof It)return new lt({type:$.TEXT,createdAt:F(n.getCreatedAt())});if(n instanceof ie)return new lt({type:fy(n.getType()),createdAt:F(n.getCreatedAt()),value:n.toBytes()});if(n instanceof nt)return new lt({type:dy(n.getType()),createdAt:F(n.getCreatedAt()),value:n.toBytes()});if(n instanceof Et)return new lt({type:$.TREE,createdAt:F(n.getCreatedAt()),value:BS(n)});throw new k(S.ErrUnimplemented,"unimplemented element")}function nS(n){return new go({createdAt:F(n.getCreatedAt()),offset:n.getOffset()})}function Zo(n){return new kr({createdAt:F(n.getID().getCreatedAt()),offset:n.getID().getOffset(),relativeOffset:n.getRelativeOffset()})}function ea(n){return new Ti({parentId:Hs(n.getParentID()),leftSiblingId:Hs(n.getLeftSiblingID())})}function Hs(n){return new Kr({createdAt:F(n.getCreatedAt()),offset:n.getOffset()})}function hy(n){const e=new qf;if(n instanceof Ii){const t=n,r=new Ga;r.parentCreatedAt=F(t.getParentCreatedAt()),r.key=t.getKey(),r.value=ku(t.getValue()),r.executedAt=F(t.getExecutedAt()),e.body.case="set",e.body.value=r}else if(n instanceof Po){const t=n,r=new Ya;r.parentCreatedAt=F(t.getParentCreatedAt()),r.prevCreatedAt=F(t.getPrevCreatedAt()),r.value=ku(t.getValue()),r.executedAt=F(t.getExecutedAt()),e.body.case="add",e.body.value=r}else if(n instanceof br){const t=n,r=new Qa;r.parentCreatedAt=F(t.getParentCreatedAt()),r.prevCreatedAt=F(t.getPrevCreatedAt()),r.createdAt=F(t.getCreatedAt()),r.executedAt=F(t.getExecutedAt()),e.body.case="move",e.body.value=r}else if(n instanceof Xr){const t=n,r=new Xa;r.parentCreatedAt=F(t.getParentCreatedAt()),r.createdAt=F(t.getCreatedAt()),r.executedAt=F(t.getExecutedAt()),e.body.case="remove",e.body.value=r}else if(n instanceof Do){const t=n,r=new Za;r.parentCreatedAt=F(t.getParentCreatedAt()),r.from=Zo(t.getFromPos()),r.to=Zo(t.getToPos());const i=r.createdAtMapByActor;for(const[o,a]of t.getMaxCreatedAtMapByActor())i[o]=F(a);r.content=t.getContent();const s=r.attributes;for(const[o,a]of t.getAttributes())s[o]=a;r.executedAt=F(t.getExecutedAt()),e.body.case="edit",e.body.value=r}else if(n instanceof Oo){const t=n,r=new el;r.parentCreatedAt=F(t.getParentCreatedAt()),r.from=Zo(t.getFromPos()),r.to=Zo(t.getToPos());const i=r.createdAtMapByActor;for(const[o,a]of t.getMaxCreatedAtMapByActor())i[o]=F(a);const s=r.attributes;for(const[o,a]of t.getAttributes())s[o]=a;r.executedAt=F(t.getExecutedAt()),e.body.case="style",e.body.value=r}else if(n instanceof ms){const t=n,r=new tl;r.parentCreatedAt=F(t.getParentCreatedAt()),r.value=ku(t.getValue()),r.executedAt=F(t.getExecutedAt()),e.body.case="increase",e.body.value=r}else if(n instanceof Ro){const t=n,r=new nl,i=r.createdAtMapByActor;for(const[s,o]of t.getMaxCreatedAtMapByActor())i[s]=F(o);r.parentCreatedAt=F(t.getParentCreatedAt()),r.from=ea(t.getFromPos()),r.to=ea(t.getToPos()),r.contents=uS(t.getContents()),r.splitLevel=t.getSplitLevel(),r.executedAt=F(t.getExecutedAt()),e.body.case="treeEdit",e.body.value=r}else if(n instanceof pr){const t=n,r=new rl;r.parentCreatedAt=F(t.getParentCreatedAt()),r.from=ea(t.getFromPos()),r.to=ea(t.getToPos());const i=r.createdAtMapByActor;for(const[o,a]of t.getMaxCreatedAtMapByActor())i[o]=F(a);const s=t.getAttributesToRemove();if(s.length>0)r.attributesToRemove=s;else{const o=r.attributes;for(const[a,l]of t.getAttributes())o[a]=l}r.executedAt=F(t.getExecutedAt()),e.body.case="treeStyle",e.body.value=r}else throw new k(S.ErrUnimplemented,"unimplemented operation");return e}function rS(n){const e=[];for(const t of n)e.push(hy(t));return e}function iS(n){const e=new Gp({id:cy(n.getID()),message:n.getMessage()});return n.hasOperations()&&(e.operations=rS(n.getOperations())),n.hasPresenceChange()&&(e.presenceChange=eS(n.getPresenceChange())),e}function sS(n){const e=[];for(const t of n)e.push(iS(t));return e}function oS(n){const e=[];for(const t of n)e.push(new Yp({key:t.getStrKey(),element:Xf(t.getValue())}));return e}function aS(n){const e=[];for(const t of n)e.push(new cl({element:Xf(t.getValue())}));return e}function lS(n){const e=[];for(const t of n){const r=new fl;r.id=nS(t.getID()),r.value=t.getValue().getContent(),r.removedAt=F(t.getRemovedAt());const i=r.attributes,s=t.getValue().getAttrs();for(const o of s){const a=new cs;a.value=o.getValue(),a.updatedAt=F(o.getUpdatedAt()),i[o.getKey()]=a}e.push(r)}return e}function uS(n){const e=[];if(!n||!n.length)return e;for(const t of n)e.push(new dl({content:Qf(t)}));return e}function cS(n){const e={};for(const t of n)e[t.getKey()]=new cs({value:t.getValue(),updatedAt:F(t.getUpdatedAt()),isRemoved:t.isRemoved()});return e}function Qf(n){if(!n)return[];const e=[];return Fl(n,(t,r)=>{const i=new mo({id:Hs(t.id),type:t.type,removedAt:F(t.removedAt),depth:r});t.isText&&(i.value=t.value),t.insPrevID&&(i.insPrevId=Hs(t.insPrevID)),t.insNextID&&(i.insNextId=Hs(t.insNextID)),t.attrs&&(i.attributes=cS(t.attrs)),e.push(i)}),e}function fS(n){const e=new He;return e.body.case="jsonObject",e.body.value=new il({nodes:oS(n.getRHT()),createdAt:F(n.getCreatedAt()),movedAt:F(n.getMovedAt()),removedAt:F(n.getRemovedAt())}),e}function gy(n){const e=new He;return e.body.case="jsonArray",e.body.value=new sl({nodes:aS(n.getElements()),createdAt:F(n.getCreatedAt()),movedAt:F(n.getMovedAt()),removedAt:F(n.getRemovedAt())}),e}function dS(n){const e=new He;return e.body.case="primitive",e.body.value=new ol({type:fy(n.getType()),value:n.toBytes(),createdAt:F(n.getCreatedAt()),movedAt:F(n.getMovedAt()),removedAt:F(n.getRemovedAt())}),e}function hS(n){const e=new He;return e.body.case="text",e.body.value=new al({nodes:lS(n.getRGATreeSplit()),createdAt:F(n.getCreatedAt()),movedAt:F(n.getMovedAt()),removedAt:F(n.getRemovedAt())}),e}function gS(n){const e=new He;return e.body.case="counter",e.body.value=new ll({type:dy(n.getType()),value:n.toBytes(),createdAt:F(n.getCreatedAt()),movedAt:F(n.getMovedAt()),removedAt:F(n.getRemovedAt())}),e}function my(n){const e=new He;return e.body.case="tree",e.body.value=new ul({nodes:Qf(n.getRoot()),createdAt:F(n.getCreatedAt()),movedAt:F(n.getMovedAt()),removedAt:F(n.getRemovedAt())}),e}function Xf(n){if(n instanceof We)return fS(n);if(n instanceof tt)return gy(n);if(n instanceof ie)return dS(n);if(n instanceof It)return hS(n);if(n instanceof nt)return gS(n);if(n instanceof Et)return my(n);throw new k(S.ErrUnimplemented,"unimplemented element")}function mS(n){return new Ir({documentKey:n.getDocumentKey(),checkpoint:tS(n.getCheckpoint()),isRemoved:n.getIsRemoved(),changes:sS(n.getChanges()),snapshot:n.getSnapshot(),versionVector:Yf(n.getVersionVector()),minSyncedTicket:F(n.getMinSyncedTicket())})}function rg(n){const e=n.findDetails(O1);for(const t of e)if(t.metadata.code)return t.metadata.code;return""}function py(n){return ar.of(n.clientSeq,BigInt(n.lamport),id(n.actorId),Zf(n.versionVector),BigInt(n.serverSeq))}function Zf(n){if(!n)return;const e=new Zi;return Object.entries(n.vector).forEach(([t,r])=>{e.set(t,BigInt(r.toString()))}),e}function M(n){if(n)return et.of(BigInt(n.lamport),n.delimiter,id(n.actorId))}function ed(n){const e={};return Object.entries(n.data).forEach(([t,r])=>{e[t]=JSON.parse(r)}),e}function pS(n){const e=n.type;if(e===Ai.PUT){const t=ed(n.presence);return{type:Qr.Put,presence:t}}if(e===Ai.CLEAR)return{type:Qr.Clear};throw new k(S.ErrInvalidType,`unsupported type: ${e}`)}function yS(n){const e=new Map;return Object.entries(n).forEach(([t,r])=>{e.set(t,ed(r))}),e}function yy(n){switch(n){case $.NULL:return ve.Null;case $.BOOLEAN:return ve.Boolean;case $.INTEGER:return ve.Integer;case $.LONG:return ve.Long;case $.DOUBLE:return ve.Double;case $.STRING:return ve.String;case $.BYTES:return ve.Bytes;case $.DATE:return ve.Date}throw new k(S.ErrUnimplemented,`unimplemented value type: ${n}`)}function ml(n){switch(n){case $.INTEGER_CNT:return sn.IntegerCnt;case $.LONG_CNT:return sn.LongCnt}throw new k(S.ErrUnimplemented,`unimplemented value type: ${n}`)}function Tu(n){switch(n.type){case $.JSON_OBJECT:return n.value?Iy(n.value):We.create(M(n.createdAt));case $.JSON_ARRAY:return n.value?OS(n.value):tt.create(M(n.createdAt));case $.TEXT:return It.create(gs.create(),M(n.createdAt));case $.TREE:return LS(n.value);case $.NULL:case $.BOOLEAN:case $.INTEGER:case $.LONG:case $.DOUBLE:case $.STRING:case $.BYTES:case $.DATE:return ie.of(ie.valueFromBytes(yy(n.type),n.value),M(n.createdAt));case $.INTEGER_CNT:case $.LONG_CNT:return nt.create(ml(n.type),nt.valueFromBytes(ml(n.type),n.value),M(n.createdAt))}}function ta(n){return Ft.of(rn.of(M(n.createdAt),n.offset),n.relativeOffset)}function vy(n){return rn.of(M(n.createdAt),n.offset)}function vS(n){const e=So.create(n.value);Object.entries(n.attributes).forEach(([r,i])=>{e.setAttr(r,i.value,M(i.updatedAt))});const t=Hr.create(vy(n.id),e);return t.remove(M(n.removedAt)),t}function Di(n){return Rt.of(_s(n.parentId),_s(n.leftSiblingId))}function _s(n){return Ee.of(M(n.createdAt),n.offset)}function wS(n){if(!n.length)return;const e=[];return n.forEach(t=>{const r=td(t.content);e.push(r)}),e}function td(n){if(n.length===0)return;const e=[];for(const i of n)e.push(kS(i));const t=e[e.length-1],r=new Map;r.set(n[e.length-1].depth,e[e.length-1]);for(let i=e.length-2;i>=0;i--)r.get(n[i].depth-1).prepend(e[i]),r.set(n[i].depth,e[i]);return t.updateDescendantsSize(),Et.create(t,bt).getRoot()}function SS(n){const e=Tr.create();for(const[t,r]of Object.entries(n))e.setInternal(t,r.value,M(r.updatedAt),r.isRemoved);return e}function kS(n){const e=_s(n.id),t=Xe.create(e,n.type),r=Object.entries(n.attributes);return t.isText?t.value=n.value:r.length&&(t.attrs=SS(n.attributes)),n.insPrevId&&(t.insPrevID=_s(n.insPrevId)),n.insNextId&&(t.insNextID=_s(n.insNextId)),t.removedAt=M(n.removedAt),t}function wy(n){if(n.body.case==="set"){const e=n.body.value;return Ii.create(e.key,Tu(e.value),M(e.parentCreatedAt),M(e.executedAt))}else if(n.body.case==="add"){const e=n.body.value;return Po.create(M(e.parentCreatedAt),M(e.prevCreatedAt),Tu(e.value),M(e.executedAt))}else if(n.body.case==="move"){const e=n.body.value;return br.create(M(e.parentCreatedAt),M(e.prevCreatedAt),M(e.createdAt),M(e.executedAt))}else if(n.body.case==="remove"){const e=n.body.value;return Xr.create(M(e.parentCreatedAt),M(e.createdAt),M(e.executedAt))}else if(n.body.case==="edit"){const e=n.body.value,t=new Map;Object.entries(e.createdAtMapByActor).forEach(([i,s])=>{t.set(i,M(s))});const r=new Map;return Object.entries(e.attributes).forEach(([i,s])=>{r.set(i,s)}),Do.create(M(e.parentCreatedAt),ta(e.from),ta(e.to),t,e.content,r,M(e.executedAt))}else if(n.body.case==="style"){const e=n.body.value,t=new Map;Object.entries(e.createdAtMapByActor).forEach(([i,s])=>{t.set(i,M(s))});const r=new Map;return Object.entries(e.attributes).forEach(([i,s])=>{r.set(i,s)}),Oo.create(M(e.parentCreatedAt),ta(e.from),ta(e.to),t,r,M(e.executedAt))}else{if(n.body.case==="select")return;if(n.body.case==="increase"){const e=n.body.value;return ms.create(M(e.parentCreatedAt),Tu(e.value),M(e.executedAt))}else if(n.body.case==="treeEdit"){const e=n.body.value,t=new Map;return Object.entries(e.createdAtMapByActor).forEach(([r,i])=>{t.set(r,M(i))}),Ro.create(M(e.parentCreatedAt),Di(e.from),Di(e.to),wS(e.contents),e.splitLevel,t,M(e.executedAt))}else if(n.body.case==="treeStyle"){const e=n.body.value,t=new Map,r=e.attributesToRemove,i=new Map;return e!=null&&e.createdAtMapByActor&&Object.entries(e.createdAtMapByActor).forEach(([s,o])=>{i.set(s,M(o))}),(r==null?void 0:r.length)>0?pr.createTreeRemoveStyleOperation(M(e.parentCreatedAt),Di(e.from),Di(e.to),i,r,M(e.executedAt)):(Object.entries(e.attributes).forEach(([s,o])=>{t.set(s,o)}),pr.create(M(e.parentCreatedAt),Di(e.from),Di(e.to),i,t,M(e.executedAt)))}else throw new k(S.ErrUnimplemented,"unimplemented operation")}}function TS(n){const e=[];for(const t of n){const r=wy(t);r&&e.push(r)}return e}function Sy(n){const e=[];for(const t of n)e.push(hs.create({id:py(t.id),operations:TS(t.operations),presenceChange:t.presenceChange?pS(t.presenceChange):void 0,message:t.message}));return e}function AS(n){return es.of(BigInt(n.serverSeq),n.clientSeq)}function IS(n){return Ml.create(n.documentKey,AS(n.checkpoint),n.isRemoved,Sy(n.changes),Zf(n.versionVector),n.snapshot,M(n.minSyncedTicket))}function ky(n){const e=new yo;for(const r of n.nodes){const i=nd(r.element);e.set(r.key,i,i.getPositionedAt())}const t=new We(M(n.createdAt),e);return t.setMovedAt(M(n.movedAt)),t.setRemovedAt(M(n.removedAt)),t}function Ty(n){const e=new wo;for(const r of n.nodes)e.insert(nd(r.element));const t=new tt(M(n.createdAt),e);return t.setMovedAt(M(n.movedAt)),t.setRemovedAt(M(n.removedAt)),t}function ES(n){const e=ie.of(ie.valueFromBytes(yy(n.type),n.value),M(n.createdAt));return e.setMovedAt(M(n.movedAt)),e.setRemovedAt(M(n.removedAt)),e}function xS(n){const e=new gs;let t=e.getHead();for(const i of n.nodes){const s=e.insertAfter(t,vS(i));i.insPrevId&&s.setInsPrev(e.findNode(vy(i.insPrevId))),t=s}const r=new It(e,M(n.createdAt));return r.setMovedAt(M(n.movedAt)),r.setRemovedAt(M(n.removedAt)),r}function CS(n){const e=nt.create(ml(n.type),nt.valueFromBytes(ml(n.type),n.value),M(n.createdAt));return e.setMovedAt(M(n.movedAt)),e.setRemovedAt(M(n.removedAt)),e}function Ay(n){const e=td(n.nodes);return Et.create(e,M(n.createdAt))}function nd(n){if(n.body.case==="jsonObject")return ky(n.body.value);if(n.body.case==="jsonArray")return Ty(n.body.value);if(n.body.case==="primitive")return ES(n.body.value);if(n.body.case==="text")return xS(n.body.value);if(n.body.case==="counter")return CS(n.body.value);if(n.body.case==="tree")return Ay(n.body.value);throw new k(S.ErrUnimplemented,"unimplemented element")}function NS(n){if(!n)return{root:We.create(bt),presences:new Map};const e=wc.fromBinary(n);return{root:nd(e.root),presences:yS(e.presences)}}function PS(n){const e=Yf(n);return rd(e.toBinary())}function DS(n){const e=sd(n),t=bl.fromBinary(e);return Zf(t)}function Iy(n){if(!n)throw new k(S.ErrInvalidArgument,"bytes is empty");const e=He.fromBinary(n);return ky(e.body.value)}function Ey(n){return Xf(n).toBinary()}function OS(n){if(!n)throw new k(S.ErrInvalidArgument,"bytes is empty");const e=He.fromBinary(n);return Ty(e.body.value)}function RS(n){return gy(n).toBinary()}function LS(n){if(!n)throw new k(S.ErrInvalidArgument,"bytes is empty");const e=He.fromBinary(n);return Ay(e.body.value)}function BS(n){return my(n).toBinary()}function rd(n){return n?Array.from(n).map(e=>e.toString(16).padStart(2,"0")).join(""):""}function id(n){return rd(n)}function sd(n){return new Uint8Array(n.match(/.{1,2}/g).map(e=>parseInt(e,16)))}function od(n){return sd(n)}function bS(n){const e=Bl.fromBinary(n);return py(e)}function FS(n){const e=qf.fromBinary(n);return wy(e)}const fe={fromPresence:ed,toChangePack:mS,fromChangePack:IS,fromChanges:Sy,toTreeNodes:Qf,fromTreeNodes:td,objectToBytes:Ey,bytesToObject:Iy,bytesToSnapshot:NS,bytesToHex:rd,hexToBytes:sd,toHexString:id,toUint8Array:od,toOperation:hy,toChangeID:cy,PbChangeID:Bl,bytesToChangeID:bS,bytesToOperation:FS,versionVectorToHex:PS,hexToVersionVector:DS};var be=(n=>(n[n.Trivial=0]="Trivial",n[n.Debug=1]="Debug",n[n.Info=2]="Info",n[n.Warn=3]="Warn",n[n.Error=4]="Error",n[n.Fatal=5]="Fatal",n))(be||{});let oi=3;function xy(n){oi=n}const J={trivial:(...n)=>{oi>0||typeof console<"u"&&console.log("YORKIE T:",...n)},debug:(...n)=>{oi>1||typeof console<"u"&&console.log("YORKIE D:",...n)},info:(...n)=>{oi>2||typeof console<"u"&&console.log("YORKIE I:",...n)},warn:(...n)=>{oi>3||typeof console<"u"&&(typeof console.warn<"u"?console.warn("YORKIE W:",...n):console.log("YORKIE W:",...n))},error:(...n)=>{oi>4||typeof console<"u"&&(typeof console.error<"u"?console.error("YORKIE E:",...n):console.log("YORKIE E:",...n))},fatal:(...n)=>{typeof console<"u"&&(typeof console.error<"u"?console.error("YORKIE F:",...n):console.log("YORKIE F:",...n))},isEnabled:n=>oi<=n};function Cy(){return"xxxxxxxx-xxxx-4xxxy-xxxx-xxxxxxxxxxx".replace(/[xy]/g,n=>{const e=Math.random()*16|0;return(n==="x"?e:e&3|8).toString(16)})}class MS{constructor(e,t,r,i,s){u(this,"reconnectStreamDelay");u(this,"doc");u(this,"docID");u(this,"syncMode");u(this,"remoteChangeEventReceived");u(this,"watchStream");u(this,"watchLoopTimerID");u(this,"watchAbortController");u(this,"unsubscribeBroadcastEvent");this.reconnectStreamDelay=e,this.doc=t,this.docID=r,this.syncMode=i,this.remoteChangeEventReceived=!1,this.unsubscribeBroadcastEvent=s}changeSyncMode(e){this.syncMode=e}needRealtimeSync(){return this.syncMode===Ta.RealtimeSyncOff?!1:this.syncMode===Ta.RealtimePushOnly?this.doc.hasLocalChanges():this.syncMode!==Ta.Manual&&(this.doc.hasLocalChanges()||this.remoteChangeEventReceived)}async runWatchLoop(e){const t=async()=>{if(this.watchStream)return Promise.resolve();this.watchLoopTimerID&&(clearTimeout(this.watchLoopTimerID),this.watchLoopTimerID=void 0);try{[this.watchStream,this.watchAbortController]=await e(()=>{this.watchStream=void 0,this.watchAbortController=void 0,this.watchLoopTimerID=setTimeout(t,this.reconnectStreamDelay)})}catch{}};await t()}cancelWatchStream(){this.watchStream&&this.watchAbortController&&(this.watchAbortController.abort(),this.watchStream=void 0,this.watchAbortController=void 0),clearTimeout(this.watchLoopTimerID),this.watchLoopTimerID=void 0}}const Au=()=>{};class JS{constructor(e){u(this,"finalized",!1);u(this,"observers",[]);u(this,"finalError");try{e(this)}catch(t){this.error(t)}}next(e){this.forEachObserver(t=>{t.next(e)})}error(e){this.forEachObserver(t=>{t.error(e)}),this.close(e)}complete(){this.forEachObserver(e=>{e.complete()}),this.close()}subscribe(e,t,r){let i;if(!e)throw new k(S.ErrInvalidArgument,"missing observer");if(this.finalized)throw new k(S.ErrRefused,"observable is finalized due to previous error");typeof e=="object"?i=e:i={next:e,error:t,complete:r},i.next===void 0&&(i.next=Au),i.error===void 0&&(i.error=Au),i.complete===void 0&&(i.complete=Au);const s=Cy(),o=this.unsubscribeOne.bind(this,s);if(this.observers.push({subscriptionID:s,observer:i}),this.finalized)try{this.finalError?i.error(this.finalError):i.complete()}catch(a){J.warn(a)}return o}unsubscribeOne(e){var t;this.observers=(t=this.observers)==null?void 0:t.filter(r=>r.subscriptionID!==e)}forEachObserver(e){if(!this.finalized)for(let t=0;te}}class Ki{constructor(e,t,r,i){u(this,"id");u(this,"delimiter");u(this,"message");u(this,"root");u(this,"operations");u(this,"presenceChange");u(this,"previousPresence");u(this,"reversePresenceKeys");this.id=e,this.delimiter=Zp,this.root=t,this.operations=[],this.previousPresence=Nt(r),this.presenceChange=void 0,this.reversePresenceKeys=new Set,this.message=i}static create(e,t,r,i){return new Ki(e,t,r,i)}push(e){this.operations.push(e)}registerElement(e,t){this.root.registerElement(e,t)}registerRemovedElement(e){this.root.registerRemovedElement(e)}registerGCPair(e){this.root.registerGCPair(e)}getChange(){return hs.create({id:this.id,operations:this.operations,presenceChange:this.presenceChange,message:this.message})}hasChange(){return this.operations.length>0||this.presenceChange!==void 0}setPresenceChange(e){this.presenceChange=e}setReversePresence(e,t){for(const r of Object.keys(e))t!=null&&t.addToHistory?this.reversePresenceKeys.add(r):this.reversePresenceKeys.delete(r)}getReversePresence(){if(this.reversePresenceKeys.size===0)return;const e={};for(const t of this.reversePresenceKeys)e[t]=this.previousPresence[t];return e}issueTimeTicket(){return this.delimiter+=1,this.id.createTimeTicket(this.delimiter)}getLastTimeTicket(){return this.id.createTimeTicket(this.delimiter)}}class ko{constructor(e){u(this,"rootObject");u(this,"elementPairMapByCreatedAt");u(this,"gcElementSetByCreatedAt");u(this,"gcPairMap");this.rootObject=e,this.elementPairMapByCreatedAt=new Map,this.gcElementSetByCreatedAt=new Set,this.gcPairMap=new Map,this.registerElement(e,void 0),e.getDescendants(t=>{if(t.getRemovedAt()&&this.registerRemovedElement(t),t instanceof It||t instanceof Et)for(const r of t.getGCPairs())this.registerGCPair(r);return!1})}static create(){return new ko(We.create(bt))}findByCreatedAt(e){const t=this.elementPairMapByCreatedAt.get(e.toIDString());if(t)return t.element}findElementPairByCreatedAt(e){return this.elementPairMapByCreatedAt.get(e.toIDString())}createSubPaths(e){let t=this.elementPairMapByCreatedAt.get(e.toIDString());if(!t)return[];const r=[];for(;t.parent;){const i=t.element.getCreatedAt(),s=t.parent.subPathOf(i);if(s===void 0)throw new k(S.ErrInvalidArgument,`cant find the given element: ${i.toIDString()}`);r.unshift(s),t=this.elementPairMapByCreatedAt.get(t.parent.getCreatedAt().toIDString())}return r.unshift("$"),r}createPath(e){return this.createSubPaths(e).join(".")}registerElement(e,t){this.elementPairMapByCreatedAt.set(e.getCreatedAt().toIDString(),{parent:t,element:e}),e instanceof Wr&&e.getDescendants((r,i)=>(this.registerElement(r,i),!1))}deregisterElement(e){let t=0;const r=i=>{const s=i.getCreatedAt().toIDString();this.elementPairMapByCreatedAt.delete(s),this.gcElementSetByCreatedAt.delete(s),t++};return r(e),e instanceof Wr&&e.getDescendants(i=>(r(i),!1)),t}registerRemovedElement(e){this.gcElementSetByCreatedAt.add(e.getCreatedAt().toIDString())}registerGCPair(e){if(this.gcPairMap.get(e.child.toIDString())){this.gcPairMap.delete(e.child.toIDString());return}this.gcPairMap.set(e.child.toIDString(),e)}getElementMapSize(){return this.elementPairMapByCreatedAt.size}getGarbageElementSetSize(){const e=new Set;for(const t of this.gcElementSetByCreatedAt){e.add(t);const r=this.elementPairMapByCreatedAt.get(t);r.element instanceof Wr&&r.element.getDescendants(i=>(e.add(i.getCreatedAt().toIDString()),!1))}return e.size}getObject(){return this.rootObject}getGarbageLen(){return this.getGarbageElementSetSize()+this.gcPairMap.size}deepcopy(){return new ko(this.rootObject.deepcopy())}garbageCollect(e){let t=0;for(const r of this.gcElementSetByCreatedAt){const i=this.elementPairMapByCreatedAt.get(r),s=i.element.getRemovedAt();s&&(e!=null&&e.afterOrEqual(s))&&(i.parent.purge(i.element),t+=this.deregisterElement(i.element))}for(const[,r]of this.gcPairMap){const i=r.child.getRemovedAt();i&&(e!=null&&e.afterOrEqual(i))&&(r.parent.purge(r.child),this.gcPairMap.delete(r.child.toIDString()),t+=1)}return t}toJSON(){return this.rootObject.toJSON()}toSortedJSON(){return this.rootObject.toSortedJSON()}getStats(){return{elements:this.getElementMapSize(),gcPairs:this.gcPairMap.size,gcElements:this.getGarbageElementSetSize()}}}function Ny(n,e){const t=new To(n);return new Proxy(e,t.getHandlers())}class To{constructor(e){u(this,"context");u(this,"handlers");this.context=e,this.handlers={set:(t,r,i)=>(J.isEnabled(be.Trivial)&&J.trivial(`obj[${r}]=${JSON.stringify(i)}`),To.setInternal(e,t,r,i),!0),get:(t,r)=>(J.isEnabled(be.Trivial)&&J.trivial(`obj[${r}]`),r==="getID"?()=>t.getCreatedAt():r==="toJSON"||r==="toString"?()=>t.toJSON():r==="toJS"?()=>t.toJS():r==="toJSForTest"?()=>t.toJSForTest():ai(e,t.get(r))),ownKeys:t=>t.getKeys(),getOwnPropertyDescriptor:()=>({enumerable:!0,configurable:!0}),deleteProperty:(t,r)=>(J.isEnabled(be.Trivial)&&J.trivial(`obj[${r}]`),To.deleteInternal(e,t,r),!0)}}static setInternal(e,t,r,i){if(r.includes("."))throw new k(S.ErrInvalidObjectKey,"key must not contain the '.'.");const s=e.issueTimeTicket(),o=pl(e,i,s),a=t.set(r,o,s);e.registerElement(o,t),a&&e.registerRemovedElement(a),e.push(Ii.create(r,o.deepcopy(),t.getCreatedAt(),s))}static buildObjectMembers(e,t){const r={};for(const[i,s]of Object.entries(t)){if(i.includes("."))throw new k(S.ErrInvalidObjectKey,"key must not contain the '.'.");const o=e.issueTimeTicket(),a=pl(e,s,o);r[i]=a}return r}static deleteInternal(e,t,r){const i=e.issueTimeTicket(),s=t.deleteByKey(r,i);s&&(e.push(Xr.create(t.getCreatedAt(),s.getCreatedAt(),i)),e.registerRemovedElement(s))}getHandlers(){return this.handlers}}function zS(n,e){const t=new ae(n,e);return new Proxy(e,t.getHandlers())}function US(n){return typeof n=="string"||n instanceof String?!isNaN(n):!1}function jS(n){return["concat","entries","every","filter","find","findIndex","forEach","join","keys","map","reduce","reduceRight","slice","some","toLocaleString","toString","values"].includes(n)}class ae{constructor(e,t){u(this,"context");u(this,"handlers");u(this,"array");this.context=e,this.array=t,this.handlers={get:(r,i,s)=>i==="getID"?()=>r.getCreatedAt():i==="getElementByID"?o=>{const a=r.getByID(o);if(!(!a||a.isRemoved()))return Cr(e,a)}:i==="getElementByIndex"?o=>{const a=r.get(o);return Cr(e,a)}:i==="getLast"?()=>Cr(e,r.getLast()):i==="deleteByID"?o=>{const a=ae.deleteInternalByID(e,r,o);return Cr(e,a)}:i==="insertAfter"?(o,a)=>{const l=ae.insertAfterInternal(e,r,o,a);return Cr(e,l)}:i==="insertBefore"?(o,a)=>{const l=ae.insertBeforeInternal(e,r,o,a);return Cr(e,l)}:i==="moveBefore"?(o,a)=>{ae.moveBeforeInternal(e,r,o,a)}:i==="moveAfter"?(o,a)=>{ae.moveAfterInternal(e,r,o,a)}:i==="moveFront"?o=>{ae.moveFrontInternal(e,r,o)}:i==="moveLast"?o=>{ae.moveLastInternal(e,r,o)}:US(i)?ai(e,r.get(Number(i))):i==="push"?o=>ae.pushInternal(e,r,o):i==="splice"?(o,a,...l)=>ae.splice(e,r,o,a,...l):i==="length"?r.length:typeof i=="symbol"&&i===Symbol.iterator?ae.iteratorInternal.bind(this,e,r):i==="includes"?(o,a)=>ae.includes(e,r,o,a):i==="indexOf"?(o,a)=>ae.indexOf(e,r,o,a):i==="lastIndexOf"?(o,a)=>ae.lastIndexOf(e,r,o,a):i==="toJSForTest"?()=>r.toJSForTest():i==="toTestString"?()=>ae.toTestString(r):typeof i=="string"&&jS(i)?(...o)=>{const a=Array.from(r).map(l=>ai(e,l));return Array.prototype[i].apply(a,o)}:Reflect.get(r,i,s),deleteProperty:(r,i)=>(J.isEnabled(be.Trivial)&&J.trivial(`array[${i}]`),ae.deleteInternalByIndex(e,r,Number.parseInt(i)),!0)}}static*iteratorInternal(e,t){for(const r of t)yield Cr(e,r)}static buildArrayElements(e,t){const r=[];for(const i of t){const s=e.issueTimeTicket(),o=pl(e,i,s);r.push(o)}return r}static pushInternal(e,t,r){return ae.insertAfterInternal(e,t,t.getLastCreatedAt(),r),t.length}static moveBeforeInternal(e,t,r,i){const s=e.issueTimeTicket(),o=t.getPrevCreatedAt(r);t.moveAfter(o,i,s),e.push(br.create(t.getCreatedAt(),o,i,s))}static moveAfterInternal(e,t,r,i){const s=e.issueTimeTicket();t.moveAfter(r,i,s),e.push(br.create(t.getCreatedAt(),r,i,s))}static moveFrontInternal(e,t,r){const i=e.issueTimeTicket(),s=t.getHead();t.moveAfter(s.getCreatedAt(),r,i),e.push(br.create(t.getCreatedAt(),s.getCreatedAt(),r,i))}static moveLastInternal(e,t,r){const i=e.issueTimeTicket(),s=t.getLastCreatedAt();t.moveAfter(s,r,i),e.push(br.create(t.getCreatedAt(),s,r,i))}static insertAfterInternal(e,t,r,i){const s=e.issueTimeTicket(),o=pl(e,i,s);return t.insertAfter(r,o),e.registerElement(o,t),e.push(Po.create(t.getCreatedAt(),r,o.deepcopy(),s)),o}static insertBeforeInternal(e,t,r,i){return ae.insertAfterInternal(e,t,t.getPrevCreatedAt(r),i)}static deleteInternalByIndex(e,t,r){const i=e.issueTimeTicket(),s=t.deleteByIndex(r,i);if(s)return e.push(Xr.create(t.getCreatedAt(),s.getCreatedAt(),i)),e.registerRemovedElement(s),s}static deleteInternalByID(e,t,r){const i=e.issueTimeTicket(),s=t.delete(r,i);return e.push(Xr.create(t.getCreatedAt(),s.getCreatedAt(),i)),e.registerRemovedElement(s),s}static splice(e,t,r,i,...s){const o=t.length,a=r>=0?Math.min(r,o):Math.max(o+r,0),l=i===void 0?o:i<0?a:Math.min(a+i,o),c=[];for(let d=a;d=s)return!1;if(ie.isSupport(r))return Array.from(t).map(c=>ai(e,c)).includes(r,o);for(let l=o;l=s)return-1;if(ie.isSupport(r))return Array.from(t).map(c=>ai(e,c)).indexOf(r,o);for(let l=o;l=s?s-1:i<0?i+s:i;if(o<0)return-1;if(ie.isSupport(r))return Array.from(t).map(c=>ai(e,c)).lastIndexOf(r,o);for(let l=o;l>0;l--)if(((a=t.get(l))==null?void 0:a.getID())===r.getID())return l;return-1}static toTestString(e){return e.toTestString()}getHandlers(){return this.handlers}}class Jl{constructor(e,t){u(this,"context");u(this,"text");this.context=e,this.text=t}initialize(e,t){this.context=e,this.text=t}getID(){return this.text.getID()}edit(e,t,r,i){if(!this.context||!this.text)throw new k(S.ErrNotInitialized,"Text is not initialized yet");if(e>t)throw new k(S.ErrInvalidArgument,"from should be less than or equal to to");const s=this.text.indexRangeToPosRange(e,t);J.isEnabled(be.Debug)&&J.debug(`EDIT: f:${e}->${s[0].toTestString()}, t:${t}->${s[1].toTestString()} c:${r}`);const o=i?fs(i):void 0,a=this.context.issueTimeTicket(),[l,,c,d]=this.text.edit(s,r,a,o);for(const h of c)this.context.registerGCPair(h);return this.context.push(new Do(this.text.getCreatedAt(),s[0],s[1],l,r,o?new Map(Object.entries(o)):new Map,a)),this.text.findIndexesFromRange(d)}delete(e,t){return this.edit(e,t,"")}empty(){return this.edit(0,this.length,"")}setStyle(e,t,r){if(!this.context||!this.text)throw new k(S.ErrNotInitialized,"Text is not initialized yet");if(e>t)throw new k(S.ErrInvalidArgument,"from should be less than or equal to to");const i=this.text.indexRangeToPosRange(e,t);J.isEnabled(be.Debug)&&J.debug(`STYL: f:${e}->${i[0].toTestString()}, t:${t}->${i[1].toTestString()} a:${JSON.stringify(r)}`);const s=fs(r),o=this.context.issueTimeTicket(),[a,l]=this.text.setStyle(i,s,o);for(const c of l)this.context.registerGCPair(c);return this.context.push(new Oo(this.text.getCreatedAt(),i[0],i[1],a,new Map(Object.entries(s)),o)),!0}indexRangeToPosRange(e){if(!this.context||!this.text)throw new k(S.ErrNotInitialized,"Text is not initialized yet");const t=this.text.indexRangeToPosRange(e[0],e[1]);return[t[0].toStruct(),t[1].toStruct()]}posRangeToIndexRange(e){if(!this.context||!this.text)throw new k(S.ErrNotInitialized,"Text is not initialized yet");const t=this.text.findIndexesFromRange([Ft.fromStruct(e[0]),Ft.fromStruct(e[1])]);return[t[0],t[1]]}toTestString(){if(!this.context||!this.text)throw new k(S.ErrNotInitialized,"Text is not initialized yet");return this.text.toTestString()}values(){if(!this.context||!this.text)throw new k(S.ErrNotInitialized,"Text is not initialized yet");return this.text.values()}get length(){return this.text.length}getTreeByIndex(){return this.text.getTreeByIndex()}getTreeByID(){return this.text.getTreeByID()}toString(){if(!this.context||!this.text)throw new k(S.ErrNotInitialized,"Text is not initialized yet");return this.text.toString()}toJSON(){if(!this.context||!this.text)throw new k(S.ErrNotInitialized,"Text is not initialized yet");return this.text.toJSON()}toJSForTest(){if(!this.context||!this.text)throw new k(S.ErrNotInitialized,"Text is not initialized yet");return this.text.toJSForTest()}createRangeForTest(e,t){if(!this.context||!this.text)throw new k(S.ErrNotInitialized,"Text is not initialized yet");return this.text.indexRangeToPosRange(e,t)}}class $l{constructor(e,t){u(this,"valueType");u(this,"value");u(this,"context");u(this,"counter");this.valueType=e,this.value=t}initialize(e,t){this.valueType=t.getValueType(),this.context=e,this.counter=t,this.value=t.getValue()}getID(){return this.counter.getID()}getValue(){return this.value}getValueType(){return this.valueType}increase(e){if(!this.context||!this.counter)throw new k(S.ErrNotInitialized,"Counter is not initialized yet");const t=this.context.issueTimeTicket(),r=ie.of(e,t);if(!r.isNumericType())throw new TypeError(`Unsupported type of value: ${typeof r.getValue()}`);return this.counter.increase(r),this.context.push(ms.create(this.counter.getCreatedAt(),r,t)),this}toJSForTest(){if(!this.context||!this.counter)throw new k(S.ErrNotInitialized,"Counter is not initialized yet");return this.counter.toJSForTest()}}function ad(n,e,t){const{type:r}=n,i=t.issueTimeTicket();if(r===mr){Py(n);const{value:s}=n,o=Xe.create(Ee.of(i,0),r,s);e.append(o)}else{const{children:s=[]}=n,{attributes:o}=n;let a;if(typeof o=="object"&&!Xp(o)){const c=fs(o);a=new Tr;for(const[d,h]of Object.entries(c))a.set(d,h,i)}const l=Xe.create(Ee.of(i,0),r,void 0,a);e.append(l);for(const c of s)ad(c,l,t)}}function VS(n,e){const{type:t}=e,r=n.issueTimeTicket();let i;if(e.type===mr){const{value:s}=e;i=Xe.create(Ee.of(r,0),t,s)}else if(e){const{children:s=[]}=e,{attributes:o}=e;let a;if(typeof o=="object"&&!Xp(o)){const l=fs(o);a=new Tr;for(const[c,d]of Object.entries(l))a.set(c,d,r)}i=Xe.create(Ee.of(n.issueTimeTicket(),0),t,void 0,a);for(const l of s)ad(l,i,n)}return i}function Py(n){if(!n.value.length)throw new k(S.ErrInvalidArgument,"text node cannot have empty value");return!0}function ig(n){if(!n.length)return!0;if(n[0].type===mr)for(const t of n){const{type:r}=t;if(r!==mr)throw new k(S.ErrInvalidArgument,"element node and text node cannot be passed together");Py(t)}else for(const t of n){const{type:r}=t;if(r===mr)throw new k(S.ErrInvalidArgument,"element node and text node cannot be passed together")}return!0}class zl{constructor(e){u(this,"initialRoot");u(this,"context");u(this,"tree");this.initialRoot=e}initialize(e,t){this.context=e,this.tree=t}getID(){return this.tree.getID()}buildRoot(e){if(!this.initialRoot)return Xe.create(Ee.of(e.issueTimeTicket(),0),U1);const t=Xe.create(Ee.of(e.issueTimeTicket(),0),this.initialRoot.type);for(const r of this.initialRoot.children)ad(r,t,e);return t}getSize(){if(!this.context||!this.tree)throw new k(S.ErrNotInitialized,"Tree is not initialized yet");return this.tree.getSize()}getNodeSize(){if(!this.context||!this.tree)throw new k(S.ErrNotInitialized,"Tree is not initialized yet");return this.tree.getNodeSize()}getIndexTree(){if(!this.context||!this.tree)throw new k(S.ErrNotInitialized,"Tree is not initialized yet");return this.tree.getIndexTree()}styleByPath(e,t){if(!this.context||!this.tree)throw new k(S.ErrNotInitialized,"Tree is not initialized yet");if(!e.length)throw new k(S.ErrInvalidArgument,"path should not be empty");const[r,i]=this.tree.pathToPosRange(e),s=this.context.issueTimeTicket(),o=t?fs(t):void 0,[a]=this.tree.style([r,i],o,s);this.context.push(pr.create(this.tree.getCreatedAt(),r,i,a,o?new Map(Object.entries(o)):new Map,s))}style(e,t,r){if(!this.context||!this.tree)throw new k(S.ErrNotInitialized,"Tree is not initialized yet");if(e>t)throw new k(S.ErrInvalidArgument,"from should be less than or equal to to");const i=this.tree.findPos(e),s=this.tree.findPos(t),o=this.context.issueTimeTicket(),a=r?fs(r):void 0,[l,c]=this.tree.style([i,s],a,o);for(const d of c)this.context.registerGCPair(d);this.context.push(pr.create(this.tree.getCreatedAt(),i,s,l,a?new Map(Object.entries(a)):new Map,o))}removeStyle(e,t,r){if(!this.context||!this.tree)throw new k(S.ErrNotInitialized,"Tree is not initialized yet");if(e>t)throw new k(S.ErrInvalidArgument,"from should be less than or equal to to");const i=this.tree.findPos(e),s=this.tree.findPos(t),o=this.context.issueTimeTicket(),[a,l]=this.tree.removeStyle([i,s],r,o);for(const c of l)this.context.registerGCPair(c);this.context.push(pr.createTreeRemoveStyleOperation(this.tree.getCreatedAt(),i,s,a,r,o))}editInternal(e,t,r,i=0){var c;if(r.length!==0&&r[0]&&(ig(r),r[0].type!==mr))for(const d of r){const{children:h=[]}=d;ig(h)}const s=this.context.getLastTimeTicket();let o=new Array;if(((c=r[0])==null?void 0:c.type)===mr){let d="";for(const h of r){const{value:p}=h;d+=p}o.push(Xe.create(Ee.of(this.context.issueTimeTicket(),0),mr,d))}else o=r.map(d=>d&&VS(this.context,d)).filter(d=>d);const[,a,l]=this.tree.edit([e,t],o.length?o.map(d=>d==null?void 0:d.deepcopy()):void 0,i,s,()=>this.context.issueTimeTicket());for(const d of a)this.context.registerGCPair(d);return this.context.push(Ro.create(this.tree.getCreatedAt(),e,t,o.length?o:void 0,i,l,s)),!0}editByPath(e,t,r,i=0){if(!this.context||!this.tree)throw new k(S.ErrNotInitialized,"Tree is not initialized yet");if(e.length!==t.length)throw new k(S.ErrInvalidArgument,"path length should be equal");if(!e.length||!t.length)throw new k(S.ErrInvalidArgument,"path should not be empty");const s=this.tree.pathToPos(e),o=this.tree.pathToPos(t);return this.editInternal(s,o,r?[r]:[],i)}editBulkByPath(e,t,r,i=0){if(!this.context||!this.tree)throw new k(S.ErrNotInitialized,"Tree is not initialized yet");if(e.length!==t.length)throw new k(S.ErrInvalidArgument,"path length should be equal");if(!e.length||!t.length)throw new k(S.ErrInvalidArgument,"path should not be empty");const s=this.tree.pathToPos(e),o=this.tree.pathToPos(t);return this.editInternal(s,o,r,i)}edit(e,t,r,i=0){if(!this.context||!this.tree)throw new k(S.ErrNotInitialized,"Tree is not initialized yet");if(e>t)throw new k(S.ErrInvalidArgument,"from should be less than or equal to to");const s=this.tree.findPos(e),o=this.tree.findPos(t);return this.editInternal(s,o,r?[r]:[],i)}editBulk(e,t,r,i=0){if(!this.context||!this.tree)throw new k(S.ErrNotInitialized,"Tree is not initialized yet");if(e>t)throw new k(S.ErrInvalidArgument,"from should be less than or equal to to");const s=this.tree.findPos(e),o=this.tree.findPos(t);return this.editInternal(s,o,r,i)}toXML(){if(!this.context||!this.tree)throw new k(S.ErrNotInitialized,"Tree is not initialized yet");return this.tree.toXML()}toJSON(){if(!this.context||!this.tree)throw new k(S.ErrNotInitialized,"Tree is not initialized yet");return this.tree.toJSON()}toJSForTest(){if(!this.context||!this.tree)throw new k(S.ErrNotInitialized,"Tree is not initialized yet");return this.tree.toJSForTest()}toJSInfoForTest(){if(!this.context||!this.tree)throw new k(S.ErrNotInitialized,"Tree is not initialized yet");return this.tree.toJSInfoForTest()}getRootTreeNode(){if(!this.context||!this.tree)throw new k(S.ErrNotInitialized,"Tree is not initialized yet");return this.tree.getRootTreeNode()}indexToPath(e){if(!this.context||!this.tree)throw new k(S.ErrNotInitialized,"Tree is not initialized yet");return this.tree.indexToPath(e)}pathToIndex(e){if(!this.context||!this.tree)throw new k(S.ErrNotInitialized,"Tree is not initialized yet");return this.tree.pathToIndex(e)}pathRangeToPosRange(e){if(!this.context||!this.tree)throw new k(S.ErrNotInitialized,"Tree is not initialized yet");const t=[this.tree.pathToIndex(e[0]),this.tree.pathToIndex(e[1])],r=this.tree.indexRangeToPosRange(t);return[r[0].toStruct(),r[1].toStruct()]}indexRangeToPosRange(e){if(!this.context||!this.tree)throw new k(S.ErrNotInitialized,"Tree is not initialized yet");return this.tree.indexRangeToPosStructRange(e)}posRangeToIndexRange(e){if(!this.context||!this.tree)throw new k(S.ErrNotInitialized,"Tree is not initialized yet");const t=[Rt.fromStruct(e[0]),Rt.fromStruct(e[1])];return this.tree.posRangeToIndexRange(t)}posRangeToPathRange(e){if(!this.context||!this.tree)throw new k(S.ErrNotInitialized,"Tree is not initialized yet");const t=[Rt.fromStruct(e[0]),Rt.fromStruct(e[1])];return this.tree.posRangeToPathRange(t)}}function sg(n,e){return Ny(n,e)}function Cr(n,e){if(e){if(e instanceof ie)return e;if(e instanceof We)return Ny(n,e);if(e instanceof tt)return zS(n,e);if(e instanceof It)return new Jl(n,e);if(e instanceof nt){const t=new $l(sn.IntegerCnt,0);return t.initialize(n,e),t}else if(e instanceof Et){const t=new zl;return t.initialize(n,e),t}}else return;throw new TypeError(`Unsupported type of element: ${typeof e}`)}function ai(n,e){const t=Cr(n,e);return t instanceof ie?t.getValue():t}function pl(n,e,t){let r;if(ie.isSupport(e))r=ie.of(e,t);else if(Array.isArray(e))r=tt.create(t,ae.buildArrayElements(n,e));else if(typeof e=="object")e instanceof Jl?(r=It.create(gs.create(),t),e.initialize(n,r)):e instanceof $l?(r=nt.create(e.getValueType(),e.getValue(),t),e.initialize(n,r)):e instanceof zl?(r=Et.create(e.buildRoot(n),t),e.initialize(n,r)):r=We.create(t,To.buildObjectMembers(n,e));else throw new TypeError(`Unsupported type of value: ${typeof e}`);return r}const og=50;class qS{constructor(){u(this,"undoStack",[]);u(this,"redoStack",[])}hasUndo(){return this.undoStack.length>0}hasRedo(){return this.redoStack.length>0}pushUndo(e){this.undoStack.length>=og&&this.undoStack.shift(),this.undoStack.push(e)}popUndo(){return this.undoStack.pop()}pushRedo(e){this.redoStack.length>=og&&this.redoStack.shift(),this.redoStack.push(e)}popRedo(){return this.redoStack.pop()}clearRedo(){this.redoStack=[]}getUndoStackForTest(){return this.undoStack}getRedoStackForTest(){return this.redoStack}}const KS="yorkie-devtools-panel",WS="yorkie-devtools-sdk";let Oi="disconnected";const ag=new Map,ka=new Map;typeof window<"u"&&(window.transactionEventsByDocKey=ka);function na(n,e){(e!=null&&e.force||Oi!=="disconnected")&&window.postMessage({source:WS,...n},"*")}function HS(n){if(!n.isEnableDevtools()||typeof window>"u"||ag.has(n.getKey()))return;ka.set(n.getKey(),[]);const e=n.subscribe("all",t=>{t.some(r=>r.type!==$e.StatusChanged&&r.type!==$e.Snapshot&&r.type!==$e.LocalChange&&r.type!==$e.RemoteChange&&r.type!==$e.Initialized&&r.type!==$e.Watched&&r.type!==$e.Unwatched&&r.type!==$e.PresenceChanged)||(ka.get(n.getKey()).push(t),Oi==="synced"&&na({msg:"doc::sync::partial",docKey:n.getKey(),event:t}))});ag.set(n.getKey(),[e]),na({msg:"refresh-devtools"},{force:!0}),window.addEventListener("message",t=>{var i;if(((i=t.data)==null?void 0:i.source)!==KS)return;switch(t.data.msg){case"devtools::connect":if(Oi!=="disconnected")break;Oi="connected",na({msg:"doc::available",docKey:n.getKey()}),J.info(`[YD] Devtools connected. Doc: ${n.getKey()}`);break;case"devtools::disconnect":Oi="disconnected",J.info(`[YD] Devtools disconnected. Doc: ${n.getKey()}`);break;case"devtools::subscribe":Oi="synced",na({msg:"doc::sync::full",docKey:n.getKey(),events:ka.get(n.getKey())}),J.info(`[YD] Devtools subscribed. Doc: ${n.getKey()}`);break}})}var Nr=(n=>(n.Detached="detached",n.Attached="attached",n.Removed="removed",n))(Nr||{}),$e=(n=>(n.StatusChanged="status-changed",n.ConnectionChanged="connection-changed",n.SyncStatusChanged="sync-status-changed",n.Snapshot="snapshot",n.LocalChange="local-change",n.RemoteChange="remote-change",n.Initialized="initialized",n.Watched="watched",n.Unwatched="unwatched",n.PresenceChanged="presence-changed",n.Broadcast="broadcast",n.LocalBroadcast="local-broadcast",n))($e||{}),Kc=(n=>(n.Connected="connected",n.Disconnected="disconnected",n))(Kc||{}),Wc=(n=>(n.Synced="synced",n.SyncFailed="sync-failed",n))(Wc||{});class Dy{constructor(e,t){u(this,"key");u(this,"status");u(this,"opts");u(this,"changeID");u(this,"checkpoint");u(this,"localChanges");u(this,"root");u(this,"clone");u(this,"eventStream");u(this,"eventStreamObserver");u(this,"onlineClients");u(this,"presences");u(this,"history");u(this,"internalHistory");u(this,"isUpdating");this.opts=t||{},this.key=e,this.status="detached",this.root=ko.create(),this.changeID=Y1,this.checkpoint=Q1,this.localChanges=[],this.eventStream=$S(r=>{this.eventStreamObserver=r}),this.onlineClients=new Set,this.presences=new Map,this.isUpdating=!1,this.internalHistory=new qS,this.history={canUndo:this.canUndo.bind(this),canRedo:this.canRedo.bind(this),undo:this.undo.bind(this),redo:this.redo.bind(this)},HS(this)}update(e,t){if(this.getStatus()==="removed")throw new k(S.ErrDocumentRemoved,`${this.key} is removed`);this.ensureClone();const r=this.changeID.getActorID(),i=Ki.create(this.changeID.next(),this.clone.root,this.clone.presences.get(r)||{},t);try{const s=sg(i,this.clone.root.getObject());this.presences.has(r)||this.clone.presences.set(r,{}),this.isUpdating=!0,e(s,new Su(i,this.clone.presences.get(r)))}catch(s){throw this.clone=void 0,s}finally{this.isUpdating=!1}if(i.hasChange()){J.isEnabled(be.Trivial)&&J.trivial(`trying to update a local change: ${this.toJSON()}`);const s=i.getChange(),{opInfos:o,reverseOps:a}=s.execute(this.root,this.presences,Y.Local),l=i.getReversePresence();l&&a.push({type:"presence",value:l}),this.localChanges.push(s),a.length>0&&this.internalHistory.pushUndo(a),o.length>0&&this.internalHistory.clearRedo(),this.changeID=s.getID();const c=[];o.length>0&&c.push({type:"local-change",source:Y.Local,value:{message:s.getMessage()||"",operations:o,actor:r,clientSeq:s.getID().getClientSeq(),serverSeq:s.getID().getServerSeq()},rawChange:this.isEnableDevtools()?s.toStruct():void 0}),s.hasPresenceChange()&&c.push({type:"presence-changed",source:Y.Local,value:{clientID:r,presence:this.getPresence(r)}}),this.publish(c),J.isEnabled(be.Trivial)&&J.trivial(`after update a local change: ${this.toJSON()}`)}}subscribe(e,t,r,i){if(typeof e=="string"){if(typeof t!="function")throw new k(S.ErrInvalidArgument,"Second argument must be a callback function");if(e==="presence"){const a=t;return this.eventStream.subscribe(l=>{for(const c of l)c.type!=="initialized"&&c.type!=="watched"&&c.type!=="unwatched"&&c.type!=="presence-changed"||a(c)},r,i)}if(e==="my-presence"){const a=t;return this.eventStream.subscribe(l=>{for(const c of l)c.type!=="initialized"&&c.type!=="presence-changed"||c.type==="presence-changed"&&c.value.clientID!==this.changeID.getActorID()||a(c)},r,i)}if(e==="others"){const a=t;return this.eventStream.subscribe(l=>{for(const c of l)c.type!=="watched"&&c.type!=="unwatched"&&c.type!=="presence-changed"||c.value.clientID!==this.changeID.getActorID()&&a(c)},r,i)}if(e==="connection"){const a=t;return this.eventStream.subscribe(l=>{for(const c of l)c.type==="connection-changed"&&a(c)},r,i)}if(e==="status"){const a=t;return this.eventStream.subscribe(l=>{for(const c of l)c.type==="status-changed"&&a(c)},r,i)}if(e==="sync"){const a=t;return this.eventStream.subscribe(l=>{for(const c of l)c.type==="sync-status-changed"&&a(c)},r,i)}if(e==="local-broadcast"){const a=t;return this.eventStream.subscribe(l=>{for(const c of l)c.type==="local-broadcast"&&a(c)},r)}if(e==="broadcast"){const a=t;return this.eventStream.subscribe(l=>{for(const c of l)c.type==="broadcast"&&a(c)},r)}if(e==="all"){const a=t;return this.eventStream.subscribe(a,r,i)}const s=e,o=t;return this.eventStream.subscribe(a=>{for(const l of a){if(l.type!=="local-change"&&l.type!=="remote-change")continue;const c=[];for(const d of l.value.operations)this.isSameElementOrChildOf(d.path,s)&&c.push(d);c.length&&o({...l,value:{...l.value,operations:c}})}},r,i)}if(typeof e=="function"){const s=e,o=t,a=r;return this.eventStream.subscribe(l=>{for(const c of l)c.type!=="snapshot"&&c.type!=="local-change"&&c.type!=="remote-change"||s(c)},o,a)}throw new k(S.ErrInvalidArgument,`"${e}" is not a valid`)}publish(e){this.eventStreamObserver&&this.eventStreamObserver.next(e)}isSameElementOrChildOf(e,t){if(t===e)return!0;const r=e.split(".");return t.split(".").every((s,o)=>s===r[o])}removePushedLocalChanges(e){for(;this.localChanges.length&&!(this.localChanges[0].getID().getClientSeq()>e);)this.localChanges.shift()}applyChangePack(e){const t=e.hasSnapshot();t?this.applySnapshot(e.getCheckpoint().getServerSeq(),e.getVersionVector(),e.getSnapshot(),e.getCheckpoint().getClientSeq()):(this.applyChanges(e.getChanges(),Y.Remote),this.removePushedLocalChanges(e.getCheckpoint().getClientSeq())),this.checkpoint=this.checkpoint.forward(e.getCheckpoint()),t||this.garbageCollect(e.getVersionVector()),t||this.filterVersionVector(e.getVersionVector()),e.getIsRemoved()&&this.applyStatus("removed"),J.isEnabled(be.Trivial)&&J.trivial(`${this.root.toJSON()}`)}getCheckpoint(){return this.checkpoint}getChangeID(){return this.changeID}hasLocalChanges(){return this.localChanges.length>0}ensureClone(){this.clone||(this.clone={root:this.root.deepcopy(),presences:Nt(this.presences)})}createChangePack(){const e=Array.from(this.localChanges),t=this.checkpoint.increaseClientSeq(e.length);return Ml.create(this.key,t,!1,e,this.getVersionVector())}setActor(e){for(const t of this.localChanges)t.setActor(e);this.changeID=this.changeID.setActor(e)}isEnableDevtools(){return!!this.opts.enableDevtools}getKey(){return this.key}getStatus(){return this.status}getCloneRoot(){if(this.clone)return this.clone.root.getObject()}getRoot(){this.ensureClone();const e=Ki.create(this.changeID.next(),this.clone.root,this.clone.presences.get(this.changeID.getActorID())||{});return sg(e,this.clone.root.getObject())}garbageCollect(e){return this.opts.disableGC?0:(this.clone&&this.clone.root.garbageCollect(e),this.root.garbageCollect(e))}getRootObject(){return this.root.getObject()}getGarbageLen(){return this.root.getGarbageLen()}getGarbageLenFromClone(){return this.clone.root.getGarbageLen()}toJSON(){return this.root.toJSON()}toSortedJSON(){return this.root.toSortedJSON()}getStats(){return this.root.getStats()}toJSForTest(){return{...this.getRoot().toJSForTest(),key:"root"}}applySnapshot(e,t,r,i=-1){const{root:s,presences:o}=fe.bytesToSnapshot(r);this.root=new ko(s),this.presences=o,this.changeID=this.changeID.setClocks(e,t),this.clone=void 0,this.removePushedLocalChanges(i),this.applyChanges(this.localChanges,Y.Local),this.publish([{type:"snapshot",source:Y.Remote,value:{serverSeq:e.toString(),snapshot:this.isEnableDevtools()?fe.bytesToHex(r):void 0,snapshotVector:fe.versionVectorToHex(t)}}])}applyChanges(e,t){J.isEnabled(be.Debug)&&J.debug(`trying to apply ${e.length} remote changes.elements:${this.root.getElementMapSize()}, removeds:${this.root.getGarbageElementSetSize()}`),J.isEnabled(be.Trivial)&&J.trivial(e.map(r=>`${r.getID().toTestString()} ${r.toTestString()}`).join(` `));for(const r of e)this.applyChange(r,t);J.isEnabled(be.Debug)&&J.debug(`after appling ${e.length} remote changes.elements:${this.root.getElementMapSize()}, removeds:${this.root.getGarbageElementSetSize()}`)}applyChange(e,t){this.ensureClone(),e.execute(this.clone.root,this.clone.presences,t);const r=[],i=e.getID().getActorID();if(e.hasPresenceChange()&&this.onlineClients.has(i)){const o=e.getPresenceChange();switch(o.type){case Qr.Put:r.push(this.presences.has(i)?{type:"presence-changed",source:t,value:{clientID:i,presence:o.presence}}:{type:"watched",source:Y.Remote,value:{clientID:i,presence:o.presence}});break;case Qr.Clear:r.push({type:"unwatched",source:Y.Remote,value:{clientID:i,presence:this.getPresence(i)}}),this.removeOnlineClient(i);break}}const{opInfos:s}=e.execute(this.root,this.presences,t);if(this.changeID=this.changeID.syncClocks(e.getID()),s.length>0){const o=this.isEnableDevtools()?e.toStruct():void 0;r.push(t===Y.Remote?{type:"remote-change",source:t,value:{actor:i,clientSeq:e.getID().getClientSeq(),serverSeq:e.getID().getServerSeq(),message:e.getMessage()||"",operations:s},rawChange:o}:{type:"local-change",source:t,value:{actor:i,clientSeq:e.getID().getClientSeq(),serverSeq:e.getID().getServerSeq(),message:e.getMessage()||"",operations:s},rawChange:o})}r.length>0&&this.publish(r)}applyWatchStream(e){if(e.body.case==="initialization"){const t=e.body.value.clientIds,r=new Set;for(const i of t)i!==this.changeID.getActorID()&&r.add(i);this.setOnlineClients(r),this.publish([{type:"initialized",source:Y.Local,value:this.getPresences()}]);return}if(e.body.case==="event"){const{type:t,publisher:r}=e.body.value,i=[];if(t===pi.DOCUMENT_WATCHED){if(this.onlineClients.has(r)&&this.hasPresence(r))return;this.addOnlineClient(r),this.hasPresence(r)&&i.push({type:"watched",source:Y.Remote,value:{clientID:r,presence:this.getPresence(r)}})}else if(t===pi.DOCUMENT_UNWATCHED){const s=this.getPresence(r);this.removeOnlineClient(r),s&&i.push({type:"unwatched",source:Y.Remote,value:{clientID:r,presence:s}})}else if(t===pi.DOCUMENT_BROADCAST&&e.body.value.body){const{topic:s,payload:o}=e.body.value.body,a=new TextDecoder;i.push({type:"broadcast",value:{clientID:r,topic:s,payload:JSON.parse(a.decode(o))}})}i.length>0&&this.publish(i)}}applyStatus(e){this.status=e,e==="detached"&&this.setActor(Wf),this.publish([{source:e==="removed"?Y.Remote:Y.Local,type:"status-changed",value:e==="attached"?{status:e,actorID:this.changeID.getActorID()}:{status:e}}])}applyDocEvent(e){if(e.type==="status-changed"){this.applyStatus(e.value.status),e.value.status==="attached"&&this.setActor(e.value.actorID);return}if(e.type==="snapshot"){const{snapshot:t,serverSeq:r,snapshotVector:i}=e.value;if(!t)return;this.applySnapshot(BigInt(r),fe.hexToVersionVector(i),fe.hexToBytes(t));return}if(e.type==="local-change"||e.type==="remote-change"){if(!e.rawChange)return;const t=hs.fromStruct(e.rawChange);this.applyChange(t,e.source)}if(e.type==="initialized"){const t=new Set;for(const{clientID:r,presence:i}of e.value)t.add(r),this.presences.set(r,i);this.setOnlineClients(t);return}if(e.type==="watched"){const{clientID:t,presence:r}=e.value;this.addOnlineClient(t),this.presences.set(t,r);return}if(e.type==="unwatched"){const{clientID:t}=e.value;this.removeOnlineClient(t),this.presences.delete(t)}if(e.type==="presence-changed"){const{clientID:t,presence:r}=e.value;this.presences.set(t,r)}}applyTransactionEvent(e){for(const t of e)this.applyDocEvent(t)}getValueByPath(e){if(!e.startsWith("$"))throw new k(S.ErrInvalidArgument,'path must start with "$"');const t=e.split(".");t.shift();let r=this.getRoot();for(const i of t)if(r=r[i],r===void 0)return;return r}setOnlineClients(e){this.onlineClients=e}resetOnlineClients(){this.onlineClients=new Set}addOnlineClient(e){this.onlineClients.add(e)}removeOnlineClient(e){this.onlineClients.delete(e)}hasPresence(e){return this.presences.has(e)}getMyPresence(){if(this.status!=="attached")return{};const e=this.presences.get(this.changeID.getActorID());return e?Nt(e):{}}getPresence(e){if(e===this.changeID.getActorID())return this.getMyPresence();if(!this.onlineClients.has(e))return;const t=this.presences.get(e);return t?Nt(t):void 0}getPresenceForTest(e){const t=this.presences.get(e);return t?Nt(t):void 0}getPresences(){const e=[];e.push({clientID:this.changeID.getActorID(),presence:Nt(this.getMyPresence())});for(const t of this.onlineClients)this.presences.has(t)&&e.push({clientID:t,presence:Nt(this.presences.get(t))});return e}getSelfForTest(){return{clientID:this.getChangeID().getActorID(),presence:this.getMyPresence()}}getOthersForTest(){const e=this.getChangeID().getActorID();return this.getPresences().filter(t=>t.clientID!==e).sort((t,r)=>t.clientID>r.clientID?1:-1)}canUndo(){return this.internalHistory.hasUndo()&&!this.isUpdating}filterVersionVector(e){const r=this.changeID.getVersionVector().filter(e);this.changeID=this.changeID.setVersionVector(r)}canRedo(){return this.internalHistory.hasRedo()&&!this.isUpdating}undo(){if(this.isUpdating)throw new k(S.ErrRefused,"Undo is not allowed during an update");const e=this.internalHistory.popUndo();if(e===void 0)throw new k(S.ErrRefused,"There is no operation to be undone");this.ensureClone();const t=Ki.create(this.changeID.next(),this.clone.root,this.clone.presences.get(this.changeID.getActorID())||{});for(const c of e){if(!(c instanceof Jt)){new Su(t,Nt(this.clone.presences.get(this.changeID.getActorID()))).set(c.value,{addToHistory:!0});continue}const d=t.issueTimeTicket();c.setExecutedAt(d),t.push(c)}const r=t.getChange();r.execute(this.clone.root,this.clone.presences,Y.UndoRedo);const{opInfos:i,reverseOps:s}=r.execute(this.root,this.presences,Y.UndoRedo),o=t.getReversePresence();if(o&&s.push({type:"presence",value:o}),s.length>0&&this.internalHistory.pushRedo(s),!r.hasPresenceChange()&&i.length===0)return;this.localChanges.push(r),this.changeID=r.getID();const a=this.changeID.getActorID(),l=[];i.length>0&&l.push({type:"local-change",source:Y.UndoRedo,value:{message:r.getMessage()||"",operations:i,actor:a,clientSeq:r.getID().getClientSeq(),serverSeq:r.getID().getServerSeq()},rawChange:this.isEnableDevtools()?r.toStruct():void 0}),r.hasPresenceChange()&&l.push({type:"presence-changed",source:Y.UndoRedo,value:{clientID:a,presence:this.getPresence(a)}}),this.publish(l)}redo(){if(this.isUpdating)throw new k(S.ErrRefused,"Redo is not allowed during an update");const e=this.internalHistory.popRedo();if(e===void 0)throw new k(S.ErrRefused,"There is no operation to be redone");this.ensureClone();const t=Ki.create(this.changeID.next(),this.clone.root,this.clone.presences.get(this.changeID.getActorID())||{});for(const c of e){if(!(c instanceof Jt)){new Su(t,Nt(this.clone.presences.get(this.changeID.getActorID()))).set(c.value,{addToHistory:!0});continue}const d=t.issueTimeTicket();c.setExecutedAt(d),t.push(c)}const r=t.getChange();r.execute(this.clone.root,this.clone.presences,Y.UndoRedo);const{opInfos:i,reverseOps:s}=r.execute(this.root,this.presences,Y.UndoRedo),o=t.getReversePresence();if(o&&s.push({type:"presence",value:o}),s.length>0&&this.internalHistory.pushUndo(s),!r.hasPresenceChange()&&i.length===0)return;this.localChanges.push(r),this.changeID=r.getID();const a=this.changeID.getActorID(),l=[];i.length>0&&l.push({type:"local-change",source:Y.UndoRedo,value:{message:r.getMessage()||"",operations:i,actor:a,clientSeq:r.getID().getClientSeq(),serverSeq:r.getID().getServerSeq()},rawChange:this.isEnableDevtools()?r.toStruct():void 0}),r.hasPresenceChange()&&l.push({type:"presence-changed",source:Y.UndoRedo,value:{clientID:a,presence:this.getPresence(a)}}),this.publish(l)}getUndoStackForTest(){return this.internalHistory.getUndoStackForTest()}getRedoStackForTest(){return this.internalHistory.getRedoStackForTest()}broadcast(e,t,r){const i={type:"local-broadcast",value:{topic:e,payload:t},options:r};this.publish([i])}getVersionVector(){return this.changeID.getVersionVector()}}function _S(n,e){return t=>async r=>(n&&r.header.set("x-api-key",n),e&&r.header.set("authorization",e),await t(r))}const GS="yorkie-js-sdk",YS="0.5.4",QS="Yorkie JS SDK",XS="./src/yorkie.ts",ZS={access:"public",main:"./dist/yorkie-js-sdk.js",typings:"./dist/yorkie-js-sdk.d.ts"},ek=["dist"],tk={build:"tsc && vite build","build:proto":"npx buf generate","build:docs":"typedoc","build:ghpages":"mkdir -p ghpages/examples && cp -r docs ghpages/api-reference && find ../../examples -name 'dist' -type d -exec sh -c 'cp -r {} ghpages/examples/$(basename $(dirname {}))' \\;",dev:"vite build -c vite.preview.ts && vite preview",test:"vitest run","test:watch":"vitest","test:bench":"vitest bench","test:ci":"vitest run --coverage","test:yorkie.dev":"TEST_RPC_ADDR=https://api.yorkie.dev vitest run --coverage",prepare:"pnpm build"},nk={node:">=18.0.0",npm:">=7.1.0"},rk={type:"git",url:"git+https://github.com/yorkie-team/yorkie-js-sdk.git"},ik={name:"hackerwins",email:"susukang98@gmail.com"},sk="Apache-2.0",ok={url:"https://github.com/yorkie-team/yorkie-js-sdk/issues"},ak="https://github.com/yorkie-team/yorkie-js-sdk#readme",lk={"@buf/googleapis_googleapis.bufbuild_es":"^1.4.0-20240524201209-f0e53af8f2fc.3","@bufbuild/buf":"^1.28.1","@bufbuild/protoc-gen-es":"^1.6.0","@connectrpc/protoc-gen-connect-es":"^1.4.0","@types/google-protobuf":"^3.15.5","@types/long":"^4.0.1","@typescript-eslint/eslint-plugin":"^6.21.0","@typescript-eslint/parser":"^6.21.0","@vitest/coverage-istanbul":"^0.34.5","@vitest/coverage-v8":"^0.34.5","eslint-plugin-tsdoc":"^0.2.16",prettier:"^2.7.1","ts-node":"^10.9.1",typedoc:"^0.25.13",typescript:"^5.3.3","typescript-transform-paths":"^3.3.1",vite:"^5.0.12","vite-plugin-commonjs":"^0.10.1","vite-plugin-dts":"^3.9.1","vite-tsconfig-paths":"^4.2.1",vitest:"^0.34.5"},uk={"@bufbuild/protobuf":"^1.6.0","@connectrpc/connect":"^1.4.0","@connectrpc/connect-web":"^1.4.0",long:"^5.2.0"},lg={name:GS,version:YS,description:QS,main:XS,publishConfig:ZS,files:ek,scripts:tk,engines:nk,repository:rk,author:ik,license:sk,bugs:ok,homepage:ak,devDependencies:lk,dependencies:uk};function ck(){return n=>async e=>(e.header.set("x-yorkie-user-agent",lg.name+"/"+lg.version),await n(e))}const fk=n=>{try{if(JSON.stringify(n)===void 0)return!1}catch{return!1}return!0};var Ta=(n=>(n.Manual="manual",n.Realtime="realtime",n.RealtimePushOnly="realtime-pushonly",n.RealtimeSyncOff="realtime-syncoff",n))(Ta||{});const ra={syncLoopDuration:50,retrySyncLoopDelay:1e3,reconnectStreamDelay:1e3},Iu={maxRetries:1/0,initialRetryInterval:1e3,maxBackoff:2e4};class Oy{constructor(e,t){u(this,"id");u(this,"key");u(this,"status");u(this,"attachmentMap");u(this,"apiKey");u(this,"conditions");u(this,"syncLoopDuration");u(this,"reconnectStreamDelay");u(this,"retrySyncLoopDelay");u(this,"rpcClient");u(this,"taskQueue");u(this,"processing",!1);t=t||ra,this.key=t.key?t.key:Cy(),this.status="deactivated",this.attachmentMap=new Map,this.apiKey=t.apiKey||"",this.conditions={SyncLoop:!1,WatchLoop:!1},this.syncLoopDuration=t.syncLoopDuration||ra.syncLoopDuration,this.reconnectStreamDelay=t.reconnectStreamDelay||ra.reconnectStreamDelay,this.retrySyncLoopDelay=t.retrySyncLoopDelay||ra.retrySyncLoopDelay,this.rpcClient=a1(D1,P1({baseUrl:e,interceptors:[_S(t.apiKey,t.token),ck()]})),this.taskQueue=[]}activate(){return this.isActive()?Promise.resolve():this.enqueueTask(async()=>this.rpcClient.activateClient({clientKey:this.key},{headers:{"x-shard-key":this.apiKey}}).then(e=>{this.id=e.clientId,this.status="activated",this.runSyncLoop(),J.info(`[AC] c:"${this.getKey()}" activated, id:"${this.id}"`)}).catch(e=>{throw J.error(`[AC] c:"${this.getKey()}" err :`,e),this.handleConnectError(e),e}))}deactivate(){return this.status==="deactivated"?Promise.resolve():this.enqueueTask(async()=>this.rpcClient.deactivateClient({clientId:this.id},{headers:{"x-shard-key":this.apiKey}}).then(()=>{this.deactivateInternal(),J.info(`[DC] c"${this.getKey()}" deactivated`)}).catch(e=>{throw J.error(`[DC] c:"${this.getKey()}" err :`,e),this.handleConnectError(e),e}))}attach(e,t={}){if(!this.isActive())throw new k(S.ErrClientNotActivated,`${this.key} is not active`);if(e.getStatus()!==Nr.Detached)throw new k(S.ErrDocumentNotDetached,`${e.getKey()} is not detached`);e.setActor(this.id),e.update((s,o)=>o.set(t.initialPresence||{}));const r=e.subscribe("local-broadcast",async s=>{var d;const{topic:o,payload:a}=s.value,l=(d=s.options)==null?void 0:d.error,c=s.options;try{await this.broadcast(e.getKey(),o,a,c)}catch(h){h instanceof Error&&(l==null||l(h))}}),i=t.syncMode??"realtime";return this.enqueueTask(async()=>this.rpcClient.attachDocument({clientId:this.id,changePack:fe.toChangePack(e.createChangePack())},{headers:{"x-shard-key":`${this.apiKey}/${e.getKey()}`}}).then(async s=>{const o=fe.fromChangePack(s.changePack);if(e.applyChangePack(o),e.getStatus()===Nr.Removed)return e;e.applyStatus(Nr.Attached),this.attachmentMap.set(e.getKey(),new MS(this.reconnectStreamDelay,e,s.documentId,i,r)),i!=="manual"&&await this.runWatchLoop(e.getKey()),J.info(`[AD] c:"${this.getKey()}" attaches d:"${e.getKey()}"`);const a=e.getRootObject();if(t.initialRoot){const l=t.initialRoot;e.update(c=>{for(const[d,h]of Object.entries(l))if(!a.has(d)){const p=d;c[p]=h}})}return e}).catch(s=>{throw J.error(`[AD] c:"${this.getKey()}" err :`,s),this.handleConnectError(s),s}))}detach(e,t={}){if(!this.isActive())throw new k(S.ErrClientNotActivated,`${this.key} is not active`);const r=this.attachmentMap.get(e.getKey());if(!r)throw new k(S.ErrDocumentNotAttached,`${e.getKey()} is not attached`);return e.update((i,s)=>s.clear()),this.enqueueTask(async()=>this.rpcClient.detachDocument({clientId:this.id,documentId:r.docID,changePack:fe.toChangePack(e.createChangePack()),removeIfNotAttached:t.removeIfNotAttached??!1},{headers:{"x-shard-key":`${this.apiKey}/${e.getKey()}`}}).then(i=>{const s=fe.fromChangePack(i.changePack);return e.applyChangePack(s),e.getStatus()!==Nr.Removed&&e.applyStatus(Nr.Detached),this.detachInternal(e.getKey()),J.info(`[DD] c:"${this.getKey()}" detaches d:"${e.getKey()}"`),e}).catch(i=>{throw J.error(`[DD] c:"${this.getKey()}" err :`,i),this.handleConnectError(i),i}))}async changeSyncMode(e,t){if(!this.isActive())throw new k(S.ErrClientNotActivated,`${this.key} is not active`);const r=this.attachmentMap.get(e.getKey());if(!r)throw new k(S.ErrDocumentNotAttached,`${e.getKey()} is not attached`);const i=r.syncMode;return i===t?e:(r.changeSyncMode(t),t==="manual"?(r.cancelWatchStream(),e):(t==="realtime"&&(r.remoteChangeEventReceived=!0),i==="manual"&&await this.runWatchLoop(e.getKey()),e))}sync(e){if(!this.isActive())throw new k(S.ErrClientNotActivated,`${this.key} is not active`);if(e){const t=this.attachmentMap.get(e.getKey());if(!t)throw new k(S.ErrDocumentNotAttached,`${e.getKey()} is not attached`);return this.enqueueTask(async()=>this.syncInternal(t,"realtime").catch(r=>{throw J.error(`[SY] c:"${this.getKey()}" err :`,r),this.handleConnectError(r),r}))}return this.enqueueTask(async()=>{const t=[];for(const[,r]of this.attachmentMap)t.push(this.syncInternal(r,r.syncMode));return Promise.all(t).catch(r=>{throw J.error(`[SY] c:"${this.getKey()}" err :`,r),this.handleConnectError(r),r})})}remove(e){if(!this.isActive())throw new k(S.ErrClientNotActivated,`${this.key} is not active`);const t=this.attachmentMap.get(e.getKey());if(!t)throw new k(S.ErrDocumentNotAttached,`${e.getKey()} is not attached`);e.setActor(this.id);const r=fe.toChangePack(e.createChangePack());return r.isRemoved=!0,this.enqueueTask(async()=>this.rpcClient.removeDocument({clientId:this.id,documentId:t.docID,changePack:r},{headers:{"x-shard-key":`${this.apiKey}/${e.getKey()}`}}).then(i=>{const s=fe.fromChangePack(i.changePack);e.applyChangePack(s),this.detachInternal(e.getKey()),J.info(`[RD] c:"${this.getKey()}" removes d:"${e.getKey()}"`)}).catch(i=>{throw J.error(`[RD] c:"${this.getKey()}" err :`,i),this.handleConnectError(i),i}))}getID(){return this.id}getKey(){return this.key}isActive(){return this.status==="activated"}getStatus(){return this.status}getCondition(e){return this.conditions[e]}broadcast(e,t,r,i){if(!this.isActive())throw new k(S.ErrClientNotActivated,`${this.key} is not active`);const s=this.attachmentMap.get(e);if(!s)throw new k(S.ErrDocumentNotAttached,`${e} is not attached`);if(!fk(r))throw new k(S.ErrInvalidArgument,"payload is not serializable");const o=(i==null?void 0:i.maxRetries)??Iu.maxRetries,a=Iu.maxBackoff;let l=0;const c=h=>Math.min(Iu.initialRetryInterval*2**h,a),d=async()=>this.enqueueTask(async()=>this.rpcClient.broadcast({clientId:this.id,documentId:s.docID,topic:t,payload:new TextEncoder().encode(JSON.stringify(r))},{headers:{"x-shard-key":`${this.apiKey}/${e}`}}).then(()=>{J.info(`[BC] c:"${this.getKey()}" broadcasts d:"${e}" t:"${t}"`)}).catch(h=>{if(J.error(`[BC] c:"${this.getKey()}" err:`,h),this.handleConnectError(h))if(ld(),c(l-1)),J.info(`[BC] c:"${this.getKey()}" retry attempt ${l}/${o}`);else throw J.error(`[BC] c:"${this.getKey()}" exceeded maximum retry attempts`),h;else throw h}));return d()}runSyncLoop(){const e=()=>{if(!this.isActive()){J.debug(`[SL] c:"${this.getKey()}" exit sync loop`),this.conditions.SyncLoop=!1;return}const t=[];for(const[,r]of this.attachmentMap)r.needRealtimeSync()&&(r.remoteChangeEventReceived=!1,t.push(this.syncInternal(r,r.syncMode)));Promise.all(t).then(()=>setTimeout(e,this.syncLoopDuration)).catch(r=>{J.error(`[SL] c:"${this.getKey()}" sync failed:`,r),this.handleConnectError(r)?setTimeout(e,this.retrySyncLoopDelay):this.conditions.SyncLoop=!1})};J.debug(`[SL] c:"${this.getKey()}" run sync loop`),this.conditions.SyncLoop=!0,e()}async runWatchLoop(e){const t=this.attachmentMap.get(e);if(!t)throw new k(S.ErrDocumentNotAttached,`${e} is not attached`);return this.conditions.WatchLoop=!0,t.runWatchLoop(r=>{if(!this.isActive())return this.conditions.WatchLoop=!1,Promise.reject(new k(S.ErrClientNotActivated,`${this.key} is not active`));const i=new AbortController,s=this.rpcClient.watchDocument({clientId:this.id,documentId:t.docID},{headers:{"x-shard-key":`${this.apiKey}/${e}`},signal:i.signal});return t.doc.publish([{type:$e.ConnectionChanged,value:Kc.Connected}]),J.info(`[WD] c:"${this.getKey()}" watches d:"${e}"`),new Promise((o,a)=>{(async()=>{try{for await(const c of s)this.handleWatchDocumentsResponse(t,c),c.body.case==="initialization"&&o([s,i])}catch(c){t.doc.resetOnlineClients(),t.doc.publish([{type:$e.Initialized,source:Y.Local,value:t.doc.getPresences()}]),t.doc.publish([{type:$e.ConnectionChanged,value:Kc.Disconnected}]),J.debug(`[WD] c:"${this.getKey()}" unwatches`),this.handleConnectError(c)?r():this.conditions.WatchLoop=!1,a(c)}})()})})}handleWatchDocumentsResponse(e,t){if(t.body.case==="event"&&t.body.value.type===pi.DOCUMENT_CHANGED){e.remoteChangeEventReceived=!0;return}e.doc.applyWatchStream(t)}deactivateInternal(){this.status="deactivated";for(const[e,t]of this.attachmentMap)this.detachInternal(e),t.doc.applyStatus(Nr.Detached)}detachInternal(e){const t=this.attachmentMap.get(e);t&&(t.cancelWatchStream(),t.unsubscribeBroadcastEvent(),this.attachmentMap.delete(e))}syncInternal(e,t){const{doc:r,docID:i}=e,s=r.createChangePack();return this.rpcClient.pushPullChanges({clientId:this.id,documentId:i,changePack:fe.toChangePack(s),pushOnly:t==="realtime-pushonly"},{headers:{"x-shard-key":`${this.apiKey}/${r.getKey()}`}}).then(o=>{const a=fe.fromChangePack(o.changePack);if(a.hasChanges()&&(e.syncMode==="realtime-pushonly"||e.syncMode==="realtime-syncoff"))return r;r.applyChangePack(a),e.doc.publish([{type:$e.SyncStatusChanged,value:Wc.Synced}]),r.getStatus()===Nr.Removed&&this.detachInternal(r.getKey());const l=r.getKey(),c=a.getChangeSize();return J.info(`[PP] c:"${this.getKey()}" sync d:"${l}", push:${s.getChangeSize()} pull:${c} cp:${a.getCheckpoint().toTestString()}`),r}).catch(o=>{throw r.publish([{type:$e.SyncStatusChanged,value:Wc.SyncFailed}]),J.error(`[PP] c:"${this.getKey()}" err :`,o),o})}handleConnectError(e){return e instanceof pe?e.code===_.Canceled||e.code===_.Unknown||e.code===_.ResourceExhausted||e.code===_.Unavailable?!0:((rg(e)===S.ErrClientNotActivated||rg(e)===S.ErrClientNotFound)&&this.deactivateInternal(),!1):!1}enqueueTask(e){return new Promise((t,r)=>{this.taskQueue.push(()=>e().then(t).catch(r)),this.processing||this.processNext()})}async processNext(){if(this.taskQueue.length===0){this.processing=!1;return}try{this.processing=!0,await this.taskQueue.shift()()}catch{J.error(`[TQ] c:"${this.getKey()}" process failed, id:"${this.id}"`)}this.processNext()}}const ug={Client:Oy,Document:Dy,Primitive:ie,Text:Jl,Counter:$l,Tree:zl,LogLevel:be,setLogLevel:xy,IntType:sn.IntegerCnt,LongType:sn.LongCnt};typeof globalThis<"u"&&(globalThis.yorkie={Client:Oy,Document:Dy,Primitive:ie,Text:Jl,Counter:$l,Tree:zl,LogLevel:be,setLogLevel:xy,IntType:sn.IntegerCnt,LongType:sn.LongCnt});var Ry={exports:{}};/*! Copyright (c) 2018 Jed Watson. Licensed under the MIT License (MIT), see diff --git a/examples/react-todomvc/index.html b/examples/react-todomvc/index.html index 0a4678246..55a40170f 100644 --- a/examples/react-todomvc/index.html +++ b/examples/react-todomvc/index.html @@ -5,7 +5,7 @@ Vite + React + TS - + diff --git a/examples/simultaneous-cursors/assets/index-BSvZl1Rn.js b/examples/simultaneous-cursors/assets/index-CxBZH87P.js similarity index 99% rename from examples/simultaneous-cursors/assets/index-BSvZl1Rn.js rename to examples/simultaneous-cursors/assets/index-CxBZH87P.js index a6a26cfe3..5299d60df 100644 --- a/examples/simultaneous-cursors/assets/index-BSvZl1Rn.js +++ b/examples/simultaneous-cursors/assets/index-CxBZH87P.js @@ -58,5 +58,5 @@ Error generating stack: `+s.message+` * limitations under the License. * * SPDX-License-Identifier: Apache-2.0 - */var St=null;try{St=new WebAssembly.Instance(new WebAssembly.Module(new Uint8Array([0,97,115,109,1,0,0,0,1,13,2,96,0,1,127,96,4,127,127,127,127,1,127,3,7,6,0,1,1,1,1,1,6,6,1,127,1,65,0,11,7,50,6,3,109,117,108,0,1,5,100,105,118,95,115,0,2,5,100,105,118,95,117,0,3,5,114,101,109,95,115,0,4,5,114,101,109,95,117,0,5,8,103,101,116,95,104,105,103,104,0,0,10,191,1,6,4,0,35,0,11,36,1,1,126,32,0,173,32,1,173,66,32,134,132,32,2,173,32,3,173,66,32,134,132,126,34,4,66,32,135,167,36,0,32,4,167,11,36,1,1,126,32,0,173,32,1,173,66,32,134,132,32,2,173,32,3,173,66,32,134,132,127,34,4,66,32,135,167,36,0,32,4,167,11,36,1,1,126,32,0,173,32,1,173,66,32,134,132,32,2,173,32,3,173,66,32,134,132,128,34,4,66,32,135,167,36,0,32,4,167,11,36,1,1,126,32,0,173,32,1,173,66,32,134,132,32,2,173,32,3,173,66,32,134,132,129,34,4,66,32,135,167,36,0,32,4,167,11,36,1,1,126,32,0,173,32,1,173,66,32,134,132,32,2,173,32,3,173,66,32,134,132,130,34,4,66,32,135,167,36,0,32,4,167,11])),{}).exports}catch{}function q(n,e,t){this.low=n|0,this.high=e|0,this.unsigned=!!t}q.prototype.__isLong__;Object.defineProperty(q.prototype,"__isLong__",{value:!0});function Re(n){return(n&&n.__isLong__)===!0}function Xh(n){var e=Math.clz32(n&-n);return n?31-e:e}q.isLong=Re;var Zh={},eg={};function Ni(n,e){var t,r,i;return e?(n>>>=0,(i=0<=n&&n<256)&&(r=eg[n],r)?r:(t=W(n,0,!0),i&&(eg[n]=t),t)):(n|=0,(i=-128<=n&&n<128)&&(r=Zh[n],r)?r:(t=W(n,n<0?-1:0,!1),i&&(Zh[n]=t),t))}q.fromInt=Ni;function kt(n,e){if(isNaN(n))return e?gr:Rt;if(e){if(n<0)return gr;if(n>=ry)return oy}else{if(n<=-ng)return je;if(n+1>=ng)return sy}return n<0?kt(-n,e).neg():W(n%hs|0,n/hs|0,e)}q.fromNumber=kt;function W(n,e,t){return new q(n,e,t)}q.fromBits=W;var gl=Math.pow;function Qf(n,e,t){if(n.length===0)throw Error("empty string");if(typeof e=="number"?(t=e,e=!1):e=!!e,n==="NaN"||n==="Infinity"||n==="+Infinity"||n==="-Infinity")return e?gr:Rt;if(t=t||10,t<2||360)throw Error("interior hyphen");if(r===0)return Qf(n.substring(1),e,t).neg();for(var i=kt(gl(t,8)),s=Rt,o=0;o>>0:this.low};C.toNumber=function(){return this.unsigned?(this.high>>>0)*hs+(this.low>>>0):this.high*hs+(this.low>>>0)};C.toString=function(e){if(e=e||10,e<2||36>>0,d=c.toString(e);if(o=l,o.isZero())return d+a;for(;d.length<6;)d="0"+d;a=""+d+a}};C.getHighBits=function(){return this.high};C.getHighBitsUnsigned=function(){return this.high>>>0};C.getLowBits=function(){return this.low};C.getLowBitsUnsigned=function(){return this.low>>>0};C.getNumBitsAbs=function(){if(this.isNegative())return this.eq(je)?64:this.neg().getNumBitsAbs();for(var e=this.high!=0?this.high:this.low,t=31;t>0&&!(e&1<=0};C.isOdd=function(){return(this.low&1)===1};C.isEven=function(){return(this.low&1)===0};C.equals=function(e){return Re(e)||(e=zt(e)),this.unsigned!==e.unsigned&&this.high>>>31===1&&e.high>>>31===1?!1:this.high===e.high&&this.low===e.low};C.eq=C.equals;C.notEquals=function(e){return!this.eq(e)};C.neq=C.notEquals;C.ne=C.notEquals;C.lessThan=function(e){return this.comp(e)<0};C.lt=C.lessThan;C.lessThanOrEqual=function(e){return this.comp(e)<=0};C.lte=C.lessThanOrEqual;C.le=C.lessThanOrEqual;C.greaterThan=function(e){return this.comp(e)>0};C.gt=C.greaterThan;C.greaterThanOrEqual=function(e){return this.comp(e)>=0};C.gte=C.greaterThanOrEqual;C.ge=C.greaterThanOrEqual;C.compare=function(e){if(Re(e)||(e=zt(e)),this.eq(e))return 0;var t=this.isNegative(),r=e.isNegative();return t&&!r?-1:!t&&r?1:this.unsigned?e.high>>>0>this.high>>>0||e.high===this.high&&e.low>>>0>this.low>>>0?-1:1:this.sub(e).isNegative()?-1:1};C.comp=C.compare;C.negate=function(){return!this.unsigned&&this.eq(je)?je:this.not().add(Ki)};C.neg=C.negate;C.add=function(e){Re(e)||(e=zt(e));var t=this.high>>>16,r=this.high&65535,i=this.low>>>16,s=this.low&65535,o=e.high>>>16,a=e.high&65535,l=e.low>>>16,c=e.low&65535,d=0,h=0,p=0,m=0;return m+=s+c,p+=m>>>16,m&=65535,p+=i+l,h+=p>>>16,p&=65535,h+=r+a,d+=h>>>16,h&=65535,d+=t+o,d&=65535,W(p<<16|m,d<<16|h,this.unsigned)};C.subtract=function(e){return Re(e)||(e=zt(e)),this.add(e.neg())};C.sub=C.subtract;C.multiply=function(e){if(this.isZero())return this;if(Re(e)||(e=zt(e)),St){var t=St.mul(this.low,this.high,e.low,e.high);return W(t,St.get_high(),this.unsigned)}if(e.isZero())return this.unsigned?gr:Rt;if(this.eq(je))return e.isOdd()?je:Rt;if(e.eq(je))return this.isOdd()?je:Rt;if(this.isNegative())return e.isNegative()?this.neg().mul(e.neg()):this.neg().mul(e).neg();if(e.isNegative())return this.mul(e.neg()).neg();if(this.lt(rg)&&e.lt(rg))return kt(this.toNumber()*e.toNumber(),this.unsigned);var r=this.high>>>16,i=this.high&65535,s=this.low>>>16,o=this.low&65535,a=e.high>>>16,l=e.high&65535,c=e.low>>>16,d=e.low&65535,h=0,p=0,m=0,w=0;return w+=o*d,m+=w>>>16,w&=65535,m+=s*d,p+=m>>>16,m&=65535,m+=o*c,p+=m>>>16,m&=65535,p+=i*d,h+=p>>>16,p&=65535,p+=s*c,h+=p>>>16,p&=65535,p+=o*l,h+=p>>>16,p&=65535,h+=r*d+i*c+s*l+o*a,h&=65535,W(m<<16|w,h<<16|p,this.unsigned)};C.mul=C.multiply;C.divide=function(e){if(Re(e)||(e=zt(e)),e.isZero())throw Error("division by zero");if(St){if(!this.unsigned&&this.high===-2147483648&&e.low===-1&&e.high===-1)return this;var t=(this.unsigned?St.div_u:St.div_s)(this.low,this.high,e.low,e.high);return W(t,St.get_high(),this.unsigned)}if(this.isZero())return this.unsigned?gr:Rt;var r,i,s;if(this.unsigned){if(e.unsigned||(e=e.toUnsigned()),e.gt(this))return gr;if(e.gt(this.shru(1)))return iy;s=gr}else{if(this.eq(je)){if(e.eq(Ki)||e.eq(Kc))return je;if(e.eq(je))return Ki;var o=this.shr(1);return r=o.div(e).shl(1),r.eq(Rt)?e.isNegative()?Ki:Kc:(i=this.sub(e.mul(r)),s=r.add(i.div(e)),s)}else if(e.eq(je))return this.unsigned?gr:Rt;if(this.isNegative())return e.isNegative()?this.neg().div(e.neg()):this.neg().div(e).neg();if(e.isNegative())return this.div(e.neg()).neg();s=Rt}for(i=this;i.gte(e);){r=Math.max(1,Math.floor(i.toNumber()/e.toNumber()));for(var a=Math.ceil(Math.log(r)/Math.LN2),l=a<=48?1:gl(2,a-48),c=kt(r),d=c.mul(e);d.isNegative()||d.gt(i);)r-=l,c=kt(r,this.unsigned),d=c.mul(e);c.isZero()&&(c=Ki),s=s.add(c),i=i.sub(d)}return s};C.div=C.divide;C.modulo=function(e){if(Re(e)||(e=zt(e)),St){var t=(this.unsigned?St.rem_u:St.rem_s)(this.low,this.high,e.low,e.high);return W(t,St.get_high(),this.unsigned)}return this.sub(this.div(e).mul(e))};C.mod=C.modulo;C.rem=C.modulo;C.not=function(){return W(~this.low,~this.high,this.unsigned)};C.countLeadingZeros=function(){return this.high?Math.clz32(this.high):Math.clz32(this.low)+32};C.clz=C.countLeadingZeros;C.countTrailingZeros=function(){return this.low?Xh(this.low):Xh(this.high)+32};C.ctz=C.countTrailingZeros;C.and=function(e){return Re(e)||(e=zt(e)),W(this.low&e.low,this.high&e.high,this.unsigned)};C.or=function(e){return Re(e)||(e=zt(e)),W(this.low|e.low,this.high|e.high,this.unsigned)};C.xor=function(e){return Re(e)||(e=zt(e)),W(this.low^e.low,this.high^e.high,this.unsigned)};C.shiftLeft=function(e){return Re(e)&&(e=e.toInt()),(e&=63)===0?this:e<32?W(this.low<>>32-e,this.unsigned):W(0,this.low<>>e|this.high<<32-e,this.high>>e,this.unsigned):W(this.high>>e-32,this.high>=0?0:-1,this.unsigned)};C.shr=C.shiftRight;C.shiftRightUnsigned=function(e){return Re(e)&&(e=e.toInt()),(e&=63)===0?this:e<32?W(this.low>>>e|this.high<<32-e,this.high>>>e,this.unsigned):e===32?W(this.high,0,this.unsigned):W(this.high>>>e-32,0,this.unsigned)};C.shru=C.shiftRightUnsigned;C.shr_u=C.shiftRightUnsigned;C.rotateLeft=function(e){var t;return Re(e)&&(e=e.toInt()),(e&=63)===0?this:e===32?W(this.high,this.low,this.unsigned):e<32?(t=32-e,W(this.low<>>t,this.high<>>t,this.unsigned)):(e-=32,t=32-e,W(this.high<>>t,this.low<>>t,this.unsigned))};C.rotl=C.rotateLeft;C.rotateRight=function(e){var t;return Re(e)&&(e=e.toInt()),(e&=63)===0?this:e===32?W(this.high,this.low,this.unsigned):e<32?(t=32-e,W(this.high<>>e,this.low<>>e,this.unsigned)):(e-=32,t=32-e,W(this.low<>>e,this.high<>>e,this.unsigned))};C.rotr=C.rotateRight;C.toSigned=function(){return this.unsigned?W(this.low,this.high,!1):this};C.toUnsigned=function(){return this.unsigned?this:W(this.low,this.high,!0)};C.toBytes=function(e){return e?this.toBytesLE():this.toBytesBE()};C.toBytesLE=function(){var e=this.high,t=this.low;return[t&255,t>>>8&255,t>>>16&255,t>>>24,e&255,e>>>8&255,e>>>16&255,e>>>24]};C.toBytesBE=function(){var e=this.high,t=this.low;return[e>>>24,e>>>16&255,e>>>8&255,e&255,t>>>24,t>>>16&255,t>>>8&255,t&255]};q.fromBytes=function(e,t,r){return r?q.fromBytesLE(e,t):q.fromBytesBE(e,t)};q.fromBytesLE=function(e,t){return new q(e[0]|e[1]<<8|e[2]<<16|e[3]<<24,e[4]|e[5]<<8|e[6]<<16|e[7]<<24,t)};q.fromBytesBE=function(e,t){return new q(e[4]<<24|e[5]<<16|e[6]<<8|e[7],e[0]<<24|e[1]<<16|e[2]<<8|e[3],t)};var ve=(n=>(n[n.Null=0]="Null",n[n.Boolean=1]="Boolean",n[n.Integer=2]="Integer",n[n.Long=3]="Long",n[n.Double=4]="Double",n[n.String=5]="String",n[n.Bytes=6]="Bytes",n[n.Date=7]="Date",n))(ve||{});class re extends Po{constructor(t,r){super(r);u(this,"valueType");u(this,"value");this.valueType=re.getPrimitiveType(t),this.value=t===void 0?null:t}static of(t,r){return new re(t,r)}static valueFromBytes(t,r){switch(t){case 0:return null;case 1:return!!r[0];case 2:return r[0]|r[1]<<8|r[2]<<16|r[3]<<24;case 4:{const i=new DataView(r.buffer);return r.forEach(function(s,o){i.setUint8(o,s)}),i.getFloat64(0,!0)}case 5:return new TextDecoder("utf-8").decode(r);case 3:return q.fromBytesLE(Array.from(r));case 6:return r;case 7:return new Date(q.fromBytesLE(Array.from(r),!0).toNumber());default:throw new k(S.ErrUnimplemented,`unimplemented type: ${t}`)}}toJSON(){return this.valueType===5?`"${tn(this.value)}"`:`${this.value}`}toSortedJSON(){return this.toJSON()}toJSForTest(){return{createdAt:this.getCreatedAt().toTestString(),value:this.value,type:"YORKIE_PRIMITIVE"}}deepcopy(){const t=re.of(this.value,this.getCreatedAt());return t.setMovedAt(this.getMovedAt()),t.setRemovedAt(this.getRemovedAt()),t}getType(){return this.valueType}static getPrimitiveType(t){switch(typeof t){case"undefined":return 0;case"boolean":return 1;case"number":return this.isInteger(t)?2:4;case"string":return 5;case"object":if(t===null)return 0;if(t instanceof q)return 3;if(t instanceof Uint8Array)return 6;if(t instanceof Date)return 7}}static isSupport(t){return re.getPrimitiveType(t)!==void 0}static isInteger(t){return t%1===0}isNumericType(){const t=this.valueType;return t===2||t===3||t===4}getValue(){return this.value}toBytes(){switch(this.valueType){case 0:return new Uint8Array;case 1:return this.value?new Uint8Array([1]):new Uint8Array([0]);case 2:{const t=this.value;return new Uint8Array([t&255,t>>8&255,t>>16&255,t>>24&255])}case 4:{const t=this.value,r=new Uint8Array(8);return new DataView(r.buffer).setFloat64(0,t,!0),r}case 5:return new TextEncoder().encode(this.value);case 3:{const r=this.value.toBytesLE();return Uint8Array.from(r)}case 6:return this.value;case 7:{const t=this.value,r=q.fromNumber(t.getTime(),!0).toBytesLE();return Uint8Array.from(r)}default:throw new k(S.ErrUnimplemented,`unimplemented type: ${this.valueType}`)}}}class ml extends ny{constructor(t){super(t);u(this,"prev");u(this,"next");this.value=t}static createAfter(t,r){const i=new ml(r),s=t.next;return t.next=i,i.prev=t,i.next=s,s&&(s.prev=i),i}remove(t){return this.value.remove(t)}getCreatedAt(){return this.value.getCreatedAt()}getPositionedAt(){return this.value.getPositionedAt()}release(){this.prev&&(this.prev.next=this.next),this.next&&(this.next.prev=this.prev),this.prev=void 0,this.next=void 0}getLength(){return this.value.isRemoved()?0:1}getPrev(){return this.prev}getNext(){return this.next}getValue(){return this.value}isRemoved(){return this.value.isRemoved()}}class So{constructor(){u(this,"dummyHead");u(this,"last");u(this,"nodeMapByIndex");u(this,"nodeMapByCreatedAt");const e=re.of(0,Ft);e.setRemovedAt(Ft),this.dummyHead=new ml(e),this.last=this.dummyHead,this.nodeMapByIndex=new wo,this.nodeMapByCreatedAt=new Map,this.nodeMapByIndex.insert(this.dummyHead),this.nodeMapByCreatedAt.set(this.dummyHead.getCreatedAt().toIDString(),this.dummyHead)}static create(){return new So}get length(){return this.nodeMapByIndex.length}findNextBeforeExecutedAt(e,t){let r=this.nodeMapByCreatedAt.get(e.toIDString());if(!r)throw new k(S.ErrInvalidArgument,`cant find the given node: ${e.toIDString()}`);for(;r.getNext()&&r.getNext().getPositionedAt().after(t);)r=r.getNext();return r}release(e){this.last===e&&(this.last=e.getPrev()),e.release(),this.nodeMapByIndex.delete(e),this.nodeMapByCreatedAt.delete(e.getValue().getCreatedAt().toIDString())}insertAfter(e,t,r=t.getCreatedAt()){const i=this.findNextBeforeExecutedAt(e,r),s=ml.createAfter(i,t);i===this.last&&(this.last=s),this.nodeMapByIndex.insertAfter(i,s),this.nodeMapByCreatedAt.set(s.getCreatedAt().toIDString(),s)}moveAfter(e,t,r){const i=this.nodeMapByCreatedAt.get(e.toIDString());if(!i)throw new k(S.ErrInvalidArgument,`cant find the given node: ${e.toIDString()}`);const s=this.nodeMapByCreatedAt.get(t.toIDString());if(!s)throw new k(S.ErrInvalidArgument,`cant find the given node: ${t.toIDString()}`);i!==s&&(!s.getValue().getMovedAt()||r.after(s.getValue().getMovedAt()))&&(this.release(s),this.insertAfter(i.getCreatedAt(),s.getValue(),r),s.getValue().setMovedAt(r))}insert(e){this.insertAfter(this.last.getCreatedAt(),e)}getByID(e){return this.nodeMapByCreatedAt.get(e.toIDString())}subPathOf(e){const t=this.nodeMapByCreatedAt.get(e.toIDString());if(t)return String(this.nodeMapByIndex.indexOf(t))}purge(e){const t=this.nodeMapByCreatedAt.get(e.getCreatedAt().toIDString());if(!t)throw new k(S.ErrInvalidArgument,`fail to find the given createdAt: ${e.getCreatedAt().toIDString()}`);this.release(t)}getByIndex(e){if(e>=this.length)return;const[t,r]=this.nodeMapByIndex.find(e);let i=t;if(e===0&&t===this.dummyHead||r>0)do i&&(i=i.getNext());while(i&&i.isRemoved());return i}getPrevCreatedAt(e){let t=this.nodeMapByCreatedAt.get(e.toIDString());do t=t.getPrev();while(this.dummyHead!==t&&t.isRemoved());return t.getValue().getCreatedAt()}delete(e,t){const r=this.nodeMapByCreatedAt.get(e.toIDString()),i=r.isRemoved();return r.remove(t)&&!i&&this.nodeMapByIndex.splayNode(r),r.getValue()}deleteByIndex(e,t){const r=this.getByIndex(e);if(r)return r.remove(t)&&this.nodeMapByIndex.splayNode(r),r.getValue()}getHead(){return this.dummyHead.getValue()}getLast(){return this.last.getValue()}getLastCreatedAt(){return this.last.getCreatedAt()}toTestString(){const e=[];for(const t of this){const r=`${t.getCreatedAt().toIDString()}:${t.getValue().toJSON()}`;t.isRemoved()?e.push(`{${r}}`):e.push(`[${r}]`)}return e.join("")}*[Symbol.iterator](){let e=this.dummyHead.getNext();for(;e;)yield e,e=e.getNext()}}class nt extends Wr{constructor(t,r){super(t);u(this,"elements");this.elements=r}static create(t,r){if(!r)return new nt(t,So.create());const i=So.create();for(const s of r)i.insertAfter(i.getLastCreatedAt(),s.deepcopy());return new nt(t,i)}subPathOf(t){return this.elements.subPathOf(t)}purge(t){this.elements.purge(t)}insertAfter(t,r){this.elements.insertAfter(t,r)}moveAfter(t,r,i){this.elements.moveAfter(t,r,i)}get(t){const r=this.elements.getByIndex(t);return r==null?void 0:r.getValue()}getByID(t){const r=this.elements.getByID(t);return r==null?void 0:r.getValue()}getHead(){return this.elements.getHead()}getLast(){return this.elements.getLast()}getPrevCreatedAt(t){return this.elements.getPrevCreatedAt(t)}delete(t,r){return this.elements.delete(t,r)}deleteByIndex(t,r){return this.elements.deleteByIndex(t,r)}getLastCreatedAt(){return this.elements.getLastCreatedAt()}get length(){return this.elements.length}*[Symbol.iterator](){for(const t of this.elements)t.isRemoved()||(yield t.getValue())}toTestString(){return this.elements.toTestString()}getDescendants(t){for(const r of this.elements){const i=r.getValue();if(t(i,this))return;i instanceof Wr&&i.getDescendants(t)}}toJSON(){const t=[];for(const r of this)t.push(r.toJSON());return`[${t.join(",")}]`}toJS(){return JSON.parse(this.toJSON())}toJSForTest(){const t={};for(let r=0;r({...m,value:m.value?{attributes:Zi(m.value.getAttributes()),content:m.value.getContent()}:{attributes:void 0,content:""},type:"content"}));return[c,p,d,[l,l]]}setStyle(t,r,i,s){const[,o]=this.rgaTreeSplit.findNodeWithSplit(t[1],i),[,a]=this.rgaTreeSplit.findNodeWithSplit(t[0],i),l=[],c=this.rgaTreeSplit.findBetween(a,o),d=new Map,h=[];for(const m of c){const w=m.getCreatedAt().getActorID(),I=s!=null&&s.size?s.has(w)?s.get(w):Ft:Hs;if(m.canStyle(i,I)){const O=d.get(w),y=m.getCreatedAt();(!O||y.after(O))&&d.set(w,y),h.push(m)}}const p=[];for(const m of h){if(m.isRemoved())continue;const[w,I]=this.rgaTreeSplit.findIndexesFromRange(m.createPosRange());l.push({type:"style",actor:i.getActorID(),from:w,to:I,value:{attributes:Zi(r)}});for(const[O,y]of Object.entries(r)){const[g]=m.getValue().setAttr(O,y,i);g!==void 0&&p.push({parent:m.getValue(),child:g})}}return[d,p,l]}indexRangeToPosRange(t,r){const i=this.rgaTreeSplit.indexToPos(t);return t===r?[i,i]:[i,this.rgaTreeSplit.indexToPos(r)]}get length(){return this.rgaTreeSplit.length}getTreeByIndex(){return this.rgaTreeSplit.getTreeByIndex()}getTreeByID(){return this.rgaTreeSplit.getTreeByID()}toJSON(){const t=[];for(const r of this.rgaTreeSplit)r.isRemoved()||t.push(r.getValue().toJSON());return`[${t.join(",")}]`}toSortedJSON(){return this.toJSON()}toJSForTest(){return{createdAt:this.getCreatedAt().toTestString(),value:JSON.parse(this.toJSON()),type:"YORKIE_TEXT"}}toString(){return this.rgaTreeSplit.toString()}values(){const t=[];for(const r of this.rgaTreeSplit)if(!r.isRemoved()){const i=r.getValue();t.push({attributes:Zi(i.getAttributes()),content:i.getContent()})}return t}getRGATreeSplit(){return this.rgaTreeSplit}toTestString(){return this.rgaTreeSplit.toTestString()}deepcopy(){const t=new Et(this.rgaTreeSplit.deepcopy(),this.getCreatedAt());return t.remove(this.getRemovedAt()),t}findIndexesFromRange(t){return this.rgaTreeSplit.findIndexesFromRange(t)}getGCPairs(){const t=[];for(const r of this.rgaTreeSplit){r.getRemovedAt()&&t.push({parent:this.rgaTreeSplit,child:r});for(const i of r.getValue().getGCPairs())t.push(i)}return t}}class Oo extends $t{constructor(t,r,i,s,o,a,l){super(t,l);u(this,"fromPos");u(this,"toPos");u(this,"maxCreatedAtMapByActor");u(this,"content");u(this,"attributes");this.fromPos=r,this.toPos=i,this.maxCreatedAtMapByActor=s,this.content=o,this.attributes=a}static create(t,r,i,s,o,a,l){return new Oo(t,r,i,s,o,a,l)}execute(t){const r=t.findByCreatedAt(this.getParentCreatedAt());if(!r)throw new k(S.ErrInvalidArgument,`fail to find ${this.getParentCreatedAt()}`);if(!(r instanceof Et))throw new k(S.ErrInvalidArgument,"fail to execute, only Text can execute edit");const i=r,[,s,o]=i.edit([this.fromPos,this.toPos],this.content,this.getExecutedAt(),Object.fromEntries(this.attributes),this.maxCreatedAtMapByActor);for(const a of o)t.registerGCPair(a);return{opInfos:s.map(({from:a,to:l,value:c})=>({type:"edit",from:a,to:l,value:c,path:t.createPath(this.getParentCreatedAt())}))}}getEffectedCreatedAt(){return this.getParentCreatedAt()}toTestString(){const t=this.getParentCreatedAt().toTestString(),r=this.fromPos.toTestString(),i=this.toPos.toTestString(),s=this.content;return`${t}.EDIT(${r},${i},${s})`}getFromPos(){return this.fromPos}getToPos(){return this.toPos}getContent(){return this.content}getAttributes(){return this.attributes||new Map}getMaxCreatedAtMapByActor(){return this.maxCreatedAtMapByActor}}class Ro extends $t{constructor(t,r,i,s,o,a){super(t,a);u(this,"fromPos");u(this,"toPos");u(this,"maxCreatedAtMapByActor");u(this,"attributes");this.fromPos=r,this.toPos=i,this.maxCreatedAtMapByActor=s,this.attributes=o}static create(t,r,i,s,o,a){return new Ro(t,r,i,s,o,a)}execute(t){const r=t.findByCreatedAt(this.getParentCreatedAt());if(!r)throw new k(S.ErrInvalidArgument,`fail to find ${this.getParentCreatedAt()}`);if(!(r instanceof Et))throw new k(S.ErrInvalidArgument,"fail to execute, only Text can execute edit");const i=r,[,s,o]=i.setStyle([this.fromPos,this.toPos],this.attributes?Object.fromEntries(this.attributes):{},this.getExecutedAt(),this.maxCreatedAtMapByActor);for(const a of s)t.registerGCPair(a);return{opInfos:o.map(({from:a,to:l,value:c})=>({type:"style",from:a,to:l,value:c,path:t.createPath(this.getParentCreatedAt())}))}}getEffectedCreatedAt(){return this.getParentCreatedAt()}toTestString(){const t=this.getParentCreatedAt().toTestString(),r=this.fromPos.toTestString(),i=this.toPos.toTestString(),s=this.attributes;return`${t}.STYL(${r},${i},${JSON.stringify(s)})`}getFromPos(){return this.fromPos}getToPos(){return this.toPos}getAttributes(){return this.attributes}getMaxCreatedAtMapByActor(){return this.maxCreatedAtMapByActor}}const z1=2,U1="root",pr="text";function Os(n,e){let t=0;const r=n.children;for(let i=0;i0)throw new k(S.ErrRefused,"Text node cannot have children")}updateAncestorsSize(){let e=this.parent;const t=this.isRemoved?-1:1;for(;e&&(e.size+=this.paddedSize*t,!e.isRemoved);)e=e.parent}updateDescendantsSize(){let e=0;for(const t of this._children){const r=t.updateDescendantsSize();t.isRemoved||(e+=r)}return this.size+=e,this.paddedSize}get isText(){return this.type===pr}get paddedSize(){return this.size+(this.isText?0:z1)}isAncestorOf(e){return j1(this,e)}get nextSibling(){const e=this.parent.findOffset(this),t=this.parent.children[e+1];if(t)return t}get prevSibling(){const e=this.parent.findOffset(this),t=this.parent.children[e-1];if(t)return t}splitText(e,t){if(e===0||e===this.size)return;const r=this.value.slice(0,e),i=this.value.slice(e);if(!i.length)return;this.value=r;const s=this.cloneText(e+t);return s.value=i,this.parent.insertAfterInternal(s,this),s}get children(){return this._children.filter(e=>!e.isRemoved)}get allChildren(){return[...this._children]}hasTextChild(){return this.children.length>0&&this.children.every(e=>e.isText)}append(...e){if(this.isText)throw new k(S.ErrRefused,"Text node cannot have children");this._children.push(...e);for(const t of e)t.parent=this,t.updateAncestorsSize()}prepend(...e){if(this.isText)throw new k(S.ErrRefused,"Text node cannot have children");this._children.unshift(...e);for(const t of e)t.parent=this}insertBefore(e,t){if(this.isText)throw new k(S.ErrRefused,"Text node cannot have children");const r=this._children.indexOf(t);if(r===-1)throw new k(S.ErrInvalidArgument,"child not found");this.insertAtInternal(e,r),e.updateAncestorsSize()}insertAfter(e,t){if(this.isText)throw new k(S.ErrRefused,"Text node cannot have children");const r=this._children.indexOf(t);if(r===-1)throw new k(S.ErrInvalidArgument,"child not found");this.insertAtInternal(e,r+1),e.updateAncestorsSize()}insertAt(e,t){if(this.isText)throw new k(S.ErrRefused,"Text node cannot have children");this.insertAtInternal(e,t),e.updateAncestorsSize()}removeChild(e){if(this.isText)throw new k(S.ErrRefused,"Text node cannot have children");const t=this._children.indexOf(e);if(t===-1)throw new k(S.ErrInvalidArgument,"child not found");this._children.splice(t,1),e.parent=void 0}splitElement(e,t){const r=this.cloneElement(t);this.parent.insertAfterInternal(r,this),r.updateAncestorsSize();const i=this.children.slice(0,e),s=this.children.slice(e);this._children=i,r._children=s,this.size=this._children.reduce((o,a)=>o+a.paddedSize,0),r.size=r._children.reduce((o,a)=>o+a.paddedSize,0);for(const o of r._children)o.parent=r;return r}insertAfterInternal(e,t){if(this.isText)throw new k(S.ErrRefused,"Text node cannot have children");const r=this._children.indexOf(t);if(r===-1)throw new k(S.ErrInvalidArgument,"child not found");this.insertAtInternal(e,r+1)}insertAtInternal(e,t){if(this.isText)throw new k(S.ErrRefused,"Text node cannot have children");this._children.splice(t,0,e),e.parent=this}findOffset(e){if(this.isText)throw new k(S.ErrRefused,"Text node cannot have children");if(e.isRemoved){const t=this._children.indexOf(e);return this.allChildren.splice(0,t).filter(i=>!i.isRemoved).length}return this.children.indexOf(e)}findBranchOffset(e){if(this.isText)throw new k(S.ErrRefused,"Text node cannot have children");let t=e;for(;t;){const r=this._children.indexOf(t);if(r!==-1)return r;t=t.parent}return-1}}function j1(n,e){if(n===e)return!1;for(;e.parent;){if(e.parent===n)return!0;e=e.parent}return!1}var ge=(n=>(n.Start="Start",n.End="End",n.Text="Text",n))(ge||{});function ay(n,e,t,r){if(e>t)throw new k(S.ErrInvalidArgument,`from is greater than to: ${e} > ${t}`);if(e>n.size)throw new k(S.ErrInvalidArgument,`from is out of range: ${e} > ${n.size}`);if(t>n.size)throw new k(S.ErrInvalidArgument,`to is out of range: ${t} > ${n.size}`);if(e===t)return;let i=0;for(const s of n.children){if(e-s.paddedSizes.size;(s.isText||l)&&r([s,s.isText?"Text":"Start"],c),ay(s,Math.max(0,o),Math.min(a,s.size),r),c&&r([s,"End"],c)}i+=s.paddedSize}}function ly(n,e,t=0){for(const r of n.children)ly(r,e,t+1);e(n,t)}function Ml(n,e,t=0){for(const r of n._children)Ml(r,e,t+1);e(n,t)}function Wc(n,e,t=!0){if(e>n.size)throw new k(S.ErrInvalidArgument,`index is out of range: ${e} > ${n.size}`);if(n.isText)return{node:n,offset:e};let r=0,i=0;for(const s of n.children){if(t&&s.isText&&s.size>=e-i)return Wc(s,e-i,t);if(e===i)return{node:n,offset:r};if(!t&&s.paddedSize===e-i)return{node:n,offset:r+1};if(s.paddedSize>e-i)return Wc(s,e-i-1,t);i+=s.paddedSize,r+=1}return{node:n,offset:r}}function uy(n){return n.isText||n.children.length===0?n:uy(n.children[0])}function q1(n,e){if(n.sizen===e?0:n0)if(t.right)t.right.parent=t,t=t.right;else return t;else if(r<0)if(t.left)t.left.parent=t,t=t.left;else{let i=t.parent,s=t;for(;i&&s===i.left;)s=i,i=i.parent;return i}else return t}}lastEntry(){if(!this.root)return this.root;let e=this.root;for(;e.right;)e=e.right;return e}size(){return this.counter}isEmpty(){return this.counter===0}getInternal(e,t){for(;t;){const r=this.comparator(e,t.key);if(r===0)return t;r<0?t=t.left:r>0&&(t=t.right)}}putInternal(e,t,r){if(!r)return this.counter+=1,new H1(e,t,!0);const i=this.comparator(e,r.key);return i<0?r.left=this.putInternal(e,t,r.left):i>0?r.right=this.putInternal(e,t,r.right):r.value=t,this.isRed(r.right)&&!this.isRed(r.left)&&(r=this.rotateLeft(r)),this.isRed(r.left)&&this.isRed(r.left.left)&&(r=this.rotateRight(r)),this.isRed(r.left)&&this.isRed(r.right)&&this.flipColors(r),r}removeInternal(e,t){if(this.comparator(t,e.key)<0)!this.isRed(e.left)&&!this.isRed(e.left.left)&&(e=this.moveRedLeft(e)),e.left=this.removeInternal(e.left,t);else{if(this.isRed(e.left)&&(e=this.rotateRight(e)),this.comparator(t,e.key)===0&&!e.right){this.counter-=1;return}if(!this.isRed(e.right)&&!this.isRed(e.right.left)&&(e=this.moveRedRight(e)),this.comparator(t,e.key)===0){this.counter-=1;const r=this.min(e.right);e.value=r.value,e.key=r.key,e.right=this.removeMin(e.right)}else e.right=this.removeInternal(e.right,t)}return this.fixUp(e)}min(e){return e.left?this.min(e.left):e}removeMin(e){if(e.left)return!this.isRed(e.left)&&!this.isRed(e.left.left)&&(e=this.moveRedLeft(e)),e.left=this.removeMin(e.left),this.fixUp(e)}fixUp(e){return this.isRed(e.right)&&(e=this.rotateLeft(e)),this.isRed(e.left)&&this.isRed(e.left.left)&&(e=this.rotateRight(e)),this.isRed(e.left)&&this.isRed(e.right)&&this.flipColors(e),e}moveRedLeft(e){return this.flipColors(e),this.isRed(e.right.left)&&(e.right=this.rotateRight(e.right),e=this.rotateLeft(e),this.flipColors(e)),e}moveRedRight(e){return this.flipColors(e),this.isRed(e.left.left)&&(e=this.rotateRight(e),this.flipColors(e)),e}isRed(e){return e&&e.isRed}rotateLeft(e){const t=e.right;return e.right=t.left,t.left=e,t.isRed=t.left.isRed,t.left.isRed=!0,t}rotateRight(e){const t=e.left;return e.left=t.right,t.right=e,t.isRed=t.right.isRed,t.right.isRed=!0,t}flipColors(e){e.isRed=!e.isRed,e.left.isRed=!e.left.isRed,e.right.isRed=!e.right.isRed}}class Lt{constructor(e,t){u(this,"parentID");u(this,"leftSiblingID");this.parentID=e,this.leftSiblingID=t}static of(e,t){return new Lt(e,t)}static fromTreePos(e){const{offset:t}=e;let{node:r}=e,i;return r.isText?(r.parent.children[0]===r&&t===0?i=r.parent:i=r,r=r.parent):t===0?i=r:i=r.children[t-1],Lt.of(r.id,Ee.of(i.getCreatedAt(),i.getOffset()+t))}getParentID(){return this.parentID}static fromStruct(e){return Lt.of(Ee.of(tt.fromStruct(e.parentID.createdAt),e.parentID.offset),Ee.of(tt.fromStruct(e.leftSiblingID.createdAt),e.leftSiblingID.offset))}toStruct(){return{parentID:{createdAt:this.getParentID().getCreatedAt().toStruct(),offset:this.getParentID().getOffset()},leftSiblingID:{createdAt:this.getLeftSiblingID().getCreatedAt().toStruct(),offset:this.getLeftSiblingID().getOffset()}}}toTreeNodePair(e){const t=this.getParentID(),r=this.getLeftSiblingID(),i=e.findFloorNode(t);let s=e.findFloorNode(r);if(!i||!s)throw new k(S.ErrRefused,`cannot find node of CRDTTreePos(${t.toTestString()}, ${r.toTestString()})`);return!r.equals(t)&&r.getOffset()>0&&r.getOffset()===s.id.getOffset()&&s.insPrevID&&(s=e.findFloorNode(s.insPrevID)),[i,s]}getLeftSiblingID(){return this.leftSiblingID}equals(e){return this.getParentID().getCreatedAt().equals(e.getParentID().getCreatedAt())&&this.getParentID().getOffset()===e.getParentID().getOffset()&&this.getLeftSiblingID().getCreatedAt().equals(e.getLeftSiblingID().getCreatedAt())&&this.getLeftSiblingID().getOffset()===e.getLeftSiblingID().getOffset()}}class Ee{constructor(e,t){u(this,"createdAt");u(this,"offset");this.createdAt=e,this.offset=t}static of(e,t){return new Ee(e,t)}static fromStruct(e){return Ee.of(tt.fromStruct(e.createdAt),e.offset)}static createComparator(){return(e,t)=>{const r=e.getCreatedAt().compare(t.getCreatedAt());return r!==0?r:e.getOffset()>t.getOffset()?1:e.getOffset(){const s=i.deepcopy();return s.parent=t,s}),t.insPrevID=this.insPrevID,t.insNextID=this.insNextID,t}get value(){if(!this.isText)throw new k(S.ErrInvalidType,`cannot get value of element node: ${this.type}`);return this._value}set value(t){if(!this.isText)throw new k(S.ErrInvalidType,`cannot set value of element node: ${this.type}`);this._value=t,this.size=t.length}get isRemoved(){return!!this.removedAt}remove(t){const r=!this.removedAt;(!this.removedAt||this.removedAt.compare(t)>0)&&(this.removedAt=t),r&&this.updateAncestorsSize()}cloneText(t){return new Ze(Ee.of(this.id.getCreatedAt(),t),this.type,void 0,void 0,this.removedAt)}cloneElement(t){return new Ze(Ee.of(t(),0),this.type,void 0,void 0,this.removedAt)}split(t,r,i){const s=this.isText?this.splitText(r,this.id.getOffset()):this.splitElement(r,i);if(s){if(s.insPrevID=this.id,this.insNextID){const o=t.findFloorNode(this.insNextID);o.insPrevID=s.id,s.insNextID=this.insNextID}this.insNextID=s.id,t.registerNode(s)}return s}getCreatedAt(){return this.id.getCreatedAt()}getOffset(){return this.id.getOffset()}canDelete(t,r){return!this.getCreatedAt().after(r)&&(!this.removedAt||t.after(this.removedAt))}canStyle(t,r){return this.isText?!1:!this.getCreatedAt().after(r)&&(!this.removedAt||t.after(this.removedAt))}setAttrs(t,r){this.attrs||(this.attrs=new Ar);const i=new Array;for(const[s,o]of Object.entries(t))i.push(this.attrs.set(s,o,r));return i}purge(t){this.attrs&&this.attrs.purge(t)}getGCPairs(){const t=[];if(!this.attrs)return t;for(const r of this.attrs)r.getRemovedAt()&&t.push({parent:this,child:r});return t}}function Hc(n){var t;if(n.isText){const r=n;return{type:r.type,value:r.value}}const e={type:n.type,children:n.children.map(Hc)};return n.attrs&&(e.attributes=Zi((t=n.attrs)==null?void 0:t.toObject())),e}function Xf(n){if(n.isText)return n.value;let e="";return n.attrs&&n.attrs.size()&&(e=" "+Array.from(n.attrs).filter(t=>!t.isRemoved()).sort((t,r)=>t.getKey().localeCompare(r.getKey())).map(t=>{const r=JSON.parse(t.getValue());return typeof r=="string"?`${t.getKey()}="${r}"`:`${t.getKey()}="${tn(t.getValue())}"`}).join(" ")),`<${n.type}${e}>${n.children.map(t=>Xf(t)).join("")}`}function fy(n){if(n.isText){const e=n;return{type:e.type,value:e.value,size:e.size,isRemoved:e.isRemoved}}return{type:n.type,children:n.children.map(fy),size:n.size,isRemoved:n.isRemoved}}class xt extends Po{constructor(t,r){super(r);u(this,"indexTree");u(this,"nodeMapByID");this.indexTree=new K1(t),this.nodeMapByID=new cy(Ee.createComparator()),this.indexTree.traverseAll(i=>{this.nodeMapByID.put(i.id,i)})}static create(t,r){return new xt(t,r)}findFloorNode(t){const r=this.nodeMapByID.floorEntry(t);if(!(!r||!r.key.getCreatedAt().equals(t.getCreatedAt())))return r.value}registerNode(t){this.nodeMapByID.put(t.id,t)}findNodesAndSplitText(t,r){const[i,s]=t.toTreeNodePair(this);let o=s;const a=i===o,l=o.parent&&!a?o.parent:i;if(o.isText&&o.split(this,t.getLeftSiblingID().getOffset()-o.id.getOffset()),r){const c=l.allChildren,d=a?0:c.indexOf(o)+1;for(let h=d;h{const I=w.getCreatedAt().getActorID(),O=s?s.has(I)?s.get(I):Ft:Hs;if(w.canStyle(i,O)&&r){const y=p.get(I),g=w.getCreatedAt();(!y||g.after(y))&&p.set(I,g);const v=w.setAttrs(r,i),T=v.reduce((P,[,B])=>(B&&(P[B.getKey()]=h[B.getKey()]),P),{}),x=w.parent,N=w.prevSibling||w.parent;Object.keys(T).length>0&&d.push({type:"style",from:this.toIndex(x,N),to:this.toIndex(w,w),fromPath:this.toPath(x,N),toPath:this.toPath(w,w),actor:i.getActorID(),value:T});for(const[P]of v)P&&m.push({parent:w,child:P})}}),[p,m,d]}removeStyle(t,r,i,s){const[o,a]=this.findNodesAndSplitText(t[0],i),[l,c]=this.findNodesAndSplitText(t[1],i),d=[],h=new Map,p=[];return this.traverseInPosRange(o,a,l,c,([m])=>{const w=m.getCreatedAt().getActorID(),I=s?s.has(w)?s.get(w):Ft:Hs;if(m.canStyle(i,I)&&r){const O=h.get(w),y=m.getCreatedAt();(!O||y.after(O))&&h.set(w,y),m.attrs||(m.attrs=new Ar);for(const T of r){const x=m.attrs.remove(T,i);for(const N of x)p.push({parent:m,child:N})}const g=m.parent,v=m.prevSibling||m.parent;d.push({actor:i.getActorID(),type:"removeStyle",from:this.toIndex(g,v),to:this.toIndex(m,m),fromPath:this.toPath(g,v),toPath:this.toPath(m,m),value:r})}}),[h,p,d]}edit(t,r,i,s,o,a){const[l,c]=this.findNodesAndSplitText(t[0],s),[d,h]=this.findNodesAndSplitText(t[1],s),p=this.toIndex(l,c),m=this.toPath(l,c),w=[],I=[],O=[],y=new Map;this.traverseInPosRange(l,c,d,h,([T,x],N)=>{if(x===ge.Start&&!N)for(const H of T.children)O.push(H);const P=T.getCreatedAt().getActorID(),B=a?a.has(P)?a.get(P):Ft:Hs;if(T.canDelete(s,B)||w.includes(T.parent)){const H=y.get(P),U=T.getCreatedAt();(!H||U.after(H))&&y.set(P,U),(x===ge.Text||x===ge.Start)&&w.push(T),I.push([T,x])}});const g=this.makeDeletionChanges(I,s),v=[];for(const T of w)T.remove(s),T.isRemoved&&v.push({parent:this,child:T});for(const T of O)T.removedAt||l.append(T);if(i>0){let T=0,x=l,N=c;for(;T{l.isRemoved&&(P.remove(s),v.push({parent:this,child:P})),this.nodeMapByID.put(P.id,P)}),N.isRemoved||T.push(N);if(T.length){const N=T.map(P=>Hc(P));g.length&&g[g.length-1].from===p?g[g.length-1].value=N:g.push({type:"content",from:p,to:p,fromPath:m,toPath:m,actor:s.getActorID(),value:N})}}return[g,v,y]}editT(t,r,i,s,o){const a=this.findPos(t[0]),l=this.findPos(t[1]);this.edit([a,l],r,i,s,o)}move(t,r,i){throw new k(S.ErrUnimplemented,`not implemented: ${t}, ${r}, ${i}`)}purge(t){var s;(s=t.parent)==null||s.removeChild(t),this.nodeMapByID.remove(t.id);const r=t.insPrevID,i=t.insNextID;if(r){const o=this.findFloorNode(r);o.insNextID=i}if(i){const o=this.findFloorNode(i);o.insPrevID=r}t.insPrevID=void 0,t.insNextID=void 0}getGCPairs(){const t=[];return this.indexTree.traverse(r=>{r.getRemovedAt()&&t.push({parent:this,child:r});for(const i of r.getGCPairs())t.push(i)}),t}findPos(t,r=!0){const i=this.indexTree.findTreePos(t,r);return Lt.fromTreePos(i)}pathToPosRange(t){const r=this.pathToIndex(t);return[this.findPos(r),this.findPos(r+1)]}pathToPos(t){const r=this.indexTree.pathToIndex(t);return this.findPos(r)}getRoot(){return this.indexTree.getRoot()}getSize(){return this.indexTree.size}getNodeSize(){return this.nodeMapByID.size()}getIndexTree(){return this.indexTree}toXML(){return Xf(this.indexTree.getRoot())}toJSON(){return JSON.stringify(this.getRootTreeNode())}toJSForTest(){return{createdAt:this.getCreatedAt().toTestString(),value:JSON.parse(this.toJSON()),type:"YORKIE_TREE"}}toJSInfoForTest(){const t=this.indexTree.getRoot(),r=(i,s=void 0,o=void 0,a=0)=>{var m,w,I,O;let l,c,d;const h=i.isText?{node:i,offset:0}:s&&o?this.toTreePos(s,o):null;h&&(l=this.indexTree.indexOf(h),c=this.indexTree.treePosToPath(h),d=Lt.fromTreePos(h).toStruct());const p={type:i.type,parent:s==null?void 0:s.id.toTestString(),size:i.size,id:i.id.toTestString(),removedAt:(m=i.removedAt)==null?void 0:m.toTestString(),insPrev:(w=i.insPrevID)==null?void 0:w.toTestString(),insNext:(I=i.insNextID)==null?void 0:I.toTestString(),value:i.isText?i.value:void 0,isRemoved:i.isRemoved,children:[],depth:a,attributes:i.attrs?Zi((O=i.attrs)==null?void 0:O.toObject()):void 0,index:l,path:c,pos:d};for(let y=0;y0&&y===i[i.length-1].to?(i[i.length-1].to=g,i[i.length-1].toPath=this.toPath(O,m)):i.push({type:"content",from:y,to:g,fromPath:this.toPath(I,h),toPath:this.toPath(O,m),actor:r.getActorID()}))}return i.reverse()}findRightToken([t,r]){if(r===ge.Start){const l=t.allChildren;return l.length>0?[l[0],l[0].isText?ge.Text:ge.Start]:[t,ge.End]}const i=t.parent,s=i.allChildren,o=s.indexOf(t);if(i&&o===s.length-1)return[i,ge.End];const a=s[o+1];return[a,a.isText?ge.Text:ge.Start]}findLeftToken([t,r]){if(r===ge.End){const l=t.allChildren;if(l.length>0){const c=l[l.length-1];return[c,c.isText?ge.Text:ge.End]}return[t,ge.Start]}const i=t.parent,s=i.allChildren,o=s.indexOf(t);if(i&&o===0)return[i,ge.Start];const a=s[o-1];return[a,a.isText?ge.Text:ge.End]}}class Lo extends $t{constructor(t,r,i,s,o,a,l){super(t,l);u(this,"fromPos");u(this,"toPos");u(this,"contents");u(this,"splitLevel");u(this,"maxCreatedAtMapByActor");this.fromPos=r,this.toPos=i,this.contents=s,this.splitLevel=o,this.maxCreatedAtMapByActor=a}static create(t,r,i,s,o,a,l){return new Lo(t,r,i,s,o,a,l)}execute(t){var l;const r=t.findByCreatedAt(this.getParentCreatedAt());if(!r)throw new k(S.ErrInvalidArgument,`fail to find ${this.getParentCreatedAt()}`);if(!(r instanceof xt))throw new k(S.ErrInvalidArgument,"fail to execute, only Tree can execute edit");const i=this.getExecutedAt(),s=r,[o,a]=s.edit([this.fromPos,this.toPos],(l=this.contents)==null?void 0:l.map(c=>c.deepcopy()),this.splitLevel,i,(()=>{let c=i.getDelimiter();return this.contents!==void 0&&(c+=this.contents.length),()=>tt.of(i.getLamport(),++c,i.getActorID())})(),this.maxCreatedAtMapByActor);for(const c of a)t.registerGCPair(c);return{opInfos:o.map(({from:c,to:d,value:h,splitLevel:p,fromPath:m,toPath:w})=>({type:"tree-edit",path:t.createPath(this.getParentCreatedAt()),from:c,to:d,value:h,splitLevel:p,fromPath:m,toPath:w}))}}getEffectedCreatedAt(){return this.getParentCreatedAt()}toTestString(){const t=this.getParentCreatedAt().toTestString(),r=`${this.fromPos.getLeftSiblingID().getCreatedAt().toTestString()}/${this.fromPos.getLeftSiblingID().getOffset()}`,i=`${this.toPos.getLeftSiblingID().getCreatedAt().toTestString()}/${this.toPos.getLeftSiblingID().getOffset()}`,s=this.contents||[];return`${t}.EDIT(${r},${i},${s.map(o=>Xf(o)).join("")})`}getFromPos(){return this.fromPos}getToPos(){return this.toPos}getContents(){return this.contents}getSplitLevel(){return this.splitLevel}getMaxCreatedAtMapByActor(){return this.maxCreatedAtMapByActor}}class es{constructor(e){u(this,"vector");this.vector=e||new Map}set(e,t){this.vector.set(e,t)}get(e){return this.vector.get(e)}maxLamport(){let e=BigInt(0);for(const[,t]of this)t>e&&(e=t);return e}max(e){const t=new Map;for(const[r,i]of e){const s=this.vector.get(r),o=s&&s>i?s:i;t.set(r,o)}for(const[r,i]of this){const s=e.get(r),o=s&&s>i?s:i;t.set(r,o)}return new es(t)}afterOrEqual(e){const t=this.vector.get(e.getActorID());return t===void 0?!1:t>=e.getLamport()}deepcopy(){const e=new Map;for(const[t,r]of this.vector)e.set(t,r);return new es(e)}filter(e){const t=new Map;for(const[r]of e){const i=this.vector.get(r);i!==void 0&&t.set(r,i)}return new es(t)}size(){return this.vector.size}*[Symbol.iterator](){for(const[e,t]of this.vector)yield[e,t]}}const G1=new es(new Map);class lr{constructor(e,t,r,i,s){u(this,"clientSeq");u(this,"serverSeq");u(this,"lamport");u(this,"actor");u(this,"versionVector");this.clientSeq=e,this.serverSeq=s,this.lamport=t,this.versionVector=i,this.actor=r}static of(e,t,r,i,s){return new lr(e,t,r,i,s)}next(){const e=this.versionVector.deepcopy();return e.set(this.actor,this.lamport+1n),new lr(this.clientSeq+1,this.lamport+1n,this.actor,e)}syncClocks(e){const t=e.lamport>this.lamport?e.lamport+1n:this.lamport+1n,r=this.versionVector.max(e.versionVector),i=new lr(this.clientSeq,t,this.actor,r);return i.versionVector.set(this.actor,t),i}setClocks(e,t){const r=e>this.lamport?e:this.lamport+1n,i=this.versionVector.max(t);return i.set(this.actor,r),lr.of(this.clientSeq,r,this.actor,i)}createTimeTicket(e){return tt.of(this.lamport,e,this.actor)}setActor(e){return new lr(this.clientSeq,this.lamport,e,this.versionVector,this.serverSeq)}setVersionVector(e){return new lr(this.clientSeq,this.lamport,this.actor,e,this.serverSeq)}getClientSeq(){return this.clientSeq}getServerSeq(){return this.serverSeq?this.serverSeq.toString():""}getLamport(){return this.lamport}getLamportAsString(){return this.lamport.toString()}getActorID(){return this.actor}getVersionVector(){return this.versionVector}toTestString(){return`${this.lamport.toString()}:${this.actor.slice(-2)}:${this.clientSeq}`}}const Y1=new lr(0,0n,Gf,G1);class gs{constructor({id:e,operations:t,presenceChange:r,message:i}){u(this,"id");u(this,"operations");u(this,"presenceChange");u(this,"message");this.id=e,this.operations=t||[],this.presenceChange=r,this.message=i}static create({id:e,operations:t,presenceChange:r,message:i}){return new gs({id:e,operations:t,presenceChange:r,message:i})}getID(){return this.id}getMessage(){return this.message}hasOperations(){return this.operations.length>0}getOperations(){return this.operations}setActor(e){for(const t of this.operations)t.setActor(e);this.id=this.id.setActor(e)}hasPresenceChange(){return this.presenceChange!==void 0}getPresenceChange(){return this.presenceChange}execute(e,t,r){const i=[],s=[];for(const o of this.operations){const a=o.execute(e,r);if(!a)continue;const{opInfos:l,reverseOp:c}=a;i.push(...l),c&&s.unshift(c)}return this.presenceChange&&(this.presenceChange.type===Qr.Put?t.set(this.id.getActorID(),Pt(this.presenceChange.presence)):t.delete(this.id.getActorID())),{opInfos:i,reverseOps:s}}toTestString(){return`${this.operations.map(e=>e.toTestString()).join(",")}`}toStruct(){return{changeID:fe.bytesToHex(fe.toChangeID(this.getID()).toBinary()),message:this.getMessage(),operations:this.getOperations().map(e=>fe.bytesToHex(fe.toOperation(e).toBinary())),presenceChange:this.getPresenceChange()}}static fromStruct(e){const{changeID:t,operations:r,presenceChange:i,message:s}=e;return gs.create({id:fe.bytesToChangeID(fe.hexToBytes(t)),operations:r==null?void 0:r.map(o=>fe.bytesToOperation(fe.hexToBytes(o))),presenceChange:i,message:s})}}class Jl{constructor(e,t,r,i,s,o,a){u(this,"documentKey");u(this,"checkpoint");u(this,"isRemoved");u(this,"changes");u(this,"snapshot");u(this,"minSyncedTicket");u(this,"versionVector");this.documentKey=e,this.checkpoint=t,this.isRemoved=r,this.changes=i,this.snapshot=o,this.minSyncedTicket=a,this.versionVector=s}static create(e,t,r,i,s,o,a){return new Jl(e,t,r,i,s,o,a)}getDocumentKey(){return this.documentKey}getCheckpoint(){return this.checkpoint}getIsRemoved(){return this.isRemoved}getChanges(){return this.changes}hasChanges(){return this.changes.length>0}getChangeSize(){return this.changes.length}hasSnapshot(){return!!this.snapshot&&!!this.snapshot.length}getSnapshot(){return this.snapshot}getMinSyncedTicket(){return this.minSyncedTicket}getVersionVector(){return this.versionVector}}class ts{constructor(e,t){u(this,"serverSeq");u(this,"clientSeq");this.serverSeq=e,this.clientSeq=t}static of(e,t){return new ts(e,t)}increaseClientSeq(e){return e===0?this:new ts(this.serverSeq,this.clientSeq+e)}forward(e){if(this.equals(e))return this;const t=this.serverSeq>e.serverSeq?this.serverSeq:e.serverSeq,r=Math.max(this.clientSeq,e.clientSeq);return ts.of(t,r)}getServerSeqAsString(){return this.serverSeq.toString()}getClientSeq(){return this.clientSeq}getServerSeq(){return this.serverSeq}equals(e){return this.clientSeq===e.clientSeq&&this.serverSeq==e.serverSeq}toTestString(){return`serverSeq=${this.serverSeq}, clientSeq=${this.clientSeq}`}}const Q1=new ts(0n,0);class sn{constructor(e,t){u(this,"createdAt");u(this,"offset");this.createdAt=e,this.offset=t}static of(e,t){return new sn(e,t)}static fromStruct(e){return sn.of(tt.fromStruct(e.createdAt),e.offset)}getCreatedAt(){return this.createdAt}getOffset(){return this.offset}equals(e){return this.createdAt.compare(e.createdAt)===0&&this.offset===e.offset}hasSameCreatedAt(e){return this.createdAt.compare(e.createdAt)===0}split(e){return new sn(this.createdAt,this.offset+e)}toStruct(){return{createdAt:this.createdAt.toStruct(),offset:this.offset}}toTestString(){return`${this.createdAt.toTestString()}:${this.offset}`}toIDString(){return`${this.createdAt.toIDString()}:${this.offset}`}}const X1=sn.of(Ft,0);class Mt{constructor(e,t){u(this,"id");u(this,"relativeOffset");this.id=e,this.relativeOffset=t}static of(e,t){return new Mt(e,t)}static fromStruct(e){const t=sn.fromStruct(e.id);return Mt.of(t,e.relativeOffset)}getID(){return this.id}getRelativeOffset(){return this.relativeOffset}getAbsoluteID(){return sn.of(this.id.getCreatedAt(),this.id.getOffset()+this.relativeOffset)}toTestString(){return`${this.id.toTestString()}:${this.relativeOffset}`}toStruct(){return{id:this.id.toStruct(),relativeOffset:this.relativeOffset}}equals(e){return this.id.equals(e.id)?this.relativeOffset===e.relativeOffset:!1}}class Hr extends ny{constructor(t,r,i){super(r);u(this,"id");u(this,"removedAt");u(this,"prev");u(this,"next");u(this,"insPrev");u(this,"insNext");this.id=t,this.removedAt=i}static create(t,r){return new Hr(t,r)}static createComparator(){return(t,r)=>{const i=t.getCreatedAt().compare(r.getCreatedAt());return i!==0?i:t.getOffset()>r.getOffset()?1:t.getOffset()0&&t.getID().getOffset()==e.getOffset()){if(!t.hasInsPrev())return t;t=t.getInsPrev()}return t}findFloorNode(e){const t=this.treeByID.floorEntry(e);if(t&&!(!t.key.equals(e)&&!t.key.hasSameCreatedAt(e)))return t.value}findBetween(e,t){const r=[];let i=e;for(;i&&i!==t;)r.push(i),i=i.getNext();return r}splitNode(e,t){if(t>e.getContentLength())throw new k(S.ErrInvalidArgument,"offset should be less than or equal to length");if(t===0)return e;if(t===e.getContentLength())return e.getNext();const r=e.split(t);this.treeByIndex.updateWeight(r),this.insertAfter(e,r);const i=e.getInsNext();return i&&i.setInsPrev(r),r.setInsPrev(e),r}deleteNodes(e,t,r){if(!e.length)return[[],new Map,new Map];const[i,s]=this.filterNodes(e,t,r),o=new Map,a=new Map,l=this.makeChanges(s,t);for(const c of i){const d=c.getCreatedAt().getActorID();(!o.has(d)||c.getID().getCreatedAt().after(o.get(d)))&&o.set(d,c.getID().getCreatedAt()),a.set(c.getID().toIDString(),c),c.remove(t)}return this.deleteIndexNodes(s),[l,o,a]}filterNodes(e,t,r){const i=!!r,s=[],o=[],[a,l]=this.findEdgesOfCandidates(e);o.push(a);for(const c of e){const d=c.getCreatedAt().getActorID(),h=i?r.has(d)?r.get(d):Ft:Hs;c.canDelete(t,h)?s.push(c):o.push(c)}return o.push(l),[s,o]}findEdgesOfCandidates(e){return[e[0].getPrev(),e[e.length-1].getNext()]}makeChanges(e,t){const r=[];let i,s;for(let o=0;on<0?Math.ceil(n):Math.floor(n);var on=(n=>(n[n.IntegerCnt=0]="IntegerCnt",n[n.LongCnt=1]="LongCnt",n))(on||{});class rt extends Po{constructor(t,r,i){super(i);u(this,"valueType");u(this,"value");switch(this.valueType=t,t){case 0:typeof r=="number"?r>Math.pow(2,31)-1||r<-Math.pow(2,31)?this.value=q.fromNumber(r).toInt():this.value=ig(r):this.value=r.toInt();break;case 1:typeof r=="number"?this.value=q.fromNumber(r):this.value=r;break;default:throw new k(S.ErrUnimplemented,`unimplemented type: ${t}`)}}static create(t,r,i){return new rt(t,r,i)}static valueFromBytes(t,r){switch(t){case 0:return r[0]|r[1]<<8|r[2]<<16|r[3]<<24;case 1:return q.fromBytesLE(Array.from(r));default:throw new k(S.ErrUnimplemented,`unimplemented type: ${t}`)}}toJSON(){return`${this.value}`}toSortedJSON(){return this.toJSON()}toJSForTest(){return{createdAt:this.getCreatedAt().toTestString(),value:this.value,type:"YORKIE_COUNTER"}}deepcopy(){const t=rt.create(this.valueType,this.value,this.getCreatedAt());return t.setMovedAt(this.getMovedAt()),t}getType(){return this.valueType}static getCounterType(t){switch(typeof t){case"object":return t instanceof q?1:void 0;case"number":return t>Math.pow(2,31)-1||t<-Math.pow(2,31)?1:0;default:return}}static isSupport(t){return!!rt.getCounterType(t)}static isInteger(t){return t%1===0}isNumericType(){const t=this.valueType;return t===0||t===1}getValueType(){return this.valueType}getValue(){return this.value}toBytes(){switch(this.valueType){case 0:{const t=this.value;return new Uint8Array([t&255,t>>8&255,t>>16&255,t>>24&255])}case 1:{const r=this.value.toBytesLE();return Uint8Array.from(r)}default:throw new k(S.ErrUnimplemented,`unimplemented type: ${this.valueType}`)}}increase(t){function r(i){if(!i.isNumericType())throw new TypeError(`Unsupported type of value: ${typeof i.getValue()}`)}return r(this),r(t),this.valueType===1?this.value=this.value.add(t.getValue()):t.getType()===ve.Long?this.value=this.value+t.getValue().toInt():this.value=q.fromNumber(this.value+ig(t.getValue())).toInt(),this}}class ps extends $t{constructor(t,r,i){super(t,i);u(this,"value");this.value=r}static create(t,r,i){return new ps(t,r,i)}execute(t){const r=t.findByCreatedAt(this.getParentCreatedAt());if(!r)throw new k(S.ErrInvalidArgument,`fail to find ${this.getParentCreatedAt()}`);if(!(r instanceof rt))throw new k(S.ErrInvalidArgument,"fail to execute, only Counter can execute increase");const i=r,s=this.value.deepcopy();return i.increase(s),{opInfos:[{type:"increase",path:t.createPath(this.getParentCreatedAt()),value:s.getValue()}],reverseOp:this.toReverseOperation()}}toReverseOperation(){const t=this.value.deepcopy(),i=t.getType()===ve.Long?t.getValue().multiply(-1):t.getValue()*-1;return ps.create(this.getParentCreatedAt(),re.of(i,t.getCreatedAt()))}getEffectedCreatedAt(){return this.getParentCreatedAt()}toTestString(){return`${this.getParentCreatedAt().toTestString()}.INCREASE.${this.value.toJSON()}`}getValue(){return this.value}}class yr extends $t{constructor(t,r,i,s,o,a,l){super(t,l);u(this,"fromPos");u(this,"toPos");u(this,"maxCreatedAtMapByActor");u(this,"attributes");u(this,"attributesToRemove");this.fromPos=r,this.toPos=i,this.maxCreatedAtMapByActor=s,this.attributes=o,this.attributesToRemove=a}static create(t,r,i,s,o,a){return new yr(t,r,i,s,o,new Array,a)}static createTreeRemoveStyleOperation(t,r,i,s,o,a){return new yr(t,r,i,s,new Map,o,a)}execute(t){const r=t.findByCreatedAt(this.getParentCreatedAt());if(!r)throw new k(S.ErrInvalidArgument,`fail to find ${this.getParentCreatedAt()}`);if(!(r instanceof xt))throw new k(S.ErrInvalidArgument,"fail to execute, only Tree can execute edit");const i=r;let s,o;if(this.attributes.size){const a={};[...this.attributes].forEach(([l,c])=>a[l]=c),[,o,s]=i.style([this.fromPos,this.toPos],a,this.getExecutedAt(),this.maxCreatedAtMapByActor)}else{const a=this.attributesToRemove;[,o,s]=i.removeStyle([this.fromPos,this.toPos],a,this.getExecutedAt(),this.maxCreatedAtMapByActor)}for(const a of o)t.registerGCPair(a);return{opInfos:s.map(({from:a,to:l,value:c,fromPath:d,toPath:h})=>({type:"tree-style",from:a,to:l,value:this.attributes.size?{attributes:c}:{attributesToRemove:c},fromPath:d,toPath:h,path:t.createPath(this.getParentCreatedAt())}))}}getEffectedCreatedAt(){return this.getParentCreatedAt()}toTestString(){const t=this.getParentCreatedAt().toTestString(),r=`${this.fromPos.getLeftSiblingID().getCreatedAt().toTestString()}:${this.fromPos.getLeftSiblingID().getOffset()}`,i=`${this.toPos.getLeftSiblingID().getCreatedAt().toTestString()}:${this.toPos.getLeftSiblingID().getOffset()}`;return`${t}.STYLE(${r},${i},${Object.entries(this.attributes||{}).map(([s,o])=>`${s}:"${o}"`).join(" ")})`}getFromPos(){return this.fromPos}getToPos(){return this.toPos}getAttributes(){return this.attributes}getAttributesToRemove(){return this.attributesToRemove}getMaxCreatedAtMapByActor(){return this.maxCreatedAtMapByActor}}function Z1(n){const e=new _f,t=e.data;for(const[r,i]of Object.entries(n))t[r]=JSON.stringify(i);return e}function eS(n){if(n.type===Qr.Put)return new yo({type:Ii.PUT,presence:Z1(n.presence)});if(n.type===Qr.Clear)return new yo({type:Ii.CLEAR});throw new k(S.ErrUnimplemented,"unimplemented type")}function tS(n){return new Zp({serverSeq:n.getServerSeq(),clientSeq:n.getClientSeq()})}function dy(n){return new bl({clientSeq:n.getClientSeq(),lamport:n.getLamport(),actorId:ud(n.getActorID()),versionVector:Zf(n.getVersionVector())})}function F(n){if(n)return new b({lamport:n.getLamport(),delimiter:n.getDelimiter(),actorId:ud(n.getActorID())})}function Zf(n){if(!n)return;const e=new Fl;for(const[t,r]of n)e.vector[t]=BigInt(r.toString());return e}function hy(n){switch(n){case ve.Null:return $.NULL;case ve.Boolean:return $.BOOLEAN;case ve.Integer:return $.INTEGER;case ve.Long:return $.LONG;case ve.Double:return $.DOUBLE;case ve.String:return $.STRING;case ve.Bytes:return $.BYTES;case ve.Date:return $.DATE;default:throw new k(S.ErrInvalidType,`unsupported type: ${n}`)}}function gy(n){switch(n){case on.IntegerCnt:return $.INTEGER_CNT;case on.LongCnt:return $.LONG_CNT;default:throw new k(S.ErrInvalidType,`unsupported type: ${n}`)}}function Tu(n){if(n instanceof He)return new ut({type:$.JSON_OBJECT,createdAt:F(n.getCreatedAt()),value:Cy(n)});if(n instanceof nt)return new ut({type:$.JSON_ARRAY,createdAt:F(n.getCreatedAt()),value:RS(n)});if(n instanceof Et)return new ut({type:$.TEXT,createdAt:F(n.getCreatedAt())});if(n instanceof re)return new ut({type:hy(n.getType()),createdAt:F(n.getCreatedAt()),value:n.toBytes()});if(n instanceof rt)return new ut({type:gy(n.getType()),createdAt:F(n.getCreatedAt()),value:n.toBytes()});if(n instanceof xt)return new ut({type:$.TREE,createdAt:F(n.getCreatedAt()),value:BS(n)});throw new k(S.ErrUnimplemented,"unimplemented element")}function nS(n){return new mo({createdAt:F(n.getCreatedAt()),offset:n.getOffset()})}function ea(n){return new Tr({createdAt:F(n.getID().getCreatedAt()),offset:n.getID().getOffset(),relativeOffset:n.getRelativeOffset()})}function ta(n){return new Ai({parentId:_s(n.getParentID()),leftSiblingId:_s(n.getLeftSiblingID())})}function _s(n){return new Kr({createdAt:F(n.getCreatedAt()),offset:n.getOffset()})}function my(n){const e=new Hf;if(n instanceof Ei){const t=n,r=new Ya;r.parentCreatedAt=F(t.getParentCreatedAt()),r.key=t.getKey(),r.value=Tu(t.getValue()),r.executedAt=F(t.getExecutedAt()),e.body.case="set",e.body.value=r}else if(n instanceof Do){const t=n,r=new Qa;r.parentCreatedAt=F(t.getParentCreatedAt()),r.prevCreatedAt=F(t.getPrevCreatedAt()),r.value=Tu(t.getValue()),r.executedAt=F(t.getExecutedAt()),e.body.case="add",e.body.value=r}else if(n instanceof Fr){const t=n,r=new Xa;r.parentCreatedAt=F(t.getParentCreatedAt()),r.prevCreatedAt=F(t.getPrevCreatedAt()),r.createdAt=F(t.getCreatedAt()),r.executedAt=F(t.getExecutedAt()),e.body.case="move",e.body.value=r}else if(n instanceof Xr){const t=n,r=new Za;r.parentCreatedAt=F(t.getParentCreatedAt()),r.createdAt=F(t.getCreatedAt()),r.executedAt=F(t.getExecutedAt()),e.body.case="remove",e.body.value=r}else if(n instanceof Oo){const t=n,r=new el;r.parentCreatedAt=F(t.getParentCreatedAt()),r.from=ea(t.getFromPos()),r.to=ea(t.getToPos());const i=r.createdAtMapByActor;for(const[o,a]of t.getMaxCreatedAtMapByActor())i[o]=F(a);r.content=t.getContent();const s=r.attributes;for(const[o,a]of t.getAttributes())s[o]=a;r.executedAt=F(t.getExecutedAt()),e.body.case="edit",e.body.value=r}else if(n instanceof Ro){const t=n,r=new tl;r.parentCreatedAt=F(t.getParentCreatedAt()),r.from=ea(t.getFromPos()),r.to=ea(t.getToPos());const i=r.createdAtMapByActor;for(const[o,a]of t.getMaxCreatedAtMapByActor())i[o]=F(a);const s=r.attributes;for(const[o,a]of t.getAttributes())s[o]=a;r.executedAt=F(t.getExecutedAt()),e.body.case="style",e.body.value=r}else if(n instanceof ps){const t=n,r=new nl;r.parentCreatedAt=F(t.getParentCreatedAt()),r.value=Tu(t.getValue()),r.executedAt=F(t.getExecutedAt()),e.body.case="increase",e.body.value=r}else if(n instanceof Lo){const t=n,r=new rl,i=r.createdAtMapByActor;for(const[s,o]of t.getMaxCreatedAtMapByActor())i[s]=F(o);r.parentCreatedAt=F(t.getParentCreatedAt()),r.from=ta(t.getFromPos()),r.to=ta(t.getToPos()),r.contents=uS(t.getContents()),r.splitLevel=t.getSplitLevel(),r.executedAt=F(t.getExecutedAt()),e.body.case="treeEdit",e.body.value=r}else if(n instanceof yr){const t=n,r=new il;r.parentCreatedAt=F(t.getParentCreatedAt()),r.from=ta(t.getFromPos()),r.to=ta(t.getToPos());const i=r.createdAtMapByActor;for(const[o,a]of t.getMaxCreatedAtMapByActor())i[o]=F(a);const s=t.getAttributesToRemove();if(s.length>0)r.attributesToRemove=s;else{const o=r.attributes;for(const[a,l]of t.getAttributes())o[a]=l}r.executedAt=F(t.getExecutedAt()),e.body.case="treeStyle",e.body.value=r}else throw new k(S.ErrUnimplemented,"unimplemented operation");return e}function rS(n){const e=[];for(const t of n)e.push(my(t));return e}function iS(n){const e=new Qp({id:dy(n.getID()),message:n.getMessage()});return n.hasOperations()&&(e.operations=rS(n.getOperations())),n.hasPresenceChange()&&(e.presenceChange=eS(n.getPresenceChange())),e}function sS(n){const e=[];for(const t of n)e.push(iS(t));return e}function oS(n){const e=[];for(const t of n)e.push(new Xp({key:t.getStrKey(),element:td(t.getValue())}));return e}function aS(n){const e=[];for(const t of n)e.push(new fl({element:td(t.getValue())}));return e}function lS(n){const e=[];for(const t of n){const r=new dl;r.id=nS(t.getID()),r.value=t.getValue().getContent(),r.removedAt=F(t.getRemovedAt());const i=r.attributes,s=t.getValue().getAttrs();for(const o of s){const a=new fs;a.value=o.getValue(),a.updatedAt=F(o.getUpdatedAt()),i[o.getKey()]=a}e.push(r)}return e}function uS(n){const e=[];if(!n||!n.length)return e;for(const t of n)e.push(new hl({content:ed(t)}));return e}function cS(n){const e={};for(const t of n)e[t.getKey()]=new fs({value:t.getValue(),updatedAt:F(t.getUpdatedAt()),isRemoved:t.isRemoved()});return e}function ed(n){if(!n)return[];const e=[];return Ml(n,(t,r)=>{const i=new po({id:_s(t.id),type:t.type,removedAt:F(t.removedAt),depth:r});t.isText&&(i.value=t.value),t.insPrevID&&(i.insPrevId=_s(t.insPrevID)),t.insNextID&&(i.insNextId=_s(t.insNextID)),t.attrs&&(i.attributes=cS(t.attrs)),e.push(i)}),e}function fS(n){const e=new _e;return e.body.case="jsonObject",e.body.value=new sl({nodes:oS(n.getRHT()),createdAt:F(n.getCreatedAt()),movedAt:F(n.getMovedAt()),removedAt:F(n.getRemovedAt())}),e}function py(n){const e=new _e;return e.body.case="jsonArray",e.body.value=new ol({nodes:aS(n.getElements()),createdAt:F(n.getCreatedAt()),movedAt:F(n.getMovedAt()),removedAt:F(n.getRemovedAt())}),e}function dS(n){const e=new _e;return e.body.case="primitive",e.body.value=new al({type:hy(n.getType()),value:n.toBytes(),createdAt:F(n.getCreatedAt()),movedAt:F(n.getMovedAt()),removedAt:F(n.getRemovedAt())}),e}function hS(n){const e=new _e;return e.body.case="text",e.body.value=new ll({nodes:lS(n.getRGATreeSplit()),createdAt:F(n.getCreatedAt()),movedAt:F(n.getMovedAt()),removedAt:F(n.getRemovedAt())}),e}function gS(n){const e=new _e;return e.body.case="counter",e.body.value=new ul({type:gy(n.getType()),value:n.toBytes(),createdAt:F(n.getCreatedAt()),movedAt:F(n.getMovedAt()),removedAt:F(n.getRemovedAt())}),e}function yy(n){const e=new _e;return e.body.case="tree",e.body.value=new cl({nodes:ed(n.getRoot()),createdAt:F(n.getCreatedAt()),movedAt:F(n.getMovedAt()),removedAt:F(n.getRemovedAt())}),e}function td(n){if(n instanceof He)return fS(n);if(n instanceof nt)return py(n);if(n instanceof re)return dS(n);if(n instanceof Et)return hS(n);if(n instanceof rt)return gS(n);if(n instanceof xt)return yy(n);throw new k(S.ErrUnimplemented,"unimplemented element")}function mS(n){return new Er({documentKey:n.getDocumentKey(),checkpoint:tS(n.getCheckpoint()),isRemoved:n.getIsRemoved(),changes:sS(n.getChanges()),snapshot:n.getSnapshot(),versionVector:Zf(n.getVersionVector()),minSyncedTicket:F(n.getMinSyncedTicket())})}function sg(n){const e=n.findDetails(O1);for(const t of e)if(t.metadata.code)return t.metadata.code;return""}function vy(n){return lr.of(n.clientSeq,BigInt(n.lamport),ad(n.actorId),nd(n.versionVector),BigInt(n.serverSeq))}function nd(n){if(!n)return;const e=new es;return Object.entries(n.vector).forEach(([t,r])=>{e.set(t,BigInt(r.toString()))}),e}function M(n){if(n)return tt.of(BigInt(n.lamport),n.delimiter,ad(n.actorId))}function rd(n){const e={};return Object.entries(n.data).forEach(([t,r])=>{e[t]=JSON.parse(r)}),e}function pS(n){const e=n.type;if(e===Ii.PUT){const t=rd(n.presence);return{type:Qr.Put,presence:t}}if(e===Ii.CLEAR)return{type:Qr.Clear};throw new k(S.ErrInvalidType,`unsupported type: ${e}`)}function yS(n){const e=new Map;return Object.entries(n).forEach(([t,r])=>{e.set(t,rd(r))}),e}function wy(n){switch(n){case $.NULL:return ve.Null;case $.BOOLEAN:return ve.Boolean;case $.INTEGER:return ve.Integer;case $.LONG:return ve.Long;case $.DOUBLE:return ve.Double;case $.STRING:return ve.String;case $.BYTES:return ve.Bytes;case $.DATE:return ve.Date}throw new k(S.ErrUnimplemented,`unimplemented value type: ${n}`)}function pl(n){switch(n){case $.INTEGER_CNT:return on.IntegerCnt;case $.LONG_CNT:return on.LongCnt}throw new k(S.ErrUnimplemented,`unimplemented value type: ${n}`)}function Au(n){switch(n.type){case $.JSON_OBJECT:return n.value?xy(n.value):He.create(M(n.createdAt));case $.JSON_ARRAY:return n.value?OS(n.value):nt.create(M(n.createdAt));case $.TEXT:return Et.create(ms.create(),M(n.createdAt));case $.TREE:return LS(n.value);case $.NULL:case $.BOOLEAN:case $.INTEGER:case $.LONG:case $.DOUBLE:case $.STRING:case $.BYTES:case $.DATE:return re.of(re.valueFromBytes(wy(n.type),n.value),M(n.createdAt));case $.INTEGER_CNT:case $.LONG_CNT:return rt.create(pl(n.type),rt.valueFromBytes(pl(n.type),n.value),M(n.createdAt))}}function na(n){return Mt.of(sn.of(M(n.createdAt),n.offset),n.relativeOffset)}function Sy(n){return sn.of(M(n.createdAt),n.offset)}function vS(n){const e=ko.create(n.value);Object.entries(n.attributes).forEach(([r,i])=>{e.setAttr(r,i.value,M(i.updatedAt))});const t=Hr.create(Sy(n.id),e);return t.remove(M(n.removedAt)),t}function Oi(n){return Lt.of(Gs(n.parentId),Gs(n.leftSiblingId))}function Gs(n){return Ee.of(M(n.createdAt),n.offset)}function wS(n){if(!n.length)return;const e=[];return n.forEach(t=>{const r=id(t.content);e.push(r)}),e}function id(n){if(n.length===0)return;const e=[];for(const i of n)e.push(kS(i));const t=e[e.length-1],r=new Map;r.set(n[e.length-1].depth,e[e.length-1]);for(let i=e.length-2;i>=0;i--)r.get(n[i].depth-1).prepend(e[i]),r.set(n[i].depth,e[i]);return t.updateDescendantsSize(),xt.create(t,Ft).getRoot()}function SS(n){const e=Ar.create();for(const[t,r]of Object.entries(n))e.setInternal(t,r.value,M(r.updatedAt),r.isRemoved);return e}function kS(n){const e=Gs(n.id),t=Ze.create(e,n.type),r=Object.entries(n.attributes);return t.isText?t.value=n.value:r.length&&(t.attrs=SS(n.attributes)),n.insPrevId&&(t.insPrevID=Gs(n.insPrevId)),n.insNextId&&(t.insNextID=Gs(n.insNextId)),t.removedAt=M(n.removedAt),t}function ky(n){if(n.body.case==="set"){const e=n.body.value;return Ei.create(e.key,Au(e.value),M(e.parentCreatedAt),M(e.executedAt))}else if(n.body.case==="add"){const e=n.body.value;return Do.create(M(e.parentCreatedAt),M(e.prevCreatedAt),Au(e.value),M(e.executedAt))}else if(n.body.case==="move"){const e=n.body.value;return Fr.create(M(e.parentCreatedAt),M(e.prevCreatedAt),M(e.createdAt),M(e.executedAt))}else if(n.body.case==="remove"){const e=n.body.value;return Xr.create(M(e.parentCreatedAt),M(e.createdAt),M(e.executedAt))}else if(n.body.case==="edit"){const e=n.body.value,t=new Map;Object.entries(e.createdAtMapByActor).forEach(([i,s])=>{t.set(i,M(s))});const r=new Map;return Object.entries(e.attributes).forEach(([i,s])=>{r.set(i,s)}),Oo.create(M(e.parentCreatedAt),na(e.from),na(e.to),t,e.content,r,M(e.executedAt))}else if(n.body.case==="style"){const e=n.body.value,t=new Map;Object.entries(e.createdAtMapByActor).forEach(([i,s])=>{t.set(i,M(s))});const r=new Map;return Object.entries(e.attributes).forEach(([i,s])=>{r.set(i,s)}),Ro.create(M(e.parentCreatedAt),na(e.from),na(e.to),t,r,M(e.executedAt))}else{if(n.body.case==="select")return;if(n.body.case==="increase"){const e=n.body.value;return ps.create(M(e.parentCreatedAt),Au(e.value),M(e.executedAt))}else if(n.body.case==="treeEdit"){const e=n.body.value,t=new Map;return Object.entries(e.createdAtMapByActor).forEach(([r,i])=>{t.set(r,M(i))}),Lo.create(M(e.parentCreatedAt),Oi(e.from),Oi(e.to),wS(e.contents),e.splitLevel,t,M(e.executedAt))}else if(n.body.case==="treeStyle"){const e=n.body.value,t=new Map,r=e.attributesToRemove,i=new Map;return e!=null&&e.createdAtMapByActor&&Object.entries(e.createdAtMapByActor).forEach(([s,o])=>{i.set(s,M(o))}),(r==null?void 0:r.length)>0?yr.createTreeRemoveStyleOperation(M(e.parentCreatedAt),Oi(e.from),Oi(e.to),i,r,M(e.executedAt)):(Object.entries(e.attributes).forEach(([s,o])=>{t.set(s,o)}),yr.create(M(e.parentCreatedAt),Oi(e.from),Oi(e.to),i,t,M(e.executedAt)))}else throw new k(S.ErrUnimplemented,"unimplemented operation")}}function TS(n){const e=[];for(const t of n){const r=ky(t);r&&e.push(r)}return e}function Ty(n){const e=[];for(const t of n)e.push(gs.create({id:vy(t.id),operations:TS(t.operations),presenceChange:t.presenceChange?pS(t.presenceChange):void 0,message:t.message}));return e}function AS(n){return ts.of(BigInt(n.serverSeq),n.clientSeq)}function IS(n){return Jl.create(n.documentKey,AS(n.checkpoint),n.isRemoved,Ty(n.changes),nd(n.versionVector),n.snapshot,M(n.minSyncedTicket))}function Ay(n){const e=new vo;for(const r of n.nodes){const i=sd(r.element);e.set(r.key,i,i.getPositionedAt())}const t=new He(M(n.createdAt),e);return t.setMovedAt(M(n.movedAt)),t.setRemovedAt(M(n.removedAt)),t}function Iy(n){const e=new So;for(const r of n.nodes)e.insert(sd(r.element));const t=new nt(M(n.createdAt),e);return t.setMovedAt(M(n.movedAt)),t.setRemovedAt(M(n.removedAt)),t}function ES(n){const e=re.of(re.valueFromBytes(wy(n.type),n.value),M(n.createdAt));return e.setMovedAt(M(n.movedAt)),e.setRemovedAt(M(n.removedAt)),e}function xS(n){const e=new ms;let t=e.getHead();for(const i of n.nodes){const s=e.insertAfter(t,vS(i));i.insPrevId&&s.setInsPrev(e.findNode(Sy(i.insPrevId))),t=s}const r=new Et(e,M(n.createdAt));return r.setMovedAt(M(n.movedAt)),r.setRemovedAt(M(n.removedAt)),r}function CS(n){const e=rt.create(pl(n.type),rt.valueFromBytes(pl(n.type),n.value),M(n.createdAt));return e.setMovedAt(M(n.movedAt)),e.setRemovedAt(M(n.removedAt)),e}function Ey(n){const e=id(n.nodes);return xt.create(e,M(n.createdAt))}function sd(n){if(n.body.case==="jsonObject")return Ay(n.body.value);if(n.body.case==="jsonArray")return Iy(n.body.value);if(n.body.case==="primitive")return ES(n.body.value);if(n.body.case==="text")return xS(n.body.value);if(n.body.case==="counter")return CS(n.body.value);if(n.body.case==="tree")return Ey(n.body.value);throw new k(S.ErrUnimplemented,"unimplemented element")}function NS(n){if(!n)return{root:He.create(Ft),presences:new Map};const e=Tc.fromBinary(n);return{root:sd(e.root),presences:yS(e.presences)}}function PS(n){const e=Zf(n);return od(e.toBinary())}function DS(n){const e=ld(n),t=Fl.fromBinary(e);return nd(t)}function xy(n){if(!n)throw new k(S.ErrInvalidArgument,"bytes is empty");const e=_e.fromBinary(n);return Ay(e.body.value)}function Cy(n){return td(n).toBinary()}function OS(n){if(!n)throw new k(S.ErrInvalidArgument,"bytes is empty");const e=_e.fromBinary(n);return Iy(e.body.value)}function RS(n){return py(n).toBinary()}function LS(n){if(!n)throw new k(S.ErrInvalidArgument,"bytes is empty");const e=_e.fromBinary(n);return Ey(e.body.value)}function BS(n){return yy(n).toBinary()}function od(n){return n?Array.from(n).map(e=>e.toString(16).padStart(2,"0")).join(""):""}function ad(n){return od(n)}function ld(n){return new Uint8Array(n.match(/.{1,2}/g).map(e=>parseInt(e,16)))}function ud(n){return ld(n)}function bS(n){const e=bl.fromBinary(n);return vy(e)}function FS(n){const e=Hf.fromBinary(n);return ky(e)}const fe={fromPresence:rd,toChangePack:mS,fromChangePack:IS,fromChanges:Ty,toTreeNodes:ed,fromTreeNodes:id,objectToBytes:Cy,bytesToObject:xy,bytesToSnapshot:NS,bytesToHex:od,hexToBytes:ld,toHexString:ad,toUint8Array:ud,toOperation:my,toChangeID:dy,PbChangeID:bl,bytesToChangeID:bS,bytesToOperation:FS,versionVectorToHex:PS,hexToVersionVector:DS};var be=(n=>(n[n.Trivial=0]="Trivial",n[n.Debug=1]="Debug",n[n.Info=2]="Info",n[n.Warn=3]="Warn",n[n.Error=4]="Error",n[n.Fatal=5]="Fatal",n))(be||{});let ai=3;function Ny(n){ai=n}const J={trivial:(...n)=>{ai>0||typeof console<"u"&&console.log("YORKIE T:",...n)},debug:(...n)=>{ai>1||typeof console<"u"&&console.log("YORKIE D:",...n)},info:(...n)=>{ai>2||typeof console<"u"&&console.log("YORKIE I:",...n)},warn:(...n)=>{ai>3||typeof console<"u"&&(typeof console.warn<"u"?console.warn("YORKIE W:",...n):console.log("YORKIE W:",...n))},error:(...n)=>{ai>4||typeof console<"u"&&(typeof console.error<"u"?console.error("YORKIE E:",...n):console.log("YORKIE E:",...n))},fatal:(...n)=>{typeof console<"u"&&(typeof console.error<"u"?console.error("YORKIE F:",...n):console.log("YORKIE F:",...n))},isEnabled:n=>ai<=n};function Py(){return"xxxxxxxx-xxxx-4xxxy-xxxx-xxxxxxxxxxx".replace(/[xy]/g,n=>{const e=Math.random()*16|0;return(n==="x"?e:e&3|8).toString(16)})}class MS{constructor(e,t,r,i,s){u(this,"reconnectStreamDelay");u(this,"doc");u(this,"docID");u(this,"syncMode");u(this,"remoteChangeEventReceived");u(this,"watchStream");u(this,"watchLoopTimerID");u(this,"watchAbortController");u(this,"unsubscribeBroadcastEvent");this.reconnectStreamDelay=e,this.doc=t,this.docID=r,this.syncMode=i,this.remoteChangeEventReceived=!1,this.unsubscribeBroadcastEvent=s}changeSyncMode(e){this.syncMode=e}needRealtimeSync(){return this.syncMode===Aa.RealtimeSyncOff?!1:this.syncMode===Aa.RealtimePushOnly?this.doc.hasLocalChanges():this.syncMode!==Aa.Manual&&(this.doc.hasLocalChanges()||this.remoteChangeEventReceived)}async runWatchLoop(e){const t=async()=>{if(this.watchStream)return Promise.resolve();this.watchLoopTimerID&&(clearTimeout(this.watchLoopTimerID),this.watchLoopTimerID=void 0);try{[this.watchStream,this.watchAbortController]=await e(()=>{this.watchStream=void 0,this.watchAbortController=void 0,this.watchLoopTimerID=setTimeout(t,this.reconnectStreamDelay)})}catch{}};await t()}cancelWatchStream(){this.watchStream&&this.watchAbortController&&(this.watchAbortController.abort(),this.watchStream=void 0,this.watchAbortController=void 0),clearTimeout(this.watchLoopTimerID),this.watchLoopTimerID=void 0}}const Iu=()=>{};class JS{constructor(e){u(this,"finalized",!1);u(this,"observers",[]);u(this,"finalError");try{e(this)}catch(t){this.error(t)}}next(e){this.forEachObserver(t=>{t.next(e)})}error(e){this.forEachObserver(t=>{t.error(e)}),this.close(e)}complete(){this.forEachObserver(e=>{e.complete()}),this.close()}subscribe(e,t,r){let i;if(!e)throw new k(S.ErrInvalidArgument,"missing observer");if(this.finalized)throw new k(S.ErrRefused,"observable is finalized due to previous error");typeof e=="object"?i=e:i={next:e,error:t,complete:r},i.next===void 0&&(i.next=Iu),i.error===void 0&&(i.error=Iu),i.complete===void 0&&(i.complete=Iu);const s=Py(),o=this.unsubscribeOne.bind(this,s);if(this.observers.push({subscriptionID:s,observer:i}),this.finalized)try{this.finalError?i.error(this.finalError):i.complete()}catch(a){J.warn(a)}return o}unsubscribeOne(e){var t;this.observers=(t=this.observers)==null?void 0:t.filter(r=>r.subscriptionID!==e)}forEachObserver(e){if(!this.finalized)for(let t=0;te}}class Wi{constructor(e,t,r,i){u(this,"id");u(this,"delimiter");u(this,"message");u(this,"root");u(this,"operations");u(this,"presenceChange");u(this,"previousPresence");u(this,"reversePresenceKeys");this.id=e,this.delimiter=ty,this.root=t,this.operations=[],this.previousPresence=Pt(r),this.presenceChange=void 0,this.reversePresenceKeys=new Set,this.message=i}static create(e,t,r,i){return new Wi(e,t,r,i)}push(e){this.operations.push(e)}registerElement(e,t){this.root.registerElement(e,t)}registerRemovedElement(e){this.root.registerRemovedElement(e)}registerGCPair(e){this.root.registerGCPair(e)}getChange(){return gs.create({id:this.id,operations:this.operations,presenceChange:this.presenceChange,message:this.message})}hasChange(){return this.operations.length>0||this.presenceChange!==void 0}setPresenceChange(e){this.presenceChange=e}setReversePresence(e,t){for(const r of Object.keys(e))t!=null&&t.addToHistory?this.reversePresenceKeys.add(r):this.reversePresenceKeys.delete(r)}getReversePresence(){if(this.reversePresenceKeys.size===0)return;const e={};for(const t of this.reversePresenceKeys)e[t]=this.previousPresence[t];return e}issueTimeTicket(){return this.delimiter+=1,this.id.createTimeTicket(this.delimiter)}getLastTimeTicket(){return this.id.createTimeTicket(this.delimiter)}}class To{constructor(e){u(this,"rootObject");u(this,"elementPairMapByCreatedAt");u(this,"gcElementSetByCreatedAt");u(this,"gcPairMap");this.rootObject=e,this.elementPairMapByCreatedAt=new Map,this.gcElementSetByCreatedAt=new Set,this.gcPairMap=new Map,this.registerElement(e,void 0),e.getDescendants(t=>{if(t.getRemovedAt()&&this.registerRemovedElement(t),t instanceof Et||t instanceof xt)for(const r of t.getGCPairs())this.registerGCPair(r);return!1})}static create(){return new To(He.create(Ft))}findByCreatedAt(e){const t=this.elementPairMapByCreatedAt.get(e.toIDString());if(t)return t.element}findElementPairByCreatedAt(e){return this.elementPairMapByCreatedAt.get(e.toIDString())}createSubPaths(e){let t=this.elementPairMapByCreatedAt.get(e.toIDString());if(!t)return[];const r=[];for(;t.parent;){const i=t.element.getCreatedAt(),s=t.parent.subPathOf(i);if(s===void 0)throw new k(S.ErrInvalidArgument,`cant find the given element: ${i.toIDString()}`);r.unshift(s),t=this.elementPairMapByCreatedAt.get(t.parent.getCreatedAt().toIDString())}return r.unshift("$"),r}createPath(e){return this.createSubPaths(e).join(".")}registerElement(e,t){this.elementPairMapByCreatedAt.set(e.getCreatedAt().toIDString(),{parent:t,element:e}),e instanceof Wr&&e.getDescendants((r,i)=>(this.registerElement(r,i),!1))}deregisterElement(e){let t=0;const r=i=>{const s=i.getCreatedAt().toIDString();this.elementPairMapByCreatedAt.delete(s),this.gcElementSetByCreatedAt.delete(s),t++};return r(e),e instanceof Wr&&e.getDescendants(i=>(r(i),!1)),t}registerRemovedElement(e){this.gcElementSetByCreatedAt.add(e.getCreatedAt().toIDString())}registerGCPair(e){if(this.gcPairMap.get(e.child.toIDString())){this.gcPairMap.delete(e.child.toIDString());return}this.gcPairMap.set(e.child.toIDString(),e)}getElementMapSize(){return this.elementPairMapByCreatedAt.size}getGarbageElementSetSize(){const e=new Set;for(const t of this.gcElementSetByCreatedAt){e.add(t);const r=this.elementPairMapByCreatedAt.get(t);r.element instanceof Wr&&r.element.getDescendants(i=>(e.add(i.getCreatedAt().toIDString()),!1))}return e.size}getObject(){return this.rootObject}getGarbageLen(){return this.getGarbageElementSetSize()+this.gcPairMap.size}deepcopy(){return new To(this.rootObject.deepcopy())}garbageCollect(e){let t=0;for(const r of this.gcElementSetByCreatedAt){const i=this.elementPairMapByCreatedAt.get(r),s=i.element.getRemovedAt();s&&(e!=null&&e.afterOrEqual(s))&&(i.parent.purge(i.element),t+=this.deregisterElement(i.element))}for(const[,r]of this.gcPairMap){const i=r.child.getRemovedAt();i&&(e!=null&&e.afterOrEqual(i))&&(r.parent.purge(r.child),this.gcPairMap.delete(r.child.toIDString()),t+=1)}return t}toJSON(){return this.rootObject.toJSON()}toSortedJSON(){return this.rootObject.toSortedJSON()}getStats(){return{elements:this.getElementMapSize(),gcPairs:this.gcPairMap.size,gcElements:this.getGarbageElementSetSize()}}}function Dy(n,e){const t=new Ao(n);return new Proxy(e,t.getHandlers())}class Ao{constructor(e){u(this,"context");u(this,"handlers");this.context=e,this.handlers={set:(t,r,i)=>(J.isEnabled(be.Trivial)&&J.trivial(`obj[${r}]=${JSON.stringify(i)}`),Ao.setInternal(e,t,r,i),!0),get:(t,r)=>(J.isEnabled(be.Trivial)&&J.trivial(`obj[${r}]`),r==="getID"?()=>t.getCreatedAt():r==="toJSON"||r==="toString"?()=>t.toJSON():r==="toJS"?()=>t.toJS():r==="toJSForTest"?()=>t.toJSForTest():li(e,t.get(r))),ownKeys:t=>t.getKeys(),getOwnPropertyDescriptor:()=>({enumerable:!0,configurable:!0}),deleteProperty:(t,r)=>(J.isEnabled(be.Trivial)&&J.trivial(`obj[${r}]`),Ao.deleteInternal(e,t,r),!0)}}static setInternal(e,t,r,i){if(r.includes("."))throw new k(S.ErrInvalidObjectKey,"key must not contain the '.'.");const s=e.issueTimeTicket(),o=yl(e,i,s),a=t.set(r,o,s);e.registerElement(o,t),a&&e.registerRemovedElement(a),e.push(Ei.create(r,o.deepcopy(),t.getCreatedAt(),s))}static buildObjectMembers(e,t){const r={};for(const[i,s]of Object.entries(t)){if(i.includes("."))throw new k(S.ErrInvalidObjectKey,"key must not contain the '.'.");const o=e.issueTimeTicket(),a=yl(e,s,o);r[i]=a}return r}static deleteInternal(e,t,r){const i=e.issueTimeTicket(),s=t.deleteByKey(r,i);s&&(e.push(Xr.create(t.getCreatedAt(),s.getCreatedAt(),i)),e.registerRemovedElement(s))}getHandlers(){return this.handlers}}function zS(n,e){const t=new oe(n,e);return new Proxy(e,t.getHandlers())}function US(n){return typeof n=="string"||n instanceof String?!isNaN(n):!1}function VS(n){return["concat","entries","every","filter","find","findIndex","forEach","join","keys","map","reduce","reduceRight","slice","some","toLocaleString","toString","values"].includes(n)}class oe{constructor(e,t){u(this,"context");u(this,"handlers");u(this,"array");this.context=e,this.array=t,this.handlers={get:(r,i,s)=>i==="getID"?()=>r.getCreatedAt():i==="getElementByID"?o=>{const a=r.getByID(o);if(!(!a||a.isRemoved()))return Nr(e,a)}:i==="getElementByIndex"?o=>{const a=r.get(o);return Nr(e,a)}:i==="getLast"?()=>Nr(e,r.getLast()):i==="deleteByID"?o=>{const a=oe.deleteInternalByID(e,r,o);return Nr(e,a)}:i==="insertAfter"?(o,a)=>{const l=oe.insertAfterInternal(e,r,o,a);return Nr(e,l)}:i==="insertBefore"?(o,a)=>{const l=oe.insertBeforeInternal(e,r,o,a);return Nr(e,l)}:i==="moveBefore"?(o,a)=>{oe.moveBeforeInternal(e,r,o,a)}:i==="moveAfter"?(o,a)=>{oe.moveAfterInternal(e,r,o,a)}:i==="moveFront"?o=>{oe.moveFrontInternal(e,r,o)}:i==="moveLast"?o=>{oe.moveLastInternal(e,r,o)}:US(i)?li(e,r.get(Number(i))):i==="push"?o=>oe.pushInternal(e,r,o):i==="splice"?(o,a,...l)=>oe.splice(e,r,o,a,...l):i==="length"?r.length:typeof i=="symbol"&&i===Symbol.iterator?oe.iteratorInternal.bind(this,e,r):i==="includes"?(o,a)=>oe.includes(e,r,o,a):i==="indexOf"?(o,a)=>oe.indexOf(e,r,o,a):i==="lastIndexOf"?(o,a)=>oe.lastIndexOf(e,r,o,a):i==="toJSForTest"?()=>r.toJSForTest():i==="toTestString"?()=>oe.toTestString(r):typeof i=="string"&&VS(i)?(...o)=>{const a=Array.from(r).map(l=>li(e,l));return Array.prototype[i].apply(a,o)}:Reflect.get(r,i,s),deleteProperty:(r,i)=>(J.isEnabled(be.Trivial)&&J.trivial(`array[${i}]`),oe.deleteInternalByIndex(e,r,Number.parseInt(i)),!0)}}static*iteratorInternal(e,t){for(const r of t)yield Nr(e,r)}static buildArrayElements(e,t){const r=[];for(const i of t){const s=e.issueTimeTicket(),o=yl(e,i,s);r.push(o)}return r}static pushInternal(e,t,r){return oe.insertAfterInternal(e,t,t.getLastCreatedAt(),r),t.length}static moveBeforeInternal(e,t,r,i){const s=e.issueTimeTicket(),o=t.getPrevCreatedAt(r);t.moveAfter(o,i,s),e.push(Fr.create(t.getCreatedAt(),o,i,s))}static moveAfterInternal(e,t,r,i){const s=e.issueTimeTicket();t.moveAfter(r,i,s),e.push(Fr.create(t.getCreatedAt(),r,i,s))}static moveFrontInternal(e,t,r){const i=e.issueTimeTicket(),s=t.getHead();t.moveAfter(s.getCreatedAt(),r,i),e.push(Fr.create(t.getCreatedAt(),s.getCreatedAt(),r,i))}static moveLastInternal(e,t,r){const i=e.issueTimeTicket(),s=t.getLastCreatedAt();t.moveAfter(s,r,i),e.push(Fr.create(t.getCreatedAt(),s,r,i))}static insertAfterInternal(e,t,r,i){const s=e.issueTimeTicket(),o=yl(e,i,s);return t.insertAfter(r,o),e.registerElement(o,t),e.push(Do.create(t.getCreatedAt(),r,o.deepcopy(),s)),o}static insertBeforeInternal(e,t,r,i){return oe.insertAfterInternal(e,t,t.getPrevCreatedAt(r),i)}static deleteInternalByIndex(e,t,r){const i=e.issueTimeTicket(),s=t.deleteByIndex(r,i);if(s)return e.push(Xr.create(t.getCreatedAt(),s.getCreatedAt(),i)),e.registerRemovedElement(s),s}static deleteInternalByID(e,t,r){const i=e.issueTimeTicket(),s=t.delete(r,i);return e.push(Xr.create(t.getCreatedAt(),s.getCreatedAt(),i)),e.registerRemovedElement(s),s}static splice(e,t,r,i,...s){const o=t.length,a=r>=0?Math.min(r,o):Math.max(o+r,0),l=i===void 0?o:i<0?a:Math.min(a+i,o),c=[];for(let d=a;d=s)return!1;if(re.isSupport(r))return Array.from(t).map(c=>li(e,c)).includes(r,o);for(let l=o;l=s)return-1;if(re.isSupport(r))return Array.from(t).map(c=>li(e,c)).indexOf(r,o);for(let l=o;l=s?s-1:i<0?i+s:i;if(o<0)return-1;if(re.isSupport(r))return Array.from(t).map(c=>li(e,c)).lastIndexOf(r,o);for(let l=o;l>0;l--)if(((a=t.get(l))==null?void 0:a.getID())===r.getID())return l;return-1}static toTestString(e){return e.toTestString()}getHandlers(){return this.handlers}}class $l{constructor(e,t){u(this,"context");u(this,"text");this.context=e,this.text=t}initialize(e,t){this.context=e,this.text=t}getID(){return this.text.getID()}edit(e,t,r,i){if(!this.context||!this.text)throw new k(S.ErrNotInitialized,"Text is not initialized yet");if(e>t)throw new k(S.ErrInvalidArgument,"from should be less than or equal to to");const s=this.text.indexRangeToPosRange(e,t);J.isEnabled(be.Debug)&&J.debug(`EDIT: f:${e}->${s[0].toTestString()}, t:${t}->${s[1].toTestString()} c:${r}`);const o=i?ds(i):void 0,a=this.context.issueTimeTicket(),[l,,c,d]=this.text.edit(s,r,a,o);for(const h of c)this.context.registerGCPair(h);return this.context.push(new Oo(this.text.getCreatedAt(),s[0],s[1],l,r,o?new Map(Object.entries(o)):new Map,a)),this.text.findIndexesFromRange(d)}delete(e,t){return this.edit(e,t,"")}empty(){return this.edit(0,this.length,"")}setStyle(e,t,r){if(!this.context||!this.text)throw new k(S.ErrNotInitialized,"Text is not initialized yet");if(e>t)throw new k(S.ErrInvalidArgument,"from should be less than or equal to to");const i=this.text.indexRangeToPosRange(e,t);J.isEnabled(be.Debug)&&J.debug(`STYL: f:${e}->${i[0].toTestString()}, t:${t}->${i[1].toTestString()} a:${JSON.stringify(r)}`);const s=ds(r),o=this.context.issueTimeTicket(),[a,l]=this.text.setStyle(i,s,o);for(const c of l)this.context.registerGCPair(c);return this.context.push(new Ro(this.text.getCreatedAt(),i[0],i[1],a,new Map(Object.entries(s)),o)),!0}indexRangeToPosRange(e){if(!this.context||!this.text)throw new k(S.ErrNotInitialized,"Text is not initialized yet");const t=this.text.indexRangeToPosRange(e[0],e[1]);return[t[0].toStruct(),t[1].toStruct()]}posRangeToIndexRange(e){if(!this.context||!this.text)throw new k(S.ErrNotInitialized,"Text is not initialized yet");const t=this.text.findIndexesFromRange([Mt.fromStruct(e[0]),Mt.fromStruct(e[1])]);return[t[0],t[1]]}toTestString(){if(!this.context||!this.text)throw new k(S.ErrNotInitialized,"Text is not initialized yet");return this.text.toTestString()}values(){if(!this.context||!this.text)throw new k(S.ErrNotInitialized,"Text is not initialized yet");return this.text.values()}get length(){return this.text.length}getTreeByIndex(){return this.text.getTreeByIndex()}getTreeByID(){return this.text.getTreeByID()}toString(){if(!this.context||!this.text)throw new k(S.ErrNotInitialized,"Text is not initialized yet");return this.text.toString()}toJSON(){if(!this.context||!this.text)throw new k(S.ErrNotInitialized,"Text is not initialized yet");return this.text.toJSON()}toJSForTest(){if(!this.context||!this.text)throw new k(S.ErrNotInitialized,"Text is not initialized yet");return this.text.toJSForTest()}createRangeForTest(e,t){if(!this.context||!this.text)throw new k(S.ErrNotInitialized,"Text is not initialized yet");return this.text.indexRangeToPosRange(e,t)}}class zl{constructor(e,t){u(this,"valueType");u(this,"value");u(this,"context");u(this,"counter");this.valueType=e,this.value=t}initialize(e,t){this.valueType=t.getValueType(),this.context=e,this.counter=t,this.value=t.getValue()}getID(){return this.counter.getID()}getValue(){return this.value}getValueType(){return this.valueType}increase(e){if(!this.context||!this.counter)throw new k(S.ErrNotInitialized,"Counter is not initialized yet");const t=this.context.issueTimeTicket(),r=re.of(e,t);if(!r.isNumericType())throw new TypeError(`Unsupported type of value: ${typeof r.getValue()}`);return this.counter.increase(r),this.context.push(ps.create(this.counter.getCreatedAt(),r,t)),this}toJSForTest(){if(!this.context||!this.counter)throw new k(S.ErrNotInitialized,"Counter is not initialized yet");return this.counter.toJSForTest()}}function cd(n,e,t){const{type:r}=n,i=t.issueTimeTicket();if(r===pr){Oy(n);const{value:s}=n,o=Ze.create(Ee.of(i,0),r,s);e.append(o)}else{const{children:s=[]}=n,{attributes:o}=n;let a;if(typeof o=="object"&&!ey(o)){const c=ds(o);a=new Ar;for(const[d,h]of Object.entries(c))a.set(d,h,i)}const l=Ze.create(Ee.of(i,0),r,void 0,a);e.append(l);for(const c of s)cd(c,l,t)}}function jS(n,e){const{type:t}=e,r=n.issueTimeTicket();let i;if(e.type===pr){const{value:s}=e;i=Ze.create(Ee.of(r,0),t,s)}else if(e){const{children:s=[]}=e,{attributes:o}=e;let a;if(typeof o=="object"&&!ey(o)){const l=ds(o);a=new Ar;for(const[c,d]of Object.entries(l))a.set(c,d,r)}i=Ze.create(Ee.of(n.issueTimeTicket(),0),t,void 0,a);for(const l of s)cd(l,i,n)}return i}function Oy(n){if(!n.value.length)throw new k(S.ErrInvalidArgument,"text node cannot have empty value");return!0}function og(n){if(!n.length)return!0;if(n[0].type===pr)for(const t of n){const{type:r}=t;if(r!==pr)throw new k(S.ErrInvalidArgument,"element node and text node cannot be passed together");Oy(t)}else for(const t of n){const{type:r}=t;if(r===pr)throw new k(S.ErrInvalidArgument,"element node and text node cannot be passed together")}return!0}class Ul{constructor(e){u(this,"initialRoot");u(this,"context");u(this,"tree");this.initialRoot=e}initialize(e,t){this.context=e,this.tree=t}getID(){return this.tree.getID()}buildRoot(e){if(!this.initialRoot)return Ze.create(Ee.of(e.issueTimeTicket(),0),U1);const t=Ze.create(Ee.of(e.issueTimeTicket(),0),this.initialRoot.type);for(const r of this.initialRoot.children)cd(r,t,e);return t}getSize(){if(!this.context||!this.tree)throw new k(S.ErrNotInitialized,"Tree is not initialized yet");return this.tree.getSize()}getNodeSize(){if(!this.context||!this.tree)throw new k(S.ErrNotInitialized,"Tree is not initialized yet");return this.tree.getNodeSize()}getIndexTree(){if(!this.context||!this.tree)throw new k(S.ErrNotInitialized,"Tree is not initialized yet");return this.tree.getIndexTree()}styleByPath(e,t){if(!this.context||!this.tree)throw new k(S.ErrNotInitialized,"Tree is not initialized yet");if(!e.length)throw new k(S.ErrInvalidArgument,"path should not be empty");const[r,i]=this.tree.pathToPosRange(e),s=this.context.issueTimeTicket(),o=t?ds(t):void 0,[a]=this.tree.style([r,i],o,s);this.context.push(yr.create(this.tree.getCreatedAt(),r,i,a,o?new Map(Object.entries(o)):new Map,s))}style(e,t,r){if(!this.context||!this.tree)throw new k(S.ErrNotInitialized,"Tree is not initialized yet");if(e>t)throw new k(S.ErrInvalidArgument,"from should be less than or equal to to");const i=this.tree.findPos(e),s=this.tree.findPos(t),o=this.context.issueTimeTicket(),a=r?ds(r):void 0,[l,c]=this.tree.style([i,s],a,o);for(const d of c)this.context.registerGCPair(d);this.context.push(yr.create(this.tree.getCreatedAt(),i,s,l,a?new Map(Object.entries(a)):new Map,o))}removeStyle(e,t,r){if(!this.context||!this.tree)throw new k(S.ErrNotInitialized,"Tree is not initialized yet");if(e>t)throw new k(S.ErrInvalidArgument,"from should be less than or equal to to");const i=this.tree.findPos(e),s=this.tree.findPos(t),o=this.context.issueTimeTicket(),[a,l]=this.tree.removeStyle([i,s],r,o);for(const c of l)this.context.registerGCPair(c);this.context.push(yr.createTreeRemoveStyleOperation(this.tree.getCreatedAt(),i,s,a,r,o))}editInternal(e,t,r,i=0){var c;if(r.length!==0&&r[0]&&(og(r),r[0].type!==pr))for(const d of r){const{children:h=[]}=d;og(h)}const s=this.context.getLastTimeTicket();let o=new Array;if(((c=r[0])==null?void 0:c.type)===pr){let d="";for(const h of r){const{value:p}=h;d+=p}o.push(Ze.create(Ee.of(this.context.issueTimeTicket(),0),pr,d))}else o=r.map(d=>d&&jS(this.context,d)).filter(d=>d);const[,a,l]=this.tree.edit([e,t],o.length?o.map(d=>d==null?void 0:d.deepcopy()):void 0,i,s,()=>this.context.issueTimeTicket());for(const d of a)this.context.registerGCPair(d);return this.context.push(Lo.create(this.tree.getCreatedAt(),e,t,o.length?o:void 0,i,l,s)),!0}editByPath(e,t,r,i=0){if(!this.context||!this.tree)throw new k(S.ErrNotInitialized,"Tree is not initialized yet");if(e.length!==t.length)throw new k(S.ErrInvalidArgument,"path length should be equal");if(!e.length||!t.length)throw new k(S.ErrInvalidArgument,"path should not be empty");const s=this.tree.pathToPos(e),o=this.tree.pathToPos(t);return this.editInternal(s,o,r?[r]:[],i)}editBulkByPath(e,t,r,i=0){if(!this.context||!this.tree)throw new k(S.ErrNotInitialized,"Tree is not initialized yet");if(e.length!==t.length)throw new k(S.ErrInvalidArgument,"path length should be equal");if(!e.length||!t.length)throw new k(S.ErrInvalidArgument,"path should not be empty");const s=this.tree.pathToPos(e),o=this.tree.pathToPos(t);return this.editInternal(s,o,r,i)}edit(e,t,r,i=0){if(!this.context||!this.tree)throw new k(S.ErrNotInitialized,"Tree is not initialized yet");if(e>t)throw new k(S.ErrInvalidArgument,"from should be less than or equal to to");const s=this.tree.findPos(e),o=this.tree.findPos(t);return this.editInternal(s,o,r?[r]:[],i)}editBulk(e,t,r,i=0){if(!this.context||!this.tree)throw new k(S.ErrNotInitialized,"Tree is not initialized yet");if(e>t)throw new k(S.ErrInvalidArgument,"from should be less than or equal to to");const s=this.tree.findPos(e),o=this.tree.findPos(t);return this.editInternal(s,o,r,i)}toXML(){if(!this.context||!this.tree)throw new k(S.ErrNotInitialized,"Tree is not initialized yet");return this.tree.toXML()}toJSON(){if(!this.context||!this.tree)throw new k(S.ErrNotInitialized,"Tree is not initialized yet");return this.tree.toJSON()}toJSForTest(){if(!this.context||!this.tree)throw new k(S.ErrNotInitialized,"Tree is not initialized yet");return this.tree.toJSForTest()}toJSInfoForTest(){if(!this.context||!this.tree)throw new k(S.ErrNotInitialized,"Tree is not initialized yet");return this.tree.toJSInfoForTest()}getRootTreeNode(){if(!this.context||!this.tree)throw new k(S.ErrNotInitialized,"Tree is not initialized yet");return this.tree.getRootTreeNode()}indexToPath(e){if(!this.context||!this.tree)throw new k(S.ErrNotInitialized,"Tree is not initialized yet");return this.tree.indexToPath(e)}pathToIndex(e){if(!this.context||!this.tree)throw new k(S.ErrNotInitialized,"Tree is not initialized yet");return this.tree.pathToIndex(e)}pathRangeToPosRange(e){if(!this.context||!this.tree)throw new k(S.ErrNotInitialized,"Tree is not initialized yet");const t=[this.tree.pathToIndex(e[0]),this.tree.pathToIndex(e[1])],r=this.tree.indexRangeToPosRange(t);return[r[0].toStruct(),r[1].toStruct()]}indexRangeToPosRange(e){if(!this.context||!this.tree)throw new k(S.ErrNotInitialized,"Tree is not initialized yet");return this.tree.indexRangeToPosStructRange(e)}posRangeToIndexRange(e){if(!this.context||!this.tree)throw new k(S.ErrNotInitialized,"Tree is not initialized yet");const t=[Lt.fromStruct(e[0]),Lt.fromStruct(e[1])];return this.tree.posRangeToIndexRange(t)}posRangeToPathRange(e){if(!this.context||!this.tree)throw new k(S.ErrNotInitialized,"Tree is not initialized yet");const t=[Lt.fromStruct(e[0]),Lt.fromStruct(e[1])];return this.tree.posRangeToPathRange(t)}}function ag(n,e){return Dy(n,e)}function Nr(n,e){if(e){if(e instanceof re)return e;if(e instanceof He)return Dy(n,e);if(e instanceof nt)return zS(n,e);if(e instanceof Et)return new $l(n,e);if(e instanceof rt){const t=new zl(on.IntegerCnt,0);return t.initialize(n,e),t}else if(e instanceof xt){const t=new Ul;return t.initialize(n,e),t}}else return;throw new TypeError(`Unsupported type of element: ${typeof e}`)}function li(n,e){const t=Nr(n,e);return t instanceof re?t.getValue():t}function yl(n,e,t){let r;if(re.isSupport(e))r=re.of(e,t);else if(Array.isArray(e))r=nt.create(t,oe.buildArrayElements(n,e));else if(typeof e=="object")e instanceof $l?(r=Et.create(ms.create(),t),e.initialize(n,r)):e instanceof zl?(r=rt.create(e.getValueType(),e.getValue(),t),e.initialize(n,r)):e instanceof Ul?(r=xt.create(e.buildRoot(n),t),e.initialize(n,r)):r=He.create(t,Ao.buildObjectMembers(n,e));else throw new TypeError(`Unsupported type of value: ${typeof e}`);return r}const lg=50;class qS{constructor(){u(this,"undoStack",[]);u(this,"redoStack",[])}hasUndo(){return this.undoStack.length>0}hasRedo(){return this.redoStack.length>0}pushUndo(e){this.undoStack.length>=lg&&this.undoStack.shift(),this.undoStack.push(e)}popUndo(){return this.undoStack.pop()}pushRedo(e){this.redoStack.length>=lg&&this.redoStack.shift(),this.redoStack.push(e)}popRedo(){return this.redoStack.pop()}clearRedo(){this.redoStack=[]}getUndoStackForTest(){return this.undoStack}getRedoStackForTest(){return this.redoStack}}const KS="yorkie-devtools-panel",WS="yorkie-devtools-sdk";let Ri="disconnected";const ug=new Map,Ta=new Map;typeof window<"u"&&(window.transactionEventsByDocKey=Ta);function ra(n,e){(e!=null&&e.force||Ri!=="disconnected")&&window.postMessage({source:WS,...n},"*")}function HS(n){if(!n.isEnableDevtools()||typeof window>"u"||ug.has(n.getKey()))return;Ta.set(n.getKey(),[]);const e=n.subscribe("all",t=>{t.some(r=>r.type!==$e.StatusChanged&&r.type!==$e.Snapshot&&r.type!==$e.LocalChange&&r.type!==$e.RemoteChange&&r.type!==$e.Initialized&&r.type!==$e.Watched&&r.type!==$e.Unwatched&&r.type!==$e.PresenceChanged)||(Ta.get(n.getKey()).push(t),Ri==="synced"&&ra({msg:"doc::sync::partial",docKey:n.getKey(),event:t}))});ug.set(n.getKey(),[e]),ra({msg:"refresh-devtools"},{force:!0}),window.addEventListener("message",t=>{var i;if(((i=t.data)==null?void 0:i.source)!==KS)return;switch(t.data.msg){case"devtools::connect":if(Ri!=="disconnected")break;Ri="connected",ra({msg:"doc::available",docKey:n.getKey()}),J.info(`[YD] Devtools connected. Doc: ${n.getKey()}`);break;case"devtools::disconnect":Ri="disconnected",J.info(`[YD] Devtools disconnected. Doc: ${n.getKey()}`);break;case"devtools::subscribe":Ri="synced",ra({msg:"doc::sync::full",docKey:n.getKey(),events:Ta.get(n.getKey())}),J.info(`[YD] Devtools subscribed. Doc: ${n.getKey()}`);break}})}var Pr=(n=>(n.Detached="detached",n.Attached="attached",n.Removed="removed",n))(Pr||{}),$e=(n=>(n.StatusChanged="status-changed",n.ConnectionChanged="connection-changed",n.SyncStatusChanged="sync-status-changed",n.Snapshot="snapshot",n.LocalChange="local-change",n.RemoteChange="remote-change",n.Initialized="initialized",n.Watched="watched",n.Unwatched="unwatched",n.PresenceChanged="presence-changed",n.Broadcast="broadcast",n.LocalBroadcast="local-broadcast",n))($e||{}),_c=(n=>(n.Connected="connected",n.Disconnected="disconnected",n))(_c||{}),Gc=(n=>(n.Synced="synced",n.SyncFailed="sync-failed",n))(Gc||{});class Ry{constructor(e,t){u(this,"key");u(this,"status");u(this,"opts");u(this,"changeID");u(this,"checkpoint");u(this,"localChanges");u(this,"root");u(this,"clone");u(this,"eventStream");u(this,"eventStreamObserver");u(this,"onlineClients");u(this,"presences");u(this,"history");u(this,"internalHistory");u(this,"isUpdating");this.opts=t||{},this.key=e,this.status="detached",this.root=To.create(),this.changeID=Y1,this.checkpoint=Q1,this.localChanges=[],this.eventStream=$S(r=>{this.eventStreamObserver=r}),this.onlineClients=new Set,this.presences=new Map,this.isUpdating=!1,this.internalHistory=new qS,this.history={canUndo:this.canUndo.bind(this),canRedo:this.canRedo.bind(this),undo:this.undo.bind(this),redo:this.redo.bind(this)},HS(this)}update(e,t){if(this.getStatus()==="removed")throw new k(S.ErrDocumentRemoved,`${this.key} is removed`);this.ensureClone();const r=this.changeID.getActorID(),i=Wi.create(this.changeID.next(),this.clone.root,this.clone.presences.get(r)||{},t);try{const s=ag(i,this.clone.root.getObject());this.presences.has(r)||this.clone.presences.set(r,{}),this.isUpdating=!0,e(s,new ku(i,this.clone.presences.get(r)))}catch(s){throw this.clone=void 0,s}finally{this.isUpdating=!1}if(i.hasChange()){J.isEnabled(be.Trivial)&&J.trivial(`trying to update a local change: ${this.toJSON()}`);const s=i.getChange(),{opInfos:o,reverseOps:a}=s.execute(this.root,this.presences,Y.Local),l=i.getReversePresence();l&&a.push({type:"presence",value:l}),this.localChanges.push(s),a.length>0&&this.internalHistory.pushUndo(a),o.length>0&&this.internalHistory.clearRedo(),this.changeID=s.getID();const c=[];o.length>0&&c.push({type:"local-change",source:Y.Local,value:{message:s.getMessage()||"",operations:o,actor:r,clientSeq:s.getID().getClientSeq(),serverSeq:s.getID().getServerSeq()},rawChange:this.isEnableDevtools()?s.toStruct():void 0}),s.hasPresenceChange()&&c.push({type:"presence-changed",source:Y.Local,value:{clientID:r,presence:this.getPresence(r)}}),this.publish(c),J.isEnabled(be.Trivial)&&J.trivial(`after update a local change: ${this.toJSON()}`)}}subscribe(e,t,r,i){if(typeof e=="string"){if(typeof t!="function")throw new k(S.ErrInvalidArgument,"Second argument must be a callback function");if(e==="presence"){const a=t;return this.eventStream.subscribe(l=>{for(const c of l)c.type!=="initialized"&&c.type!=="watched"&&c.type!=="unwatched"&&c.type!=="presence-changed"||a(c)},r,i)}if(e==="my-presence"){const a=t;return this.eventStream.subscribe(l=>{for(const c of l)c.type!=="initialized"&&c.type!=="presence-changed"||c.type==="presence-changed"&&c.value.clientID!==this.changeID.getActorID()||a(c)},r,i)}if(e==="others"){const a=t;return this.eventStream.subscribe(l=>{for(const c of l)c.type!=="watched"&&c.type!=="unwatched"&&c.type!=="presence-changed"||c.value.clientID!==this.changeID.getActorID()&&a(c)},r,i)}if(e==="connection"){const a=t;return this.eventStream.subscribe(l=>{for(const c of l)c.type==="connection-changed"&&a(c)},r,i)}if(e==="status"){const a=t;return this.eventStream.subscribe(l=>{for(const c of l)c.type==="status-changed"&&a(c)},r,i)}if(e==="sync"){const a=t;return this.eventStream.subscribe(l=>{for(const c of l)c.type==="sync-status-changed"&&a(c)},r,i)}if(e==="local-broadcast"){const a=t;return this.eventStream.subscribe(l=>{for(const c of l)c.type==="local-broadcast"&&a(c)},r)}if(e==="broadcast"){const a=t;return this.eventStream.subscribe(l=>{for(const c of l)c.type==="broadcast"&&a(c)},r)}if(e==="all"){const a=t;return this.eventStream.subscribe(a,r,i)}const s=e,o=t;return this.eventStream.subscribe(a=>{for(const l of a){if(l.type!=="local-change"&&l.type!=="remote-change")continue;const c=[];for(const d of l.value.operations)this.isSameElementOrChildOf(d.path,s)&&c.push(d);c.length&&o({...l,value:{...l.value,operations:c}})}},r,i)}if(typeof e=="function"){const s=e,o=t,a=r;return this.eventStream.subscribe(l=>{for(const c of l)c.type!=="snapshot"&&c.type!=="local-change"&&c.type!=="remote-change"||s(c)},o,a)}throw new k(S.ErrInvalidArgument,`"${e}" is not a valid`)}publish(e){this.eventStreamObserver&&this.eventStreamObserver.next(e)}isSameElementOrChildOf(e,t){if(t===e)return!0;const r=e.split(".");return t.split(".").every((s,o)=>s===r[o])}applyChangePack(e){const t=e.hasSnapshot();for(t?this.applySnapshot(e.getCheckpoint().getServerSeq(),e.getVersionVector(),e.getSnapshot()):e.hasChanges()&&this.applyChanges(e.getChanges(),Y.Remote);this.localChanges.length&&!(this.localChanges[0].getID().getClientSeq()>e.getCheckpoint().getClientSeq());)this.localChanges.shift();t&&this.applyChanges(this.localChanges,Y.Remote),this.checkpoint=this.checkpoint.forward(e.getCheckpoint()),t||this.garbageCollect(e.getVersionVector()),t||this.filterVersionVector(e.getVersionVector()),e.getIsRemoved()&&this.applyStatus("removed"),J.isEnabled(be.Trivial)&&J.trivial(`${this.root.toJSON()}`)}getCheckpoint(){return this.checkpoint}getChangeID(){return this.changeID}hasLocalChanges(){return this.localChanges.length>0}ensureClone(){this.clone||(this.clone={root:this.root.deepcopy(),presences:Pt(this.presences)})}createChangePack(){const e=Array.from(this.localChanges),t=this.checkpoint.increaseClientSeq(e.length);return Jl.create(this.key,t,!1,e,this.getVersionVector())}setActor(e){for(const t of this.localChanges)t.setActor(e);this.changeID=this.changeID.setActor(e)}isEnableDevtools(){return!!this.opts.enableDevtools}getKey(){return this.key}getStatus(){return this.status}getCloneRoot(){if(this.clone)return this.clone.root.getObject()}getRoot(){this.ensureClone();const e=Wi.create(this.changeID.next(),this.clone.root,this.clone.presences.get(this.changeID.getActorID())||{});return ag(e,this.clone.root.getObject())}garbageCollect(e){return this.opts.disableGC?0:(this.clone&&this.clone.root.garbageCollect(e),this.root.garbageCollect(e))}getRootObject(){return this.root.getObject()}getGarbageLen(){return this.root.getGarbageLen()}getGarbageLenFromClone(){return this.clone.root.getGarbageLen()}toJSON(){return this.root.toJSON()}toSortedJSON(){return this.root.toSortedJSON()}getStats(){return this.root.getStats()}toJSForTest(){return{...this.getRoot().toJSForTest(),key:"root"}}applySnapshot(e,t,r){const{root:i,presences:s}=fe.bytesToSnapshot(r);this.root=new To(i),this.presences=s,this.changeID=this.changeID.setClocks(e,t),this.clone=void 0,this.publish([{type:"snapshot",source:Y.Remote,value:{serverSeq:e.toString(),snapshot:this.isEnableDevtools()?fe.bytesToHex(r):void 0,snapshotVector:fe.versionVectorToHex(t)}}])}applyChanges(e,t){J.isEnabled(be.Debug)&&J.debug(`trying to apply ${e.length} remote changes.elements:${this.root.getElementMapSize()}, removeds:${this.root.getGarbageElementSetSize()}`),J.isEnabled(be.Trivial)&&J.trivial(e.map(r=>`${r.getID().toTestString()} ${r.toTestString()}`).join(` + */var St=null;try{St=new WebAssembly.Instance(new WebAssembly.Module(new Uint8Array([0,97,115,109,1,0,0,0,1,13,2,96,0,1,127,96,4,127,127,127,127,1,127,3,7,6,0,1,1,1,1,1,6,6,1,127,1,65,0,11,7,50,6,3,109,117,108,0,1,5,100,105,118,95,115,0,2,5,100,105,118,95,117,0,3,5,114,101,109,95,115,0,4,5,114,101,109,95,117,0,5,8,103,101,116,95,104,105,103,104,0,0,10,191,1,6,4,0,35,0,11,36,1,1,126,32,0,173,32,1,173,66,32,134,132,32,2,173,32,3,173,66,32,134,132,126,34,4,66,32,135,167,36,0,32,4,167,11,36,1,1,126,32,0,173,32,1,173,66,32,134,132,32,2,173,32,3,173,66,32,134,132,127,34,4,66,32,135,167,36,0,32,4,167,11,36,1,1,126,32,0,173,32,1,173,66,32,134,132,32,2,173,32,3,173,66,32,134,132,128,34,4,66,32,135,167,36,0,32,4,167,11,36,1,1,126,32,0,173,32,1,173,66,32,134,132,32,2,173,32,3,173,66,32,134,132,129,34,4,66,32,135,167,36,0,32,4,167,11,36,1,1,126,32,0,173,32,1,173,66,32,134,132,32,2,173,32,3,173,66,32,134,132,130,34,4,66,32,135,167,36,0,32,4,167,11])),{}).exports}catch{}function q(n,e,t){this.low=n|0,this.high=e|0,this.unsigned=!!t}q.prototype.__isLong__;Object.defineProperty(q.prototype,"__isLong__",{value:!0});function Re(n){return(n&&n.__isLong__)===!0}function Xh(n){var e=Math.clz32(n&-n);return n?31-e:e}q.isLong=Re;var Zh={},eg={};function Ni(n,e){var t,r,i;return e?(n>>>=0,(i=0<=n&&n<256)&&(r=eg[n],r)?r:(t=W(n,0,!0),i&&(eg[n]=t),t)):(n|=0,(i=-128<=n&&n<128)&&(r=Zh[n],r)?r:(t=W(n,n<0?-1:0,!1),i&&(Zh[n]=t),t))}q.fromInt=Ni;function kt(n,e){if(isNaN(n))return e?gr:Rt;if(e){if(n<0)return gr;if(n>=ry)return oy}else{if(n<=-ng)return je;if(n+1>=ng)return sy}return n<0?kt(-n,e).neg():W(n%hs|0,n/hs|0,e)}q.fromNumber=kt;function W(n,e,t){return new q(n,e,t)}q.fromBits=W;var gl=Math.pow;function Qf(n,e,t){if(n.length===0)throw Error("empty string");if(typeof e=="number"?(t=e,e=!1):e=!!e,n==="NaN"||n==="Infinity"||n==="+Infinity"||n==="-Infinity")return e?gr:Rt;if(t=t||10,t<2||360)throw Error("interior hyphen");if(r===0)return Qf(n.substring(1),e,t).neg();for(var i=kt(gl(t,8)),s=Rt,o=0;o>>0:this.low};C.toNumber=function(){return this.unsigned?(this.high>>>0)*hs+(this.low>>>0):this.high*hs+(this.low>>>0)};C.toString=function(e){if(e=e||10,e<2||36>>0,d=c.toString(e);if(o=l,o.isZero())return d+a;for(;d.length<6;)d="0"+d;a=""+d+a}};C.getHighBits=function(){return this.high};C.getHighBitsUnsigned=function(){return this.high>>>0};C.getLowBits=function(){return this.low};C.getLowBitsUnsigned=function(){return this.low>>>0};C.getNumBitsAbs=function(){if(this.isNegative())return this.eq(je)?64:this.neg().getNumBitsAbs();for(var e=this.high!=0?this.high:this.low,t=31;t>0&&!(e&1<=0};C.isOdd=function(){return(this.low&1)===1};C.isEven=function(){return(this.low&1)===0};C.equals=function(e){return Re(e)||(e=zt(e)),this.unsigned!==e.unsigned&&this.high>>>31===1&&e.high>>>31===1?!1:this.high===e.high&&this.low===e.low};C.eq=C.equals;C.notEquals=function(e){return!this.eq(e)};C.neq=C.notEquals;C.ne=C.notEquals;C.lessThan=function(e){return this.comp(e)<0};C.lt=C.lessThan;C.lessThanOrEqual=function(e){return this.comp(e)<=0};C.lte=C.lessThanOrEqual;C.le=C.lessThanOrEqual;C.greaterThan=function(e){return this.comp(e)>0};C.gt=C.greaterThan;C.greaterThanOrEqual=function(e){return this.comp(e)>=0};C.gte=C.greaterThanOrEqual;C.ge=C.greaterThanOrEqual;C.compare=function(e){if(Re(e)||(e=zt(e)),this.eq(e))return 0;var t=this.isNegative(),r=e.isNegative();return t&&!r?-1:!t&&r?1:this.unsigned?e.high>>>0>this.high>>>0||e.high===this.high&&e.low>>>0>this.low>>>0?-1:1:this.sub(e).isNegative()?-1:1};C.comp=C.compare;C.negate=function(){return!this.unsigned&&this.eq(je)?je:this.not().add(Ki)};C.neg=C.negate;C.add=function(e){Re(e)||(e=zt(e));var t=this.high>>>16,r=this.high&65535,i=this.low>>>16,s=this.low&65535,o=e.high>>>16,a=e.high&65535,l=e.low>>>16,c=e.low&65535,d=0,h=0,p=0,m=0;return m+=s+c,p+=m>>>16,m&=65535,p+=i+l,h+=p>>>16,p&=65535,h+=r+a,d+=h>>>16,h&=65535,d+=t+o,d&=65535,W(p<<16|m,d<<16|h,this.unsigned)};C.subtract=function(e){return Re(e)||(e=zt(e)),this.add(e.neg())};C.sub=C.subtract;C.multiply=function(e){if(this.isZero())return this;if(Re(e)||(e=zt(e)),St){var t=St.mul(this.low,this.high,e.low,e.high);return W(t,St.get_high(),this.unsigned)}if(e.isZero())return this.unsigned?gr:Rt;if(this.eq(je))return e.isOdd()?je:Rt;if(e.eq(je))return this.isOdd()?je:Rt;if(this.isNegative())return e.isNegative()?this.neg().mul(e.neg()):this.neg().mul(e).neg();if(e.isNegative())return this.mul(e.neg()).neg();if(this.lt(rg)&&e.lt(rg))return kt(this.toNumber()*e.toNumber(),this.unsigned);var r=this.high>>>16,i=this.high&65535,s=this.low>>>16,o=this.low&65535,a=e.high>>>16,l=e.high&65535,c=e.low>>>16,d=e.low&65535,h=0,p=0,m=0,w=0;return w+=o*d,m+=w>>>16,w&=65535,m+=s*d,p+=m>>>16,m&=65535,m+=o*c,p+=m>>>16,m&=65535,p+=i*d,h+=p>>>16,p&=65535,p+=s*c,h+=p>>>16,p&=65535,p+=o*l,h+=p>>>16,p&=65535,h+=r*d+i*c+s*l+o*a,h&=65535,W(m<<16|w,h<<16|p,this.unsigned)};C.mul=C.multiply;C.divide=function(e){if(Re(e)||(e=zt(e)),e.isZero())throw Error("division by zero");if(St){if(!this.unsigned&&this.high===-2147483648&&e.low===-1&&e.high===-1)return this;var t=(this.unsigned?St.div_u:St.div_s)(this.low,this.high,e.low,e.high);return W(t,St.get_high(),this.unsigned)}if(this.isZero())return this.unsigned?gr:Rt;var r,i,s;if(this.unsigned){if(e.unsigned||(e=e.toUnsigned()),e.gt(this))return gr;if(e.gt(this.shru(1)))return iy;s=gr}else{if(this.eq(je)){if(e.eq(Ki)||e.eq(Kc))return je;if(e.eq(je))return Ki;var o=this.shr(1);return r=o.div(e).shl(1),r.eq(Rt)?e.isNegative()?Ki:Kc:(i=this.sub(e.mul(r)),s=r.add(i.div(e)),s)}else if(e.eq(je))return this.unsigned?gr:Rt;if(this.isNegative())return e.isNegative()?this.neg().div(e.neg()):this.neg().div(e).neg();if(e.isNegative())return this.div(e.neg()).neg();s=Rt}for(i=this;i.gte(e);){r=Math.max(1,Math.floor(i.toNumber()/e.toNumber()));for(var a=Math.ceil(Math.log(r)/Math.LN2),l=a<=48?1:gl(2,a-48),c=kt(r),d=c.mul(e);d.isNegative()||d.gt(i);)r-=l,c=kt(r,this.unsigned),d=c.mul(e);c.isZero()&&(c=Ki),s=s.add(c),i=i.sub(d)}return s};C.div=C.divide;C.modulo=function(e){if(Re(e)||(e=zt(e)),St){var t=(this.unsigned?St.rem_u:St.rem_s)(this.low,this.high,e.low,e.high);return W(t,St.get_high(),this.unsigned)}return this.sub(this.div(e).mul(e))};C.mod=C.modulo;C.rem=C.modulo;C.not=function(){return W(~this.low,~this.high,this.unsigned)};C.countLeadingZeros=function(){return this.high?Math.clz32(this.high):Math.clz32(this.low)+32};C.clz=C.countLeadingZeros;C.countTrailingZeros=function(){return this.low?Xh(this.low):Xh(this.high)+32};C.ctz=C.countTrailingZeros;C.and=function(e){return Re(e)||(e=zt(e)),W(this.low&e.low,this.high&e.high,this.unsigned)};C.or=function(e){return Re(e)||(e=zt(e)),W(this.low|e.low,this.high|e.high,this.unsigned)};C.xor=function(e){return Re(e)||(e=zt(e)),W(this.low^e.low,this.high^e.high,this.unsigned)};C.shiftLeft=function(e){return Re(e)&&(e=e.toInt()),(e&=63)===0?this:e<32?W(this.low<>>32-e,this.unsigned):W(0,this.low<>>e|this.high<<32-e,this.high>>e,this.unsigned):W(this.high>>e-32,this.high>=0?0:-1,this.unsigned)};C.shr=C.shiftRight;C.shiftRightUnsigned=function(e){return Re(e)&&(e=e.toInt()),(e&=63)===0?this:e<32?W(this.low>>>e|this.high<<32-e,this.high>>>e,this.unsigned):e===32?W(this.high,0,this.unsigned):W(this.high>>>e-32,0,this.unsigned)};C.shru=C.shiftRightUnsigned;C.shr_u=C.shiftRightUnsigned;C.rotateLeft=function(e){var t;return Re(e)&&(e=e.toInt()),(e&=63)===0?this:e===32?W(this.high,this.low,this.unsigned):e<32?(t=32-e,W(this.low<>>t,this.high<>>t,this.unsigned)):(e-=32,t=32-e,W(this.high<>>t,this.low<>>t,this.unsigned))};C.rotl=C.rotateLeft;C.rotateRight=function(e){var t;return Re(e)&&(e=e.toInt()),(e&=63)===0?this:e===32?W(this.high,this.low,this.unsigned):e<32?(t=32-e,W(this.high<>>e,this.low<>>e,this.unsigned)):(e-=32,t=32-e,W(this.low<>>e,this.high<>>e,this.unsigned))};C.rotr=C.rotateRight;C.toSigned=function(){return this.unsigned?W(this.low,this.high,!1):this};C.toUnsigned=function(){return this.unsigned?this:W(this.low,this.high,!0)};C.toBytes=function(e){return e?this.toBytesLE():this.toBytesBE()};C.toBytesLE=function(){var e=this.high,t=this.low;return[t&255,t>>>8&255,t>>>16&255,t>>>24,e&255,e>>>8&255,e>>>16&255,e>>>24]};C.toBytesBE=function(){var e=this.high,t=this.low;return[e>>>24,e>>>16&255,e>>>8&255,e&255,t>>>24,t>>>16&255,t>>>8&255,t&255]};q.fromBytes=function(e,t,r){return r?q.fromBytesLE(e,t):q.fromBytesBE(e,t)};q.fromBytesLE=function(e,t){return new q(e[0]|e[1]<<8|e[2]<<16|e[3]<<24,e[4]|e[5]<<8|e[6]<<16|e[7]<<24,t)};q.fromBytesBE=function(e,t){return new q(e[4]<<24|e[5]<<16|e[6]<<8|e[7],e[0]<<24|e[1]<<16|e[2]<<8|e[3],t)};var ve=(n=>(n[n.Null=0]="Null",n[n.Boolean=1]="Boolean",n[n.Integer=2]="Integer",n[n.Long=3]="Long",n[n.Double=4]="Double",n[n.String=5]="String",n[n.Bytes=6]="Bytes",n[n.Date=7]="Date",n))(ve||{});class re extends Po{constructor(t,r){super(r);u(this,"valueType");u(this,"value");this.valueType=re.getPrimitiveType(t),this.value=t===void 0?null:t}static of(t,r){return new re(t,r)}static valueFromBytes(t,r){switch(t){case 0:return null;case 1:return!!r[0];case 2:return r[0]|r[1]<<8|r[2]<<16|r[3]<<24;case 4:{const i=new DataView(r.buffer);return r.forEach(function(s,o){i.setUint8(o,s)}),i.getFloat64(0,!0)}case 5:return new TextDecoder("utf-8").decode(r);case 3:return q.fromBytesLE(Array.from(r));case 6:return r;case 7:return new Date(q.fromBytesLE(Array.from(r),!0).toNumber());default:throw new k(S.ErrUnimplemented,`unimplemented type: ${t}`)}}toJSON(){return this.valueType===5?`"${tn(this.value)}"`:`${this.value}`}toSortedJSON(){return this.toJSON()}toJSForTest(){return{createdAt:this.getCreatedAt().toTestString(),value:this.value,type:"YORKIE_PRIMITIVE"}}deepcopy(){const t=re.of(this.value,this.getCreatedAt());return t.setMovedAt(this.getMovedAt()),t.setRemovedAt(this.getRemovedAt()),t}getType(){return this.valueType}static getPrimitiveType(t){switch(typeof t){case"undefined":return 0;case"boolean":return 1;case"number":return this.isInteger(t)?2:4;case"string":return 5;case"object":if(t===null)return 0;if(t instanceof q)return 3;if(t instanceof Uint8Array)return 6;if(t instanceof Date)return 7}}static isSupport(t){return re.getPrimitiveType(t)!==void 0}static isInteger(t){return t%1===0}isNumericType(){const t=this.valueType;return t===2||t===3||t===4}getValue(){return this.value}toBytes(){switch(this.valueType){case 0:return new Uint8Array;case 1:return this.value?new Uint8Array([1]):new Uint8Array([0]);case 2:{const t=this.value;return new Uint8Array([t&255,t>>8&255,t>>16&255,t>>24&255])}case 4:{const t=this.value,r=new Uint8Array(8);return new DataView(r.buffer).setFloat64(0,t,!0),r}case 5:return new TextEncoder().encode(this.value);case 3:{const r=this.value.toBytesLE();return Uint8Array.from(r)}case 6:return this.value;case 7:{const t=this.value,r=q.fromNumber(t.getTime(),!0).toBytesLE();return Uint8Array.from(r)}default:throw new k(S.ErrUnimplemented,`unimplemented type: ${this.valueType}`)}}}class ml extends ny{constructor(t){super(t);u(this,"prev");u(this,"next");this.value=t}static createAfter(t,r){const i=new ml(r),s=t.next;return t.next=i,i.prev=t,i.next=s,s&&(s.prev=i),i}remove(t){return this.value.remove(t)}getCreatedAt(){return this.value.getCreatedAt()}getPositionedAt(){return this.value.getPositionedAt()}release(){this.prev&&(this.prev.next=this.next),this.next&&(this.next.prev=this.prev),this.prev=void 0,this.next=void 0}getLength(){return this.value.isRemoved()?0:1}getPrev(){return this.prev}getNext(){return this.next}getValue(){return this.value}isRemoved(){return this.value.isRemoved()}}class So{constructor(){u(this,"dummyHead");u(this,"last");u(this,"nodeMapByIndex");u(this,"nodeMapByCreatedAt");const e=re.of(0,Ft);e.setRemovedAt(Ft),this.dummyHead=new ml(e),this.last=this.dummyHead,this.nodeMapByIndex=new wo,this.nodeMapByCreatedAt=new Map,this.nodeMapByIndex.insert(this.dummyHead),this.nodeMapByCreatedAt.set(this.dummyHead.getCreatedAt().toIDString(),this.dummyHead)}static create(){return new So}get length(){return this.nodeMapByIndex.length}findNextBeforeExecutedAt(e,t){let r=this.nodeMapByCreatedAt.get(e.toIDString());if(!r)throw new k(S.ErrInvalidArgument,`cant find the given node: ${e.toIDString()}`);for(;r.getNext()&&r.getNext().getPositionedAt().after(t);)r=r.getNext();return r}release(e){this.last===e&&(this.last=e.getPrev()),e.release(),this.nodeMapByIndex.delete(e),this.nodeMapByCreatedAt.delete(e.getValue().getCreatedAt().toIDString())}insertAfter(e,t,r=t.getCreatedAt()){const i=this.findNextBeforeExecutedAt(e,r),s=ml.createAfter(i,t);i===this.last&&(this.last=s),this.nodeMapByIndex.insertAfter(i,s),this.nodeMapByCreatedAt.set(s.getCreatedAt().toIDString(),s)}moveAfter(e,t,r){const i=this.nodeMapByCreatedAt.get(e.toIDString());if(!i)throw new k(S.ErrInvalidArgument,`cant find the given node: ${e.toIDString()}`);const s=this.nodeMapByCreatedAt.get(t.toIDString());if(!s)throw new k(S.ErrInvalidArgument,`cant find the given node: ${t.toIDString()}`);i!==s&&(!s.getValue().getMovedAt()||r.after(s.getValue().getMovedAt()))&&(this.release(s),this.insertAfter(i.getCreatedAt(),s.getValue(),r),s.getValue().setMovedAt(r))}insert(e){this.insertAfter(this.last.getCreatedAt(),e)}getByID(e){return this.nodeMapByCreatedAt.get(e.toIDString())}subPathOf(e){const t=this.nodeMapByCreatedAt.get(e.toIDString());if(t)return String(this.nodeMapByIndex.indexOf(t))}purge(e){const t=this.nodeMapByCreatedAt.get(e.getCreatedAt().toIDString());if(!t)throw new k(S.ErrInvalidArgument,`fail to find the given createdAt: ${e.getCreatedAt().toIDString()}`);this.release(t)}getByIndex(e){if(e>=this.length)return;const[t,r]=this.nodeMapByIndex.find(e);let i=t;if(e===0&&t===this.dummyHead||r>0)do i&&(i=i.getNext());while(i&&i.isRemoved());return i}getPrevCreatedAt(e){let t=this.nodeMapByCreatedAt.get(e.toIDString());do t=t.getPrev();while(this.dummyHead!==t&&t.isRemoved());return t.getValue().getCreatedAt()}delete(e,t){const r=this.nodeMapByCreatedAt.get(e.toIDString()),i=r.isRemoved();return r.remove(t)&&!i&&this.nodeMapByIndex.splayNode(r),r.getValue()}deleteByIndex(e,t){const r=this.getByIndex(e);if(r)return r.remove(t)&&this.nodeMapByIndex.splayNode(r),r.getValue()}getHead(){return this.dummyHead.getValue()}getLast(){return this.last.getValue()}getLastCreatedAt(){return this.last.getCreatedAt()}toTestString(){const e=[];for(const t of this){const r=`${t.getCreatedAt().toIDString()}:${t.getValue().toJSON()}`;t.isRemoved()?e.push(`{${r}}`):e.push(`[${r}]`)}return e.join("")}*[Symbol.iterator](){let e=this.dummyHead.getNext();for(;e;)yield e,e=e.getNext()}}class nt extends Wr{constructor(t,r){super(t);u(this,"elements");this.elements=r}static create(t,r){if(!r)return new nt(t,So.create());const i=So.create();for(const s of r)i.insertAfter(i.getLastCreatedAt(),s.deepcopy());return new nt(t,i)}subPathOf(t){return this.elements.subPathOf(t)}purge(t){this.elements.purge(t)}insertAfter(t,r){this.elements.insertAfter(t,r)}moveAfter(t,r,i){this.elements.moveAfter(t,r,i)}get(t){const r=this.elements.getByIndex(t);return r==null?void 0:r.getValue()}getByID(t){const r=this.elements.getByID(t);return r==null?void 0:r.getValue()}getHead(){return this.elements.getHead()}getLast(){return this.elements.getLast()}getPrevCreatedAt(t){return this.elements.getPrevCreatedAt(t)}delete(t,r){return this.elements.delete(t,r)}deleteByIndex(t,r){return this.elements.deleteByIndex(t,r)}getLastCreatedAt(){return this.elements.getLastCreatedAt()}get length(){return this.elements.length}*[Symbol.iterator](){for(const t of this.elements)t.isRemoved()||(yield t.getValue())}toTestString(){return this.elements.toTestString()}getDescendants(t){for(const r of this.elements){const i=r.getValue();if(t(i,this))return;i instanceof Wr&&i.getDescendants(t)}}toJSON(){const t=[];for(const r of this)t.push(r.toJSON());return`[${t.join(",")}]`}toJS(){return JSON.parse(this.toJSON())}toJSForTest(){const t={};for(let r=0;r({...m,value:m.value?{attributes:Zi(m.value.getAttributes()),content:m.value.getContent()}:{attributes:void 0,content:""},type:"content"}));return[c,p,d,[l,l]]}setStyle(t,r,i,s){const[,o]=this.rgaTreeSplit.findNodeWithSplit(t[1],i),[,a]=this.rgaTreeSplit.findNodeWithSplit(t[0],i),l=[],c=this.rgaTreeSplit.findBetween(a,o),d=new Map,h=[];for(const m of c){const w=m.getCreatedAt().getActorID(),I=s!=null&&s.size?s.has(w)?s.get(w):Ft:Hs;if(m.canStyle(i,I)){const O=d.get(w),y=m.getCreatedAt();(!O||y.after(O))&&d.set(w,y),h.push(m)}}const p=[];for(const m of h){if(m.isRemoved())continue;const[w,I]=this.rgaTreeSplit.findIndexesFromRange(m.createPosRange());l.push({type:"style",actor:i.getActorID(),from:w,to:I,value:{attributes:Zi(r)}});for(const[O,y]of Object.entries(r)){const[g]=m.getValue().setAttr(O,y,i);g!==void 0&&p.push({parent:m.getValue(),child:g})}}return[d,p,l]}indexRangeToPosRange(t,r){const i=this.rgaTreeSplit.indexToPos(t);return t===r?[i,i]:[i,this.rgaTreeSplit.indexToPos(r)]}get length(){return this.rgaTreeSplit.length}getTreeByIndex(){return this.rgaTreeSplit.getTreeByIndex()}getTreeByID(){return this.rgaTreeSplit.getTreeByID()}toJSON(){const t=[];for(const r of this.rgaTreeSplit)r.isRemoved()||t.push(r.getValue().toJSON());return`[${t.join(",")}]`}toSortedJSON(){return this.toJSON()}toJSForTest(){return{createdAt:this.getCreatedAt().toTestString(),value:JSON.parse(this.toJSON()),type:"YORKIE_TEXT"}}toString(){return this.rgaTreeSplit.toString()}values(){const t=[];for(const r of this.rgaTreeSplit)if(!r.isRemoved()){const i=r.getValue();t.push({attributes:Zi(i.getAttributes()),content:i.getContent()})}return t}getRGATreeSplit(){return this.rgaTreeSplit}toTestString(){return this.rgaTreeSplit.toTestString()}deepcopy(){const t=new Et(this.rgaTreeSplit.deepcopy(),this.getCreatedAt());return t.remove(this.getRemovedAt()),t}findIndexesFromRange(t){return this.rgaTreeSplit.findIndexesFromRange(t)}getGCPairs(){const t=[];for(const r of this.rgaTreeSplit){r.getRemovedAt()&&t.push({parent:this.rgaTreeSplit,child:r});for(const i of r.getValue().getGCPairs())t.push(i)}return t}}class Oo extends $t{constructor(t,r,i,s,o,a,l){super(t,l);u(this,"fromPos");u(this,"toPos");u(this,"maxCreatedAtMapByActor");u(this,"content");u(this,"attributes");this.fromPos=r,this.toPos=i,this.maxCreatedAtMapByActor=s,this.content=o,this.attributes=a}static create(t,r,i,s,o,a,l){return new Oo(t,r,i,s,o,a,l)}execute(t){const r=t.findByCreatedAt(this.getParentCreatedAt());if(!r)throw new k(S.ErrInvalidArgument,`fail to find ${this.getParentCreatedAt()}`);if(!(r instanceof Et))throw new k(S.ErrInvalidArgument,"fail to execute, only Text can execute edit");const i=r,[,s,o]=i.edit([this.fromPos,this.toPos],this.content,this.getExecutedAt(),Object.fromEntries(this.attributes),this.maxCreatedAtMapByActor);for(const a of o)t.registerGCPair(a);return{opInfos:s.map(({from:a,to:l,value:c})=>({type:"edit",from:a,to:l,value:c,path:t.createPath(this.getParentCreatedAt())}))}}getEffectedCreatedAt(){return this.getParentCreatedAt()}toTestString(){const t=this.getParentCreatedAt().toTestString(),r=this.fromPos.toTestString(),i=this.toPos.toTestString(),s=this.content;return`${t}.EDIT(${r},${i},${s})`}getFromPos(){return this.fromPos}getToPos(){return this.toPos}getContent(){return this.content}getAttributes(){return this.attributes||new Map}getMaxCreatedAtMapByActor(){return this.maxCreatedAtMapByActor}}class Ro extends $t{constructor(t,r,i,s,o,a){super(t,a);u(this,"fromPos");u(this,"toPos");u(this,"maxCreatedAtMapByActor");u(this,"attributes");this.fromPos=r,this.toPos=i,this.maxCreatedAtMapByActor=s,this.attributes=o}static create(t,r,i,s,o,a){return new Ro(t,r,i,s,o,a)}execute(t){const r=t.findByCreatedAt(this.getParentCreatedAt());if(!r)throw new k(S.ErrInvalidArgument,`fail to find ${this.getParentCreatedAt()}`);if(!(r instanceof Et))throw new k(S.ErrInvalidArgument,"fail to execute, only Text can execute edit");const i=r,[,s,o]=i.setStyle([this.fromPos,this.toPos],this.attributes?Object.fromEntries(this.attributes):{},this.getExecutedAt(),this.maxCreatedAtMapByActor);for(const a of s)t.registerGCPair(a);return{opInfos:o.map(({from:a,to:l,value:c})=>({type:"style",from:a,to:l,value:c,path:t.createPath(this.getParentCreatedAt())}))}}getEffectedCreatedAt(){return this.getParentCreatedAt()}toTestString(){const t=this.getParentCreatedAt().toTestString(),r=this.fromPos.toTestString(),i=this.toPos.toTestString(),s=this.attributes;return`${t}.STYL(${r},${i},${JSON.stringify(s)})`}getFromPos(){return this.fromPos}getToPos(){return this.toPos}getAttributes(){return this.attributes}getMaxCreatedAtMapByActor(){return this.maxCreatedAtMapByActor}}const z1=2,U1="root",pr="text";function Os(n,e){let t=0;const r=n.children;for(let i=0;i0)throw new k(S.ErrRefused,"Text node cannot have children")}updateAncestorsSize(){let e=this.parent;const t=this.isRemoved?-1:1;for(;e&&(e.size+=this.paddedSize*t,!e.isRemoved);)e=e.parent}updateDescendantsSize(){let e=0;for(const t of this._children){const r=t.updateDescendantsSize();t.isRemoved||(e+=r)}return this.size+=e,this.paddedSize}get isText(){return this.type===pr}get paddedSize(){return this.size+(this.isText?0:z1)}isAncestorOf(e){return j1(this,e)}get nextSibling(){const e=this.parent.findOffset(this),t=this.parent.children[e+1];if(t)return t}get prevSibling(){const e=this.parent.findOffset(this),t=this.parent.children[e-1];if(t)return t}splitText(e,t){if(e===0||e===this.size)return;const r=this.value.slice(0,e),i=this.value.slice(e);if(!i.length)return;this.value=r;const s=this.cloneText(e+t);return s.value=i,this.parent.insertAfterInternal(s,this),s}get children(){return this._children.filter(e=>!e.isRemoved)}get allChildren(){return[...this._children]}hasTextChild(){return this.children.length>0&&this.children.every(e=>e.isText)}append(...e){if(this.isText)throw new k(S.ErrRefused,"Text node cannot have children");this._children.push(...e);for(const t of e)t.parent=this,t.updateAncestorsSize()}prepend(...e){if(this.isText)throw new k(S.ErrRefused,"Text node cannot have children");this._children.unshift(...e);for(const t of e)t.parent=this}insertBefore(e,t){if(this.isText)throw new k(S.ErrRefused,"Text node cannot have children");const r=this._children.indexOf(t);if(r===-1)throw new k(S.ErrInvalidArgument,"child not found");this.insertAtInternal(e,r),e.updateAncestorsSize()}insertAfter(e,t){if(this.isText)throw new k(S.ErrRefused,"Text node cannot have children");const r=this._children.indexOf(t);if(r===-1)throw new k(S.ErrInvalidArgument,"child not found");this.insertAtInternal(e,r+1),e.updateAncestorsSize()}insertAt(e,t){if(this.isText)throw new k(S.ErrRefused,"Text node cannot have children");this.insertAtInternal(e,t),e.updateAncestorsSize()}removeChild(e){if(this.isText)throw new k(S.ErrRefused,"Text node cannot have children");const t=this._children.indexOf(e);if(t===-1)throw new k(S.ErrInvalidArgument,"child not found");this._children.splice(t,1),e.parent=void 0}splitElement(e,t){const r=this.cloneElement(t);this.parent.insertAfterInternal(r,this),r.updateAncestorsSize();const i=this.children.slice(0,e),s=this.children.slice(e);this._children=i,r._children=s,this.size=this._children.reduce((o,a)=>o+a.paddedSize,0),r.size=r._children.reduce((o,a)=>o+a.paddedSize,0);for(const o of r._children)o.parent=r;return r}insertAfterInternal(e,t){if(this.isText)throw new k(S.ErrRefused,"Text node cannot have children");const r=this._children.indexOf(t);if(r===-1)throw new k(S.ErrInvalidArgument,"child not found");this.insertAtInternal(e,r+1)}insertAtInternal(e,t){if(this.isText)throw new k(S.ErrRefused,"Text node cannot have children");this._children.splice(t,0,e),e.parent=this}findOffset(e){if(this.isText)throw new k(S.ErrRefused,"Text node cannot have children");if(e.isRemoved){const t=this._children.indexOf(e);return this.allChildren.splice(0,t).filter(i=>!i.isRemoved).length}return this.children.indexOf(e)}findBranchOffset(e){if(this.isText)throw new k(S.ErrRefused,"Text node cannot have children");let t=e;for(;t;){const r=this._children.indexOf(t);if(r!==-1)return r;t=t.parent}return-1}}function j1(n,e){if(n===e)return!1;for(;e.parent;){if(e.parent===n)return!0;e=e.parent}return!1}var ge=(n=>(n.Start="Start",n.End="End",n.Text="Text",n))(ge||{});function ay(n,e,t,r){if(e>t)throw new k(S.ErrInvalidArgument,`from is greater than to: ${e} > ${t}`);if(e>n.size)throw new k(S.ErrInvalidArgument,`from is out of range: ${e} > ${n.size}`);if(t>n.size)throw new k(S.ErrInvalidArgument,`to is out of range: ${t} > ${n.size}`);if(e===t)return;let i=0;for(const s of n.children){if(e-s.paddedSizes.size;(s.isText||l)&&r([s,s.isText?"Text":"Start"],c),ay(s,Math.max(0,o),Math.min(a,s.size),r),c&&r([s,"End"],c)}i+=s.paddedSize}}function ly(n,e,t=0){for(const r of n.children)ly(r,e,t+1);e(n,t)}function Ml(n,e,t=0){for(const r of n._children)Ml(r,e,t+1);e(n,t)}function Wc(n,e,t=!0){if(e>n.size)throw new k(S.ErrInvalidArgument,`index is out of range: ${e} > ${n.size}`);if(n.isText)return{node:n,offset:e};let r=0,i=0;for(const s of n.children){if(t&&s.isText&&s.size>=e-i)return Wc(s,e-i,t);if(e===i)return{node:n,offset:r};if(!t&&s.paddedSize===e-i)return{node:n,offset:r+1};if(s.paddedSize>e-i)return Wc(s,e-i-1,t);i+=s.paddedSize,r+=1}return{node:n,offset:r}}function uy(n){return n.isText||n.children.length===0?n:uy(n.children[0])}function q1(n,e){if(n.sizen===e?0:n0)if(t.right)t.right.parent=t,t=t.right;else return t;else if(r<0)if(t.left)t.left.parent=t,t=t.left;else{let i=t.parent,s=t;for(;i&&s===i.left;)s=i,i=i.parent;return i}else return t}}lastEntry(){if(!this.root)return this.root;let e=this.root;for(;e.right;)e=e.right;return e}size(){return this.counter}isEmpty(){return this.counter===0}getInternal(e,t){for(;t;){const r=this.comparator(e,t.key);if(r===0)return t;r<0?t=t.left:r>0&&(t=t.right)}}putInternal(e,t,r){if(!r)return this.counter+=1,new H1(e,t,!0);const i=this.comparator(e,r.key);return i<0?r.left=this.putInternal(e,t,r.left):i>0?r.right=this.putInternal(e,t,r.right):r.value=t,this.isRed(r.right)&&!this.isRed(r.left)&&(r=this.rotateLeft(r)),this.isRed(r.left)&&this.isRed(r.left.left)&&(r=this.rotateRight(r)),this.isRed(r.left)&&this.isRed(r.right)&&this.flipColors(r),r}removeInternal(e,t){if(this.comparator(t,e.key)<0)!this.isRed(e.left)&&!this.isRed(e.left.left)&&(e=this.moveRedLeft(e)),e.left=this.removeInternal(e.left,t);else{if(this.isRed(e.left)&&(e=this.rotateRight(e)),this.comparator(t,e.key)===0&&!e.right){this.counter-=1;return}if(!this.isRed(e.right)&&!this.isRed(e.right.left)&&(e=this.moveRedRight(e)),this.comparator(t,e.key)===0){this.counter-=1;const r=this.min(e.right);e.value=r.value,e.key=r.key,e.right=this.removeMin(e.right)}else e.right=this.removeInternal(e.right,t)}return this.fixUp(e)}min(e){return e.left?this.min(e.left):e}removeMin(e){if(e.left)return!this.isRed(e.left)&&!this.isRed(e.left.left)&&(e=this.moveRedLeft(e)),e.left=this.removeMin(e.left),this.fixUp(e)}fixUp(e){return this.isRed(e.right)&&(e=this.rotateLeft(e)),this.isRed(e.left)&&this.isRed(e.left.left)&&(e=this.rotateRight(e)),this.isRed(e.left)&&this.isRed(e.right)&&this.flipColors(e),e}moveRedLeft(e){return this.flipColors(e),this.isRed(e.right.left)&&(e.right=this.rotateRight(e.right),e=this.rotateLeft(e),this.flipColors(e)),e}moveRedRight(e){return this.flipColors(e),this.isRed(e.left.left)&&(e=this.rotateRight(e),this.flipColors(e)),e}isRed(e){return e&&e.isRed}rotateLeft(e){const t=e.right;return e.right=t.left,t.left=e,t.isRed=t.left.isRed,t.left.isRed=!0,t}rotateRight(e){const t=e.left;return e.left=t.right,t.right=e,t.isRed=t.right.isRed,t.right.isRed=!0,t}flipColors(e){e.isRed=!e.isRed,e.left.isRed=!e.left.isRed,e.right.isRed=!e.right.isRed}}class Lt{constructor(e,t){u(this,"parentID");u(this,"leftSiblingID");this.parentID=e,this.leftSiblingID=t}static of(e,t){return new Lt(e,t)}static fromTreePos(e){const{offset:t}=e;let{node:r}=e,i;return r.isText?(r.parent.children[0]===r&&t===0?i=r.parent:i=r,r=r.parent):t===0?i=r:i=r.children[t-1],Lt.of(r.id,Ee.of(i.getCreatedAt(),i.getOffset()+t))}getParentID(){return this.parentID}static fromStruct(e){return Lt.of(Ee.of(tt.fromStruct(e.parentID.createdAt),e.parentID.offset),Ee.of(tt.fromStruct(e.leftSiblingID.createdAt),e.leftSiblingID.offset))}toStruct(){return{parentID:{createdAt:this.getParentID().getCreatedAt().toStruct(),offset:this.getParentID().getOffset()},leftSiblingID:{createdAt:this.getLeftSiblingID().getCreatedAt().toStruct(),offset:this.getLeftSiblingID().getOffset()}}}toTreeNodePair(e){const t=this.getParentID(),r=this.getLeftSiblingID(),i=e.findFloorNode(t);let s=e.findFloorNode(r);if(!i||!s)throw new k(S.ErrRefused,`cannot find node of CRDTTreePos(${t.toTestString()}, ${r.toTestString()})`);return!r.equals(t)&&r.getOffset()>0&&r.getOffset()===s.id.getOffset()&&s.insPrevID&&(s=e.findFloorNode(s.insPrevID)),[i,s]}getLeftSiblingID(){return this.leftSiblingID}equals(e){return this.getParentID().getCreatedAt().equals(e.getParentID().getCreatedAt())&&this.getParentID().getOffset()===e.getParentID().getOffset()&&this.getLeftSiblingID().getCreatedAt().equals(e.getLeftSiblingID().getCreatedAt())&&this.getLeftSiblingID().getOffset()===e.getLeftSiblingID().getOffset()}}class Ee{constructor(e,t){u(this,"createdAt");u(this,"offset");this.createdAt=e,this.offset=t}static of(e,t){return new Ee(e,t)}static fromStruct(e){return Ee.of(tt.fromStruct(e.createdAt),e.offset)}static createComparator(){return(e,t)=>{const r=e.getCreatedAt().compare(t.getCreatedAt());return r!==0?r:e.getOffset()>t.getOffset()?1:e.getOffset(){const s=i.deepcopy();return s.parent=t,s}),t.insPrevID=this.insPrevID,t.insNextID=this.insNextID,t}get value(){if(!this.isText)throw new k(S.ErrInvalidType,`cannot get value of element node: ${this.type}`);return this._value}set value(t){if(!this.isText)throw new k(S.ErrInvalidType,`cannot set value of element node: ${this.type}`);this._value=t,this.size=t.length}get isRemoved(){return!!this.removedAt}remove(t){const r=!this.removedAt;(!this.removedAt||this.removedAt.compare(t)>0)&&(this.removedAt=t),r&&this.updateAncestorsSize()}cloneText(t){return new Ze(Ee.of(this.id.getCreatedAt(),t),this.type,void 0,void 0,this.removedAt)}cloneElement(t){return new Ze(Ee.of(t(),0),this.type,void 0,void 0,this.removedAt)}split(t,r,i){const s=this.isText?this.splitText(r,this.id.getOffset()):this.splitElement(r,i);if(s){if(s.insPrevID=this.id,this.insNextID){const o=t.findFloorNode(this.insNextID);o.insPrevID=s.id,s.insNextID=this.insNextID}this.insNextID=s.id,t.registerNode(s)}return s}getCreatedAt(){return this.id.getCreatedAt()}getOffset(){return this.id.getOffset()}canDelete(t,r){return!this.getCreatedAt().after(r)&&(!this.removedAt||t.after(this.removedAt))}canStyle(t,r){return this.isText?!1:!this.getCreatedAt().after(r)&&(!this.removedAt||t.after(this.removedAt))}setAttrs(t,r){this.attrs||(this.attrs=new Ar);const i=new Array;for(const[s,o]of Object.entries(t))i.push(this.attrs.set(s,o,r));return i}purge(t){this.attrs&&this.attrs.purge(t)}getGCPairs(){const t=[];if(!this.attrs)return t;for(const r of this.attrs)r.getRemovedAt()&&t.push({parent:this,child:r});return t}}function Hc(n){var t;if(n.isText){const r=n;return{type:r.type,value:r.value}}const e={type:n.type,children:n.children.map(Hc)};return n.attrs&&(e.attributes=Zi((t=n.attrs)==null?void 0:t.toObject())),e}function Xf(n){if(n.isText)return n.value;let e="";return n.attrs&&n.attrs.size()&&(e=" "+Array.from(n.attrs).filter(t=>!t.isRemoved()).sort((t,r)=>t.getKey().localeCompare(r.getKey())).map(t=>{const r=JSON.parse(t.getValue());return typeof r=="string"?`${t.getKey()}="${r}"`:`${t.getKey()}="${tn(t.getValue())}"`}).join(" ")),`<${n.type}${e}>${n.children.map(t=>Xf(t)).join("")}`}function fy(n){if(n.isText){const e=n;return{type:e.type,value:e.value,size:e.size,isRemoved:e.isRemoved}}return{type:n.type,children:n.children.map(fy),size:n.size,isRemoved:n.isRemoved}}class xt extends Po{constructor(t,r){super(r);u(this,"indexTree");u(this,"nodeMapByID");this.indexTree=new K1(t),this.nodeMapByID=new cy(Ee.createComparator()),this.indexTree.traverseAll(i=>{this.nodeMapByID.put(i.id,i)})}static create(t,r){return new xt(t,r)}findFloorNode(t){const r=this.nodeMapByID.floorEntry(t);if(!(!r||!r.key.getCreatedAt().equals(t.getCreatedAt())))return r.value}registerNode(t){this.nodeMapByID.put(t.id,t)}findNodesAndSplitText(t,r){const[i,s]=t.toTreeNodePair(this);let o=s;const a=i===o,l=o.parent&&!a?o.parent:i;if(o.isText&&o.split(this,t.getLeftSiblingID().getOffset()-o.id.getOffset()),r){const c=l.allChildren,d=a?0:c.indexOf(o)+1;for(let h=d;h{const I=w.getCreatedAt().getActorID(),O=s?s.has(I)?s.get(I):Ft:Hs;if(w.canStyle(i,O)&&r){const y=p.get(I),g=w.getCreatedAt();(!y||g.after(y))&&p.set(I,g);const v=w.setAttrs(r,i),T=v.reduce((P,[,B])=>(B&&(P[B.getKey()]=h[B.getKey()]),P),{}),x=w.parent,N=w.prevSibling||w.parent;Object.keys(T).length>0&&d.push({type:"style",from:this.toIndex(x,N),to:this.toIndex(w,w),fromPath:this.toPath(x,N),toPath:this.toPath(w,w),actor:i.getActorID(),value:T});for(const[P]of v)P&&m.push({parent:w,child:P})}}),[p,m,d]}removeStyle(t,r,i,s){const[o,a]=this.findNodesAndSplitText(t[0],i),[l,c]=this.findNodesAndSplitText(t[1],i),d=[],h=new Map,p=[];return this.traverseInPosRange(o,a,l,c,([m])=>{const w=m.getCreatedAt().getActorID(),I=s?s.has(w)?s.get(w):Ft:Hs;if(m.canStyle(i,I)&&r){const O=h.get(w),y=m.getCreatedAt();(!O||y.after(O))&&h.set(w,y),m.attrs||(m.attrs=new Ar);for(const T of r){const x=m.attrs.remove(T,i);for(const N of x)p.push({parent:m,child:N})}const g=m.parent,v=m.prevSibling||m.parent;d.push({actor:i.getActorID(),type:"removeStyle",from:this.toIndex(g,v),to:this.toIndex(m,m),fromPath:this.toPath(g,v),toPath:this.toPath(m,m),value:r})}}),[h,p,d]}edit(t,r,i,s,o,a){const[l,c]=this.findNodesAndSplitText(t[0],s),[d,h]=this.findNodesAndSplitText(t[1],s),p=this.toIndex(l,c),m=this.toPath(l,c),w=[],I=[],O=[],y=new Map;this.traverseInPosRange(l,c,d,h,([T,x],N)=>{if(x===ge.Start&&!N)for(const H of T.children)O.push(H);const P=T.getCreatedAt().getActorID(),B=a?a.has(P)?a.get(P):Ft:Hs;if(T.canDelete(s,B)||w.includes(T.parent)){const H=y.get(P),U=T.getCreatedAt();(!H||U.after(H))&&y.set(P,U),(x===ge.Text||x===ge.Start)&&w.push(T),I.push([T,x])}});const g=this.makeDeletionChanges(I,s),v=[];for(const T of w)T.remove(s),T.isRemoved&&v.push({parent:this,child:T});for(const T of O)T.removedAt||l.append(T);if(i>0){let T=0,x=l,N=c;for(;T{l.isRemoved&&(P.remove(s),v.push({parent:this,child:P})),this.nodeMapByID.put(P.id,P)}),N.isRemoved||T.push(N);if(T.length){const N=T.map(P=>Hc(P));g.length&&g[g.length-1].from===p?g[g.length-1].value=N:g.push({type:"content",from:p,to:p,fromPath:m,toPath:m,actor:s.getActorID(),value:N})}}return[g,v,y]}editT(t,r,i,s,o){const a=this.findPos(t[0]),l=this.findPos(t[1]);this.edit([a,l],r,i,s,o)}move(t,r,i){throw new k(S.ErrUnimplemented,`not implemented: ${t}, ${r}, ${i}`)}purge(t){var s;(s=t.parent)==null||s.removeChild(t),this.nodeMapByID.remove(t.id);const r=t.insPrevID,i=t.insNextID;if(r){const o=this.findFloorNode(r);o.insNextID=i}if(i){const o=this.findFloorNode(i);o.insPrevID=r}t.insPrevID=void 0,t.insNextID=void 0}getGCPairs(){const t=[];return this.indexTree.traverse(r=>{r.getRemovedAt()&&t.push({parent:this,child:r});for(const i of r.getGCPairs())t.push(i)}),t}findPos(t,r=!0){const i=this.indexTree.findTreePos(t,r);return Lt.fromTreePos(i)}pathToPosRange(t){const r=this.pathToIndex(t);return[this.findPos(r),this.findPos(r+1)]}pathToPos(t){const r=this.indexTree.pathToIndex(t);return this.findPos(r)}getRoot(){return this.indexTree.getRoot()}getSize(){return this.indexTree.size}getNodeSize(){return this.nodeMapByID.size()}getIndexTree(){return this.indexTree}toXML(){return Xf(this.indexTree.getRoot())}toJSON(){return JSON.stringify(this.getRootTreeNode())}toJSForTest(){return{createdAt:this.getCreatedAt().toTestString(),value:JSON.parse(this.toJSON()),type:"YORKIE_TREE"}}toJSInfoForTest(){const t=this.indexTree.getRoot(),r=(i,s=void 0,o=void 0,a=0)=>{var m,w,I,O;let l,c,d;const h=i.isText?{node:i,offset:0}:s&&o?this.toTreePos(s,o):null;h&&(l=this.indexTree.indexOf(h),c=this.indexTree.treePosToPath(h),d=Lt.fromTreePos(h).toStruct());const p={type:i.type,parent:s==null?void 0:s.id.toTestString(),size:i.size,id:i.id.toTestString(),removedAt:(m=i.removedAt)==null?void 0:m.toTestString(),insPrev:(w=i.insPrevID)==null?void 0:w.toTestString(),insNext:(I=i.insNextID)==null?void 0:I.toTestString(),value:i.isText?i.value:void 0,isRemoved:i.isRemoved,children:[],depth:a,attributes:i.attrs?Zi((O=i.attrs)==null?void 0:O.toObject()):void 0,index:l,path:c,pos:d};for(let y=0;y0&&y===i[i.length-1].to?(i[i.length-1].to=g,i[i.length-1].toPath=this.toPath(O,m)):i.push({type:"content",from:y,to:g,fromPath:this.toPath(I,h),toPath:this.toPath(O,m),actor:r.getActorID()}))}return i.reverse()}findRightToken([t,r]){if(r===ge.Start){const l=t.allChildren;return l.length>0?[l[0],l[0].isText?ge.Text:ge.Start]:[t,ge.End]}const i=t.parent,s=i.allChildren,o=s.indexOf(t);if(i&&o===s.length-1)return[i,ge.End];const a=s[o+1];return[a,a.isText?ge.Text:ge.Start]}findLeftToken([t,r]){if(r===ge.End){const l=t.allChildren;if(l.length>0){const c=l[l.length-1];return[c,c.isText?ge.Text:ge.End]}return[t,ge.Start]}const i=t.parent,s=i.allChildren,o=s.indexOf(t);if(i&&o===0)return[i,ge.Start];const a=s[o-1];return[a,a.isText?ge.Text:ge.End]}}class Lo extends $t{constructor(t,r,i,s,o,a,l){super(t,l);u(this,"fromPos");u(this,"toPos");u(this,"contents");u(this,"splitLevel");u(this,"maxCreatedAtMapByActor");this.fromPos=r,this.toPos=i,this.contents=s,this.splitLevel=o,this.maxCreatedAtMapByActor=a}static create(t,r,i,s,o,a,l){return new Lo(t,r,i,s,o,a,l)}execute(t){var l;const r=t.findByCreatedAt(this.getParentCreatedAt());if(!r)throw new k(S.ErrInvalidArgument,`fail to find ${this.getParentCreatedAt()}`);if(!(r instanceof xt))throw new k(S.ErrInvalidArgument,"fail to execute, only Tree can execute edit");const i=this.getExecutedAt(),s=r,[o,a]=s.edit([this.fromPos,this.toPos],(l=this.contents)==null?void 0:l.map(c=>c.deepcopy()),this.splitLevel,i,(()=>{let c=i.getDelimiter();return this.contents!==void 0&&(c+=this.contents.length),()=>tt.of(i.getLamport(),++c,i.getActorID())})(),this.maxCreatedAtMapByActor);for(const c of a)t.registerGCPair(c);return{opInfos:o.map(({from:c,to:d,value:h,splitLevel:p,fromPath:m,toPath:w})=>({type:"tree-edit",path:t.createPath(this.getParentCreatedAt()),from:c,to:d,value:h,splitLevel:p,fromPath:m,toPath:w}))}}getEffectedCreatedAt(){return this.getParentCreatedAt()}toTestString(){const t=this.getParentCreatedAt().toTestString(),r=`${this.fromPos.getLeftSiblingID().getCreatedAt().toTestString()}/${this.fromPos.getLeftSiblingID().getOffset()}`,i=`${this.toPos.getLeftSiblingID().getCreatedAt().toTestString()}/${this.toPos.getLeftSiblingID().getOffset()}`,s=this.contents||[];return`${t}.EDIT(${r},${i},${s.map(o=>Xf(o)).join("")})`}getFromPos(){return this.fromPos}getToPos(){return this.toPos}getContents(){return this.contents}getSplitLevel(){return this.splitLevel}getMaxCreatedAtMapByActor(){return this.maxCreatedAtMapByActor}}class es{constructor(e){u(this,"vector");this.vector=e||new Map}set(e,t){this.vector.set(e,t)}get(e){return this.vector.get(e)}maxLamport(){let e=BigInt(0);for(const[,t]of this)t>e&&(e=t);return e}max(e){const t=new Map;for(const[r,i]of e){const s=this.vector.get(r),o=s&&s>i?s:i;t.set(r,o)}for(const[r,i]of this){const s=e.get(r),o=s&&s>i?s:i;t.set(r,o)}return new es(t)}afterOrEqual(e){const t=this.vector.get(e.getActorID());return t===void 0?!1:t>=e.getLamport()}deepcopy(){const e=new Map;for(const[t,r]of this.vector)e.set(t,r);return new es(e)}filter(e){const t=new Map;for(const[r]of e){const i=this.vector.get(r);i!==void 0&&t.set(r,i)}return new es(t)}size(){return this.vector.size}*[Symbol.iterator](){for(const[e,t]of this.vector)yield[e,t]}}const G1=new es(new Map);class lr{constructor(e,t,r,i,s){u(this,"clientSeq");u(this,"serverSeq");u(this,"lamport");u(this,"actor");u(this,"versionVector");this.clientSeq=e,this.serverSeq=s,this.lamport=t,this.versionVector=i,this.actor=r}static of(e,t,r,i,s){return new lr(e,t,r,i,s)}next(){const e=this.versionVector.deepcopy();return e.set(this.actor,this.lamport+1n),new lr(this.clientSeq+1,this.lamport+1n,this.actor,e)}syncClocks(e){const t=e.lamport>this.lamport?e.lamport+1n:this.lamport+1n,r=this.versionVector.max(e.versionVector),i=new lr(this.clientSeq,t,this.actor,r);return i.versionVector.set(this.actor,t),i}setClocks(e,t){const r=e>this.lamport?e:this.lamport+1n,i=this.versionVector.max(t);return i.set(this.actor,r),lr.of(this.clientSeq,r,this.actor,i)}createTimeTicket(e){return tt.of(this.lamport,e,this.actor)}setActor(e){return new lr(this.clientSeq,this.lamport,e,this.versionVector,this.serverSeq)}setVersionVector(e){return new lr(this.clientSeq,this.lamport,this.actor,e,this.serverSeq)}getClientSeq(){return this.clientSeq}getServerSeq(){return this.serverSeq?this.serverSeq.toString():""}getLamport(){return this.lamport}getLamportAsString(){return this.lamport.toString()}getActorID(){return this.actor}getVersionVector(){return this.versionVector}toTestString(){return`${this.lamport.toString()}:${this.actor.slice(-2)}:${this.clientSeq}`}}const Y1=new lr(0,0n,Gf,G1);class gs{constructor({id:e,operations:t,presenceChange:r,message:i}){u(this,"id");u(this,"operations");u(this,"presenceChange");u(this,"message");this.id=e,this.operations=t||[],this.presenceChange=r,this.message=i}static create({id:e,operations:t,presenceChange:r,message:i}){return new gs({id:e,operations:t,presenceChange:r,message:i})}getID(){return this.id}getMessage(){return this.message}hasOperations(){return this.operations.length>0}getOperations(){return this.operations}setActor(e){for(const t of this.operations)t.setActor(e);this.id=this.id.setActor(e)}hasPresenceChange(){return this.presenceChange!==void 0}getPresenceChange(){return this.presenceChange}execute(e,t,r){const i=[],s=[];for(const o of this.operations){const a=o.execute(e,r);if(!a)continue;const{opInfos:l,reverseOp:c}=a;i.push(...l),c&&s.unshift(c)}return this.presenceChange&&(this.presenceChange.type===Qr.Put?t.set(this.id.getActorID(),Pt(this.presenceChange.presence)):t.delete(this.id.getActorID())),{opInfos:i,reverseOps:s}}toTestString(){return`${this.operations.map(e=>e.toTestString()).join(",")}`}toStruct(){return{changeID:fe.bytesToHex(fe.toChangeID(this.getID()).toBinary()),message:this.getMessage(),operations:this.getOperations().map(e=>fe.bytesToHex(fe.toOperation(e).toBinary())),presenceChange:this.getPresenceChange()}}static fromStruct(e){const{changeID:t,operations:r,presenceChange:i,message:s}=e;return gs.create({id:fe.bytesToChangeID(fe.hexToBytes(t)),operations:r==null?void 0:r.map(o=>fe.bytesToOperation(fe.hexToBytes(o))),presenceChange:i,message:s})}}class Jl{constructor(e,t,r,i,s,o,a){u(this,"documentKey");u(this,"checkpoint");u(this,"isRemoved");u(this,"changes");u(this,"snapshot");u(this,"minSyncedTicket");u(this,"versionVector");this.documentKey=e,this.checkpoint=t,this.isRemoved=r,this.changes=i,this.snapshot=o,this.minSyncedTicket=a,this.versionVector=s}static create(e,t,r,i,s,o,a){return new Jl(e,t,r,i,s,o,a)}getDocumentKey(){return this.documentKey}getCheckpoint(){return this.checkpoint}getIsRemoved(){return this.isRemoved}getChanges(){return this.changes}hasChanges(){return this.changes.length>0}getChangeSize(){return this.changes.length}hasSnapshot(){return!!this.snapshot&&!!this.snapshot.length}getSnapshot(){return this.snapshot}getMinSyncedTicket(){return this.minSyncedTicket}getVersionVector(){return this.versionVector}}class ts{constructor(e,t){u(this,"serverSeq");u(this,"clientSeq");this.serverSeq=e,this.clientSeq=t}static of(e,t){return new ts(e,t)}increaseClientSeq(e){return e===0?this:new ts(this.serverSeq,this.clientSeq+e)}forward(e){if(this.equals(e))return this;const t=this.serverSeq>e.serverSeq?this.serverSeq:e.serverSeq,r=Math.max(this.clientSeq,e.clientSeq);return ts.of(t,r)}getServerSeqAsString(){return this.serverSeq.toString()}getClientSeq(){return this.clientSeq}getServerSeq(){return this.serverSeq}equals(e){return this.clientSeq===e.clientSeq&&this.serverSeq==e.serverSeq}toTestString(){return`serverSeq=${this.serverSeq}, clientSeq=${this.clientSeq}`}}const Q1=new ts(0n,0);class sn{constructor(e,t){u(this,"createdAt");u(this,"offset");this.createdAt=e,this.offset=t}static of(e,t){return new sn(e,t)}static fromStruct(e){return sn.of(tt.fromStruct(e.createdAt),e.offset)}getCreatedAt(){return this.createdAt}getOffset(){return this.offset}equals(e){return this.createdAt.compare(e.createdAt)===0&&this.offset===e.offset}hasSameCreatedAt(e){return this.createdAt.compare(e.createdAt)===0}split(e){return new sn(this.createdAt,this.offset+e)}toStruct(){return{createdAt:this.createdAt.toStruct(),offset:this.offset}}toTestString(){return`${this.createdAt.toTestString()}:${this.offset}`}toIDString(){return`${this.createdAt.toIDString()}:${this.offset}`}}const X1=sn.of(Ft,0);class Mt{constructor(e,t){u(this,"id");u(this,"relativeOffset");this.id=e,this.relativeOffset=t}static of(e,t){return new Mt(e,t)}static fromStruct(e){const t=sn.fromStruct(e.id);return Mt.of(t,e.relativeOffset)}getID(){return this.id}getRelativeOffset(){return this.relativeOffset}getAbsoluteID(){return sn.of(this.id.getCreatedAt(),this.id.getOffset()+this.relativeOffset)}toTestString(){return`${this.id.toTestString()}:${this.relativeOffset}`}toStruct(){return{id:this.id.toStruct(),relativeOffset:this.relativeOffset}}equals(e){return this.id.equals(e.id)?this.relativeOffset===e.relativeOffset:!1}}class Hr extends ny{constructor(t,r,i){super(r);u(this,"id");u(this,"removedAt");u(this,"prev");u(this,"next");u(this,"insPrev");u(this,"insNext");this.id=t,this.removedAt=i}static create(t,r){return new Hr(t,r)}static createComparator(){return(t,r)=>{const i=t.getCreatedAt().compare(r.getCreatedAt());return i!==0?i:t.getOffset()>r.getOffset()?1:t.getOffset()0&&t.getID().getOffset()==e.getOffset()){if(!t.hasInsPrev())return t;t=t.getInsPrev()}return t}findFloorNode(e){const t=this.treeByID.floorEntry(e);if(t&&!(!t.key.equals(e)&&!t.key.hasSameCreatedAt(e)))return t.value}findBetween(e,t){const r=[];let i=e;for(;i&&i!==t;)r.push(i),i=i.getNext();return r}splitNode(e,t){if(t>e.getContentLength())throw new k(S.ErrInvalidArgument,"offset should be less than or equal to length");if(t===0)return e;if(t===e.getContentLength())return e.getNext();const r=e.split(t);this.treeByIndex.updateWeight(r),this.insertAfter(e,r);const i=e.getInsNext();return i&&i.setInsPrev(r),r.setInsPrev(e),r}deleteNodes(e,t,r){if(!e.length)return[[],new Map,new Map];const[i,s]=this.filterNodes(e,t,r),o=new Map,a=new Map,l=this.makeChanges(s,t);for(const c of i){const d=c.getCreatedAt().getActorID();(!o.has(d)||c.getID().getCreatedAt().after(o.get(d)))&&o.set(d,c.getID().getCreatedAt()),a.set(c.getID().toIDString(),c),c.remove(t)}return this.deleteIndexNodes(s),[l,o,a]}filterNodes(e,t,r){const i=!!r,s=[],o=[],[a,l]=this.findEdgesOfCandidates(e);o.push(a);for(const c of e){const d=c.getCreatedAt().getActorID(),h=i?r.has(d)?r.get(d):Ft:Hs;c.canDelete(t,h)?s.push(c):o.push(c)}return o.push(l),[s,o]}findEdgesOfCandidates(e){return[e[0].getPrev(),e[e.length-1].getNext()]}makeChanges(e,t){const r=[];let i,s;for(let o=0;on<0?Math.ceil(n):Math.floor(n);var on=(n=>(n[n.IntegerCnt=0]="IntegerCnt",n[n.LongCnt=1]="LongCnt",n))(on||{});class rt extends Po{constructor(t,r,i){super(i);u(this,"valueType");u(this,"value");switch(this.valueType=t,t){case 0:typeof r=="number"?r>Math.pow(2,31)-1||r<-Math.pow(2,31)?this.value=q.fromNumber(r).toInt():this.value=ig(r):this.value=r.toInt();break;case 1:typeof r=="number"?this.value=q.fromNumber(r):this.value=r;break;default:throw new k(S.ErrUnimplemented,`unimplemented type: ${t}`)}}static create(t,r,i){return new rt(t,r,i)}static valueFromBytes(t,r){switch(t){case 0:return r[0]|r[1]<<8|r[2]<<16|r[3]<<24;case 1:return q.fromBytesLE(Array.from(r));default:throw new k(S.ErrUnimplemented,`unimplemented type: ${t}`)}}toJSON(){return`${this.value}`}toSortedJSON(){return this.toJSON()}toJSForTest(){return{createdAt:this.getCreatedAt().toTestString(),value:this.value,type:"YORKIE_COUNTER"}}deepcopy(){const t=rt.create(this.valueType,this.value,this.getCreatedAt());return t.setMovedAt(this.getMovedAt()),t}getType(){return this.valueType}static getCounterType(t){switch(typeof t){case"object":return t instanceof q?1:void 0;case"number":return t>Math.pow(2,31)-1||t<-Math.pow(2,31)?1:0;default:return}}static isSupport(t){return!!rt.getCounterType(t)}static isInteger(t){return t%1===0}isNumericType(){const t=this.valueType;return t===0||t===1}getValueType(){return this.valueType}getValue(){return this.value}toBytes(){switch(this.valueType){case 0:{const t=this.value;return new Uint8Array([t&255,t>>8&255,t>>16&255,t>>24&255])}case 1:{const r=this.value.toBytesLE();return Uint8Array.from(r)}default:throw new k(S.ErrUnimplemented,`unimplemented type: ${this.valueType}`)}}increase(t){function r(i){if(!i.isNumericType())throw new TypeError(`Unsupported type of value: ${typeof i.getValue()}`)}return r(this),r(t),this.valueType===1?this.value=this.value.add(t.getValue()):t.getType()===ve.Long?this.value=this.value+t.getValue().toInt():this.value=q.fromNumber(this.value+ig(t.getValue())).toInt(),this}}class ps extends $t{constructor(t,r,i){super(t,i);u(this,"value");this.value=r}static create(t,r,i){return new ps(t,r,i)}execute(t){const r=t.findByCreatedAt(this.getParentCreatedAt());if(!r)throw new k(S.ErrInvalidArgument,`fail to find ${this.getParentCreatedAt()}`);if(!(r instanceof rt))throw new k(S.ErrInvalidArgument,"fail to execute, only Counter can execute increase");const i=r,s=this.value.deepcopy();return i.increase(s),{opInfos:[{type:"increase",path:t.createPath(this.getParentCreatedAt()),value:s.getValue()}],reverseOp:this.toReverseOperation()}}toReverseOperation(){const t=this.value.deepcopy(),i=t.getType()===ve.Long?t.getValue().multiply(-1):t.getValue()*-1;return ps.create(this.getParentCreatedAt(),re.of(i,t.getCreatedAt()))}getEffectedCreatedAt(){return this.getParentCreatedAt()}toTestString(){return`${this.getParentCreatedAt().toTestString()}.INCREASE.${this.value.toJSON()}`}getValue(){return this.value}}class yr extends $t{constructor(t,r,i,s,o,a,l){super(t,l);u(this,"fromPos");u(this,"toPos");u(this,"maxCreatedAtMapByActor");u(this,"attributes");u(this,"attributesToRemove");this.fromPos=r,this.toPos=i,this.maxCreatedAtMapByActor=s,this.attributes=o,this.attributesToRemove=a}static create(t,r,i,s,o,a){return new yr(t,r,i,s,o,new Array,a)}static createTreeRemoveStyleOperation(t,r,i,s,o,a){return new yr(t,r,i,s,new Map,o,a)}execute(t){const r=t.findByCreatedAt(this.getParentCreatedAt());if(!r)throw new k(S.ErrInvalidArgument,`fail to find ${this.getParentCreatedAt()}`);if(!(r instanceof xt))throw new k(S.ErrInvalidArgument,"fail to execute, only Tree can execute edit");const i=r;let s,o;if(this.attributes.size){const a={};[...this.attributes].forEach(([l,c])=>a[l]=c),[,o,s]=i.style([this.fromPos,this.toPos],a,this.getExecutedAt(),this.maxCreatedAtMapByActor)}else{const a=this.attributesToRemove;[,o,s]=i.removeStyle([this.fromPos,this.toPos],a,this.getExecutedAt(),this.maxCreatedAtMapByActor)}for(const a of o)t.registerGCPair(a);return{opInfos:s.map(({from:a,to:l,value:c,fromPath:d,toPath:h})=>({type:"tree-style",from:a,to:l,value:this.attributes.size?{attributes:c}:{attributesToRemove:c},fromPath:d,toPath:h,path:t.createPath(this.getParentCreatedAt())}))}}getEffectedCreatedAt(){return this.getParentCreatedAt()}toTestString(){const t=this.getParentCreatedAt().toTestString(),r=`${this.fromPos.getLeftSiblingID().getCreatedAt().toTestString()}:${this.fromPos.getLeftSiblingID().getOffset()}`,i=`${this.toPos.getLeftSiblingID().getCreatedAt().toTestString()}:${this.toPos.getLeftSiblingID().getOffset()}`;return`${t}.STYLE(${r},${i},${Object.entries(this.attributes||{}).map(([s,o])=>`${s}:"${o}"`).join(" ")})`}getFromPos(){return this.fromPos}getToPos(){return this.toPos}getAttributes(){return this.attributes}getAttributesToRemove(){return this.attributesToRemove}getMaxCreatedAtMapByActor(){return this.maxCreatedAtMapByActor}}function Z1(n){const e=new _f,t=e.data;for(const[r,i]of Object.entries(n))t[r]=JSON.stringify(i);return e}function eS(n){if(n.type===Qr.Put)return new yo({type:Ii.PUT,presence:Z1(n.presence)});if(n.type===Qr.Clear)return new yo({type:Ii.CLEAR});throw new k(S.ErrUnimplemented,"unimplemented type")}function tS(n){return new Zp({serverSeq:n.getServerSeq(),clientSeq:n.getClientSeq()})}function dy(n){return new bl({clientSeq:n.getClientSeq(),lamport:n.getLamport(),actorId:ud(n.getActorID()),versionVector:Zf(n.getVersionVector())})}function F(n){if(n)return new b({lamport:n.getLamport(),delimiter:n.getDelimiter(),actorId:ud(n.getActorID())})}function Zf(n){if(!n)return;const e=new Fl;for(const[t,r]of n)e.vector[t]=BigInt(r.toString());return e}function hy(n){switch(n){case ve.Null:return $.NULL;case ve.Boolean:return $.BOOLEAN;case ve.Integer:return $.INTEGER;case ve.Long:return $.LONG;case ve.Double:return $.DOUBLE;case ve.String:return $.STRING;case ve.Bytes:return $.BYTES;case ve.Date:return $.DATE;default:throw new k(S.ErrInvalidType,`unsupported type: ${n}`)}}function gy(n){switch(n){case on.IntegerCnt:return $.INTEGER_CNT;case on.LongCnt:return $.LONG_CNT;default:throw new k(S.ErrInvalidType,`unsupported type: ${n}`)}}function Tu(n){if(n instanceof He)return new ut({type:$.JSON_OBJECT,createdAt:F(n.getCreatedAt()),value:Cy(n)});if(n instanceof nt)return new ut({type:$.JSON_ARRAY,createdAt:F(n.getCreatedAt()),value:RS(n)});if(n instanceof Et)return new ut({type:$.TEXT,createdAt:F(n.getCreatedAt())});if(n instanceof re)return new ut({type:hy(n.getType()),createdAt:F(n.getCreatedAt()),value:n.toBytes()});if(n instanceof rt)return new ut({type:gy(n.getType()),createdAt:F(n.getCreatedAt()),value:n.toBytes()});if(n instanceof xt)return new ut({type:$.TREE,createdAt:F(n.getCreatedAt()),value:BS(n)});throw new k(S.ErrUnimplemented,"unimplemented element")}function nS(n){return new mo({createdAt:F(n.getCreatedAt()),offset:n.getOffset()})}function ea(n){return new Tr({createdAt:F(n.getID().getCreatedAt()),offset:n.getID().getOffset(),relativeOffset:n.getRelativeOffset()})}function ta(n){return new Ai({parentId:_s(n.getParentID()),leftSiblingId:_s(n.getLeftSiblingID())})}function _s(n){return new Kr({createdAt:F(n.getCreatedAt()),offset:n.getOffset()})}function my(n){const e=new Hf;if(n instanceof Ei){const t=n,r=new Ya;r.parentCreatedAt=F(t.getParentCreatedAt()),r.key=t.getKey(),r.value=Tu(t.getValue()),r.executedAt=F(t.getExecutedAt()),e.body.case="set",e.body.value=r}else if(n instanceof Do){const t=n,r=new Qa;r.parentCreatedAt=F(t.getParentCreatedAt()),r.prevCreatedAt=F(t.getPrevCreatedAt()),r.value=Tu(t.getValue()),r.executedAt=F(t.getExecutedAt()),e.body.case="add",e.body.value=r}else if(n instanceof Fr){const t=n,r=new Xa;r.parentCreatedAt=F(t.getParentCreatedAt()),r.prevCreatedAt=F(t.getPrevCreatedAt()),r.createdAt=F(t.getCreatedAt()),r.executedAt=F(t.getExecutedAt()),e.body.case="move",e.body.value=r}else if(n instanceof Xr){const t=n,r=new Za;r.parentCreatedAt=F(t.getParentCreatedAt()),r.createdAt=F(t.getCreatedAt()),r.executedAt=F(t.getExecutedAt()),e.body.case="remove",e.body.value=r}else if(n instanceof Oo){const t=n,r=new el;r.parentCreatedAt=F(t.getParentCreatedAt()),r.from=ea(t.getFromPos()),r.to=ea(t.getToPos());const i=r.createdAtMapByActor;for(const[o,a]of t.getMaxCreatedAtMapByActor())i[o]=F(a);r.content=t.getContent();const s=r.attributes;for(const[o,a]of t.getAttributes())s[o]=a;r.executedAt=F(t.getExecutedAt()),e.body.case="edit",e.body.value=r}else if(n instanceof Ro){const t=n,r=new tl;r.parentCreatedAt=F(t.getParentCreatedAt()),r.from=ea(t.getFromPos()),r.to=ea(t.getToPos());const i=r.createdAtMapByActor;for(const[o,a]of t.getMaxCreatedAtMapByActor())i[o]=F(a);const s=r.attributes;for(const[o,a]of t.getAttributes())s[o]=a;r.executedAt=F(t.getExecutedAt()),e.body.case="style",e.body.value=r}else if(n instanceof ps){const t=n,r=new nl;r.parentCreatedAt=F(t.getParentCreatedAt()),r.value=Tu(t.getValue()),r.executedAt=F(t.getExecutedAt()),e.body.case="increase",e.body.value=r}else if(n instanceof Lo){const t=n,r=new rl,i=r.createdAtMapByActor;for(const[s,o]of t.getMaxCreatedAtMapByActor())i[s]=F(o);r.parentCreatedAt=F(t.getParentCreatedAt()),r.from=ta(t.getFromPos()),r.to=ta(t.getToPos()),r.contents=uS(t.getContents()),r.splitLevel=t.getSplitLevel(),r.executedAt=F(t.getExecutedAt()),e.body.case="treeEdit",e.body.value=r}else if(n instanceof yr){const t=n,r=new il;r.parentCreatedAt=F(t.getParentCreatedAt()),r.from=ta(t.getFromPos()),r.to=ta(t.getToPos());const i=r.createdAtMapByActor;for(const[o,a]of t.getMaxCreatedAtMapByActor())i[o]=F(a);const s=t.getAttributesToRemove();if(s.length>0)r.attributesToRemove=s;else{const o=r.attributes;for(const[a,l]of t.getAttributes())o[a]=l}r.executedAt=F(t.getExecutedAt()),e.body.case="treeStyle",e.body.value=r}else throw new k(S.ErrUnimplemented,"unimplemented operation");return e}function rS(n){const e=[];for(const t of n)e.push(my(t));return e}function iS(n){const e=new Qp({id:dy(n.getID()),message:n.getMessage()});return n.hasOperations()&&(e.operations=rS(n.getOperations())),n.hasPresenceChange()&&(e.presenceChange=eS(n.getPresenceChange())),e}function sS(n){const e=[];for(const t of n)e.push(iS(t));return e}function oS(n){const e=[];for(const t of n)e.push(new Xp({key:t.getStrKey(),element:td(t.getValue())}));return e}function aS(n){const e=[];for(const t of n)e.push(new fl({element:td(t.getValue())}));return e}function lS(n){const e=[];for(const t of n){const r=new dl;r.id=nS(t.getID()),r.value=t.getValue().getContent(),r.removedAt=F(t.getRemovedAt());const i=r.attributes,s=t.getValue().getAttrs();for(const o of s){const a=new fs;a.value=o.getValue(),a.updatedAt=F(o.getUpdatedAt()),i[o.getKey()]=a}e.push(r)}return e}function uS(n){const e=[];if(!n||!n.length)return e;for(const t of n)e.push(new hl({content:ed(t)}));return e}function cS(n){const e={};for(const t of n)e[t.getKey()]=new fs({value:t.getValue(),updatedAt:F(t.getUpdatedAt()),isRemoved:t.isRemoved()});return e}function ed(n){if(!n)return[];const e=[];return Ml(n,(t,r)=>{const i=new po({id:_s(t.id),type:t.type,removedAt:F(t.removedAt),depth:r});t.isText&&(i.value=t.value),t.insPrevID&&(i.insPrevId=_s(t.insPrevID)),t.insNextID&&(i.insNextId=_s(t.insNextID)),t.attrs&&(i.attributes=cS(t.attrs)),e.push(i)}),e}function fS(n){const e=new _e;return e.body.case="jsonObject",e.body.value=new sl({nodes:oS(n.getRHT()),createdAt:F(n.getCreatedAt()),movedAt:F(n.getMovedAt()),removedAt:F(n.getRemovedAt())}),e}function py(n){const e=new _e;return e.body.case="jsonArray",e.body.value=new ol({nodes:aS(n.getElements()),createdAt:F(n.getCreatedAt()),movedAt:F(n.getMovedAt()),removedAt:F(n.getRemovedAt())}),e}function dS(n){const e=new _e;return e.body.case="primitive",e.body.value=new al({type:hy(n.getType()),value:n.toBytes(),createdAt:F(n.getCreatedAt()),movedAt:F(n.getMovedAt()),removedAt:F(n.getRemovedAt())}),e}function hS(n){const e=new _e;return e.body.case="text",e.body.value=new ll({nodes:lS(n.getRGATreeSplit()),createdAt:F(n.getCreatedAt()),movedAt:F(n.getMovedAt()),removedAt:F(n.getRemovedAt())}),e}function gS(n){const e=new _e;return e.body.case="counter",e.body.value=new ul({type:gy(n.getType()),value:n.toBytes(),createdAt:F(n.getCreatedAt()),movedAt:F(n.getMovedAt()),removedAt:F(n.getRemovedAt())}),e}function yy(n){const e=new _e;return e.body.case="tree",e.body.value=new cl({nodes:ed(n.getRoot()),createdAt:F(n.getCreatedAt()),movedAt:F(n.getMovedAt()),removedAt:F(n.getRemovedAt())}),e}function td(n){if(n instanceof He)return fS(n);if(n instanceof nt)return py(n);if(n instanceof re)return dS(n);if(n instanceof Et)return hS(n);if(n instanceof rt)return gS(n);if(n instanceof xt)return yy(n);throw new k(S.ErrUnimplemented,"unimplemented element")}function mS(n){return new Er({documentKey:n.getDocumentKey(),checkpoint:tS(n.getCheckpoint()),isRemoved:n.getIsRemoved(),changes:sS(n.getChanges()),snapshot:n.getSnapshot(),versionVector:Zf(n.getVersionVector()),minSyncedTicket:F(n.getMinSyncedTicket())})}function sg(n){const e=n.findDetails(O1);for(const t of e)if(t.metadata.code)return t.metadata.code;return""}function vy(n){return lr.of(n.clientSeq,BigInt(n.lamport),ad(n.actorId),nd(n.versionVector),BigInt(n.serverSeq))}function nd(n){if(!n)return;const e=new es;return Object.entries(n.vector).forEach(([t,r])=>{e.set(t,BigInt(r.toString()))}),e}function M(n){if(n)return tt.of(BigInt(n.lamport),n.delimiter,ad(n.actorId))}function rd(n){const e={};return Object.entries(n.data).forEach(([t,r])=>{e[t]=JSON.parse(r)}),e}function pS(n){const e=n.type;if(e===Ii.PUT){const t=rd(n.presence);return{type:Qr.Put,presence:t}}if(e===Ii.CLEAR)return{type:Qr.Clear};throw new k(S.ErrInvalidType,`unsupported type: ${e}`)}function yS(n){const e=new Map;return Object.entries(n).forEach(([t,r])=>{e.set(t,rd(r))}),e}function wy(n){switch(n){case $.NULL:return ve.Null;case $.BOOLEAN:return ve.Boolean;case $.INTEGER:return ve.Integer;case $.LONG:return ve.Long;case $.DOUBLE:return ve.Double;case $.STRING:return ve.String;case $.BYTES:return ve.Bytes;case $.DATE:return ve.Date}throw new k(S.ErrUnimplemented,`unimplemented value type: ${n}`)}function pl(n){switch(n){case $.INTEGER_CNT:return on.IntegerCnt;case $.LONG_CNT:return on.LongCnt}throw new k(S.ErrUnimplemented,`unimplemented value type: ${n}`)}function Au(n){switch(n.type){case $.JSON_OBJECT:return n.value?xy(n.value):He.create(M(n.createdAt));case $.JSON_ARRAY:return n.value?OS(n.value):nt.create(M(n.createdAt));case $.TEXT:return Et.create(ms.create(),M(n.createdAt));case $.TREE:return LS(n.value);case $.NULL:case $.BOOLEAN:case $.INTEGER:case $.LONG:case $.DOUBLE:case $.STRING:case $.BYTES:case $.DATE:return re.of(re.valueFromBytes(wy(n.type),n.value),M(n.createdAt));case $.INTEGER_CNT:case $.LONG_CNT:return rt.create(pl(n.type),rt.valueFromBytes(pl(n.type),n.value),M(n.createdAt))}}function na(n){return Mt.of(sn.of(M(n.createdAt),n.offset),n.relativeOffset)}function Sy(n){return sn.of(M(n.createdAt),n.offset)}function vS(n){const e=ko.create(n.value);Object.entries(n.attributes).forEach(([r,i])=>{e.setAttr(r,i.value,M(i.updatedAt))});const t=Hr.create(Sy(n.id),e);return t.remove(M(n.removedAt)),t}function Oi(n){return Lt.of(Gs(n.parentId),Gs(n.leftSiblingId))}function Gs(n){return Ee.of(M(n.createdAt),n.offset)}function wS(n){if(!n.length)return;const e=[];return n.forEach(t=>{const r=id(t.content);e.push(r)}),e}function id(n){if(n.length===0)return;const e=[];for(const i of n)e.push(kS(i));const t=e[e.length-1],r=new Map;r.set(n[e.length-1].depth,e[e.length-1]);for(let i=e.length-2;i>=0;i--)r.get(n[i].depth-1).prepend(e[i]),r.set(n[i].depth,e[i]);return t.updateDescendantsSize(),xt.create(t,Ft).getRoot()}function SS(n){const e=Ar.create();for(const[t,r]of Object.entries(n))e.setInternal(t,r.value,M(r.updatedAt),r.isRemoved);return e}function kS(n){const e=Gs(n.id),t=Ze.create(e,n.type),r=Object.entries(n.attributes);return t.isText?t.value=n.value:r.length&&(t.attrs=SS(n.attributes)),n.insPrevId&&(t.insPrevID=Gs(n.insPrevId)),n.insNextId&&(t.insNextID=Gs(n.insNextId)),t.removedAt=M(n.removedAt),t}function ky(n){if(n.body.case==="set"){const e=n.body.value;return Ei.create(e.key,Au(e.value),M(e.parentCreatedAt),M(e.executedAt))}else if(n.body.case==="add"){const e=n.body.value;return Do.create(M(e.parentCreatedAt),M(e.prevCreatedAt),Au(e.value),M(e.executedAt))}else if(n.body.case==="move"){const e=n.body.value;return Fr.create(M(e.parentCreatedAt),M(e.prevCreatedAt),M(e.createdAt),M(e.executedAt))}else if(n.body.case==="remove"){const e=n.body.value;return Xr.create(M(e.parentCreatedAt),M(e.createdAt),M(e.executedAt))}else if(n.body.case==="edit"){const e=n.body.value,t=new Map;Object.entries(e.createdAtMapByActor).forEach(([i,s])=>{t.set(i,M(s))});const r=new Map;return Object.entries(e.attributes).forEach(([i,s])=>{r.set(i,s)}),Oo.create(M(e.parentCreatedAt),na(e.from),na(e.to),t,e.content,r,M(e.executedAt))}else if(n.body.case==="style"){const e=n.body.value,t=new Map;Object.entries(e.createdAtMapByActor).forEach(([i,s])=>{t.set(i,M(s))});const r=new Map;return Object.entries(e.attributes).forEach(([i,s])=>{r.set(i,s)}),Ro.create(M(e.parentCreatedAt),na(e.from),na(e.to),t,r,M(e.executedAt))}else{if(n.body.case==="select")return;if(n.body.case==="increase"){const e=n.body.value;return ps.create(M(e.parentCreatedAt),Au(e.value),M(e.executedAt))}else if(n.body.case==="treeEdit"){const e=n.body.value,t=new Map;return Object.entries(e.createdAtMapByActor).forEach(([r,i])=>{t.set(r,M(i))}),Lo.create(M(e.parentCreatedAt),Oi(e.from),Oi(e.to),wS(e.contents),e.splitLevel,t,M(e.executedAt))}else if(n.body.case==="treeStyle"){const e=n.body.value,t=new Map,r=e.attributesToRemove,i=new Map;return e!=null&&e.createdAtMapByActor&&Object.entries(e.createdAtMapByActor).forEach(([s,o])=>{i.set(s,M(o))}),(r==null?void 0:r.length)>0?yr.createTreeRemoveStyleOperation(M(e.parentCreatedAt),Oi(e.from),Oi(e.to),i,r,M(e.executedAt)):(Object.entries(e.attributes).forEach(([s,o])=>{t.set(s,o)}),yr.create(M(e.parentCreatedAt),Oi(e.from),Oi(e.to),i,t,M(e.executedAt)))}else throw new k(S.ErrUnimplemented,"unimplemented operation")}}function TS(n){const e=[];for(const t of n){const r=ky(t);r&&e.push(r)}return e}function Ty(n){const e=[];for(const t of n)e.push(gs.create({id:vy(t.id),operations:TS(t.operations),presenceChange:t.presenceChange?pS(t.presenceChange):void 0,message:t.message}));return e}function AS(n){return ts.of(BigInt(n.serverSeq),n.clientSeq)}function IS(n){return Jl.create(n.documentKey,AS(n.checkpoint),n.isRemoved,Ty(n.changes),nd(n.versionVector),n.snapshot,M(n.minSyncedTicket))}function Ay(n){const e=new vo;for(const r of n.nodes){const i=sd(r.element);e.set(r.key,i,i.getPositionedAt())}const t=new He(M(n.createdAt),e);return t.setMovedAt(M(n.movedAt)),t.setRemovedAt(M(n.removedAt)),t}function Iy(n){const e=new So;for(const r of n.nodes)e.insert(sd(r.element));const t=new nt(M(n.createdAt),e);return t.setMovedAt(M(n.movedAt)),t.setRemovedAt(M(n.removedAt)),t}function ES(n){const e=re.of(re.valueFromBytes(wy(n.type),n.value),M(n.createdAt));return e.setMovedAt(M(n.movedAt)),e.setRemovedAt(M(n.removedAt)),e}function xS(n){const e=new ms;let t=e.getHead();for(const i of n.nodes){const s=e.insertAfter(t,vS(i));i.insPrevId&&s.setInsPrev(e.findNode(Sy(i.insPrevId))),t=s}const r=new Et(e,M(n.createdAt));return r.setMovedAt(M(n.movedAt)),r.setRemovedAt(M(n.removedAt)),r}function CS(n){const e=rt.create(pl(n.type),rt.valueFromBytes(pl(n.type),n.value),M(n.createdAt));return e.setMovedAt(M(n.movedAt)),e.setRemovedAt(M(n.removedAt)),e}function Ey(n){const e=id(n.nodes);return xt.create(e,M(n.createdAt))}function sd(n){if(n.body.case==="jsonObject")return Ay(n.body.value);if(n.body.case==="jsonArray")return Iy(n.body.value);if(n.body.case==="primitive")return ES(n.body.value);if(n.body.case==="text")return xS(n.body.value);if(n.body.case==="counter")return CS(n.body.value);if(n.body.case==="tree")return Ey(n.body.value);throw new k(S.ErrUnimplemented,"unimplemented element")}function NS(n){if(!n)return{root:He.create(Ft),presences:new Map};const e=Tc.fromBinary(n);return{root:sd(e.root),presences:yS(e.presences)}}function PS(n){const e=Zf(n);return od(e.toBinary())}function DS(n){const e=ld(n),t=Fl.fromBinary(e);return nd(t)}function xy(n){if(!n)throw new k(S.ErrInvalidArgument,"bytes is empty");const e=_e.fromBinary(n);return Ay(e.body.value)}function Cy(n){return td(n).toBinary()}function OS(n){if(!n)throw new k(S.ErrInvalidArgument,"bytes is empty");const e=_e.fromBinary(n);return Iy(e.body.value)}function RS(n){return py(n).toBinary()}function LS(n){if(!n)throw new k(S.ErrInvalidArgument,"bytes is empty");const e=_e.fromBinary(n);return Ey(e.body.value)}function BS(n){return yy(n).toBinary()}function od(n){return n?Array.from(n).map(e=>e.toString(16).padStart(2,"0")).join(""):""}function ad(n){return od(n)}function ld(n){return new Uint8Array(n.match(/.{1,2}/g).map(e=>parseInt(e,16)))}function ud(n){return ld(n)}function bS(n){const e=bl.fromBinary(n);return vy(e)}function FS(n){const e=Hf.fromBinary(n);return ky(e)}const fe={fromPresence:rd,toChangePack:mS,fromChangePack:IS,fromChanges:Ty,toTreeNodes:ed,fromTreeNodes:id,objectToBytes:Cy,bytesToObject:xy,bytesToSnapshot:NS,bytesToHex:od,hexToBytes:ld,toHexString:ad,toUint8Array:ud,toOperation:my,toChangeID:dy,PbChangeID:bl,bytesToChangeID:bS,bytesToOperation:FS,versionVectorToHex:PS,hexToVersionVector:DS};var be=(n=>(n[n.Trivial=0]="Trivial",n[n.Debug=1]="Debug",n[n.Info=2]="Info",n[n.Warn=3]="Warn",n[n.Error=4]="Error",n[n.Fatal=5]="Fatal",n))(be||{});let ai=3;function Ny(n){ai=n}const J={trivial:(...n)=>{ai>0||typeof console<"u"&&console.log("YORKIE T:",...n)},debug:(...n)=>{ai>1||typeof console<"u"&&console.log("YORKIE D:",...n)},info:(...n)=>{ai>2||typeof console<"u"&&console.log("YORKIE I:",...n)},warn:(...n)=>{ai>3||typeof console<"u"&&(typeof console.warn<"u"?console.warn("YORKIE W:",...n):console.log("YORKIE W:",...n))},error:(...n)=>{ai>4||typeof console<"u"&&(typeof console.error<"u"?console.error("YORKIE E:",...n):console.log("YORKIE E:",...n))},fatal:(...n)=>{typeof console<"u"&&(typeof console.error<"u"?console.error("YORKIE F:",...n):console.log("YORKIE F:",...n))},isEnabled:n=>ai<=n};function Py(){return"xxxxxxxx-xxxx-4xxxy-xxxx-xxxxxxxxxxx".replace(/[xy]/g,n=>{const e=Math.random()*16|0;return(n==="x"?e:e&3|8).toString(16)})}class MS{constructor(e,t,r,i,s){u(this,"reconnectStreamDelay");u(this,"doc");u(this,"docID");u(this,"syncMode");u(this,"remoteChangeEventReceived");u(this,"watchStream");u(this,"watchLoopTimerID");u(this,"watchAbortController");u(this,"unsubscribeBroadcastEvent");this.reconnectStreamDelay=e,this.doc=t,this.docID=r,this.syncMode=i,this.remoteChangeEventReceived=!1,this.unsubscribeBroadcastEvent=s}changeSyncMode(e){this.syncMode=e}needRealtimeSync(){return this.syncMode===Aa.RealtimeSyncOff?!1:this.syncMode===Aa.RealtimePushOnly?this.doc.hasLocalChanges():this.syncMode!==Aa.Manual&&(this.doc.hasLocalChanges()||this.remoteChangeEventReceived)}async runWatchLoop(e){const t=async()=>{if(this.watchStream)return Promise.resolve();this.watchLoopTimerID&&(clearTimeout(this.watchLoopTimerID),this.watchLoopTimerID=void 0);try{[this.watchStream,this.watchAbortController]=await e(()=>{this.watchStream=void 0,this.watchAbortController=void 0,this.watchLoopTimerID=setTimeout(t,this.reconnectStreamDelay)})}catch{}};await t()}cancelWatchStream(){this.watchStream&&this.watchAbortController&&(this.watchAbortController.abort(),this.watchStream=void 0,this.watchAbortController=void 0),clearTimeout(this.watchLoopTimerID),this.watchLoopTimerID=void 0}}const Iu=()=>{};class JS{constructor(e){u(this,"finalized",!1);u(this,"observers",[]);u(this,"finalError");try{e(this)}catch(t){this.error(t)}}next(e){this.forEachObserver(t=>{t.next(e)})}error(e){this.forEachObserver(t=>{t.error(e)}),this.close(e)}complete(){this.forEachObserver(e=>{e.complete()}),this.close()}subscribe(e,t,r){let i;if(!e)throw new k(S.ErrInvalidArgument,"missing observer");if(this.finalized)throw new k(S.ErrRefused,"observable is finalized due to previous error");typeof e=="object"?i=e:i={next:e,error:t,complete:r},i.next===void 0&&(i.next=Iu),i.error===void 0&&(i.error=Iu),i.complete===void 0&&(i.complete=Iu);const s=Py(),o=this.unsubscribeOne.bind(this,s);if(this.observers.push({subscriptionID:s,observer:i}),this.finalized)try{this.finalError?i.error(this.finalError):i.complete()}catch(a){J.warn(a)}return o}unsubscribeOne(e){var t;this.observers=(t=this.observers)==null?void 0:t.filter(r=>r.subscriptionID!==e)}forEachObserver(e){if(!this.finalized)for(let t=0;te}}class Wi{constructor(e,t,r,i){u(this,"id");u(this,"delimiter");u(this,"message");u(this,"root");u(this,"operations");u(this,"presenceChange");u(this,"previousPresence");u(this,"reversePresenceKeys");this.id=e,this.delimiter=ty,this.root=t,this.operations=[],this.previousPresence=Pt(r),this.presenceChange=void 0,this.reversePresenceKeys=new Set,this.message=i}static create(e,t,r,i){return new Wi(e,t,r,i)}push(e){this.operations.push(e)}registerElement(e,t){this.root.registerElement(e,t)}registerRemovedElement(e){this.root.registerRemovedElement(e)}registerGCPair(e){this.root.registerGCPair(e)}getChange(){return gs.create({id:this.id,operations:this.operations,presenceChange:this.presenceChange,message:this.message})}hasChange(){return this.operations.length>0||this.presenceChange!==void 0}setPresenceChange(e){this.presenceChange=e}setReversePresence(e,t){for(const r of Object.keys(e))t!=null&&t.addToHistory?this.reversePresenceKeys.add(r):this.reversePresenceKeys.delete(r)}getReversePresence(){if(this.reversePresenceKeys.size===0)return;const e={};for(const t of this.reversePresenceKeys)e[t]=this.previousPresence[t];return e}issueTimeTicket(){return this.delimiter+=1,this.id.createTimeTicket(this.delimiter)}getLastTimeTicket(){return this.id.createTimeTicket(this.delimiter)}}class To{constructor(e){u(this,"rootObject");u(this,"elementPairMapByCreatedAt");u(this,"gcElementSetByCreatedAt");u(this,"gcPairMap");this.rootObject=e,this.elementPairMapByCreatedAt=new Map,this.gcElementSetByCreatedAt=new Set,this.gcPairMap=new Map,this.registerElement(e,void 0),e.getDescendants(t=>{if(t.getRemovedAt()&&this.registerRemovedElement(t),t instanceof Et||t instanceof xt)for(const r of t.getGCPairs())this.registerGCPair(r);return!1})}static create(){return new To(He.create(Ft))}findByCreatedAt(e){const t=this.elementPairMapByCreatedAt.get(e.toIDString());if(t)return t.element}findElementPairByCreatedAt(e){return this.elementPairMapByCreatedAt.get(e.toIDString())}createSubPaths(e){let t=this.elementPairMapByCreatedAt.get(e.toIDString());if(!t)return[];const r=[];for(;t.parent;){const i=t.element.getCreatedAt(),s=t.parent.subPathOf(i);if(s===void 0)throw new k(S.ErrInvalidArgument,`cant find the given element: ${i.toIDString()}`);r.unshift(s),t=this.elementPairMapByCreatedAt.get(t.parent.getCreatedAt().toIDString())}return r.unshift("$"),r}createPath(e){return this.createSubPaths(e).join(".")}registerElement(e,t){this.elementPairMapByCreatedAt.set(e.getCreatedAt().toIDString(),{parent:t,element:e}),e instanceof Wr&&e.getDescendants((r,i)=>(this.registerElement(r,i),!1))}deregisterElement(e){let t=0;const r=i=>{const s=i.getCreatedAt().toIDString();this.elementPairMapByCreatedAt.delete(s),this.gcElementSetByCreatedAt.delete(s),t++};return r(e),e instanceof Wr&&e.getDescendants(i=>(r(i),!1)),t}registerRemovedElement(e){this.gcElementSetByCreatedAt.add(e.getCreatedAt().toIDString())}registerGCPair(e){if(this.gcPairMap.get(e.child.toIDString())){this.gcPairMap.delete(e.child.toIDString());return}this.gcPairMap.set(e.child.toIDString(),e)}getElementMapSize(){return this.elementPairMapByCreatedAt.size}getGarbageElementSetSize(){const e=new Set;for(const t of this.gcElementSetByCreatedAt){e.add(t);const r=this.elementPairMapByCreatedAt.get(t);r.element instanceof Wr&&r.element.getDescendants(i=>(e.add(i.getCreatedAt().toIDString()),!1))}return e.size}getObject(){return this.rootObject}getGarbageLen(){return this.getGarbageElementSetSize()+this.gcPairMap.size}deepcopy(){return new To(this.rootObject.deepcopy())}garbageCollect(e){let t=0;for(const r of this.gcElementSetByCreatedAt){const i=this.elementPairMapByCreatedAt.get(r),s=i.element.getRemovedAt();s&&(e!=null&&e.afterOrEqual(s))&&(i.parent.purge(i.element),t+=this.deregisterElement(i.element))}for(const[,r]of this.gcPairMap){const i=r.child.getRemovedAt();i&&(e!=null&&e.afterOrEqual(i))&&(r.parent.purge(r.child),this.gcPairMap.delete(r.child.toIDString()),t+=1)}return t}toJSON(){return this.rootObject.toJSON()}toSortedJSON(){return this.rootObject.toSortedJSON()}getStats(){return{elements:this.getElementMapSize(),gcPairs:this.gcPairMap.size,gcElements:this.getGarbageElementSetSize()}}}function Dy(n,e){const t=new Ao(n);return new Proxy(e,t.getHandlers())}class Ao{constructor(e){u(this,"context");u(this,"handlers");this.context=e,this.handlers={set:(t,r,i)=>(J.isEnabled(be.Trivial)&&J.trivial(`obj[${r}]=${JSON.stringify(i)}`),Ao.setInternal(e,t,r,i),!0),get:(t,r)=>(J.isEnabled(be.Trivial)&&J.trivial(`obj[${r}]`),r==="getID"?()=>t.getCreatedAt():r==="toJSON"||r==="toString"?()=>t.toJSON():r==="toJS"?()=>t.toJS():r==="toJSForTest"?()=>t.toJSForTest():li(e,t.get(r))),ownKeys:t=>t.getKeys(),getOwnPropertyDescriptor:()=>({enumerable:!0,configurable:!0}),deleteProperty:(t,r)=>(J.isEnabled(be.Trivial)&&J.trivial(`obj[${r}]`),Ao.deleteInternal(e,t,r),!0)}}static setInternal(e,t,r,i){if(r.includes("."))throw new k(S.ErrInvalidObjectKey,"key must not contain the '.'.");const s=e.issueTimeTicket(),o=yl(e,i,s),a=t.set(r,o,s);e.registerElement(o,t),a&&e.registerRemovedElement(a),e.push(Ei.create(r,o.deepcopy(),t.getCreatedAt(),s))}static buildObjectMembers(e,t){const r={};for(const[i,s]of Object.entries(t)){if(i.includes("."))throw new k(S.ErrInvalidObjectKey,"key must not contain the '.'.");const o=e.issueTimeTicket(),a=yl(e,s,o);r[i]=a}return r}static deleteInternal(e,t,r){const i=e.issueTimeTicket(),s=t.deleteByKey(r,i);s&&(e.push(Xr.create(t.getCreatedAt(),s.getCreatedAt(),i)),e.registerRemovedElement(s))}getHandlers(){return this.handlers}}function zS(n,e){const t=new oe(n,e);return new Proxy(e,t.getHandlers())}function US(n){return typeof n=="string"||n instanceof String?!isNaN(n):!1}function VS(n){return["concat","entries","every","filter","find","findIndex","forEach","join","keys","map","reduce","reduceRight","slice","some","toLocaleString","toString","values"].includes(n)}class oe{constructor(e,t){u(this,"context");u(this,"handlers");u(this,"array");this.context=e,this.array=t,this.handlers={get:(r,i,s)=>i==="getID"?()=>r.getCreatedAt():i==="getElementByID"?o=>{const a=r.getByID(o);if(!(!a||a.isRemoved()))return Nr(e,a)}:i==="getElementByIndex"?o=>{const a=r.get(o);return Nr(e,a)}:i==="getLast"?()=>Nr(e,r.getLast()):i==="deleteByID"?o=>{const a=oe.deleteInternalByID(e,r,o);return Nr(e,a)}:i==="insertAfter"?(o,a)=>{const l=oe.insertAfterInternal(e,r,o,a);return Nr(e,l)}:i==="insertBefore"?(o,a)=>{const l=oe.insertBeforeInternal(e,r,o,a);return Nr(e,l)}:i==="moveBefore"?(o,a)=>{oe.moveBeforeInternal(e,r,o,a)}:i==="moveAfter"?(o,a)=>{oe.moveAfterInternal(e,r,o,a)}:i==="moveFront"?o=>{oe.moveFrontInternal(e,r,o)}:i==="moveLast"?o=>{oe.moveLastInternal(e,r,o)}:US(i)?li(e,r.get(Number(i))):i==="push"?o=>oe.pushInternal(e,r,o):i==="splice"?(o,a,...l)=>oe.splice(e,r,o,a,...l):i==="length"?r.length:typeof i=="symbol"&&i===Symbol.iterator?oe.iteratorInternal.bind(this,e,r):i==="includes"?(o,a)=>oe.includes(e,r,o,a):i==="indexOf"?(o,a)=>oe.indexOf(e,r,o,a):i==="lastIndexOf"?(o,a)=>oe.lastIndexOf(e,r,o,a):i==="toJSForTest"?()=>r.toJSForTest():i==="toTestString"?()=>oe.toTestString(r):typeof i=="string"&&VS(i)?(...o)=>{const a=Array.from(r).map(l=>li(e,l));return Array.prototype[i].apply(a,o)}:Reflect.get(r,i,s),deleteProperty:(r,i)=>(J.isEnabled(be.Trivial)&&J.trivial(`array[${i}]`),oe.deleteInternalByIndex(e,r,Number.parseInt(i)),!0)}}static*iteratorInternal(e,t){for(const r of t)yield Nr(e,r)}static buildArrayElements(e,t){const r=[];for(const i of t){const s=e.issueTimeTicket(),o=yl(e,i,s);r.push(o)}return r}static pushInternal(e,t,r){return oe.insertAfterInternal(e,t,t.getLastCreatedAt(),r),t.length}static moveBeforeInternal(e,t,r,i){const s=e.issueTimeTicket(),o=t.getPrevCreatedAt(r);t.moveAfter(o,i,s),e.push(Fr.create(t.getCreatedAt(),o,i,s))}static moveAfterInternal(e,t,r,i){const s=e.issueTimeTicket();t.moveAfter(r,i,s),e.push(Fr.create(t.getCreatedAt(),r,i,s))}static moveFrontInternal(e,t,r){const i=e.issueTimeTicket(),s=t.getHead();t.moveAfter(s.getCreatedAt(),r,i),e.push(Fr.create(t.getCreatedAt(),s.getCreatedAt(),r,i))}static moveLastInternal(e,t,r){const i=e.issueTimeTicket(),s=t.getLastCreatedAt();t.moveAfter(s,r,i),e.push(Fr.create(t.getCreatedAt(),s,r,i))}static insertAfterInternal(e,t,r,i){const s=e.issueTimeTicket(),o=yl(e,i,s);return t.insertAfter(r,o),e.registerElement(o,t),e.push(Do.create(t.getCreatedAt(),r,o.deepcopy(),s)),o}static insertBeforeInternal(e,t,r,i){return oe.insertAfterInternal(e,t,t.getPrevCreatedAt(r),i)}static deleteInternalByIndex(e,t,r){const i=e.issueTimeTicket(),s=t.deleteByIndex(r,i);if(s)return e.push(Xr.create(t.getCreatedAt(),s.getCreatedAt(),i)),e.registerRemovedElement(s),s}static deleteInternalByID(e,t,r){const i=e.issueTimeTicket(),s=t.delete(r,i);return e.push(Xr.create(t.getCreatedAt(),s.getCreatedAt(),i)),e.registerRemovedElement(s),s}static splice(e,t,r,i,...s){const o=t.length,a=r>=0?Math.min(r,o):Math.max(o+r,0),l=i===void 0?o:i<0?a:Math.min(a+i,o),c=[];for(let d=a;d=s)return!1;if(re.isSupport(r))return Array.from(t).map(c=>li(e,c)).includes(r,o);for(let l=o;l=s)return-1;if(re.isSupport(r))return Array.from(t).map(c=>li(e,c)).indexOf(r,o);for(let l=o;l=s?s-1:i<0?i+s:i;if(o<0)return-1;if(re.isSupport(r))return Array.from(t).map(c=>li(e,c)).lastIndexOf(r,o);for(let l=o;l>0;l--)if(((a=t.get(l))==null?void 0:a.getID())===r.getID())return l;return-1}static toTestString(e){return e.toTestString()}getHandlers(){return this.handlers}}class $l{constructor(e,t){u(this,"context");u(this,"text");this.context=e,this.text=t}initialize(e,t){this.context=e,this.text=t}getID(){return this.text.getID()}edit(e,t,r,i){if(!this.context||!this.text)throw new k(S.ErrNotInitialized,"Text is not initialized yet");if(e>t)throw new k(S.ErrInvalidArgument,"from should be less than or equal to to");const s=this.text.indexRangeToPosRange(e,t);J.isEnabled(be.Debug)&&J.debug(`EDIT: f:${e}->${s[0].toTestString()}, t:${t}->${s[1].toTestString()} c:${r}`);const o=i?ds(i):void 0,a=this.context.issueTimeTicket(),[l,,c,d]=this.text.edit(s,r,a,o);for(const h of c)this.context.registerGCPair(h);return this.context.push(new Oo(this.text.getCreatedAt(),s[0],s[1],l,r,o?new Map(Object.entries(o)):new Map,a)),this.text.findIndexesFromRange(d)}delete(e,t){return this.edit(e,t,"")}empty(){return this.edit(0,this.length,"")}setStyle(e,t,r){if(!this.context||!this.text)throw new k(S.ErrNotInitialized,"Text is not initialized yet");if(e>t)throw new k(S.ErrInvalidArgument,"from should be less than or equal to to");const i=this.text.indexRangeToPosRange(e,t);J.isEnabled(be.Debug)&&J.debug(`STYL: f:${e}->${i[0].toTestString()}, t:${t}->${i[1].toTestString()} a:${JSON.stringify(r)}`);const s=ds(r),o=this.context.issueTimeTicket(),[a,l]=this.text.setStyle(i,s,o);for(const c of l)this.context.registerGCPair(c);return this.context.push(new Ro(this.text.getCreatedAt(),i[0],i[1],a,new Map(Object.entries(s)),o)),!0}indexRangeToPosRange(e){if(!this.context||!this.text)throw new k(S.ErrNotInitialized,"Text is not initialized yet");const t=this.text.indexRangeToPosRange(e[0],e[1]);return[t[0].toStruct(),t[1].toStruct()]}posRangeToIndexRange(e){if(!this.context||!this.text)throw new k(S.ErrNotInitialized,"Text is not initialized yet");const t=this.text.findIndexesFromRange([Mt.fromStruct(e[0]),Mt.fromStruct(e[1])]);return[t[0],t[1]]}toTestString(){if(!this.context||!this.text)throw new k(S.ErrNotInitialized,"Text is not initialized yet");return this.text.toTestString()}values(){if(!this.context||!this.text)throw new k(S.ErrNotInitialized,"Text is not initialized yet");return this.text.values()}get length(){return this.text.length}getTreeByIndex(){return this.text.getTreeByIndex()}getTreeByID(){return this.text.getTreeByID()}toString(){if(!this.context||!this.text)throw new k(S.ErrNotInitialized,"Text is not initialized yet");return this.text.toString()}toJSON(){if(!this.context||!this.text)throw new k(S.ErrNotInitialized,"Text is not initialized yet");return this.text.toJSON()}toJSForTest(){if(!this.context||!this.text)throw new k(S.ErrNotInitialized,"Text is not initialized yet");return this.text.toJSForTest()}createRangeForTest(e,t){if(!this.context||!this.text)throw new k(S.ErrNotInitialized,"Text is not initialized yet");return this.text.indexRangeToPosRange(e,t)}}class zl{constructor(e,t){u(this,"valueType");u(this,"value");u(this,"context");u(this,"counter");this.valueType=e,this.value=t}initialize(e,t){this.valueType=t.getValueType(),this.context=e,this.counter=t,this.value=t.getValue()}getID(){return this.counter.getID()}getValue(){return this.value}getValueType(){return this.valueType}increase(e){if(!this.context||!this.counter)throw new k(S.ErrNotInitialized,"Counter is not initialized yet");const t=this.context.issueTimeTicket(),r=re.of(e,t);if(!r.isNumericType())throw new TypeError(`Unsupported type of value: ${typeof r.getValue()}`);return this.counter.increase(r),this.context.push(ps.create(this.counter.getCreatedAt(),r,t)),this}toJSForTest(){if(!this.context||!this.counter)throw new k(S.ErrNotInitialized,"Counter is not initialized yet");return this.counter.toJSForTest()}}function cd(n,e,t){const{type:r}=n,i=t.issueTimeTicket();if(r===pr){Oy(n);const{value:s}=n,o=Ze.create(Ee.of(i,0),r,s);e.append(o)}else{const{children:s=[]}=n,{attributes:o}=n;let a;if(typeof o=="object"&&!ey(o)){const c=ds(o);a=new Ar;for(const[d,h]of Object.entries(c))a.set(d,h,i)}const l=Ze.create(Ee.of(i,0),r,void 0,a);e.append(l);for(const c of s)cd(c,l,t)}}function jS(n,e){const{type:t}=e,r=n.issueTimeTicket();let i;if(e.type===pr){const{value:s}=e;i=Ze.create(Ee.of(r,0),t,s)}else if(e){const{children:s=[]}=e,{attributes:o}=e;let a;if(typeof o=="object"&&!ey(o)){const l=ds(o);a=new Ar;for(const[c,d]of Object.entries(l))a.set(c,d,r)}i=Ze.create(Ee.of(n.issueTimeTicket(),0),t,void 0,a);for(const l of s)cd(l,i,n)}return i}function Oy(n){if(!n.value.length)throw new k(S.ErrInvalidArgument,"text node cannot have empty value");return!0}function og(n){if(!n.length)return!0;if(n[0].type===pr)for(const t of n){const{type:r}=t;if(r!==pr)throw new k(S.ErrInvalidArgument,"element node and text node cannot be passed together");Oy(t)}else for(const t of n){const{type:r}=t;if(r===pr)throw new k(S.ErrInvalidArgument,"element node and text node cannot be passed together")}return!0}class Ul{constructor(e){u(this,"initialRoot");u(this,"context");u(this,"tree");this.initialRoot=e}initialize(e,t){this.context=e,this.tree=t}getID(){return this.tree.getID()}buildRoot(e){if(!this.initialRoot)return Ze.create(Ee.of(e.issueTimeTicket(),0),U1);const t=Ze.create(Ee.of(e.issueTimeTicket(),0),this.initialRoot.type);for(const r of this.initialRoot.children)cd(r,t,e);return t}getSize(){if(!this.context||!this.tree)throw new k(S.ErrNotInitialized,"Tree is not initialized yet");return this.tree.getSize()}getNodeSize(){if(!this.context||!this.tree)throw new k(S.ErrNotInitialized,"Tree is not initialized yet");return this.tree.getNodeSize()}getIndexTree(){if(!this.context||!this.tree)throw new k(S.ErrNotInitialized,"Tree is not initialized yet");return this.tree.getIndexTree()}styleByPath(e,t){if(!this.context||!this.tree)throw new k(S.ErrNotInitialized,"Tree is not initialized yet");if(!e.length)throw new k(S.ErrInvalidArgument,"path should not be empty");const[r,i]=this.tree.pathToPosRange(e),s=this.context.issueTimeTicket(),o=t?ds(t):void 0,[a]=this.tree.style([r,i],o,s);this.context.push(yr.create(this.tree.getCreatedAt(),r,i,a,o?new Map(Object.entries(o)):new Map,s))}style(e,t,r){if(!this.context||!this.tree)throw new k(S.ErrNotInitialized,"Tree is not initialized yet");if(e>t)throw new k(S.ErrInvalidArgument,"from should be less than or equal to to");const i=this.tree.findPos(e),s=this.tree.findPos(t),o=this.context.issueTimeTicket(),a=r?ds(r):void 0,[l,c]=this.tree.style([i,s],a,o);for(const d of c)this.context.registerGCPair(d);this.context.push(yr.create(this.tree.getCreatedAt(),i,s,l,a?new Map(Object.entries(a)):new Map,o))}removeStyle(e,t,r){if(!this.context||!this.tree)throw new k(S.ErrNotInitialized,"Tree is not initialized yet");if(e>t)throw new k(S.ErrInvalidArgument,"from should be less than or equal to to");const i=this.tree.findPos(e),s=this.tree.findPos(t),o=this.context.issueTimeTicket(),[a,l]=this.tree.removeStyle([i,s],r,o);for(const c of l)this.context.registerGCPair(c);this.context.push(yr.createTreeRemoveStyleOperation(this.tree.getCreatedAt(),i,s,a,r,o))}editInternal(e,t,r,i=0){var c;if(r.length!==0&&r[0]&&(og(r),r[0].type!==pr))for(const d of r){const{children:h=[]}=d;og(h)}const s=this.context.getLastTimeTicket();let o=new Array;if(((c=r[0])==null?void 0:c.type)===pr){let d="";for(const h of r){const{value:p}=h;d+=p}o.push(Ze.create(Ee.of(this.context.issueTimeTicket(),0),pr,d))}else o=r.map(d=>d&&jS(this.context,d)).filter(d=>d);const[,a,l]=this.tree.edit([e,t],o.length?o.map(d=>d==null?void 0:d.deepcopy()):void 0,i,s,()=>this.context.issueTimeTicket());for(const d of a)this.context.registerGCPair(d);return this.context.push(Lo.create(this.tree.getCreatedAt(),e,t,o.length?o:void 0,i,l,s)),!0}editByPath(e,t,r,i=0){if(!this.context||!this.tree)throw new k(S.ErrNotInitialized,"Tree is not initialized yet");if(e.length!==t.length)throw new k(S.ErrInvalidArgument,"path length should be equal");if(!e.length||!t.length)throw new k(S.ErrInvalidArgument,"path should not be empty");const s=this.tree.pathToPos(e),o=this.tree.pathToPos(t);return this.editInternal(s,o,r?[r]:[],i)}editBulkByPath(e,t,r,i=0){if(!this.context||!this.tree)throw new k(S.ErrNotInitialized,"Tree is not initialized yet");if(e.length!==t.length)throw new k(S.ErrInvalidArgument,"path length should be equal");if(!e.length||!t.length)throw new k(S.ErrInvalidArgument,"path should not be empty");const s=this.tree.pathToPos(e),o=this.tree.pathToPos(t);return this.editInternal(s,o,r,i)}edit(e,t,r,i=0){if(!this.context||!this.tree)throw new k(S.ErrNotInitialized,"Tree is not initialized yet");if(e>t)throw new k(S.ErrInvalidArgument,"from should be less than or equal to to");const s=this.tree.findPos(e),o=this.tree.findPos(t);return this.editInternal(s,o,r?[r]:[],i)}editBulk(e,t,r,i=0){if(!this.context||!this.tree)throw new k(S.ErrNotInitialized,"Tree is not initialized yet");if(e>t)throw new k(S.ErrInvalidArgument,"from should be less than or equal to to");const s=this.tree.findPos(e),o=this.tree.findPos(t);return this.editInternal(s,o,r,i)}toXML(){if(!this.context||!this.tree)throw new k(S.ErrNotInitialized,"Tree is not initialized yet");return this.tree.toXML()}toJSON(){if(!this.context||!this.tree)throw new k(S.ErrNotInitialized,"Tree is not initialized yet");return this.tree.toJSON()}toJSForTest(){if(!this.context||!this.tree)throw new k(S.ErrNotInitialized,"Tree is not initialized yet");return this.tree.toJSForTest()}toJSInfoForTest(){if(!this.context||!this.tree)throw new k(S.ErrNotInitialized,"Tree is not initialized yet");return this.tree.toJSInfoForTest()}getRootTreeNode(){if(!this.context||!this.tree)throw new k(S.ErrNotInitialized,"Tree is not initialized yet");return this.tree.getRootTreeNode()}indexToPath(e){if(!this.context||!this.tree)throw new k(S.ErrNotInitialized,"Tree is not initialized yet");return this.tree.indexToPath(e)}pathToIndex(e){if(!this.context||!this.tree)throw new k(S.ErrNotInitialized,"Tree is not initialized yet");return this.tree.pathToIndex(e)}pathRangeToPosRange(e){if(!this.context||!this.tree)throw new k(S.ErrNotInitialized,"Tree is not initialized yet");const t=[this.tree.pathToIndex(e[0]),this.tree.pathToIndex(e[1])],r=this.tree.indexRangeToPosRange(t);return[r[0].toStruct(),r[1].toStruct()]}indexRangeToPosRange(e){if(!this.context||!this.tree)throw new k(S.ErrNotInitialized,"Tree is not initialized yet");return this.tree.indexRangeToPosStructRange(e)}posRangeToIndexRange(e){if(!this.context||!this.tree)throw new k(S.ErrNotInitialized,"Tree is not initialized yet");const t=[Lt.fromStruct(e[0]),Lt.fromStruct(e[1])];return this.tree.posRangeToIndexRange(t)}posRangeToPathRange(e){if(!this.context||!this.tree)throw new k(S.ErrNotInitialized,"Tree is not initialized yet");const t=[Lt.fromStruct(e[0]),Lt.fromStruct(e[1])];return this.tree.posRangeToPathRange(t)}}function ag(n,e){return Dy(n,e)}function Nr(n,e){if(e){if(e instanceof re)return e;if(e instanceof He)return Dy(n,e);if(e instanceof nt)return zS(n,e);if(e instanceof Et)return new $l(n,e);if(e instanceof rt){const t=new zl(on.IntegerCnt,0);return t.initialize(n,e),t}else if(e instanceof xt){const t=new Ul;return t.initialize(n,e),t}}else return;throw new TypeError(`Unsupported type of element: ${typeof e}`)}function li(n,e){const t=Nr(n,e);return t instanceof re?t.getValue():t}function yl(n,e,t){let r;if(re.isSupport(e))r=re.of(e,t);else if(Array.isArray(e))r=nt.create(t,oe.buildArrayElements(n,e));else if(typeof e=="object")e instanceof $l?(r=Et.create(ms.create(),t),e.initialize(n,r)):e instanceof zl?(r=rt.create(e.getValueType(),e.getValue(),t),e.initialize(n,r)):e instanceof Ul?(r=xt.create(e.buildRoot(n),t),e.initialize(n,r)):r=He.create(t,Ao.buildObjectMembers(n,e));else throw new TypeError(`Unsupported type of value: ${typeof e}`);return r}const lg=50;class qS{constructor(){u(this,"undoStack",[]);u(this,"redoStack",[])}hasUndo(){return this.undoStack.length>0}hasRedo(){return this.redoStack.length>0}pushUndo(e){this.undoStack.length>=lg&&this.undoStack.shift(),this.undoStack.push(e)}popUndo(){return this.undoStack.pop()}pushRedo(e){this.redoStack.length>=lg&&this.redoStack.shift(),this.redoStack.push(e)}popRedo(){return this.redoStack.pop()}clearRedo(){this.redoStack=[]}getUndoStackForTest(){return this.undoStack}getRedoStackForTest(){return this.redoStack}}const KS="yorkie-devtools-panel",WS="yorkie-devtools-sdk";let Ri="disconnected";const ug=new Map,Ta=new Map;typeof window<"u"&&(window.transactionEventsByDocKey=Ta);function ra(n,e){(e!=null&&e.force||Ri!=="disconnected")&&window.postMessage({source:WS,...n},"*")}function HS(n){if(!n.isEnableDevtools()||typeof window>"u"||ug.has(n.getKey()))return;Ta.set(n.getKey(),[]);const e=n.subscribe("all",t=>{t.some(r=>r.type!==$e.StatusChanged&&r.type!==$e.Snapshot&&r.type!==$e.LocalChange&&r.type!==$e.RemoteChange&&r.type!==$e.Initialized&&r.type!==$e.Watched&&r.type!==$e.Unwatched&&r.type!==$e.PresenceChanged)||(Ta.get(n.getKey()).push(t),Ri==="synced"&&ra({msg:"doc::sync::partial",docKey:n.getKey(),event:t}))});ug.set(n.getKey(),[e]),ra({msg:"refresh-devtools"},{force:!0}),window.addEventListener("message",t=>{var i;if(((i=t.data)==null?void 0:i.source)!==KS)return;switch(t.data.msg){case"devtools::connect":if(Ri!=="disconnected")break;Ri="connected",ra({msg:"doc::available",docKey:n.getKey()}),J.info(`[YD] Devtools connected. Doc: ${n.getKey()}`);break;case"devtools::disconnect":Ri="disconnected",J.info(`[YD] Devtools disconnected. Doc: ${n.getKey()}`);break;case"devtools::subscribe":Ri="synced",ra({msg:"doc::sync::full",docKey:n.getKey(),events:Ta.get(n.getKey())}),J.info(`[YD] Devtools subscribed. Doc: ${n.getKey()}`);break}})}var Pr=(n=>(n.Detached="detached",n.Attached="attached",n.Removed="removed",n))(Pr||{}),$e=(n=>(n.StatusChanged="status-changed",n.ConnectionChanged="connection-changed",n.SyncStatusChanged="sync-status-changed",n.Snapshot="snapshot",n.LocalChange="local-change",n.RemoteChange="remote-change",n.Initialized="initialized",n.Watched="watched",n.Unwatched="unwatched",n.PresenceChanged="presence-changed",n.Broadcast="broadcast",n.LocalBroadcast="local-broadcast",n))($e||{}),_c=(n=>(n.Connected="connected",n.Disconnected="disconnected",n))(_c||{}),Gc=(n=>(n.Synced="synced",n.SyncFailed="sync-failed",n))(Gc||{});class Ry{constructor(e,t){u(this,"key");u(this,"status");u(this,"opts");u(this,"changeID");u(this,"checkpoint");u(this,"localChanges");u(this,"root");u(this,"clone");u(this,"eventStream");u(this,"eventStreamObserver");u(this,"onlineClients");u(this,"presences");u(this,"history");u(this,"internalHistory");u(this,"isUpdating");this.opts=t||{},this.key=e,this.status="detached",this.root=To.create(),this.changeID=Y1,this.checkpoint=Q1,this.localChanges=[],this.eventStream=$S(r=>{this.eventStreamObserver=r}),this.onlineClients=new Set,this.presences=new Map,this.isUpdating=!1,this.internalHistory=new qS,this.history={canUndo:this.canUndo.bind(this),canRedo:this.canRedo.bind(this),undo:this.undo.bind(this),redo:this.redo.bind(this)},HS(this)}update(e,t){if(this.getStatus()==="removed")throw new k(S.ErrDocumentRemoved,`${this.key} is removed`);this.ensureClone();const r=this.changeID.getActorID(),i=Wi.create(this.changeID.next(),this.clone.root,this.clone.presences.get(r)||{},t);try{const s=ag(i,this.clone.root.getObject());this.presences.has(r)||this.clone.presences.set(r,{}),this.isUpdating=!0,e(s,new ku(i,this.clone.presences.get(r)))}catch(s){throw this.clone=void 0,s}finally{this.isUpdating=!1}if(i.hasChange()){J.isEnabled(be.Trivial)&&J.trivial(`trying to update a local change: ${this.toJSON()}`);const s=i.getChange(),{opInfos:o,reverseOps:a}=s.execute(this.root,this.presences,Y.Local),l=i.getReversePresence();l&&a.push({type:"presence",value:l}),this.localChanges.push(s),a.length>0&&this.internalHistory.pushUndo(a),o.length>0&&this.internalHistory.clearRedo(),this.changeID=s.getID();const c=[];o.length>0&&c.push({type:"local-change",source:Y.Local,value:{message:s.getMessage()||"",operations:o,actor:r,clientSeq:s.getID().getClientSeq(),serverSeq:s.getID().getServerSeq()},rawChange:this.isEnableDevtools()?s.toStruct():void 0}),s.hasPresenceChange()&&c.push({type:"presence-changed",source:Y.Local,value:{clientID:r,presence:this.getPresence(r)}}),this.publish(c),J.isEnabled(be.Trivial)&&J.trivial(`after update a local change: ${this.toJSON()}`)}}subscribe(e,t,r,i){if(typeof e=="string"){if(typeof t!="function")throw new k(S.ErrInvalidArgument,"Second argument must be a callback function");if(e==="presence"){const a=t;return this.eventStream.subscribe(l=>{for(const c of l)c.type!=="initialized"&&c.type!=="watched"&&c.type!=="unwatched"&&c.type!=="presence-changed"||a(c)},r,i)}if(e==="my-presence"){const a=t;return this.eventStream.subscribe(l=>{for(const c of l)c.type!=="initialized"&&c.type!=="presence-changed"||c.type==="presence-changed"&&c.value.clientID!==this.changeID.getActorID()||a(c)},r,i)}if(e==="others"){const a=t;return this.eventStream.subscribe(l=>{for(const c of l)c.type!=="watched"&&c.type!=="unwatched"&&c.type!=="presence-changed"||c.value.clientID!==this.changeID.getActorID()&&a(c)},r,i)}if(e==="connection"){const a=t;return this.eventStream.subscribe(l=>{for(const c of l)c.type==="connection-changed"&&a(c)},r,i)}if(e==="status"){const a=t;return this.eventStream.subscribe(l=>{for(const c of l)c.type==="status-changed"&&a(c)},r,i)}if(e==="sync"){const a=t;return this.eventStream.subscribe(l=>{for(const c of l)c.type==="sync-status-changed"&&a(c)},r,i)}if(e==="local-broadcast"){const a=t;return this.eventStream.subscribe(l=>{for(const c of l)c.type==="local-broadcast"&&a(c)},r)}if(e==="broadcast"){const a=t;return this.eventStream.subscribe(l=>{for(const c of l)c.type==="broadcast"&&a(c)},r)}if(e==="all"){const a=t;return this.eventStream.subscribe(a,r,i)}const s=e,o=t;return this.eventStream.subscribe(a=>{for(const l of a){if(l.type!=="local-change"&&l.type!=="remote-change")continue;const c=[];for(const d of l.value.operations)this.isSameElementOrChildOf(d.path,s)&&c.push(d);c.length&&o({...l,value:{...l.value,operations:c}})}},r,i)}if(typeof e=="function"){const s=e,o=t,a=r;return this.eventStream.subscribe(l=>{for(const c of l)c.type!=="snapshot"&&c.type!=="local-change"&&c.type!=="remote-change"||s(c)},o,a)}throw new k(S.ErrInvalidArgument,`"${e}" is not a valid`)}publish(e){this.eventStreamObserver&&this.eventStreamObserver.next(e)}isSameElementOrChildOf(e,t){if(t===e)return!0;const r=e.split(".");return t.split(".").every((s,o)=>s===r[o])}removePushedLocalChanges(e){for(;this.localChanges.length&&!(this.localChanges[0].getID().getClientSeq()>e);)this.localChanges.shift()}applyChangePack(e){const t=e.hasSnapshot();t?this.applySnapshot(e.getCheckpoint().getServerSeq(),e.getVersionVector(),e.getSnapshot(),e.getCheckpoint().getClientSeq()):(this.applyChanges(e.getChanges(),Y.Remote),this.removePushedLocalChanges(e.getCheckpoint().getClientSeq())),this.checkpoint=this.checkpoint.forward(e.getCheckpoint()),t||this.garbageCollect(e.getVersionVector()),t||this.filterVersionVector(e.getVersionVector()),e.getIsRemoved()&&this.applyStatus("removed"),J.isEnabled(be.Trivial)&&J.trivial(`${this.root.toJSON()}`)}getCheckpoint(){return this.checkpoint}getChangeID(){return this.changeID}hasLocalChanges(){return this.localChanges.length>0}ensureClone(){this.clone||(this.clone={root:this.root.deepcopy(),presences:Pt(this.presences)})}createChangePack(){const e=Array.from(this.localChanges),t=this.checkpoint.increaseClientSeq(e.length);return Jl.create(this.key,t,!1,e,this.getVersionVector())}setActor(e){for(const t of this.localChanges)t.setActor(e);this.changeID=this.changeID.setActor(e)}isEnableDevtools(){return!!this.opts.enableDevtools}getKey(){return this.key}getStatus(){return this.status}getCloneRoot(){if(this.clone)return this.clone.root.getObject()}getRoot(){this.ensureClone();const e=Wi.create(this.changeID.next(),this.clone.root,this.clone.presences.get(this.changeID.getActorID())||{});return ag(e,this.clone.root.getObject())}garbageCollect(e){return this.opts.disableGC?0:(this.clone&&this.clone.root.garbageCollect(e),this.root.garbageCollect(e))}getRootObject(){return this.root.getObject()}getGarbageLen(){return this.root.getGarbageLen()}getGarbageLenFromClone(){return this.clone.root.getGarbageLen()}toJSON(){return this.root.toJSON()}toSortedJSON(){return this.root.toSortedJSON()}getStats(){return this.root.getStats()}toJSForTest(){return{...this.getRoot().toJSForTest(),key:"root"}}applySnapshot(e,t,r,i=-1){const{root:s,presences:o}=fe.bytesToSnapshot(r);this.root=new To(s),this.presences=o,this.changeID=this.changeID.setClocks(e,t),this.clone=void 0,this.removePushedLocalChanges(i),this.applyChanges(this.localChanges,Y.Local),this.publish([{type:"snapshot",source:Y.Remote,value:{serverSeq:e.toString(),snapshot:this.isEnableDevtools()?fe.bytesToHex(r):void 0,snapshotVector:fe.versionVectorToHex(t)}}])}applyChanges(e,t){J.isEnabled(be.Debug)&&J.debug(`trying to apply ${e.length} remote changes.elements:${this.root.getElementMapSize()}, removeds:${this.root.getGarbageElementSetSize()}`),J.isEnabled(be.Trivial)&&J.trivial(e.map(r=>`${r.getID().toTestString()} ${r.toTestString()}`).join(` `));for(const r of e)this.applyChange(r,t);J.isEnabled(be.Debug)&&J.debug(`after appling ${e.length} remote changes.elements:${this.root.getElementMapSize()}, removeds:${this.root.getGarbageElementSetSize()}`)}applyChange(e,t){this.ensureClone(),e.execute(this.clone.root,this.clone.presences,t);const r=[],i=e.getID().getActorID();if(e.hasPresenceChange()&&this.onlineClients.has(i)){const o=e.getPresenceChange();switch(o.type){case Qr.Put:r.push(this.presences.has(i)?{type:"presence-changed",source:t,value:{clientID:i,presence:o.presence}}:{type:"watched",source:Y.Remote,value:{clientID:i,presence:o.presence}});break;case Qr.Clear:r.push({type:"unwatched",source:Y.Remote,value:{clientID:i,presence:this.getPresence(i)}}),this.removeOnlineClient(i);break}}const{opInfos:s}=e.execute(this.root,this.presences,t);if(this.changeID=this.changeID.syncClocks(e.getID()),s.length>0){const o=this.isEnableDevtools()?e.toStruct():void 0;r.push(t===Y.Remote?{type:"remote-change",source:t,value:{actor:i,clientSeq:e.getID().getClientSeq(),serverSeq:e.getID().getServerSeq(),message:e.getMessage()||"",operations:s},rawChange:o}:{type:"local-change",source:t,value:{actor:i,clientSeq:e.getID().getClientSeq(),serverSeq:e.getID().getServerSeq(),message:e.getMessage()||"",operations:s},rawChange:o})}r.length>0&&this.publish(r)}applyWatchStream(e){if(e.body.case==="initialization"){const t=e.body.value.clientIds,r=new Set;for(const i of t)i!==this.changeID.getActorID()&&r.add(i);this.setOnlineClients(r),this.publish([{type:"initialized",source:Y.Local,value:this.getPresences()}]);return}if(e.body.case==="event"){const{type:t,publisher:r}=e.body.value,i=[];if(t===yi.DOCUMENT_WATCHED){if(this.onlineClients.has(r)&&this.hasPresence(r))return;this.addOnlineClient(r),this.hasPresence(r)&&i.push({type:"watched",source:Y.Remote,value:{clientID:r,presence:this.getPresence(r)}})}else if(t===yi.DOCUMENT_UNWATCHED){const s=this.getPresence(r);this.removeOnlineClient(r),s&&i.push({type:"unwatched",source:Y.Remote,value:{clientID:r,presence:s}})}else if(t===yi.DOCUMENT_BROADCAST&&e.body.value.body){const{topic:s,payload:o}=e.body.value.body,a=new TextDecoder;i.push({type:"broadcast",value:{clientID:r,topic:s,payload:JSON.parse(a.decode(o))}})}i.length>0&&this.publish(i)}}applyStatus(e){this.status=e,e==="detached"&&this.setActor(Gf),this.publish([{source:e==="removed"?Y.Remote:Y.Local,type:"status-changed",value:e==="attached"?{status:e,actorID:this.changeID.getActorID()}:{status:e}}])}applyDocEvent(e){if(e.type==="status-changed"){this.applyStatus(e.value.status),e.value.status==="attached"&&this.setActor(e.value.actorID);return}if(e.type==="snapshot"){const{snapshot:t,serverSeq:r,snapshotVector:i}=e.value;if(!t)return;this.applySnapshot(BigInt(r),fe.hexToVersionVector(i),fe.hexToBytes(t));return}if(e.type==="local-change"||e.type==="remote-change"){if(!e.rawChange)return;const t=gs.fromStruct(e.rawChange);this.applyChange(t,e.source)}if(e.type==="initialized"){const t=new Set;for(const{clientID:r,presence:i}of e.value)t.add(r),this.presences.set(r,i);this.setOnlineClients(t);return}if(e.type==="watched"){const{clientID:t,presence:r}=e.value;this.addOnlineClient(t),this.presences.set(t,r);return}if(e.type==="unwatched"){const{clientID:t}=e.value;this.removeOnlineClient(t),this.presences.delete(t)}if(e.type==="presence-changed"){const{clientID:t,presence:r}=e.value;this.presences.set(t,r)}}applyTransactionEvent(e){for(const t of e)this.applyDocEvent(t)}getValueByPath(e){if(!e.startsWith("$"))throw new k(S.ErrInvalidArgument,'path must start with "$"');const t=e.split(".");t.shift();let r=this.getRoot();for(const i of t)if(r=r[i],r===void 0)return;return r}setOnlineClients(e){this.onlineClients=e}resetOnlineClients(){this.onlineClients=new Set}addOnlineClient(e){this.onlineClients.add(e)}removeOnlineClient(e){this.onlineClients.delete(e)}hasPresence(e){return this.presences.has(e)}getMyPresence(){if(this.status!=="attached")return{};const e=this.presences.get(this.changeID.getActorID());return e?Pt(e):{}}getPresence(e){if(e===this.changeID.getActorID())return this.getMyPresence();if(!this.onlineClients.has(e))return;const t=this.presences.get(e);return t?Pt(t):void 0}getPresenceForTest(e){const t=this.presences.get(e);return t?Pt(t):void 0}getPresences(){const e=[];e.push({clientID:this.changeID.getActorID(),presence:Pt(this.getMyPresence())});for(const t of this.onlineClients)this.presences.has(t)&&e.push({clientID:t,presence:Pt(this.presences.get(t))});return e}getSelfForTest(){return{clientID:this.getChangeID().getActorID(),presence:this.getMyPresence()}}getOthersForTest(){const e=this.getChangeID().getActorID();return this.getPresences().filter(t=>t.clientID!==e).sort((t,r)=>t.clientID>r.clientID?1:-1)}canUndo(){return this.internalHistory.hasUndo()&&!this.isUpdating}filterVersionVector(e){const r=this.changeID.getVersionVector().filter(e);this.changeID=this.changeID.setVersionVector(r)}canRedo(){return this.internalHistory.hasRedo()&&!this.isUpdating}undo(){if(this.isUpdating)throw new k(S.ErrRefused,"Undo is not allowed during an update");const e=this.internalHistory.popUndo();if(e===void 0)throw new k(S.ErrRefused,"There is no operation to be undone");this.ensureClone();const t=Wi.create(this.changeID.next(),this.clone.root,this.clone.presences.get(this.changeID.getActorID())||{});for(const c of e){if(!(c instanceof $t)){new ku(t,Pt(this.clone.presences.get(this.changeID.getActorID()))).set(c.value,{addToHistory:!0});continue}const d=t.issueTimeTicket();c.setExecutedAt(d),t.push(c)}const r=t.getChange();r.execute(this.clone.root,this.clone.presences,Y.UndoRedo);const{opInfos:i,reverseOps:s}=r.execute(this.root,this.presences,Y.UndoRedo),o=t.getReversePresence();if(o&&s.push({type:"presence",value:o}),s.length>0&&this.internalHistory.pushRedo(s),!r.hasPresenceChange()&&i.length===0)return;this.localChanges.push(r),this.changeID=r.getID();const a=this.changeID.getActorID(),l=[];i.length>0&&l.push({type:"local-change",source:Y.UndoRedo,value:{message:r.getMessage()||"",operations:i,actor:a,clientSeq:r.getID().getClientSeq(),serverSeq:r.getID().getServerSeq()},rawChange:this.isEnableDevtools()?r.toStruct():void 0}),r.hasPresenceChange()&&l.push({type:"presence-changed",source:Y.UndoRedo,value:{clientID:a,presence:this.getPresence(a)}}),this.publish(l)}redo(){if(this.isUpdating)throw new k(S.ErrRefused,"Redo is not allowed during an update");const e=this.internalHistory.popRedo();if(e===void 0)throw new k(S.ErrRefused,"There is no operation to be redone");this.ensureClone();const t=Wi.create(this.changeID.next(),this.clone.root,this.clone.presences.get(this.changeID.getActorID())||{});for(const c of e){if(!(c instanceof $t)){new ku(t,Pt(this.clone.presences.get(this.changeID.getActorID()))).set(c.value,{addToHistory:!0});continue}const d=t.issueTimeTicket();c.setExecutedAt(d),t.push(c)}const r=t.getChange();r.execute(this.clone.root,this.clone.presences,Y.UndoRedo);const{opInfos:i,reverseOps:s}=r.execute(this.root,this.presences,Y.UndoRedo),o=t.getReversePresence();if(o&&s.push({type:"presence",value:o}),s.length>0&&this.internalHistory.pushUndo(s),!r.hasPresenceChange()&&i.length===0)return;this.localChanges.push(r),this.changeID=r.getID();const a=this.changeID.getActorID(),l=[];i.length>0&&l.push({type:"local-change",source:Y.UndoRedo,value:{message:r.getMessage()||"",operations:i,actor:a,clientSeq:r.getID().getClientSeq(),serverSeq:r.getID().getServerSeq()},rawChange:this.isEnableDevtools()?r.toStruct():void 0}),r.hasPresenceChange()&&l.push({type:"presence-changed",source:Y.UndoRedo,value:{clientID:a,presence:this.getPresence(a)}}),this.publish(l)}getUndoStackForTest(){return this.internalHistory.getUndoStackForTest()}getRedoStackForTest(){return this.internalHistory.getRedoStackForTest()}broadcast(e,t,r){const i={type:"local-broadcast",value:{topic:e,payload:t},options:r};this.publish([i])}getVersionVector(){return this.changeID.getVersionVector()}}function _S(n,e){return t=>async r=>(n&&r.header.set("x-api-key",n),e&&r.header.set("authorization",e),await t(r))}const GS="yorkie-js-sdk",YS="0.5.4",QS="Yorkie JS SDK",XS="./src/yorkie.ts",ZS={access:"public",main:"./dist/yorkie-js-sdk.js",typings:"./dist/yorkie-js-sdk.d.ts"},ek=["dist"],tk={build:"tsc && vite build","build:proto":"npx buf generate","build:docs":"typedoc","build:ghpages":"mkdir -p ghpages/examples && cp -r docs ghpages/api-reference && find ../../examples -name 'dist' -type d -exec sh -c 'cp -r {} ghpages/examples/$(basename $(dirname {}))' \\;",dev:"vite build -c vite.preview.ts && vite preview",test:"vitest run","test:watch":"vitest","test:bench":"vitest bench","test:ci":"vitest run --coverage","test:yorkie.dev":"TEST_RPC_ADDR=https://api.yorkie.dev vitest run --coverage",prepare:"pnpm build"},nk={node:">=18.0.0",npm:">=7.1.0"},rk={type:"git",url:"git+https://github.com/yorkie-team/yorkie-js-sdk.git"},ik={name:"hackerwins",email:"susukang98@gmail.com"},sk="Apache-2.0",ok={url:"https://github.com/yorkie-team/yorkie-js-sdk/issues"},ak="https://github.com/yorkie-team/yorkie-js-sdk#readme",lk={"@buf/googleapis_googleapis.bufbuild_es":"^1.4.0-20240524201209-f0e53af8f2fc.3","@bufbuild/buf":"^1.28.1","@bufbuild/protoc-gen-es":"^1.6.0","@connectrpc/protoc-gen-connect-es":"^1.4.0","@types/google-protobuf":"^3.15.5","@types/long":"^4.0.1","@typescript-eslint/eslint-plugin":"^6.21.0","@typescript-eslint/parser":"^6.21.0","@vitest/coverage-istanbul":"^0.34.5","@vitest/coverage-v8":"^0.34.5","eslint-plugin-tsdoc":"^0.2.16",prettier:"^2.7.1","ts-node":"^10.9.1",typedoc:"^0.25.13",typescript:"^5.3.3","typescript-transform-paths":"^3.3.1",vite:"^5.0.12","vite-plugin-commonjs":"^0.10.1","vite-plugin-dts":"^3.9.1","vite-tsconfig-paths":"^4.2.1",vitest:"^0.34.5"},uk={"@bufbuild/protobuf":"^1.6.0","@connectrpc/connect":"^1.4.0","@connectrpc/connect-web":"^1.4.0",long:"^5.2.0"},cg={name:GS,version:YS,description:QS,main:XS,publishConfig:ZS,files:ek,scripts:tk,engines:nk,repository:rk,author:ik,license:sk,bugs:ok,homepage:ak,devDependencies:lk,dependencies:uk};function ck(){return n=>async e=>(e.header.set("x-yorkie-user-agent",cg.name+"/"+cg.version),await n(e))}const fk=n=>{try{if(JSON.stringify(n)===void 0)return!1}catch{return!1}return!0};var Aa=(n=>(n.Manual="manual",n.Realtime="realtime",n.RealtimePushOnly="realtime-pushonly",n.RealtimeSyncOff="realtime-syncoff",n))(Aa||{});const ia={syncLoopDuration:50,retrySyncLoopDelay:1e3,reconnectStreamDelay:1e3},Eu={maxRetries:1/0,initialRetryInterval:1e3,maxBackoff:2e4};class Ly{constructor(e,t){u(this,"id");u(this,"key");u(this,"status");u(this,"attachmentMap");u(this,"apiKey");u(this,"conditions");u(this,"syncLoopDuration");u(this,"reconnectStreamDelay");u(this,"retrySyncLoopDelay");u(this,"rpcClient");u(this,"taskQueue");u(this,"processing",!1);t=t||ia,this.key=t.key?t.key:Py(),this.status="deactivated",this.attachmentMap=new Map,this.apiKey=t.apiKey||"",this.conditions={SyncLoop:!1,WatchLoop:!1},this.syncLoopDuration=t.syncLoopDuration||ia.syncLoopDuration,this.reconnectStreamDelay=t.reconnectStreamDelay||ia.reconnectStreamDelay,this.retrySyncLoopDelay=t.retrySyncLoopDelay||ia.retrySyncLoopDelay,this.rpcClient=a1(D1,P1({baseUrl:e,interceptors:[_S(t.apiKey,t.token),ck()]})),this.taskQueue=[]}activate(){return this.isActive()?Promise.resolve():this.enqueueTask(async()=>this.rpcClient.activateClient({clientKey:this.key},{headers:{"x-shard-key":this.apiKey}}).then(e=>{this.id=e.clientId,this.status="activated",this.runSyncLoop(),J.info(`[AC] c:"${this.getKey()}" activated, id:"${this.id}"`)}).catch(e=>{throw J.error(`[AC] c:"${this.getKey()}" err :`,e),this.handleConnectError(e),e}))}deactivate(){return this.status==="deactivated"?Promise.resolve():this.enqueueTask(async()=>this.rpcClient.deactivateClient({clientId:this.id},{headers:{"x-shard-key":this.apiKey}}).then(()=>{this.deactivateInternal(),J.info(`[DC] c"${this.getKey()}" deactivated`)}).catch(e=>{throw J.error(`[DC] c:"${this.getKey()}" err :`,e),this.handleConnectError(e),e}))}attach(e,t={}){if(!this.isActive())throw new k(S.ErrClientNotActivated,`${this.key} is not active`);if(e.getStatus()!==Pr.Detached)throw new k(S.ErrDocumentNotDetached,`${e.getKey()} is not detached`);e.setActor(this.id),e.update((s,o)=>o.set(t.initialPresence||{}));const r=e.subscribe("local-broadcast",async s=>{var d;const{topic:o,payload:a}=s.value,l=(d=s.options)==null?void 0:d.error,c=s.options;try{await this.broadcast(e.getKey(),o,a,c)}catch(h){h instanceof Error&&(l==null||l(h))}}),i=t.syncMode??"realtime";return this.enqueueTask(async()=>this.rpcClient.attachDocument({clientId:this.id,changePack:fe.toChangePack(e.createChangePack())},{headers:{"x-shard-key":`${this.apiKey}/${e.getKey()}`}}).then(async s=>{const o=fe.fromChangePack(s.changePack);if(e.applyChangePack(o),e.getStatus()===Pr.Removed)return e;e.applyStatus(Pr.Attached),this.attachmentMap.set(e.getKey(),new MS(this.reconnectStreamDelay,e,s.documentId,i,r)),i!=="manual"&&await this.runWatchLoop(e.getKey()),J.info(`[AD] c:"${this.getKey()}" attaches d:"${e.getKey()}"`);const a=e.getRootObject();if(t.initialRoot){const l=t.initialRoot;e.update(c=>{for(const[d,h]of Object.entries(l))if(!a.has(d)){const p=d;c[p]=h}})}return e}).catch(s=>{throw J.error(`[AD] c:"${this.getKey()}" err :`,s),this.handleConnectError(s),s}))}detach(e,t={}){if(!this.isActive())throw new k(S.ErrClientNotActivated,`${this.key} is not active`);const r=this.attachmentMap.get(e.getKey());if(!r)throw new k(S.ErrDocumentNotAttached,`${e.getKey()} is not attached`);return e.update((i,s)=>s.clear()),this.enqueueTask(async()=>this.rpcClient.detachDocument({clientId:this.id,documentId:r.docID,changePack:fe.toChangePack(e.createChangePack()),removeIfNotAttached:t.removeIfNotAttached??!1},{headers:{"x-shard-key":`${this.apiKey}/${e.getKey()}`}}).then(i=>{const s=fe.fromChangePack(i.changePack);return e.applyChangePack(s),e.getStatus()!==Pr.Removed&&e.applyStatus(Pr.Detached),this.detachInternal(e.getKey()),J.info(`[DD] c:"${this.getKey()}" detaches d:"${e.getKey()}"`),e}).catch(i=>{throw J.error(`[DD] c:"${this.getKey()}" err :`,i),this.handleConnectError(i),i}))}async changeSyncMode(e,t){if(!this.isActive())throw new k(S.ErrClientNotActivated,`${this.key} is not active`);const r=this.attachmentMap.get(e.getKey());if(!r)throw new k(S.ErrDocumentNotAttached,`${e.getKey()} is not attached`);const i=r.syncMode;return i===t?e:(r.changeSyncMode(t),t==="manual"?(r.cancelWatchStream(),e):(t==="realtime"&&(r.remoteChangeEventReceived=!0),i==="manual"&&await this.runWatchLoop(e.getKey()),e))}sync(e){if(!this.isActive())throw new k(S.ErrClientNotActivated,`${this.key} is not active`);if(e){const t=this.attachmentMap.get(e.getKey());if(!t)throw new k(S.ErrDocumentNotAttached,`${e.getKey()} is not attached`);return this.enqueueTask(async()=>this.syncInternal(t,"realtime").catch(r=>{throw J.error(`[SY] c:"${this.getKey()}" err :`,r),this.handleConnectError(r),r}))}return this.enqueueTask(async()=>{const t=[];for(const[,r]of this.attachmentMap)t.push(this.syncInternal(r,r.syncMode));return Promise.all(t).catch(r=>{throw J.error(`[SY] c:"${this.getKey()}" err :`,r),this.handleConnectError(r),r})})}remove(e){if(!this.isActive())throw new k(S.ErrClientNotActivated,`${this.key} is not active`);const t=this.attachmentMap.get(e.getKey());if(!t)throw new k(S.ErrDocumentNotAttached,`${e.getKey()} is not attached`);e.setActor(this.id);const r=fe.toChangePack(e.createChangePack());return r.isRemoved=!0,this.enqueueTask(async()=>this.rpcClient.removeDocument({clientId:this.id,documentId:t.docID,changePack:r},{headers:{"x-shard-key":`${this.apiKey}/${e.getKey()}`}}).then(i=>{const s=fe.fromChangePack(i.changePack);e.applyChangePack(s),this.detachInternal(e.getKey()),J.info(`[RD] c:"${this.getKey()}" removes d:"${e.getKey()}"`)}).catch(i=>{throw J.error(`[RD] c:"${this.getKey()}" err :`,i),this.handleConnectError(i),i}))}getID(){return this.id}getKey(){return this.key}isActive(){return this.status==="activated"}getStatus(){return this.status}getCondition(e){return this.conditions[e]}broadcast(e,t,r,i){if(!this.isActive())throw new k(S.ErrClientNotActivated,`${this.key} is not active`);const s=this.attachmentMap.get(e);if(!s)throw new k(S.ErrDocumentNotAttached,`${e} is not attached`);if(!fk(r))throw new k(S.ErrInvalidArgument,"payload is not serializable");const o=(i==null?void 0:i.maxRetries)??Eu.maxRetries,a=Eu.maxBackoff;let l=0;const c=h=>Math.min(Eu.initialRetryInterval*2**h,a),d=async()=>this.enqueueTask(async()=>this.rpcClient.broadcast({clientId:this.id,documentId:s.docID,topic:t,payload:new TextEncoder().encode(JSON.stringify(r))},{headers:{"x-shard-key":`${this.apiKey}/${e}`}}).then(()=>{J.info(`[BC] c:"${this.getKey()}" broadcasts d:"${e}" t:"${t}"`)}).catch(h=>{if(J.error(`[BC] c:"${this.getKey()}" err:`,h),this.handleConnectError(h))if(ld(),c(l-1)),J.info(`[BC] c:"${this.getKey()}" retry attempt ${l}/${o}`);else throw J.error(`[BC] c:"${this.getKey()}" exceeded maximum retry attempts`),h;else throw h}));return d()}runSyncLoop(){const e=()=>{if(!this.isActive()){J.debug(`[SL] c:"${this.getKey()}" exit sync loop`),this.conditions.SyncLoop=!1;return}const t=[];for(const[,r]of this.attachmentMap)r.needRealtimeSync()&&(r.remoteChangeEventReceived=!1,t.push(this.syncInternal(r,r.syncMode)));Promise.all(t).then(()=>setTimeout(e,this.syncLoopDuration)).catch(r=>{J.error(`[SL] c:"${this.getKey()}" sync failed:`,r),this.handleConnectError(r)?setTimeout(e,this.retrySyncLoopDelay):this.conditions.SyncLoop=!1})};J.debug(`[SL] c:"${this.getKey()}" run sync loop`),this.conditions.SyncLoop=!0,e()}async runWatchLoop(e){const t=this.attachmentMap.get(e);if(!t)throw new k(S.ErrDocumentNotAttached,`${e} is not attached`);return this.conditions.WatchLoop=!0,t.runWatchLoop(r=>{if(!this.isActive())return this.conditions.WatchLoop=!1,Promise.reject(new k(S.ErrClientNotActivated,`${this.key} is not active`));const i=new AbortController,s=this.rpcClient.watchDocument({clientId:this.id,documentId:t.docID},{headers:{"x-shard-key":`${this.apiKey}/${e}`},signal:i.signal});return t.doc.publish([{type:$e.ConnectionChanged,value:_c.Connected}]),J.info(`[WD] c:"${this.getKey()}" watches d:"${e}"`),new Promise((o,a)=>{(async()=>{try{for await(const c of s)this.handleWatchDocumentsResponse(t,c),c.body.case==="initialization"&&o([s,i])}catch(c){t.doc.resetOnlineClients(),t.doc.publish([{type:$e.Initialized,source:Y.Local,value:t.doc.getPresences()}]),t.doc.publish([{type:$e.ConnectionChanged,value:_c.Disconnected}]),J.debug(`[WD] c:"${this.getKey()}" unwatches`),this.handleConnectError(c)?r():this.conditions.WatchLoop=!1,a(c)}})()})})}handleWatchDocumentsResponse(e,t){if(t.body.case==="event"&&t.body.value.type===yi.DOCUMENT_CHANGED){e.remoteChangeEventReceived=!0;return}e.doc.applyWatchStream(t)}deactivateInternal(){this.status="deactivated";for(const[e,t]of this.attachmentMap)this.detachInternal(e),t.doc.applyStatus(Pr.Detached)}detachInternal(e){const t=this.attachmentMap.get(e);t&&(t.cancelWatchStream(),t.unsubscribeBroadcastEvent(),this.attachmentMap.delete(e))}syncInternal(e,t){const{doc:r,docID:i}=e,s=r.createChangePack();return this.rpcClient.pushPullChanges({clientId:this.id,documentId:i,changePack:fe.toChangePack(s),pushOnly:t==="realtime-pushonly"},{headers:{"x-shard-key":`${this.apiKey}/${r.getKey()}`}}).then(o=>{const a=fe.fromChangePack(o.changePack);if(a.hasChanges()&&(e.syncMode==="realtime-pushonly"||e.syncMode==="realtime-syncoff"))return r;r.applyChangePack(a),e.doc.publish([{type:$e.SyncStatusChanged,value:Gc.Synced}]),r.getStatus()===Pr.Removed&&this.detachInternal(r.getKey());const l=r.getKey(),c=a.getChangeSize();return J.info(`[PP] c:"${this.getKey()}" sync d:"${l}", push:${s.getChangeSize()} pull:${c} cp:${a.getCheckpoint().toTestString()}`),r}).catch(o=>{throw r.publish([{type:$e.SyncStatusChanged,value:Gc.SyncFailed}]),J.error(`[PP] c:"${this.getKey()}" err :`,o),o})}handleConnectError(e){return e instanceof pe?e.code===_.Canceled||e.code===_.Unknown||e.code===_.ResourceExhausted||e.code===_.Unavailable?!0:((sg(e)===S.ErrClientNotActivated||sg(e)===S.ErrClientNotFound)&&this.deactivateInternal(),!1):!1}enqueueTask(e){return new Promise((t,r)=>{this.taskQueue.push(()=>e().then(t).catch(r)),this.processing||this.processNext()})}async processNext(){if(this.taskQueue.length===0){this.processing=!1;return}try{this.processing=!0,await this.taskQueue.shift()()}catch{J.error(`[TQ] c:"${this.getKey()}" process failed, id:"${this.id}"`)}this.processNext()}}const By={Client:Ly,Document:Ry,Primitive:re,Text:$l,Counter:zl,Tree:Ul,LogLevel:be,setLogLevel:Ny,IntType:on.IntegerCnt,LongType:on.LongCnt};typeof globalThis<"u"&&(globalThis.yorkie={Client:Ly,Document:Ry,Primitive:re,Text:$l,Counter:zl,Tree:Ul,LogLevel:be,setLogLevel:Ny,IntType:on.IntegerCnt,LongType:on.LongCnt});class dk{constructor(e,t){this.x=e,this.y=t,this.lifetime=0}}const hk=({xPos:n,yPos:e})=>{const[t,r]=Ue.useState([]),i=Ue.useRef(null),[s,o]=Ue.useState([]),a=(l,c)=>{const d=new dk(l,c);s.push(d),o(s),t.push(d),r(t)};return Ue.useEffect(()=>{const c=i.current.getContext("2d"),d=()=>{c.clearRect(0,0,c.canvas.width,c.canvas.height);const h=.7*(1*4e3)/60;for(let p=0;ph)s.shift();else{c.lineWidth=5,c.lineJoin="round";const I=0,O=0,y=0;c.strokeStyle=`rgb(${I},${O},${y})`,c.beginPath(),c.moveTo(w.x,w.y),c.lineTo(m.x,m.y),c.stroke(),c.closePath()}}requestAnimationFrame(d)};d()},[s]),Ue.useEffect(()=>{a(n,e)},[n,e]),ue.jsx("canvas",{className:"pen-cursor-canvas",ref:i,width:document.body.clientWidth,height:document.body.clientHeight})},gk="_goUp0_1lnal_1",mk="_goUpAnimation0_1lnal_1",pk="_fadeOut_1lnal_1",yk="_goUp1_1lnal_16",vk="_goUpAnimation1_1lnal_1",wk="_goUp2_1lnal_31",Sk="_goUpAnimation2_1lnal_1",kk="_leftRight0_1lnal_46",Tk="_leftRightAnimation0_1lnal_1",Ak="_leftRight1_1lnal_60",Ik="_leftRightAnimation1_1lnal_1",Ek="_leftRight2_1lnal_74",xk="_leftRightAnimation2_1lnal_1",xu={goUp0:gk,goUpAnimation0:mk,fadeOut:pk,goUp1:yk,goUpAnimation1:vk,goUp2:wk,goUpAnimation2:Sk,leftRight0:kk,leftRightAnimation0:Tk,leftRight1:Ak,leftRightAnimation1:Ik,leftRight2:Ek,leftRightAnimation2:xk};function Ck({x:n,y:e,timestamp:t,selectedCursorShape:r}){return ue.jsx("div",{className:"single-animation-container",children:ue.jsx("div",{className:`absolute select-none pointer-events-none ${xu.disappear} text-${t%5+2}xl ${xu["goUp"+t%3]}`,style:{left:n,top:e},children:ue.jsx("div",{className:xu["leftRight"+t%3],children:ue.jsx("div",{className:"transform -translate-x-1/2 -translate-y-1/2",children:ue.jsx("img",{src:`./icons/icon_${r}.svg`})})})})})}function fg(n,e){const t=Ue.useRef(n);Ue.useEffect(()=>{t.current=n},[n]),Ue.useEffect(()=>{function r(){t.current()}if(e!==null){let i=setInterval(r,e);return()=>clearInterval(i)}},[e])}const Nk=({pointerDown:n,xPos:e,yPos:t,selectedCursorShape:r})=>{const[i,s]=Ue.useState([]),o=100;return fg(()=>{s(a=>a.filter(l=>l.timestamp>Date.now()-4e3))},1e3),fg(()=>{n&&s(a=>a.concat([{point:{x:e,y:t},timestamp:Date.now()}]))},o),ue.jsx("div",{style:{transform:`translateX(${e}px) translateY(${t}px)`},children:i.map(a=>ue.jsx(Ck,{x:a.point.x,y:a.point.y,timestamp:a.timestamp,selectedCursorShape:r},a.timestamp.toString()))})},Pk=({selectedCursorShape:n,x:e,y:t,pointerDown:r})=>ue.jsxs(ue.Fragment,{children:[ue.jsx("img",{src:`./icons/icon_${n}.svg`,className:`${n}-cursor`,style:{transform:`translate3d(${e}px, ${t}px, 0)`}}),(n==="heart"||n==="thumbs")&&ue.jsx(Nk,{pointerDown:r,xPos:e,yPos:t,selectedCursorShape:n}),n==="pen"&&r&&ue.jsx(hk,{xPos:e,yPos:t})]}),Dk=({handleCursorShapeSelect:n,clientsLength:e})=>{const[t,r]=Ue.useState("cursor"),i=["heart","thumbs","pen","cursor"];return ue.jsxs("div",{className:"cursor-selector-container",children:[ue.jsx("div",{className:"cursor-selections-container",children:i.map(s=>ue.jsx("img",{onClick:()=>{n(s),r(s)},className:`${t===s?"cursor-shape-selected":"cursor-shape-not-selected"}`,src:`./icons/icon_${s}.svg`},s))}),ue.jsx("div",{className:"num-users-container",children:ue.jsx("p",{children:e!==1?`${e} users are here`:"1 user here"})})]})},Cu=new By.Client("https://api.yorkie.dev",{apiKey:"cedaovjuioqlk4pjqn6g"}),ii=new By.Document("simultaneous-cursors",{enableDevtools:!0}),Ok=()=>{const[n,e]=Ue.useState([]),t=r=>{ii.update((i,s)=>{s.set({cursorShape:r})})};return Ue.useEffect(()=>{(async()=>{await Cu.activate(),ii.subscribe("presence",a=>{e(ii.getPresences())}),await Cu.attach(ii,{initialPresence:{cursorShape:"cursor",cursor:{xPos:0,yPos:0},pointerDown:!1}}),window.addEventListener("beforeunload",()=>{Cu.deactivate()})})();const i=()=>{ii.update((a,l)=>{l.set({pointerDown:!1})})},s=()=>{ii.update((a,l)=>{l.set({pointerDown:!0})})},o=a=>{ii.update((l,c)=>{c.set({cursor:{xPos:a.clientX,yPos:a.clientY}})})};return window.addEventListener("mousedown",s),window.addEventListener("mouseup",i),window.addEventListener("mousemove",o),()=>{window.removeEventListener("mousedown",s),window.removeEventListener("mouseup",i),window.removeEventListener("mousemove",o)}},[]),ue.jsxs("div",{className:"general-container",children:[n.map(({clientID:r,presence:{cursorShape:i,cursor:s,pointerDown:o}})=>s?ue.jsx(Pk,{selectedCursorShape:i,x:s.xPos,y:s.yPos,pointerDown:o},r):null),ue.jsx(Dk,{handleCursorShapeSelect:t,clientsLength:n.length})]})};Nu.createRoot(document.getElementById("root")).render(ue.jsx(Ok,{})); diff --git a/examples/simultaneous-cursors/index.html b/examples/simultaneous-cursors/index.html index 3345c2ae1..14503ff3e 100644 --- a/examples/simultaneous-cursors/index.html +++ b/examples/simultaneous-cursors/index.html @@ -5,7 +5,7 @@ Simultaneous Cursors - Yorkie Example - + diff --git a/examples/vanilla-codemirror6/assets/index-BKhO_6dR.js b/examples/vanilla-codemirror6/assets/index-BPneh9Tw.js similarity index 97% rename from examples/vanilla-codemirror6/assets/index-BKhO_6dR.js rename to examples/vanilla-codemirror6/assets/index-BPneh9Tw.js index f2c17ed4d..e703e7977 100644 --- a/examples/vanilla-codemirror6/assets/index-BKhO_6dR.js +++ b/examples/vanilla-codemirror6/assets/index-BPneh9Tw.js @@ -1,6 +1,6 @@ var yS=Object.defineProperty;var bS=(n,e,t)=>e in n?yS(n,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):n[e]=t;var d=(n,e,t)=>bS(n,typeof e!="symbol"?e+"":e,t);(function(){const e=document.createElement("link").relList;if(e&&e.supports&&e.supports("modulepreload"))return;for(const r of document.querySelectorAll('link[rel="modulepreload"]'))i(r);new MutationObserver(r=>{for(const s of r)if(s.type==="childList")for(const o of s.addedNodes)o.tagName==="LINK"&&o.rel==="modulepreload"&&i(o)}).observe(document,{childList:!0,subtree:!0});function t(r){const s={};return r.integrity&&(s.integrity=r.integrity),r.referrerPolicy&&(s.referrerPolicy=r.referrerPolicy),r.crossOrigin==="use-credentials"?s.credentials="include":r.crossOrigin==="anonymous"?s.credentials="omit":s.credentials="same-origin",s}function i(r){if(r.ep)return;r.ep=!0;const s=t(r);fetch(r.href,s)}})();var ie;(function(n){n[n.Canceled=1]="Canceled",n[n.Unknown=2]="Unknown",n[n.InvalidArgument=3]="InvalidArgument",n[n.DeadlineExceeded=4]="DeadlineExceeded",n[n.NotFound=5]="NotFound",n[n.AlreadyExists=6]="AlreadyExists",n[n.PermissionDenied=7]="PermissionDenied",n[n.ResourceExhausted=8]="ResourceExhausted",n[n.FailedPrecondition=9]="FailedPrecondition",n[n.Aborted=10]="Aborted",n[n.OutOfRange=11]="OutOfRange",n[n.Unimplemented=12]="Unimplemented",n[n.Internal=13]="Internal",n[n.Unavailable=14]="Unavailable",n[n.DataLoss=15]="DataLoss",n[n.Unauthenticated=16]="Unauthenticated"})(ie||(ie={}));function Kf(n){const e=ie[n];return typeof e!="string"?n.toString():e[0].toLowerCase()+e.substring(1).replace(/[A-Z]/g,t=>"_"+t.toLowerCase())}class Te extends Error{constructor(e,t=ie.Unknown,i,r,s){super(SS(e,t)),this.name="ConnectError",Object.setPrototypeOf(this,new.target.prototype),this.rawMessage=e,this.code=t,this.metadata=new Headers(i??{}),this.details=r??[],this.cause=s}static from(e,t=ie.Unknown){return e instanceof Te?e:e instanceof Error?e.name=="AbortError"?new Te(e.message,ie.Canceled):new Te(e.message,t,void 0,void 0,e):new Te(String(e),t,void 0,void 0,e)}static[Symbol.hasInstance](e){return e instanceof Error?Object.getPrototypeOf(e)===Te.prototype?!0:e.name==="ConnectError"&&"code"in e&&typeof e.code=="number"&&"metadata"in e&&"details"in e&&Array.isArray(e.details)&&"rawMessage"in e&&typeof e.rawMessage=="string"&&"cause"in e:!1}findDetails(e){const t="typeName"in e?{findMessage:r=>r===e.typeName?e:void 0}:e,i=[];for(const r of this.details){if("getType"in r){t.findMessage(r.getType().typeName)&&i.push(r);continue}const s=t.findMessage(r.type);if(s)try{i.push(s.fromBinary(r.value))}catch{}}return i}}function SS(n,e){return n.length?`[${Kf(e)}] ${n}`:`[${Kf(e)}]`}function Oe(n,e){if(!n)throw new Error(e)}const wS=34028234663852886e22,vS=-34028234663852886e22,kS=4294967295,xS=2147483647,TS=-2147483648;function Ra(n){if(typeof n!="number")throw new Error("invalid int 32: "+typeof n);if(!Number.isInteger(n)||n>xS||nkS||n<0)throw new Error("invalid uint 32: "+n)}function wm(n){if(typeof n!="number")throw new Error("invalid float 32: "+typeof n);if(Number.isFinite(n)&&(n>wS||n({no:r.no,name:r.name,localName:n[r.no]})))}function xm(n,e,t){const i=Object.create(null),r=Object.create(null),s=[];for(const o of e){const a=Tm(o);s.push(a),i[o.name]=a,r[o.no]=a}return{typeName:n,values:s,findName(o){return i[o]},findNumber(o){return r[o]}}}function PS(n,e,t){const i={};for(const r of e){const s=Tm(r);i[s.localName]=s.no,i[s.no]=s.localName}return km(i,n,e),i}function Tm(n){return"localName"in n?n:Object.assign(Object.assign({},n),{localName:n.name})}class D{equals(e){return this.getType().runtime.util.equals(this.getType(),this,e)}clone(){return this.getType().runtime.util.clone(this)}fromBinary(e,t){const i=this.getType(),r=i.runtime.bin,s=r.makeReadOptions(t);return r.readMessage(this,s.readerFactory(e),e.byteLength,s),this}fromJson(e,t){const i=this.getType(),r=i.runtime.json,s=r.makeReadOptions(t);return r.readMessage(i,e,s,this),this}fromJsonString(e,t){let i;try{i=JSON.parse(e)}catch(r){throw new Error(`cannot decode ${this.getType().typeName} from JSON: ${r instanceof Error?r.message:String(r)}`)}return this.fromJson(i,t)}toBinary(e){const t=this.getType(),i=t.runtime.bin,r=i.makeWriteOptions(e),s=r.writerFactory();return i.writeMessage(this,s,r),s.finish()}toJson(e){const t=this.getType(),i=t.runtime.json,r=i.makeWriteOptions(e);return i.writeMessage(this,r)}toJsonString(e){var t;const i=this.toJson(e);return JSON.stringify(i,null,(t=e==null?void 0:e.prettySpaces)!==null&&t!==void 0?t:0)}toJSON(){return this.toJson({emitDefaultValues:!0})}getType(){return Object.getPrototypeOf(this).constructor}}function AS(n,e,t,i){var r;const s=(r=i==null?void 0:i.localName)!==null&&r!==void 0?r:e.substring(e.lastIndexOf(".")+1),o={[s]:function(a){n.util.initFields(this),n.util.initPartial(a,this)}}[s];return Object.setPrototypeOf(o.prototype,new D),Object.assign(o,{runtime:n,typeName:e,fields:n.util.newFieldList(t),fromBinary(a,l){return new o().fromBinary(a,l)},fromJson(a,l){return new o().fromJson(a,l)},fromJsonString(a,l){return new o().fromJsonString(a,l)},equals(a,l){return n.util.equals(o,a,l)}}),o}function $S(){let n=0,e=0;for(let i=0;i<28;i+=7){let r=this.buf[this.pos++];if(n|=(r&127)<>4,!(t&128))return this.assertBounds(),[n,e];for(let i=3;i<=31;i+=7){let r=this.buf[this.pos++];if(e|=(r&127)<>>s,a=!(!(o>>>7)&&e==0),l=(a?o|128:o)&255;if(t.push(l),!a)return}const i=n>>>28&15|(e&7)<<4,r=!!(e>>3);if(t.push((r?i|128:i)&255),!!r){for(let s=3;s<31;s=s+7){const o=e>>>s,a=!!(o>>>7),l=(a?o|128:o)&255;if(t.push(l),!a)return}t.push(e>>>31&1)}}const Ea=4294967296;function ed(n){const e=n[0]==="-";e&&(n=n.slice(1));const t=1e6;let i=0,r=0;function s(o,a){const l=Number(n.slice(o,a));r*=t,i=i*t+l,i>=Ea&&(r=r+(i/Ea|0),i=i%Ea)}return s(-24,-18),s(-18,-12),s(-12,-6),s(-6),e?Pm(i,r):Uu(i,r)}function CS(n,e){let t=Uu(n,e);const i=t.hi&2147483648;i&&(t=Pm(t.lo,t.hi));const r=Qm(t.lo,t.hi);return i?"-"+r:r}function Qm(n,e){if({lo:n,hi:e}=IS(n,e),e<=2097151)return String(Ea*e+n);const t=n&16777215,i=(n>>>24|e<<8)&16777215,r=e>>16&65535;let s=t+i*6777216+r*6710656,o=i+r*8147497,a=r*2;const l=1e7;return s>=l&&(o+=Math.floor(s/l),s%=l),o>=l&&(a+=Math.floor(o/l),o%=l),a.toString()+td(o)+td(s)}function IS(n,e){return{lo:n>>>0,hi:e>>>0}}function Uu(n,e){return{lo:n|0,hi:e|0}}function Pm(n,e){return e=~e,n?n=~n+1:e+=1,Uu(n,e)}const td=n=>{const e=String(n);return"0000000".slice(e.length)+e};function id(n,e){if(n>=0){for(;n>127;)e.push(n&127|128),n=n>>>7;e.push(n)}else{for(let t=0;t<9;t++)e.push(n&127|128),n=n>>7;e.push(1)}}function RS(){let n=this.buf[this.pos++],e=n&127;if(!(n&128))return this.assertBounds(),e;if(n=this.buf[this.pos++],e|=(n&127)<<7,!(n&128))return this.assertBounds(),e;if(n=this.buf[this.pos++],e|=(n&127)<<14,!(n&128))return this.assertBounds(),e;if(n=this.buf[this.pos++],e|=(n&127)<<21,!(n&128))return this.assertBounds(),e;n=this.buf[this.pos++],e|=(n&15)<<28;for(let t=5;n&128&&t<10;t++)n=this.buf[this.pos++];if(n&128)throw new Error("invalid varint");return this.assertBounds(),e>>>0}var nd={};function ES(){const n=new DataView(new ArrayBuffer(8));if(typeof BigInt=="function"&&typeof n.getBigInt64=="function"&&typeof n.getBigUint64=="function"&&typeof n.setBigInt64=="function"&&typeof n.setBigUint64=="function"&&(typeof process!="object"||typeof nd!="object"||nd.BUF_BIGINT_DISABLE!=="1")){const r=BigInt("-9223372036854775808"),s=BigInt("9223372036854775807"),o=BigInt("0"),a=BigInt("18446744073709551615");return{zero:BigInt(0),supported:!0,parse(l){const h=typeof l=="bigint"?l:BigInt(l);if(h>s||ha||hOe(/^-?[0-9]+$/.test(r),`int64 invalid: ${r}`),i=r=>Oe(/^[0-9]+$/.test(r),`uint64 invalid: ${r}`);return{zero:"0",supported:!1,parse(r){return typeof r!="string"&&(r=r.toString()),t(r),r},uParse(r){return typeof r!="string"&&(r=r.toString()),i(r),r},enc(r){return typeof r!="string"&&(r=r.toString()),t(r),ed(r)},uEnc(r){return typeof r!="string"&&(r=r.toString()),i(r),ed(r)},dec(r,s){return CS(r,s)},uDec(r,s){return Qm(r,s)}}}const ue=ES();var T;(function(n){n[n.DOUBLE=1]="DOUBLE",n[n.FLOAT=2]="FLOAT",n[n.INT64=3]="INT64",n[n.UINT64=4]="UINT64",n[n.INT32=5]="INT32",n[n.FIXED64=6]="FIXED64",n[n.FIXED32=7]="FIXED32",n[n.BOOL=8]="BOOL",n[n.STRING=9]="STRING",n[n.BYTES=12]="BYTES",n[n.UINT32=13]="UINT32",n[n.SFIXED32=15]="SFIXED32",n[n.SFIXED64=16]="SFIXED64",n[n.SINT32=17]="SINT32",n[n.SINT64=18]="SINT64"})(T||(T={}));var hr;(function(n){n[n.BIGINT=0]="BIGINT",n[n.STRING=1]="STRING"})(hr||(hr={}));function Fn(n,e,t){if(e===t)return!0;if(n==T.BYTES){if(!(e instanceof Uint8Array)||!(t instanceof Uint8Array)||e.length!==t.length)return!1;for(let i=0;i>>0)}raw(e){return this.buf.length&&(this.chunks.push(new Uint8Array(this.buf)),this.buf=[]),this.chunks.push(e),this}uint32(e){for(pc(e);e>127;)this.buf.push(e&127|128),e=e>>>7;return this.buf.push(e),this}int32(e){return Ra(e),id(e,this.buf),this}bool(e){return this.buf.push(e?1:0),this}bytes(e){return this.uint32(e.byteLength),this.raw(e)}string(e){let t=this.textEncoder.encode(e);return this.uint32(t.byteLength),this.raw(t)}float(e){wm(e);let t=new Uint8Array(4);return new DataView(t.buffer).setFloat32(0,e,!0),this.raw(t)}double(e){let t=new Uint8Array(8);return new DataView(t.buffer).setFloat64(0,e,!0),this.raw(t)}fixed32(e){pc(e);let t=new Uint8Array(4);return new DataView(t.buffer).setUint32(0,e,!0),this.raw(t)}sfixed32(e){Ra(e);let t=new Uint8Array(4);return new DataView(t.buffer).setInt32(0,e,!0),this.raw(t)}sint32(e){return Ra(e),e=(e<<1^e>>31)>>>0,id(e,this.buf),this}sfixed64(e){let t=new Uint8Array(8),i=new DataView(t.buffer),r=ue.enc(e);return i.setInt32(0,r.lo,!0),i.setInt32(4,r.hi,!0),this.raw(t)}fixed64(e){let t=new Uint8Array(8),i=new DataView(t.buffer),r=ue.uEnc(e);return i.setInt32(0,r.lo,!0),i.setInt32(4,r.hi,!0),this.raw(t)}int64(e){let t=ue.enc(e);return kh(t.lo,t.hi,this.buf),this}sint64(e){let t=ue.enc(e),i=t.hi>>31,r=t.lo<<1^i,s=(t.hi<<1|t.lo>>>31)^i;return kh(r,s,this.buf),this}uint64(e){let t=ue.uEnc(e);return kh(t.lo,t.hi,this.buf),this}}class NS{constructor(e,t){this.varint64=$S,this.uint32=RS,this.buf=e,this.len=e.length,this.pos=0,this.view=new DataView(e.buffer,e.byteOffset,e.byteLength),this.textDecoder=t??new TextDecoder}tag(){let e=this.uint32(),t=e>>>3,i=e&7;if(t<=0||i<0||i>5)throw new Error("illegal tag: field no "+t+" wire type "+i);return[t,i]}skip(e,t){let i=this.pos;switch(e){case ve.Varint:for(;this.buf[this.pos++]&128;);break;case ve.Bit64:this.pos+=4;case ve.Bit32:this.pos+=4;break;case ve.LengthDelimited:let r=this.uint32();this.pos+=r;break;case ve.StartGroup:for(;;){const[s,o]=this.tag();if(o===ve.EndGroup){if(t!==void 0&&s!==t)throw new Error("invalid end group tag");break}this.skip(o,s)}break;default:throw new Error("cant skip wire type "+e)}return this.assertBounds(),this.buf.subarray(i,this.pos)}assertBounds(){if(this.pos>this.len)throw new RangeError("premature EOF")}int32(){return this.uint32()|0}sint32(){let e=this.uint32();return e>>>1^-(e&1)}int64(){return ue.dec(...this.varint64())}uint64(){return ue.uDec(...this.varint64())}sint64(){let[e,t]=this.varint64(),i=-(e&1);return e=(e>>>1|(t&1)<<31)^i,t=t>>>1^i,ue.dec(e,t)}bool(){let[e,t]=this.varint64();return e!==0||t!==0}fixed32(){return this.view.getUint32((this.pos+=4)-4,!0)}sfixed32(){return this.view.getInt32((this.pos+=4)-4,!0)}fixed64(){return ue.uDec(this.sfixed32(),this.sfixed32())}sfixed64(){return ue.dec(this.sfixed32(),this.sfixed32())}float(){return this.view.getFloat32((this.pos+=4)-4,!0)}double(){return this.view.getFloat64((this.pos+=8)-8,!0)}bytes(){let e=this.uint32(),t=this.pos;return this.pos+=e,this.assertBounds(),this.buf.subarray(t,t+e)}string(){return this.textDecoder.decode(this.bytes())}}function BS(n,e,t,i){let r;return{typeName:e,extendee:t,get field(){if(!r){const s=typeof i=="function"?i():i;s.name=e.split(".").pop(),s.jsonName=`[${e}]`,r=n.util.newFieldList([s]).list()[0]}return r},runtime:n}}function $m(n){const e=n.field.localName,t=Object.create(null);return t[e]=qS(n),[t,()=>t[e]]}function qS(n){const e=n.field;if(e.repeated)return[];if(e.default!==void 0)return e.default;switch(e.kind){case"enum":return e.T.values[0].no;case"scalar":return ls(e.T,e.L);case"message":const t=e.T,i=new t;return t.fieldWrapper?t.fieldWrapper.unwrapField(i):i;case"map":throw"map fields are not allowed to be extensions"}}function MS(n,e){if(!e.repeated&&(e.kind=="enum"||e.kind=="scalar")){for(let t=n.length-1;t>=0;--t)if(n[t].no==e.no)return[n[t]];return[]}return n.filter(t=>t.no===e.no)}let Cn="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/".split(""),Hl=[];for(let n=0;n>4,o=s,r=2;break;case 2:t[i++]=(o&15)<<4|(s&60)>>2,o=s,r=3;break;case 3:t[i++]=(o&3)<<6|s,r=0;break}}if(r==1)throw Error("invalid base64 string.");return t.subarray(0,i)},enc(n){let e="",t=0,i,r=0;for(let s=0;s>2],r=(i&3)<<4,t=1;break;case 1:e+=Cn[r|i>>4],r=(i&15)<<2,t=2;break;case 2:e+=Cn[r|i>>6],e+=Cn[i&63],t=0;break}return t&&(e+=Cn[r],e+="=",t==1&&(e+="=")),e}};function VS(n,e,t){Im(e,n);const i=e.runtime.bin.makeReadOptions(t),r=MS(n.getType().runtime.bin.listUnknownFields(n),e.field),[s,o]=$m(e);for(const a of r)e.runtime.bin.readField(s,i.readerFactory(a.data),e.field,a.wireType,i);return o()}function XS(n,e,t,i){Im(e,n);const r=e.runtime.bin.makeReadOptions(i),s=e.runtime.bin.makeWriteOptions(i);if(Cm(n,e)){const h=n.getType().runtime.bin.listUnknownFields(n).filter(c=>c.no!=e.field.no);n.getType().runtime.bin.discardUnknownFields(n);for(const c of h)n.getType().runtime.bin.onUnknownField(n,c.no,c.wireType,c.data)}const o=s.writerFactory();let a=e.field;!a.opt&&!a.repeated&&(a.kind=="enum"||a.kind=="scalar")&&(a=Object.assign(Object.assign({},e.field),{opt:!0})),e.runtime.bin.writeField(a,t,o,s);const l=r.readerFactory(o.finish());for(;l.posi.no==e.field.no)}function Im(n,e){Oe(n.extendee.typeName==e.getType().typeName,`extension ${n.typeName} can only be applied to message ${n.extendee.typeName}`)}function Rm(n,e){const t=n.localName;if(n.repeated)return e[t].length>0;if(n.oneof)return e[n.oneof.localName].case===t;switch(n.kind){case"enum":case"scalar":return n.opt||n.req?e[t]!==void 0:n.kind=="enum"?e[t]!==n.T.values[0].no:!Am(n.T,e[t]);case"message":return e[t]!==void 0;case"map":return Object.keys(e[t]).length>0}}function rd(n,e){const t=n.localName,i=!n.opt&&!n.req;if(n.repeated)e[t]=[];else if(n.oneof)e[n.oneof.localName]={case:void 0};else switch(n.kind){case"map":e[t]={};break;case"enum":e[t]=i?n.T.values[0].no:void 0;break;case"scalar":e[t]=i?ls(n.T,n.L):void 0;break;case"message":e[t]=void 0;break}}function Ir(n,e){if(n===null||typeof n!="object"||!Object.getOwnPropertyNames(D.prototype).every(i=>i in n&&typeof n[i]=="function"))return!1;const t=n.getType();return t===null||typeof t!="function"||!("typeName"in t)||typeof t.typeName!="string"?!1:e===void 0?!0:t.typeName==e.typeName}function Em(n,e){return Ir(e)||!n.fieldWrapper?e:n.fieldWrapper.wrapField(e)}T.DOUBLE,T.FLOAT,T.INT64,T.UINT64,T.INT32,T.UINT32,T.BOOL,T.STRING,T.BYTES;const sd={ignoreUnknownFields:!1},od={emitDefaultValues:!1,enumAsInteger:!1,useProtoFieldName:!1,prettySpaces:0};function LS(n){return n?Object.assign(Object.assign({},sd),n):sd}function US(n){return n?Object.assign(Object.assign({},od),n):od}const Ka=Symbol(),Da=Symbol();function ZS(){return{makeReadOptions:LS,makeWriteOptions:US,readMessage(n,e,t,i){if(e==null||Array.isArray(e)||typeof e!="object")throw new Error(`cannot decode message ${n.typeName} from JSON: ${hi(e)}`);i=i??new n;const r=new Map,s=t.typeRegistry;for(const[o,a]of Object.entries(e)){const l=n.fields.findJsonName(o);if(l){if(l.oneof){if(a===null&&l.kind=="scalar")continue;const h=r.get(l.oneof);if(h!==void 0)throw new Error(`cannot decode message ${n.typeName} from JSON: multiple keys for oneof "${l.oneof.name}" present: "${h}", "${o}"`);r.set(l.oneof,o)}ad(i,a,l,t,n)}else{let h=!1;if(s!=null&&s.findExtension&&o.startsWith("[")&&o.endsWith("]")){const c=s.findExtension(o.substring(1,o.length-1));if(c&&c.extendee.typeName==n.typeName){h=!0;const[u,f]=$m(c);ad(u,a,c.field,t,c),XS(i,c,f(),t)}}if(!h&&!t.ignoreUnknownFields)throw new Error(`cannot decode message ${n.typeName} from JSON: key "${o}" is unknown`)}}return i},writeMessage(n,e){const t=n.getType(),i={};let r;try{for(r of t.fields.byNumber()){if(!Rm(r,n)){if(r.req)throw"required field not set";if(!e.emitDefaultValues||!jS(r))continue}const o=r.oneof?n[r.oneof.localName].value:n[r.localName],a=ld(r,o,e);a!==void 0&&(i[e.useProtoFieldName?r.name:r.jsonName]=a)}const s=e.typeRegistry;if(s!=null&&s.findExtensionFor)for(const o of t.runtime.bin.listUnknownFields(n)){const a=s.findExtensionFor(t.typeName,o.no);if(a&&Cm(n,a)){const l=VS(n,a,e),h=ld(a.field,l,e);h!==void 0&&(i[a.field.jsonName]=h)}}}catch(s){const o=r?`cannot encode field ${t.typeName}.${r.name} to JSON`:`cannot encode message ${t.typeName} to JSON`,a=s instanceof Error?s.message:String(s);throw new Error(o+(a.length>0?`: ${a}`:""))}return i},readScalar(n,e,t){return Gs(n,e,t??hr.BIGINT,!0)},writeScalar(n,e,t){if(e!==void 0&&(t||Am(n,e)))return Na(n,e)},debug:hi}}function hi(n){if(n===null)return"null";switch(typeof n){case"object":return Array.isArray(n)?"array":"object";case"string":return n.length>100?"string":`"${n.split('"').join('\\"')}"`;default:return String(n)}}function ad(n,e,t,i,r){let s=t.localName;if(t.repeated){if(Oe(t.kind!="map"),e===null)return;if(!Array.isArray(e))throw new Error(`cannot decode field ${r.typeName}.${t.name} from JSON: ${hi(e)}`);const o=n[s];for(const a of e){if(a===null)throw new Error(`cannot decode field ${r.typeName}.${t.name} from JSON: ${hi(a)}`);switch(t.kind){case"message":o.push(t.T.fromJson(a,i));break;case"enum":const l=xh(t.T,a,i.ignoreUnknownFields,!0);l!==Da&&o.push(l);break;case"scalar":try{o.push(Gs(t.T,a,t.L,!0))}catch(h){let c=`cannot decode field ${r.typeName}.${t.name} from JSON: ${hi(a)}`;throw h instanceof Error&&h.message.length>0&&(c+=`: ${h.message}`),new Error(c)}break}}}else if(t.kind=="map"){if(e===null)return;if(typeof e!="object"||Array.isArray(e))throw new Error(`cannot decode field ${r.typeName}.${t.name} from JSON: ${hi(e)}`);const o=n[s];for(const[a,l]of Object.entries(e)){if(l===null)throw new Error(`cannot decode field ${r.typeName}.${t.name} from JSON: map value null`);let h;try{h=WS(t.K,a)}catch(c){let u=`cannot decode map key for field ${r.typeName}.${t.name} from JSON: ${hi(e)}`;throw c instanceof Error&&c.message.length>0&&(u+=`: ${c.message}`),new Error(u)}switch(t.V.kind){case"message":o[h]=t.V.T.fromJson(l,i);break;case"enum":const c=xh(t.V.T,l,i.ignoreUnknownFields,!0);c!==Da&&(o[h]=c);break;case"scalar":try{o[h]=Gs(t.V.T,l,hr.BIGINT,!0)}catch(u){let f=`cannot decode map value for field ${r.typeName}.${t.name} from JSON: ${hi(e)}`;throw u instanceof Error&&u.message.length>0&&(f+=`: ${u.message}`),new Error(f)}break}}}else switch(t.oneof&&(n=n[t.oneof.localName]={case:s},s="value"),t.kind){case"message":const o=t.T;if(e===null&&o.typeName!="google.protobuf.Value")return;let a=n[s];Ir(a)?a.fromJson(e,i):(n[s]=a=o.fromJson(e,i),o.fieldWrapper&&!t.oneof&&(n[s]=o.fieldWrapper.unwrapField(a)));break;case"enum":const l=xh(t.T,e,i.ignoreUnknownFields,!1);switch(l){case Ka:rd(t,n);break;case Da:break;default:n[s]=l;break}break;case"scalar":try{const h=Gs(t.T,e,t.L,!1);switch(h){case Ka:rd(t,n);break;default:n[s]=h;break}}catch(h){let c=`cannot decode field ${r.typeName}.${t.name} from JSON: ${hi(e)}`;throw h instanceof Error&&h.message.length>0&&(c+=`: ${h.message}`),new Error(c)}break}}function WS(n,e){if(n===T.BOOL)switch(e){case"true":e=!0;break;case"false":e=!1;break}return Gs(n,e,hr.BIGINT,!0).toString()}function Gs(n,e,t,i){if(e===null)return i?ls(n,t):Ka;switch(n){case T.DOUBLE:case T.FLOAT:if(e==="NaN")return Number.NaN;if(e==="Infinity")return Number.POSITIVE_INFINITY;if(e==="-Infinity")return Number.NEGATIVE_INFINITY;if(e===""||typeof e=="string"&&e.trim().length!==e.length||typeof e!="string"&&typeof e!="number")break;const r=Number(e);if(Number.isNaN(r)||!Number.isFinite(r))break;return n==T.FLOAT&&wm(r),r;case T.INT32:case T.FIXED32:case T.SFIXED32:case T.SINT32:case T.UINT32:let s;if(typeof e=="number"?s=e:typeof e=="string"&&e.length>0&&e.trim().length===e.length&&(s=Number(e)),s===void 0)break;return n==T.UINT32||n==T.FIXED32?pc(s):Ra(s),s;case T.INT64:case T.SFIXED64:case T.SINT64:if(typeof e!="number"&&typeof e!="string")break;const o=ue.parse(e);return t?o.toString():o;case T.FIXED64:case T.UINT64:if(typeof e!="number"&&typeof e!="string")break;const a=ue.uParse(e);return t?a.toString():a;case T.BOOL:if(typeof e!="boolean")break;return e;case T.STRING:if(typeof e!="string")break;try{encodeURIComponent(e)}catch{throw new Error("invalid UTF8")}return e;case T.BYTES:if(e==="")return new Uint8Array(0);if(typeof e!="string")break;return Zu.dec(e)}throw new Error}function xh(n,e,t,i){if(e===null)return n.typeName=="google.protobuf.NullValue"?0:i?n.values[0].no:Ka;switch(typeof e){case"number":if(Number.isInteger(e))return e;break;case"string":const r=n.findName(e);if(r!==void 0)return r.no;if(t)return Da;break}throw new Error(`cannot decode enum ${n.typeName} from JSON: ${hi(e)}`)}function jS(n){return n.repeated||n.kind=="map"?!0:!(n.oneof||n.kind=="message"||n.opt||n.req)}function ld(n,e,t){if(n.kind=="map"){Oe(typeof e=="object"&&e!=null);const i={},r=Object.entries(e);switch(n.V.kind){case"scalar":for(const[o,a]of r)i[o.toString()]=Na(n.V.T,a);break;case"message":for(const[o,a]of r)i[o.toString()]=a.toJson(t);break;case"enum":const s=n.V.T;for(const[o,a]of r)i[o.toString()]=Th(s,a,t.enumAsInteger);break}return t.emitDefaultValues||r.length>0?i:void 0}if(n.repeated){Oe(Array.isArray(e));const i=[];switch(n.kind){case"scalar":for(let r=0;r0?i:void 0}switch(n.kind){case"scalar":return Na(n.T,e);case"enum":return Th(n.T,e,t.enumAsInteger);case"message":return Em(n.T,e).toJson(t)}}function Th(n,e,t){var i;if(Oe(typeof e=="number"),n.typeName=="google.protobuf.NullValue")return null;if(t)return e;const r=n.findNumber(e);return(i=r==null?void 0:r.name)!==null&&i!==void 0?i:e}function Na(n,e){switch(n){case T.INT32:case T.SFIXED32:case T.SINT32:case T.FIXED32:case T.UINT32:return Oe(typeof e=="number"),e;case T.FLOAT:case T.DOUBLE:return Oe(typeof e=="number"),Number.isNaN(e)?"NaN":e===Number.POSITIVE_INFINITY?"Infinity":e===Number.NEGATIVE_INFINITY?"-Infinity":e;case T.STRING:return Oe(typeof e=="string"),e;case T.BOOL:return Oe(typeof e=="boolean"),e;case T.UINT64:case T.FIXED64:case T.INT64:case T.SFIXED64:case T.SINT64:return Oe(typeof e=="bigint"||typeof e=="string"||typeof e=="number"),e.toString();case T.BYTES:return Oe(e instanceof Uint8Array),Zu.enc(e)}}const Zr=Symbol("@bufbuild/protobuf/unknown-fields"),hd={readUnknownFields:!0,readerFactory:n=>new NS(n)},cd={writeUnknownFields:!0,writerFactory:()=>new DS};function FS(n){return n?Object.assign(Object.assign({},hd),n):hd}function zS(n){return n?Object.assign(Object.assign({},cd),n):cd}function _S(){return{makeReadOptions:FS,makeWriteOptions:zS,listUnknownFields(n){var e;return(e=n[Zr])!==null&&e!==void 0?e:[]},discardUnknownFields(n){delete n[Zr]},writeUnknownFields(n,e){const i=n[Zr];if(i)for(const r of i)e.tag(r.no,r.wireType).raw(r.data)},onUnknownField(n,e,t,i){const r=n;Array.isArray(r[Zr])||(r[Zr]=[]),r[Zr].push({no:e,wireType:t,data:i})},readMessage(n,e,t,i,r){const s=n.getType(),o=r?e.len:e.pos+t;let a,l;for(;e.pos0&&(l=JS),s){let f=n[o];if(i==ve.LengthDelimited&&a!=T.STRING&&a!=T.BYTES){let g=e.uint32()+e.pos;for(;e.posIr(f,u)?f:new u(f));else{const f=o[r];u.fieldWrapper?u.typeName==="google.protobuf.BytesValue"?s[r]=Rs(f):s[r]=f:s[r]=Ir(f,u)?f:new u(f)}break}}},equals(n,e,t){return e===t?!0:!e||!t?!1:n.fields.byMember().every(i=>{const r=e[i.localName],s=t[i.localName];if(i.repeated){if(r.length!==s.length)return!1;switch(i.kind){case"message":return r.every((o,a)=>i.T.equals(o,s[a]));case"scalar":return r.every((o,a)=>Fn(i.T,o,s[a]));case"enum":return r.every((o,a)=>Fn(T.INT32,o,s[a]))}throw new Error(`repeated cannot contain ${i.kind}`)}switch(i.kind){case"message":return i.T.equals(r,s);case"enum":return Fn(T.INT32,r,s);case"scalar":return Fn(i.T,r,s);case"oneof":if(r.case!==s.case)return!1;const o=i.findField(r.case);if(o===void 0)return!0;switch(o.kind){case"message":return o.T.equals(r.value,s.value);case"enum":return Fn(T.INT32,r.value,s.value);case"scalar":return Fn(o.T,r.value,s.value)}throw new Error(`oneof cannot contain ${o.kind}`);case"map":const a=Object.keys(r).concat(Object.keys(s));switch(i.V.kind){case"message":const l=i.V.T;return a.every(c=>l.equals(r[c],s[c]));case"enum":return a.every(c=>Fn(T.INT32,r[c],s[c]));case"scalar":const h=i.V.T;return a.every(c=>Fn(h,r[c],s[c]))}break}})},clone(n){const e=n.getType(),t=new e,i=t;for(const r of e.fields.byMember()){const s=n[r.localName];let o;if(r.repeated)o=s.map(Ko);else if(r.kind=="map"){o=i[r.localName];for(const[a,l]of Object.entries(s))o[a]=Ko(l)}else r.kind=="oneof"?o=r.findField(s.case)?{case:s.case,value:Ko(s.value)}:{case:void 0}:o=Ko(s);i[r.localName]=o}for(const r of e.runtime.bin.listUnknownFields(n))e.runtime.bin.onUnknownField(i,r.no,r.wireType,r.data);return t}}}function Ko(n){if(n===void 0)return n;if(Ir(n))return n.clone();if(n instanceof Uint8Array){const e=new Uint8Array(n.byteLength);return e.set(n),e}return n}function Rs(n){return n instanceof Uint8Array?n:new Uint8Array(n)}function e1(n,e,t){return{syntax:n,json:ZS(),bin:_S(),util:Object.assign(Object.assign({},KS()),{newFieldList:e,initFields:t}),makeMessageType(i,r,s){return AS(this,i,r,s)},makeEnum:PS,makeEnumType:xm,getEnumType:QS,makeExtension(i,r,s){return BS(this,i,r,s)}}}class t1{constructor(e,t){this._fields=e,this._normalizer=t}findJsonName(e){if(!this.jsonNames){const t={};for(const i of this.list())t[i.jsonName]=t[i.name]=i;this.jsonNames=t}return this.jsonNames[e]}find(e){if(!this.numbers){const t={};for(const i of this.list())t[i.no]=i;this.numbers=t}return this.numbers[e]}list(){return this.all||(this.all=this._normalizer(this._fields)),this.all}byNumber(){return this.numbersAsc||(this.numbersAsc=this.list().concat().sort((e,t)=>e.no-t.no)),this.numbersAsc}byMember(){if(!this.members){this.members=[];const e=this.members;let t;for(const i of this.list())i.oneof?i.oneof!==t&&(t=i.oneof,e.push(t)):e.push(i)}return this.members}}function Nm(n,e){const t=Bm(n);return e?t:a1(o1(t))}function i1(n){return Nm(n,!1)}const n1=Bm;function Bm(n){let e=!1;const t=[];for(let i=0;i`${n}$`,o1=n=>s1.has(n)?qm(n):n,a1=n=>r1.has(n)?qm(n):n;class l1{constructor(e){this.kind="oneof",this.repeated=!1,this.packed=!1,this.opt=!1,this.req=!1,this.default=void 0,this.fields=[],this.name=e,this.localName=i1(e)}addField(e){Oe(e.oneof===this,`field ${e.name} not one of ${this.name}`),this.fields.push(e)}findField(e){if(!this._lookup){this._lookup=Object.create(null);for(let t=0;tnew t1(n,e=>h1(e)),n=>{for(const e of n.getType().fields.byMember()){if(e.opt)continue;const t=e.localName,i=n;if(e.repeated){i[t]=[];continue}switch(e.kind){case"oneof":i[t]={case:void 0};break;case"enum":i[t]=0;break;case"map":i[t]={};break;case"scalar":i[t]=ls(e.T,e.L);break}}});var ze;(function(n){n[n.Unary=0]="Unary",n[n.ServerStreaming=1]="ServerStreaming",n[n.ClientStreaming=2]="ClientStreaming",n[n.BiDiStreaming=3]="BiDiStreaming"})(ze||(ze={}));var pd;(function(n){n[n.NoSideEffects=1]="NoSideEffects",n[n.Idempotent=2]="Idempotent"})(pd||(pd={}));class Ue extends D{constructor(e){super(),this.seconds=ue.zero,this.nanos=0,m.util.initPartial(e,this)}fromJson(e,t){if(typeof e!="string")throw new Error(`cannot decode google.protobuf.Timestamp from JSON: ${m.json.debug(e)}`);const i=e.match(/^([0-9]{4})-([0-9]{2})-([0-9]{2})T([0-9]{2}):([0-9]{2}):([0-9]{2})(?:Z|\.([0-9]{3,9})Z|([+-][0-9][0-9]:[0-9][0-9]))$/);if(!i)throw new Error("cannot decode google.protobuf.Timestamp from JSON: invalid RFC 3339 string");const r=Date.parse(i[1]+"-"+i[2]+"-"+i[3]+"T"+i[4]+":"+i[5]+":"+i[6]+(i[8]?i[8]:"Z"));if(Number.isNaN(r))throw new Error("cannot decode google.protobuf.Timestamp from JSON: invalid RFC 3339 string");if(rDate.parse("9999-12-31T23:59:59Z"))throw new Error("cannot decode message google.protobuf.Timestamp from JSON: must be from 0001-01-01T00:00:00Z to 9999-12-31T23:59:59Z inclusive");return this.seconds=ue.parse(r/1e3),this.nanos=0,i[7]&&(this.nanos=parseInt("1"+i[7]+"0".repeat(9-i[7].length))-1e9),this}toJson(e){const t=Number(this.seconds)*1e3;if(tDate.parse("9999-12-31T23:59:59Z"))throw new Error("cannot encode google.protobuf.Timestamp to JSON: must be from 0001-01-01T00:00:00Z to 9999-12-31T23:59:59Z inclusive");if(this.nanos<0)throw new Error("cannot encode google.protobuf.Timestamp to JSON: nanos must not be negative");let i="Z";if(this.nanos>0){const r=(this.nanos+1e9).toString().substring(1);r.substring(3)==="000000"?i="."+r.substring(0,3)+"Z":r.substring(6)==="000"?i="."+r.substring(0,6)+"Z":i="."+r+"Z"}return new Date(t).toISOString().replace(".000Z",i)}toDate(){return new Date(Number(this.seconds)*1e3+Math.ceil(this.nanos/1e6))}static now(){return Ue.fromDate(new Date)}static fromDate(e){const t=e.getTime();return new Ue({seconds:ue.parse(Math.floor(t/1e3)),nanos:t%1e3*1e6})}static fromBinary(e,t){return new Ue().fromBinary(e,t)}static fromJson(e,t){return new Ue().fromJson(e,t)}static fromJsonString(e,t){return new Ue().fromJsonString(e,t)}static equals(e,t){return m.util.equals(Ue,e,t)}}Ue.runtime=m;Ue.typeName="google.protobuf.Timestamp";Ue.fields=m.util.newFieldList(()=>[{no:1,name:"seconds",kind:"scalar",T:3},{no:2,name:"nanos",kind:"scalar",T:5}]);class In extends D{constructor(e){super(),this.seconds=ue.zero,this.nanos=0,m.util.initPartial(e,this)}fromJson(e,t){if(typeof e!="string")throw new Error(`cannot decode google.protobuf.Duration from JSON: ${m.json.debug(e)}`);const i=e.match(/^(-?[0-9]+)(?:\.([0-9]+))?s/);if(i===null)throw new Error(`cannot decode google.protobuf.Duration from JSON: ${m.json.debug(e)}`);const r=Number(i[1]);if(r>315576e6||r<-315576e6)throw new Error(`cannot decode google.protobuf.Duration from JSON: ${m.json.debug(e)}`);if(this.seconds=ue.parse(r),typeof i[2]=="string"){const s=i[2]+"0".repeat(9-i[2].length);this.nanos=parseInt(s),(r<0||Object.is(r,-0))&&(this.nanos=-this.nanos)}return this}toJson(e){if(Number(this.seconds)>315576e6||Number(this.seconds)<-315576e6)throw new Error("cannot encode google.protobuf.Duration to JSON: value out of range");let t=this.seconds.toString();if(this.nanos!==0){let i=Math.abs(this.nanos).toString();i="0".repeat(9-i.length)+i,i.substring(3)==="000000"?i=i.substring(0,3):i.substring(6)==="000"&&(i=i.substring(0,6)),t+="."+i,this.nanos<0&&Number(this.seconds)==0&&(t="-"+t)}return t+"s"}static fromBinary(e,t){return new In().fromBinary(e,t)}static fromJson(e,t){return new In().fromJson(e,t)}static fromJsonString(e,t){return new In().fromJsonString(e,t)}static equals(e,t){return m.util.equals(In,e,t)}}In.runtime=m;In.typeName="google.protobuf.Duration";In.fields=m.util.newFieldList(()=>[{no:1,name:"seconds",kind:"scalar",T:3},{no:2,name:"nanos",kind:"scalar",T:5}]);class ci extends D{constructor(e){super(),this.typeUrl="",this.value=new Uint8Array(0),m.util.initPartial(e,this)}toJson(e){var t;if(this.typeUrl==="")return{};const i=this.typeUrlToName(this.typeUrl),r=(t=e==null?void 0:e.typeRegistry)===null||t===void 0?void 0:t.findMessage(i);if(!r)throw new Error(`cannot encode message google.protobuf.Any to JSON: "${this.typeUrl}" is not in the type registry`);let o=r.fromBinary(this.value).toJson(e);return(i.startsWith("google.protobuf.")||o===null||Array.isArray(o)||typeof o!="object")&&(o={value:o}),o["@type"]=this.typeUrl,o}fromJson(e,t){var i;if(e===null||Array.isArray(e)||typeof e!="object")throw new Error(`cannot decode message google.protobuf.Any from JSON: expected object but got ${e===null?"null":Array.isArray(e)?"array":typeof e}`);if(Object.keys(e).length==0)return this;const r=e["@type"];if(typeof r!="string"||r=="")throw new Error('cannot decode message google.protobuf.Any from JSON: "@type" is empty');const s=this.typeUrlToName(r),o=(i=t==null?void 0:t.typeRegistry)===null||i===void 0?void 0:i.findMessage(s);if(!o)throw new Error(`cannot decode message google.protobuf.Any from JSON: ${r} is not in the type registry`);let a;if(s.startsWith("google.protobuf.")&&Object.prototype.hasOwnProperty.call(e,"value"))a=o.fromJson(e.value,t);else{const l=Object.assign({},e);delete l["@type"],a=o.fromJson(l,t)}return this.packFrom(a),this}packFrom(e){this.value=e.toBinary(),this.typeUrl=this.typeNameToUrl(e.getType().typeName)}unpackTo(e){return this.is(e.getType())?(e.fromBinary(this.value),!0):!1}unpack(e){if(this.typeUrl==="")return;const t=e.findMessage(this.typeUrlToName(this.typeUrl));if(t)return t.fromBinary(this.value)}is(e){if(this.typeUrl==="")return!1;const t=this.typeUrlToName(this.typeUrl);let i="";return typeof e=="string"?i=e:i=e.typeName,t===i}typeNameToUrl(e){return`type.googleapis.com/${e}`}typeUrlToName(e){if(!e.length)throw new Error(`invalid type url: ${e}`);const t=e.lastIndexOf("/"),i=t>=0?e.substring(t+1):e;if(!i.length)throw new Error(`invalid type url: ${e}`);return i}static pack(e){const t=new ci;return t.packFrom(e),t}static fromBinary(e,t){return new ci().fromBinary(e,t)}static fromJson(e,t){return new ci().fromJson(e,t)}static fromJsonString(e,t){return new ci().fromJsonString(e,t)}static equals(e,t){return m.util.equals(ci,e,t)}}ci.runtime=m;ci.typeName="google.protobuf.Any";ci.fields=m.util.newFieldList(()=>[{no:1,name:"type_url",kind:"scalar",T:9},{no:2,name:"value",kind:"scalar",T:12}]);class di extends D{constructor(e){super(),this.value=0,m.util.initPartial(e,this)}toJson(e){return m.json.writeScalar(T.DOUBLE,this.value,!0)}fromJson(e,t){try{this.value=m.json.readScalar(T.DOUBLE,e)}catch(i){let r='cannot decode message google.protobuf.DoubleValue from JSON"';throw i instanceof Error&&i.message.length>0&&(r+=`: ${i.message}`),new Error(r)}return this}static fromBinary(e,t){return new di().fromBinary(e,t)}static fromJson(e,t){return new di().fromJson(e,t)}static fromJsonString(e,t){return new di().fromJsonString(e,t)}static equals(e,t){return m.util.equals(di,e,t)}}di.runtime=m;di.typeName="google.protobuf.DoubleValue";di.fields=m.util.newFieldList(()=>[{no:1,name:"value",kind:"scalar",T:1}]);di.fieldWrapper={wrapField(n){return new di({value:n})},unwrapField(n){return n.value}};class pi extends D{constructor(e){super(),this.value=0,m.util.initPartial(e,this)}toJson(e){return m.json.writeScalar(T.FLOAT,this.value,!0)}fromJson(e,t){try{this.value=m.json.readScalar(T.FLOAT,e)}catch(i){let r='cannot decode message google.protobuf.FloatValue from JSON"';throw i instanceof Error&&i.message.length>0&&(r+=`: ${i.message}`),new Error(r)}return this}static fromBinary(e,t){return new pi().fromBinary(e,t)}static fromJson(e,t){return new pi().fromJson(e,t)}static fromJsonString(e,t){return new pi().fromJsonString(e,t)}static equals(e,t){return m.util.equals(pi,e,t)}}pi.runtime=m;pi.typeName="google.protobuf.FloatValue";pi.fields=m.util.newFieldList(()=>[{no:1,name:"value",kind:"scalar",T:2}]);pi.fieldWrapper={wrapField(n){return new pi({value:n})},unwrapField(n){return n.value}};class gi extends D{constructor(e){super(),this.value=ue.zero,m.util.initPartial(e,this)}toJson(e){return m.json.writeScalar(T.INT64,this.value,!0)}fromJson(e,t){try{this.value=m.json.readScalar(T.INT64,e)}catch(i){let r='cannot decode message google.protobuf.Int64Value from JSON"';throw i instanceof Error&&i.message.length>0&&(r+=`: ${i.message}`),new Error(r)}return this}static fromBinary(e,t){return new gi().fromBinary(e,t)}static fromJson(e,t){return new gi().fromJson(e,t)}static fromJsonString(e,t){return new gi().fromJsonString(e,t)}static equals(e,t){return m.util.equals(gi,e,t)}}gi.runtime=m;gi.typeName="google.protobuf.Int64Value";gi.fields=m.util.newFieldList(()=>[{no:1,name:"value",kind:"scalar",T:3}]);gi.fieldWrapper={wrapField(n){return new gi({value:n})},unwrapField(n){return n.value}};class mi extends D{constructor(e){super(),this.value=ue.zero,m.util.initPartial(e,this)}toJson(e){return m.json.writeScalar(T.UINT64,this.value,!0)}fromJson(e,t){try{this.value=m.json.readScalar(T.UINT64,e)}catch(i){let r='cannot decode message google.protobuf.UInt64Value from JSON"';throw i instanceof Error&&i.message.length>0&&(r+=`: ${i.message}`),new Error(r)}return this}static fromBinary(e,t){return new mi().fromBinary(e,t)}static fromJson(e,t){return new mi().fromJson(e,t)}static fromJsonString(e,t){return new mi().fromJsonString(e,t)}static equals(e,t){return m.util.equals(mi,e,t)}}mi.runtime=m;mi.typeName="google.protobuf.UInt64Value";mi.fields=m.util.newFieldList(()=>[{no:1,name:"value",kind:"scalar",T:4}]);mi.fieldWrapper={wrapField(n){return new mi({value:n})},unwrapField(n){return n.value}};class Oi extends D{constructor(e){super(),this.value=0,m.util.initPartial(e,this)}toJson(e){return m.json.writeScalar(T.INT32,this.value,!0)}fromJson(e,t){try{this.value=m.json.readScalar(T.INT32,e)}catch(i){let r='cannot decode message google.protobuf.Int32Value from JSON"';throw i instanceof Error&&i.message.length>0&&(r+=`: ${i.message}`),new Error(r)}return this}static fromBinary(e,t){return new Oi().fromBinary(e,t)}static fromJson(e,t){return new Oi().fromJson(e,t)}static fromJsonString(e,t){return new Oi().fromJsonString(e,t)}static equals(e,t){return m.util.equals(Oi,e,t)}}Oi.runtime=m;Oi.typeName="google.protobuf.Int32Value";Oi.fields=m.util.newFieldList(()=>[{no:1,name:"value",kind:"scalar",T:5}]);Oi.fieldWrapper={wrapField(n){return new Oi({value:n})},unwrapField(n){return n.value}};class yi extends D{constructor(e){super(),this.value=0,m.util.initPartial(e,this)}toJson(e){return m.json.writeScalar(T.UINT32,this.value,!0)}fromJson(e,t){try{this.value=m.json.readScalar(T.UINT32,e)}catch(i){let r='cannot decode message google.protobuf.UInt32Value from JSON"';throw i instanceof Error&&i.message.length>0&&(r+=`: ${i.message}`),new Error(r)}return this}static fromBinary(e,t){return new yi().fromBinary(e,t)}static fromJson(e,t){return new yi().fromJson(e,t)}static fromJsonString(e,t){return new yi().fromJsonString(e,t)}static equals(e,t){return m.util.equals(yi,e,t)}}yi.runtime=m;yi.typeName="google.protobuf.UInt32Value";yi.fields=m.util.newFieldList(()=>[{no:1,name:"value",kind:"scalar",T:13}]);yi.fieldWrapper={wrapField(n){return new yi({value:n})},unwrapField(n){return n.value}};class bi extends D{constructor(e){super(),this.value=!1,m.util.initPartial(e,this)}toJson(e){return m.json.writeScalar(T.BOOL,this.value,!0)}fromJson(e,t){try{this.value=m.json.readScalar(T.BOOL,e)}catch(i){let r='cannot decode message google.protobuf.BoolValue from JSON"';throw i instanceof Error&&i.message.length>0&&(r+=`: ${i.message}`),new Error(r)}return this}static fromBinary(e,t){return new bi().fromBinary(e,t)}static fromJson(e,t){return new bi().fromJson(e,t)}static fromJsonString(e,t){return new bi().fromJsonString(e,t)}static equals(e,t){return m.util.equals(bi,e,t)}}bi.runtime=m;bi.typeName="google.protobuf.BoolValue";bi.fields=m.util.newFieldList(()=>[{no:1,name:"value",kind:"scalar",T:8}]);bi.fieldWrapper={wrapField(n){return new bi({value:n})},unwrapField(n){return n.value}};class ct extends D{constructor(e){super(),this.value="",m.util.initPartial(e,this)}toJson(e){return m.json.writeScalar(T.STRING,this.value,!0)}fromJson(e,t){try{this.value=m.json.readScalar(T.STRING,e)}catch(i){let r='cannot decode message google.protobuf.StringValue from JSON"';throw i instanceof Error&&i.message.length>0&&(r+=`: ${i.message}`),new Error(r)}return this}static fromBinary(e,t){return new ct().fromBinary(e,t)}static fromJson(e,t){return new ct().fromJson(e,t)}static fromJsonString(e,t){return new ct().fromJsonString(e,t)}static equals(e,t){return m.util.equals(ct,e,t)}}ct.runtime=m;ct.typeName="google.protobuf.StringValue";ct.fields=m.util.newFieldList(()=>[{no:1,name:"value",kind:"scalar",T:9}]);ct.fieldWrapper={wrapField(n){return new ct({value:n})},unwrapField(n){return n.value}};class Si extends D{constructor(e){super(),this.value=new Uint8Array(0),m.util.initPartial(e,this)}toJson(e){return m.json.writeScalar(T.BYTES,this.value,!0)}fromJson(e,t){try{this.value=m.json.readScalar(T.BYTES,e)}catch(i){let r='cannot decode message google.protobuf.BytesValue from JSON"';throw i instanceof Error&&i.message.length>0&&(r+=`: ${i.message}`),new Error(r)}return this}static fromBinary(e,t){return new Si().fromBinary(e,t)}static fromJson(e,t){return new Si().fromJson(e,t)}static fromJsonString(e,t){return new Si().fromJsonString(e,t)}static equals(e,t){return m.util.equals(Si,e,t)}}Si.runtime=m;Si.typeName="google.protobuf.BytesValue";Si.fields=m.util.newFieldList(()=>[{no:1,name:"value",kind:"scalar",T:12}]);Si.fieldWrapper={wrapField(n){return new Si({value:n})},unwrapField(n){return n.value}};function c1(n,e,t){try{const i=Zu.dec(n);return e?e.fromBinary(i,t):i}catch(i){throw Te.from(i,ie.DataLoss)}}function u1(n,e){const t={};for(const[i,r]of Object.entries(n.methods)){const s=e(Object.assign(Object.assign({},r),{localName:i,service:n}));s!=null&&(t[i]=s)}return t}function gd(n){let e,t=new Uint8Array(0);function i(r){const s=new Uint8Array(t.length+r.length);s.set(t),s.set(r,t.length),t=s}return new ReadableStream({start(){e=n.getReader()},async pull(r){let s;for(;;){if(s===void 0&&t.byteLength>=5){let l=0;for(let h=1;h<5;h++)l=(l<<8)+t[h];s={flags:t[0],length:l}}if(s!==void 0&&t.byteLength>=s.length+5)break;const a=await e.read();if(a.done)break;i(a.value)}if(s===void 0){if(t.byteLength==0){r.close();return}r.error(new Te("premature end of stream",ie.DataLoss));return}const o=t.subarray(5,5+s.length);t=t.subarray(5+s.length),r.enqueue({flags:s.flags,data:o})}})}function md(n,e){const t=new Uint8Array(e.length+5);t.set(e,5);const i=new DataView(t.buffer,t.byteOffset,t.byteLength);return i.setUint8(0,n),i.setUint32(1,e.length),t}var f1=function(n){if(!Symbol.asyncIterator)throw new TypeError("Symbol.asyncIterator is not defined.");var e=n[Symbol.asyncIterator],t;return e?e.call(n):(n=typeof __values=="function"?__values(n):n[Symbol.iterator](),t={},i("next"),i("throw"),i("return"),t[Symbol.asyncIterator]=function(){return this},t);function i(s){t[s]=n[s]&&function(o){return new Promise(function(a,l){o=n[s](o),r(a,l,o.done,o.value)})}}function r(s,o,a,l){Promise.resolve(l).then(function(h){s({value:h,done:a})},o)}},lo=function(n){return this instanceof lo?(this.v=n,this):new lo(n)},d1=function(n,e,t){if(!Symbol.asyncIterator)throw new TypeError("Symbol.asyncIterator is not defined.");var i=t.apply(n,e||[]),r,s=[];return r={},a("next"),a("throw"),a("return",o),r[Symbol.asyncIterator]=function(){return this},r;function o(p){return function(g){return Promise.resolve(g).then(p,u)}}function a(p,g){i[p]&&(r[p]=function(y){return new Promise(function(O,S){s.push([p,y,O,S])>1||l(p,y)})},g&&(r[p]=g(r[p])))}function l(p,g){try{h(i[p](g))}catch(y){f(s[0][3],y)}}function h(p){p.value instanceof lo?Promise.resolve(p.value.v).then(c,u):f(s[0][2],p)}function c(p){l("next",p)}function u(p){l("throw",p)}function f(p,g){p(g),s.shift(),s.length&&l(s[0][0],s[0][1])}},p1=function(n){var e,t;return e={},i("next"),i("throw",function(r){throw r}),i("return"),e[Symbol.iterator]=function(){return this},e;function i(r,s){e[r]=n[r]?function(o){return(t=!t)?{value:lo(n[r](o)),done:!1}:s?s(o):o}:s}};function g1(n){return d1(this,arguments,function*(){yield lo(yield*p1(f1(n)))})}var Mm=function(n){if(!Symbol.asyncIterator)throw new TypeError("Symbol.asyncIterator is not defined.");var e=n[Symbol.asyncIterator],t;return e?e.call(n):(n=typeof __values=="function"?__values(n):n[Symbol.iterator](),t={},i("next"),i("throw"),i("return"),t[Symbol.asyncIterator]=function(){return this},t);function i(s){t[s]=n[s]&&function(o){return new Promise(function(a,l){o=n[s](o),r(a,l,o.done,o.value)})}}function r(s,o,a,l){Promise.resolve(l).then(function(h){s({value:h,done:a})},o)}},hs=function(n){return this instanceof hs?(this.v=n,this):new hs(n)},m1=function(n){var e,t;return e={},i("next"),i("throw",function(r){throw r}),i("return"),e[Symbol.iterator]=function(){return this},e;function i(r,s){e[r]=n[r]?function(o){return(t=!t)?{value:hs(n[r](o)),done:!1}:s?s(o):o}:s}},O1=function(n,e,t){if(!Symbol.asyncIterator)throw new TypeError("Symbol.asyncIterator is not defined.");var i=t.apply(n,e||[]),r,s=[];return r={},a("next"),a("throw"),a("return",o),r[Symbol.asyncIterator]=function(){return this},r;function o(p){return function(g){return Promise.resolve(g).then(p,u)}}function a(p,g){i[p]&&(r[p]=function(y){return new Promise(function(O,S){s.push([p,y,O,S])>1||l(p,y)})},g&&(r[p]=g(r[p])))}function l(p,g){try{h(i[p](g))}catch(y){f(s[0][3],y)}}function h(p){p.value instanceof hs?Promise.resolve(p.value.v).then(c,u):f(s[0][2],p)}function c(p){l("next",p)}function u(p){l("throw",p)}function f(p,g){p(g),s.shift(),s.length&&l(s[0][0],s[0][1])}};function y1(n,e){return u1(n,t=>{switch(t.kind){case ze.Unary:return b1(e,n,t);case ze.ServerStreaming:return S1(e,n,t);case ze.ClientStreaming:return w1(e,n,t);case ze.BiDiStreaming:return v1(e,n,t);default:return null}})}function b1(n,e,t){return async function(i,r){var s,o;const a=await n.unary(e,t,r==null?void 0:r.signal,r==null?void 0:r.timeoutMs,r==null?void 0:r.headers,i,r==null?void 0:r.contextValues);return(s=r==null?void 0:r.onHeader)===null||s===void 0||s.call(r,a.header),(o=r==null?void 0:r.onTrailer)===null||o===void 0||o.call(r,a.trailer),a.message}}function S1(n,e,t){return function(i,r){return Vm(n.stream(e,t,r==null?void 0:r.signal,r==null?void 0:r.timeoutMs,r==null?void 0:r.headers,g1([i]),r==null?void 0:r.contextValues),r)}}function w1(n,e,t){return async function(i,r){var s,o,a,l,h,c;const u=await n.stream(e,t,r==null?void 0:r.signal,r==null?void 0:r.timeoutMs,r==null?void 0:r.headers,i,r==null?void 0:r.contextValues);(h=r==null?void 0:r.onHeader)===null||h===void 0||h.call(r,u.header);let f;try{for(var p=!0,g=Mm(u.message),y;y=await g.next(),s=y.done,!s;p=!0)l=y.value,p=!1,f=l}catch(O){o={error:O}}finally{try{!p&&!s&&(a=g.return)&&await a.call(g)}finally{if(o)throw o.error}}if(!f)throw new Te("protocol error: missing response message",ie.Internal);return(c=r==null?void 0:r.onTrailer)===null||c===void 0||c.call(r,u.trailer),f}}function v1(n,e,t){return function(i,r){return Vm(n.stream(e,t,r==null?void 0:r.signal,r==null?void 0:r.timeoutMs,r==null?void 0:r.headers,i,r==null?void 0:r.contextValues),r)}}function Vm(n,e){const t=function(){var i,r;return O1(this,arguments,function*(){const s=yield hs(n);(i=e==null?void 0:e.onHeader)===null||i===void 0||i.call(e,s.header),yield hs(yield*m1(Mm(s.message))),(r=e==null?void 0:e.onTrailer)===null||r===void 0||r.call(e,s.trailer)})}()[Symbol.asyncIterator]();return{[Symbol.asyncIterator]:()=>({next:()=>t.next()})}}function k1(...n){const e=new AbortController,t=n.filter(r=>r!==void 0).concat(e.signal);for(const r of t){if(r.aborted){i.apply(r);break}r.addEventListener("abort",i)}function i(){e.signal.aborted||e.abort(Xm(this));for(const r of t)r.removeEventListener("abort",i)}return e}function x1(n){const e=new AbortController,t=()=>{e.abort(new Te("the operation timed out",ie.DeadlineExceeded))};let i;return n!==void 0&&(n<=0?t():i=setTimeout(t,n)),{signal:e.signal,cleanup:()=>clearTimeout(i)}}function Xm(n){if(!n.aborted)return;if(n.reason!==void 0)return n.reason;const e=new Error("This operation was aborted");return e.name="AbortError",e}function Od(){return{get(n){return n.id in this?this[n.id]:n.defaultValue},set(n,e){return this[n.id]=e,this},delete(n){return delete this[n.id],this}}}const Qh=128;function yd(n){const e=new Headers,t=new TextDecoder().decode(n).split(`\r -`);for(const i of t){if(i==="")continue;const r=i.indexOf(":");if(r>0){const s=i.substring(0,r).trim(),o=i.substring(r+1).trim();e.append(s,o)}}return e}const T1="Content-Type",Q1="Grpc-Timeout",Lm="Grpc-Status",Um="Grpc-Message",P1="Grpc-Status-Details-Bin",A1="X-User-Agent",$1="X-Grpc-Web",C1="application/grpc-web+proto",I1="application/grpc-web+json";class Rn extends D{constructor(e){super(),this.code=0,this.message="",this.details=[],m.util.initPartial(e,this)}static fromBinary(e,t){return new Rn().fromBinary(e,t)}static fromJson(e,t){return new Rn().fromJson(e,t)}static fromJsonString(e,t){return new Rn().fromJsonString(e,t)}static equals(e,t){return m.util.equals(Rn,e,t)}}Rn.runtime=m;Rn.typeName="google.rpc.Status";Rn.fields=m.util.newFieldList(()=>[{no:1,name:"code",kind:"scalar",T:5},{no:2,name:"message",kind:"scalar",T:9},{no:3,name:"details",kind:"message",T:ci,repeated:!0}]);const R1="0";function Zm(n){var e;const t=n.get(P1);if(t!=null){const r=c1(t,Rn);if(r.code==0)return;const s=new Te(r.message,r.code,n);return s.details=r.details.map(o=>({type:o.typeUrl.substring(o.typeUrl.lastIndexOf("/")+1),value:o.value})),s}const i=n.get(Lm);if(i!=null){if(i===R1)return;const r=parseInt(i,10);return r in ie?new Te(decodeURIComponent((e=n.get(Um))!==null&&e!==void 0?e:""),r,n):new Te(`invalid grpc-status: ${i}`,ie.Internal,n)}}function bd(n,e,t){const i=typeof e=="string"?e:e.typeName,r=typeof t=="string"?t:t.name;return n.toString().replace(/\/?$/,`/${i}/${r}`)}function Wm(n,e){return e instanceof n?e:new n(e)}function E1(n,e){function t(i){return i.done===!0?i:{done:i.done,value:Wm(n,i.value)}}return{[Symbol.asyncIterator](){const i=e[Symbol.asyncIterator](),r={next:()=>i.next().then(t)};return i.throw!==void 0&&(r.throw=s=>i.throw(s).then(t)),i.return!==void 0&&(r.return=s=>i.return(s).then(t)),r}}}function jm(n,e){var t;return(t=e==null?void 0:e.concat().reverse().reduce((i,r)=>r(i),n))!==null&&t!==void 0?t:n}function D1(n){var e;const t=Object.assign({},n);return(e=t.ignoreUnknownFields)!==null&&e!==void 0||(t.ignoreUnknownFields=!0),t}function Sd(n,e,t,i){const r=e?wd(n.I,i):vd(n.I,t);return{parse:(e?wd(n.O,i):vd(n.O,t)).parse,serialize:r.serialize}}function wd(n,e){return{parse(t){try{return n.fromBinary(t,e)}catch(i){const r=i instanceof Error?i.message:String(i);throw new Te(`parse binary: ${r}`,ie.InvalidArgument)}},serialize(t){try{return t.toBinary(e)}catch(i){const r=i instanceof Error?i.message:String(i);throw new Te(`serialize binary: ${r}`,ie.Internal)}}}}function vd(n,e){var t,i;const r=(t=e==null?void 0:e.textEncoder)!==null&&t!==void 0?t:new TextEncoder,s=(i=e==null?void 0:e.textDecoder)!==null&&i!==void 0?i:new TextDecoder,o=D1(e);return{parse(a){try{const l=s.decode(a);return n.fromJsonString(l,o)}catch(l){throw Te.from(l,ie.InvalidArgument)}},serialize(a){try{const l=a.toJsonString(o);return r.encode(l)}catch(l){throw Te.from(l,ie.Internal)}}}}function N1(n){const e=jm(n.next,n.interceptors),[t,i,r]=Fm(n),s=Object.assign(Object.assign({},n.req),{message:Wm(n.req.method.I,n.req.message),signal:t});return e(s).then(o=>(r(),o),i)}function B1(n){const e=jm(n.next,n.interceptors),[t,i,r]=Fm(n),s=Object.assign(Object.assign({},n.req),{message:E1(n.req.method.I,n.req.message),signal:t});let o=!1;return t.addEventListener("abort",function(){var a,l;const h=n.req.message[Symbol.asyncIterator]();o||(a=h.throw)===null||a===void 0||a.call(h,this.reason).catch(()=>{}),(l=h.return)===null||l===void 0||l.call(h).catch(()=>{})}),e(s).then(a=>Object.assign(Object.assign({},a),{message:{[Symbol.asyncIterator](){const l=a.message[Symbol.asyncIterator]();return{next(){return l.next().then(h=>(h.done==!0&&(o=!0,r()),h),i)}}}}}),i)}function Fm(n){const{signal:e,cleanup:t}=x1(n.timeoutMs),i=k1(n.signal,e);return[i.signal,function(s){const o=Te.from(e.aborted?Xm(e):s);return i.abort(o),t(),Promise.reject(o)},function(){t(),i.abort()}]}function q1(){try{new Headers}catch{throw new Error("connect-web requires the fetch API. Are you running on an old version of Node.js? Node.js is not supported in Connect for Web - please stay tuned for Connect for Node.")}}function kd(n,e){const t=Zm(n);if(t)throw e.forEach((i,r)=>{t.metadata.append(r,i)}),t}function xd(n,e,t,i){const r=new Headers(t??{});return r.set(T1,n?C1:I1),r.set($1,"1"),r.set(A1,"connect-es/1.4.0"),e!==void 0&&r.set(Q1,`${e}m`),r}function M1(n){switch(n){case 400:return ie.Internal;case 401:return ie.Unauthenticated;case 403:return ie.PermissionDenied;case 404:return ie.Unimplemented;case 429:return ie.Unavailable;case 502:return ie.Unavailable;case 503:return ie.Unavailable;case 504:return ie.Unavailable;default:return ie.Unknown}}function Td(n,e){var t;if(n>=200&&n<300){const i=Zm(e);if(i)throw i;return{foundStatus:e.has(Lm)}}throw new Te(decodeURIComponent((t=e.get(Um))!==null&&t!==void 0?t:`HTTP ${n}`),M1(n),e)}var Pr=function(n){return this instanceof Pr?(this.v=n,this):new Pr(n)},V1=function(n,e,t){if(!Symbol.asyncIterator)throw new TypeError("Symbol.asyncIterator is not defined.");var i=t.apply(n,e||[]),r,s=[];return r={},a("next"),a("throw"),a("return",o),r[Symbol.asyncIterator]=function(){return this},r;function o(p){return function(g){return Promise.resolve(g).then(p,u)}}function a(p,g){i[p]&&(r[p]=function(y){return new Promise(function(O,S){s.push([p,y,O,S])>1||l(p,y)})},g&&(r[p]=g(r[p])))}function l(p,g){try{h(i[p](g))}catch(y){f(s[0][3],y)}}function h(p){p.value instanceof Pr?Promise.resolve(p.value.v).then(c,u):f(s[0][2],p)}function c(p){l("next",p)}function u(p){l("throw",p)}function f(p,g){p(g),s.shift(),s.length&&l(s[0][0],s[0][1])}};function X1(n){var e;q1();const t=(e=n.useBinaryFormat)!==null&&e!==void 0?e:!0;return{async unary(i,r,s,o,a,l,h){var c;const{serialize:u,parse:f}=Sd(r,t,n.jsonOptions,n.binaryOptions);return o=o===void 0?n.defaultTimeoutMs:o<=0?void 0:o,await N1({interceptors:n.interceptors,signal:s,timeoutMs:o,req:{stream:!1,service:i,method:r,url:bd(n.baseUrl,i,r),init:{method:"POST",credentials:(c=n.credentials)!==null&&c!==void 0?c:"same-origin",redirect:"error",mode:"cors"},header:xd(t,o,a),contextValues:h??Od(),message:l},next:async p=>{var g;const O=await((g=n.fetch)!==null&&g!==void 0?g:globalThis.fetch)(p.url,Object.assign(Object.assign({},p.init),{headers:p.header,signal:p.signal,body:md(0,u(p.message))}));if(Td(O.status,O.headers),!O.body)throw"missing response body";const S=gd(O.body).getReader();let k,$;for(;;){const x=await S.read();if(x.done)break;const{flags:Q,data:A}=x.value;if(Q===Qh){if(k!==void 0)throw"extra trailer";k=yd(A);continue}if($!==void 0)throw"extra message";$=f(A)}if(k===void 0)throw"missing trailer";if(kd(k,O.headers),$===void 0)throw"missing message";return{stream:!1,service:i,method:r,header:O.headers,message:$,trailer:k}}})},async stream(i,r,s,o,a,l,h){var c;const{serialize:u,parse:f}=Sd(r,t,n.jsonOptions,n.binaryOptions);function p(y,O,S,k){return V1(this,arguments,function*(){const x=gd(y).getReader();if(O){if(!(yield Pr(x.read())).done)throw"extra data for trailers-only";return yield Pr(void 0)}let Q=!1;for(;;){const A=yield Pr(x.read());if(A.done)break;const{flags:R,data:j}=A.value;if((R&Qh)===Qh){if(Q)throw"extra trailer";Q=!0;const W=yd(j);kd(W,k),W.forEach((G,re)=>S.set(re,G));continue}if(Q)throw"extra message";yield yield Pr(f(j))}if(!Q)throw"missing trailer"})}async function g(y){if(r.kind!=ze.ServerStreaming)throw"The fetch API does not support streaming request bodies";const O=await y[Symbol.asyncIterator]().next();if(O.done==!0)throw"missing request message";return md(0,u(O.value))}return o=o===void 0?n.defaultTimeoutMs:o<=0?void 0:o,B1({interceptors:n.interceptors,signal:s,timeoutMs:o,req:{stream:!0,service:i,method:r,url:bd(n.baseUrl,i,r),init:{method:"POST",credentials:(c=n.credentials)!==null&&c!==void 0?c:"same-origin",redirect:"error",mode:"cors"},header:xd(t,o,a),contextValues:h??Od(),message:l},next:async y=>{var O;const k=await((O=n.fetch)!==null&&O!==void 0?O:globalThis.fetch)(y.url,Object.assign(Object.assign({},y.init),{headers:y.header,signal:y.signal,body:await g(y.message)})),{foundStatus:$}=Td(k.status,k.headers);if(!k.body)throw"missing response body";const x=new Headers;return Object.assign(Object.assign({},y),{header:k.headers,trailer:x,message:p(k.body,$,x,k.headers)})}})}}}var F=(n=>(n[n.NULL=0]="NULL",n[n.BOOLEAN=1]="BOOLEAN",n[n.INTEGER=2]="INTEGER",n[n.LONG=3]="LONG",n[n.DOUBLE=4]="DOUBLE",n[n.STRING=5]="STRING",n[n.BYTES=6]="BYTES",n[n.DATE=7]="DATE",n[n.JSON_OBJECT=8]="JSON_OBJECT",n[n.JSON_ARRAY=9]="JSON_ARRAY",n[n.TEXT=10]="TEXT",n[n.INTEGER_CNT=11]="INTEGER_CNT",n[n.LONG_CNT=12]="LONG_CNT",n[n.TREE=13]="TREE",n))(F||{});m.util.setEnumType(F,"yorkie.v1.ValueType",[{no:0,name:"VALUE_TYPE_NULL"},{no:1,name:"VALUE_TYPE_BOOLEAN"},{no:2,name:"VALUE_TYPE_INTEGER"},{no:3,name:"VALUE_TYPE_LONG"},{no:4,name:"VALUE_TYPE_DOUBLE"},{no:5,name:"VALUE_TYPE_STRING"},{no:6,name:"VALUE_TYPE_BYTES"},{no:7,name:"VALUE_TYPE_DATE"},{no:8,name:"VALUE_TYPE_JSON_OBJECT"},{no:9,name:"VALUE_TYPE_JSON_ARRAY"},{no:10,name:"VALUE_TYPE_TEXT"},{no:11,name:"VALUE_TYPE_INTEGER_CNT"},{no:12,name:"VALUE_TYPE_LONG_CNT"},{no:13,name:"VALUE_TYPE_TREE"}]);var Rr=(n=>(n[n.DOCUMENT_CHANGED=0]="DOCUMENT_CHANGED",n[n.DOCUMENT_WATCHED=1]="DOCUMENT_WATCHED",n[n.DOCUMENT_UNWATCHED=2]="DOCUMENT_UNWATCHED",n[n.DOCUMENT_BROADCAST=3]="DOCUMENT_BROADCAST",n))(Rr||{});m.util.setEnumType(Rr,"yorkie.v1.DocEventType",[{no:0,name:"DOC_EVENT_TYPE_DOCUMENT_CHANGED"},{no:1,name:"DOC_EVENT_TYPE_DOCUMENT_WATCHED"},{no:2,name:"DOC_EVENT_TYPE_DOCUMENT_UNWATCHED"},{no:3,name:"DOC_EVENT_TYPE_DOCUMENT_BROADCAST"}]);const Ci=class Ci extends D{constructor(t){super();d(this,"root");d(this,"presences",{});m.util.initPartial(t,this)}static fromBinary(t,i){return new Ci().fromBinary(t,i)}static fromJson(t,i){return new Ci().fromJson(t,i)}static fromJsonString(t,i){return new Ci().fromJsonString(t,i)}static equals(t,i){return m.util.equals(Ci,t,i)}};d(Ci,"runtime",m),d(Ci,"typeName","yorkie.v1.Snapshot"),d(Ci,"fields",m.util.newFieldList(()=>[{no:1,name:"root",kind:"message",T:rt},{no:2,name:"presences",kind:"map",K:9,V:{kind:"message",T:Fu}}]));let gc=Ci;var bt;let Wn=(bt=class extends D{constructor(t){super();d(this,"documentKey","");d(this,"checkpoint");d(this,"snapshot",new Uint8Array(0));d(this,"changes",[]);d(this,"minSyncedTicket");d(this,"isRemoved",!1);d(this,"versionVector");m.util.initPartial(t,this)}static fromBinary(t,i){return new bt().fromBinary(t,i)}static fromJson(t,i){return new bt().fromJson(t,i)}static fromJsonString(t,i){return new bt().fromJsonString(t,i)}static equals(t,i){return m.util.equals(bt,t,i)}},d(bt,"runtime",m),d(bt,"typeName","yorkie.v1.ChangePack"),d(bt,"fields",m.util.newFieldList(()=>[{no:1,name:"document_key",kind:"scalar",T:9},{no:2,name:"checkpoint",kind:"message",T:Jm},{no:3,name:"snapshot",kind:"scalar",T:12},{no:4,name:"changes",kind:"message",T:zm,repeated:!0},{no:5,name:"min_synced_ticket",kind:"message",T:M},{no:6,name:"is_removed",kind:"scalar",T:8},{no:7,name:"version_vector",kind:"message",T:eh}])),bt);var St;let zm=(St=class extends D{constructor(t){super();d(this,"id");d(this,"message","");d(this,"operations",[]);d(this,"presenceChange");m.util.initPartial(t,this)}static fromBinary(t,i){return new St().fromBinary(t,i)}static fromJson(t,i){return new St().fromJson(t,i)}static fromJsonString(t,i){return new St().fromJsonString(t,i)}static equals(t,i){return m.util.equals(St,t,i)}},d(St,"runtime",m),d(St,"typeName","yorkie.v1.Change"),d(St,"fields",m.util.newFieldList(()=>[{no:1,name:"id",kind:"message",T:Kl},{no:2,name:"message",kind:"scalar",T:9},{no:3,name:"operations",kind:"message",T:Wu,repeated:!0},{no:4,name:"presence_change",kind:"message",T:co}])),St);var wt;let Kl=(wt=class extends D{constructor(t){super();d(this,"clientSeq",0);d(this,"serverSeq",ue.zero);d(this,"lamport",ue.zero);d(this,"actorId",new Uint8Array(0));d(this,"versionVector");m.util.initPartial(t,this)}static fromBinary(t,i){return new wt().fromBinary(t,i)}static fromJson(t,i){return new wt().fromJson(t,i)}static fromJsonString(t,i){return new wt().fromJsonString(t,i)}static equals(t,i){return m.util.equals(wt,t,i)}},d(wt,"runtime",m),d(wt,"typeName","yorkie.v1.ChangeID"),d(wt,"fields",m.util.newFieldList(()=>[{no:1,name:"client_seq",kind:"scalar",T:13},{no:2,name:"server_seq",kind:"scalar",T:3},{no:3,name:"lamport",kind:"scalar",T:3},{no:4,name:"actor_id",kind:"scalar",T:12},{no:5,name:"version_vector",kind:"message",T:eh}])),wt);var vt;let eh=(vt=class extends D{constructor(t){super();d(this,"vector",{});m.util.initPartial(t,this)}static fromBinary(t,i){return new vt().fromBinary(t,i)}static fromJson(t,i){return new vt().fromJson(t,i)}static fromJsonString(t,i){return new vt().fromJsonString(t,i)}static equals(t,i){return m.util.equals(vt,t,i)}},d(vt,"runtime",m),d(vt,"typeName","yorkie.v1.VersionVector"),d(vt,"fields",m.util.newFieldList(()=>[{no:1,name:"vector",kind:"map",K:9,V:{kind:"scalar",T:3}}])),vt);var kt;let Wu=(kt=class extends D{constructor(t){super();d(this,"body",{case:void 0});m.util.initPartial(t,this)}static fromBinary(t,i){return new kt().fromBinary(t,i)}static fromJson(t,i){return new kt().fromJson(t,i)}static fromJsonString(t,i){return new kt().fromJsonString(t,i)}static equals(t,i){return m.util.equals(kt,t,i)}},d(kt,"runtime",m),d(kt,"typeName","yorkie.v1.Operation"),d(kt,"fields",m.util.newFieldList(()=>[{no:1,name:"set",kind:"message",T:tl,oneof:"body"},{no:2,name:"add",kind:"message",T:il,oneof:"body"},{no:3,name:"move",kind:"message",T:nl,oneof:"body"},{no:4,name:"remove",kind:"message",T:rl,oneof:"body"},{no:5,name:"edit",kind:"message",T:sl,oneof:"body"},{no:6,name:"select",kind:"message",T:mc,oneof:"body"},{no:7,name:"style",kind:"message",T:ol,oneof:"body"},{no:8,name:"increase",kind:"message",T:al,oneof:"body"},{no:9,name:"tree_edit",kind:"message",T:ll,oneof:"body"},{no:10,name:"tree_style",kind:"message",T:hl,oneof:"body"},{no:11,name:"array_set",kind:"message",T:Oc,oneof:"body"}])),kt);const Ii=class Ii extends D{constructor(t){super();d(this,"parentCreatedAt");d(this,"key","");d(this,"value");d(this,"executedAt");m.util.initPartial(t,this)}static fromBinary(t,i){return new Ii().fromBinary(t,i)}static fromJson(t,i){return new Ii().fromJson(t,i)}static fromJsonString(t,i){return new Ii().fromJsonString(t,i)}static equals(t,i){return m.util.equals(Ii,t,i)}};d(Ii,"runtime",m),d(Ii,"typeName","yorkie.v1.Operation.Set"),d(Ii,"fields",m.util.newFieldList(()=>[{no:1,name:"parent_created_at",kind:"message",T:M},{no:2,name:"key",kind:"scalar",T:9},{no:3,name:"value",kind:"message",T:Ot},{no:4,name:"executed_at",kind:"message",T:M}]));let tl=Ii;const Ri=class Ri extends D{constructor(t){super();d(this,"parentCreatedAt");d(this,"prevCreatedAt");d(this,"value");d(this,"executedAt");m.util.initPartial(t,this)}static fromBinary(t,i){return new Ri().fromBinary(t,i)}static fromJson(t,i){return new Ri().fromJson(t,i)}static fromJsonString(t,i){return new Ri().fromJsonString(t,i)}static equals(t,i){return m.util.equals(Ri,t,i)}};d(Ri,"runtime",m),d(Ri,"typeName","yorkie.v1.Operation.Add"),d(Ri,"fields",m.util.newFieldList(()=>[{no:1,name:"parent_created_at",kind:"message",T:M},{no:2,name:"prev_created_at",kind:"message",T:M},{no:3,name:"value",kind:"message",T:Ot},{no:4,name:"executed_at",kind:"message",T:M}]));let il=Ri;const Ei=class Ei extends D{constructor(t){super();d(this,"parentCreatedAt");d(this,"prevCreatedAt");d(this,"createdAt");d(this,"executedAt");m.util.initPartial(t,this)}static fromBinary(t,i){return new Ei().fromBinary(t,i)}static fromJson(t,i){return new Ei().fromJson(t,i)}static fromJsonString(t,i){return new Ei().fromJsonString(t,i)}static equals(t,i){return m.util.equals(Ei,t,i)}};d(Ei,"runtime",m),d(Ei,"typeName","yorkie.v1.Operation.Move"),d(Ei,"fields",m.util.newFieldList(()=>[{no:1,name:"parent_created_at",kind:"message",T:M},{no:2,name:"prev_created_at",kind:"message",T:M},{no:3,name:"created_at",kind:"message",T:M},{no:4,name:"executed_at",kind:"message",T:M}]));let nl=Ei;const Di=class Di extends D{constructor(t){super();d(this,"parentCreatedAt");d(this,"createdAt");d(this,"executedAt");m.util.initPartial(t,this)}static fromBinary(t,i){return new Di().fromBinary(t,i)}static fromJson(t,i){return new Di().fromJson(t,i)}static fromJsonString(t,i){return new Di().fromJsonString(t,i)}static equals(t,i){return m.util.equals(Di,t,i)}};d(Di,"runtime",m),d(Di,"typeName","yorkie.v1.Operation.Remove"),d(Di,"fields",m.util.newFieldList(()=>[{no:1,name:"parent_created_at",kind:"message",T:M},{no:2,name:"created_at",kind:"message",T:M},{no:3,name:"executed_at",kind:"message",T:M}]));let rl=Di;const Ni=class Ni extends D{constructor(t){super();d(this,"parentCreatedAt");d(this,"from");d(this,"to");d(this,"createdAtMapByActor",{});d(this,"content","");d(this,"executedAt");d(this,"attributes",{});m.util.initPartial(t,this)}static fromBinary(t,i){return new Ni().fromBinary(t,i)}static fromJson(t,i){return new Ni().fromJson(t,i)}static fromJsonString(t,i){return new Ni().fromJsonString(t,i)}static equals(t,i){return m.util.equals(Ni,t,i)}};d(Ni,"runtime",m),d(Ni,"typeName","yorkie.v1.Operation.Edit"),d(Ni,"fields",m.util.newFieldList(()=>[{no:1,name:"parent_created_at",kind:"message",T:M},{no:2,name:"from",kind:"message",T:Mn},{no:3,name:"to",kind:"message",T:Mn},{no:4,name:"created_at_map_by_actor",kind:"map",K:9,V:{kind:"message",T:M}},{no:5,name:"content",kind:"scalar",T:9},{no:6,name:"executed_at",kind:"message",T:M},{no:7,name:"attributes",kind:"map",K:9,V:{kind:"scalar",T:9}}]));let sl=Ni;const Bi=class Bi extends D{constructor(t){super();d(this,"parentCreatedAt");d(this,"from");d(this,"to");d(this,"executedAt");m.util.initPartial(t,this)}static fromBinary(t,i){return new Bi().fromBinary(t,i)}static fromJson(t,i){return new Bi().fromJson(t,i)}static fromJsonString(t,i){return new Bi().fromJsonString(t,i)}static equals(t,i){return m.util.equals(Bi,t,i)}};d(Bi,"runtime",m),d(Bi,"typeName","yorkie.v1.Operation.Select"),d(Bi,"fields",m.util.newFieldList(()=>[{no:1,name:"parent_created_at",kind:"message",T:M},{no:2,name:"from",kind:"message",T:Mn},{no:3,name:"to",kind:"message",T:Mn},{no:4,name:"executed_at",kind:"message",T:M}]));let mc=Bi;const qi=class qi extends D{constructor(t){super();d(this,"parentCreatedAt");d(this,"from");d(this,"to");d(this,"attributes",{});d(this,"executedAt");d(this,"createdAtMapByActor",{});m.util.initPartial(t,this)}static fromBinary(t,i){return new qi().fromBinary(t,i)}static fromJson(t,i){return new qi().fromJson(t,i)}static fromJsonString(t,i){return new qi().fromJsonString(t,i)}static equals(t,i){return m.util.equals(qi,t,i)}};d(qi,"runtime",m),d(qi,"typeName","yorkie.v1.Operation.Style"),d(qi,"fields",m.util.newFieldList(()=>[{no:1,name:"parent_created_at",kind:"message",T:M},{no:2,name:"from",kind:"message",T:Mn},{no:3,name:"to",kind:"message",T:Mn},{no:4,name:"attributes",kind:"map",K:9,V:{kind:"scalar",T:9}},{no:5,name:"executed_at",kind:"message",T:M},{no:6,name:"created_at_map_by_actor",kind:"map",K:9,V:{kind:"message",T:M}}]));let ol=qi;const Mi=class Mi extends D{constructor(t){super();d(this,"parentCreatedAt");d(this,"value");d(this,"executedAt");m.util.initPartial(t,this)}static fromBinary(t,i){return new Mi().fromBinary(t,i)}static fromJson(t,i){return new Mi().fromJson(t,i)}static fromJsonString(t,i){return new Mi().fromJsonString(t,i)}static equals(t,i){return m.util.equals(Mi,t,i)}};d(Mi,"runtime",m),d(Mi,"typeName","yorkie.v1.Operation.Increase"),d(Mi,"fields",m.util.newFieldList(()=>[{no:1,name:"parent_created_at",kind:"message",T:M},{no:2,name:"value",kind:"message",T:Ot},{no:3,name:"executed_at",kind:"message",T:M}]));let al=Mi;const Vi=class Vi extends D{constructor(t){super();d(this,"parentCreatedAt");d(this,"from");d(this,"to");d(this,"createdAtMapByActor",{});d(this,"contents",[]);d(this,"splitLevel",0);d(this,"executedAt");m.util.initPartial(t,this)}static fromBinary(t,i){return new Vi().fromBinary(t,i)}static fromJson(t,i){return new Vi().fromJson(t,i)}static fromJsonString(t,i){return new Vi().fromJsonString(t,i)}static equals(t,i){return m.util.equals(Vi,t,i)}};d(Vi,"runtime",m),d(Vi,"typeName","yorkie.v1.Operation.TreeEdit"),d(Vi,"fields",m.util.newFieldList(()=>[{no:1,name:"parent_created_at",kind:"message",T:M},{no:2,name:"from",kind:"message",T:Er},{no:3,name:"to",kind:"message",T:Er},{no:4,name:"created_at_map_by_actor",kind:"map",K:9,V:{kind:"message",T:M}},{no:5,name:"contents",kind:"message",T:Ol,repeated:!0},{no:7,name:"split_level",kind:"scalar",T:5},{no:6,name:"executed_at",kind:"message",T:M}]));let ll=Vi;const Xi=class Xi extends D{constructor(t){super();d(this,"parentCreatedAt");d(this,"from");d(this,"to");d(this,"attributes",{});d(this,"executedAt");d(this,"attributesToRemove",[]);d(this,"createdAtMapByActor",{});m.util.initPartial(t,this)}static fromBinary(t,i){return new Xi().fromBinary(t,i)}static fromJson(t,i){return new Xi().fromJson(t,i)}static fromJsonString(t,i){return new Xi().fromJsonString(t,i)}static equals(t,i){return m.util.equals(Xi,t,i)}};d(Xi,"runtime",m),d(Xi,"typeName","yorkie.v1.Operation.TreeStyle"),d(Xi,"fields",m.util.newFieldList(()=>[{no:1,name:"parent_created_at",kind:"message",T:M},{no:2,name:"from",kind:"message",T:Er},{no:3,name:"to",kind:"message",T:Er},{no:4,name:"attributes",kind:"map",K:9,V:{kind:"scalar",T:9}},{no:5,name:"executed_at",kind:"message",T:M},{no:6,name:"attributes_to_remove",kind:"scalar",T:9,repeated:!0},{no:7,name:"created_at_map_by_actor",kind:"map",K:9,V:{kind:"message",T:M}}]));let hl=Xi;const Li=class Li extends D{constructor(t){super();d(this,"parentCreatedAt");d(this,"createdAt");d(this,"value");d(this,"executedAt");m.util.initPartial(t,this)}static fromBinary(t,i){return new Li().fromBinary(t,i)}static fromJson(t,i){return new Li().fromJson(t,i)}static fromJsonString(t,i){return new Li().fromJsonString(t,i)}static equals(t,i){return m.util.equals(Li,t,i)}};d(Li,"runtime",m),d(Li,"typeName","yorkie.v1.Operation.ArraySet"),d(Li,"fields",m.util.newFieldList(()=>[{no:1,name:"parent_created_at",kind:"message",T:M},{no:2,name:"created_at",kind:"message",T:M},{no:3,name:"value",kind:"message",T:Ot},{no:4,name:"executed_at",kind:"message",T:M}]));let Oc=Li;const Ui=class Ui extends D{constructor(t){super();d(this,"createdAt");d(this,"movedAt");d(this,"removedAt");d(this,"type",0);d(this,"value",new Uint8Array(0));m.util.initPartial(t,this)}static fromBinary(t,i){return new Ui().fromBinary(t,i)}static fromJson(t,i){return new Ui().fromJson(t,i)}static fromJsonString(t,i){return new Ui().fromJsonString(t,i)}static equals(t,i){return m.util.equals(Ui,t,i)}};d(Ui,"runtime",m),d(Ui,"typeName","yorkie.v1.JSONElementSimple"),d(Ui,"fields",m.util.newFieldList(()=>[{no:1,name:"created_at",kind:"message",T:M},{no:2,name:"moved_at",kind:"message",T:M},{no:3,name:"removed_at",kind:"message",T:M},{no:4,name:"type",kind:"enum",T:m.getEnumType(F)},{no:5,name:"value",kind:"scalar",T:12}]));let Ot=Ui;const Zi=class Zi extends D{constructor(t){super();d(this,"body",{case:void 0});m.util.initPartial(t,this)}static fromBinary(t,i){return new Zi().fromBinary(t,i)}static fromJson(t,i){return new Zi().fromJson(t,i)}static fromJsonString(t,i){return new Zi().fromJsonString(t,i)}static equals(t,i){return m.util.equals(Zi,t,i)}};d(Zi,"runtime",m),d(Zi,"typeName","yorkie.v1.JSONElement"),d(Zi,"fields",m.util.newFieldList(()=>[{no:1,name:"json_object",kind:"message",T:cl,oneof:"body"},{no:2,name:"json_array",kind:"message",T:ul,oneof:"body"},{no:3,name:"primitive",kind:"message",T:fl,oneof:"body"},{no:5,name:"text",kind:"message",T:dl,oneof:"body"},{no:6,name:"counter",kind:"message",T:pl,oneof:"body"},{no:7,name:"tree",kind:"message",T:gl,oneof:"body"}]));let rt=Zi;const Wi=class Wi extends D{constructor(t){super();d(this,"nodes",[]);d(this,"createdAt");d(this,"movedAt");d(this,"removedAt");m.util.initPartial(t,this)}static fromBinary(t,i){return new Wi().fromBinary(t,i)}static fromJson(t,i){return new Wi().fromJson(t,i)}static fromJsonString(t,i){return new Wi().fromJsonString(t,i)}static equals(t,i){return m.util.equals(Wi,t,i)}};d(Wi,"runtime",m),d(Wi,"typeName","yorkie.v1.JSONElement.JSONObject"),d(Wi,"fields",m.util.newFieldList(()=>[{no:1,name:"nodes",kind:"message",T:_m,repeated:!0},{no:2,name:"created_at",kind:"message",T:M},{no:3,name:"moved_at",kind:"message",T:M},{no:4,name:"removed_at",kind:"message",T:M}]));let cl=Wi;const ji=class ji extends D{constructor(t){super();d(this,"nodes",[]);d(this,"createdAt");d(this,"movedAt");d(this,"removedAt");m.util.initPartial(t,this)}static fromBinary(t,i){return new ji().fromBinary(t,i)}static fromJson(t,i){return new ji().fromJson(t,i)}static fromJsonString(t,i){return new ji().fromJsonString(t,i)}static equals(t,i){return m.util.equals(ji,t,i)}};d(ji,"runtime",m),d(ji,"typeName","yorkie.v1.JSONElement.JSONArray"),d(ji,"fields",m.util.newFieldList(()=>[{no:1,name:"nodes",kind:"message",T:ml,repeated:!0},{no:2,name:"created_at",kind:"message",T:M},{no:3,name:"moved_at",kind:"message",T:M},{no:4,name:"removed_at",kind:"message",T:M}]));let ul=ji;const Fi=class Fi extends D{constructor(t){super();d(this,"type",0);d(this,"value",new Uint8Array(0));d(this,"createdAt");d(this,"movedAt");d(this,"removedAt");m.util.initPartial(t,this)}static fromBinary(t,i){return new Fi().fromBinary(t,i)}static fromJson(t,i){return new Fi().fromJson(t,i)}static fromJsonString(t,i){return new Fi().fromJsonString(t,i)}static equals(t,i){return m.util.equals(Fi,t,i)}};d(Fi,"runtime",m),d(Fi,"typeName","yorkie.v1.JSONElement.Primitive"),d(Fi,"fields",m.util.newFieldList(()=>[{no:1,name:"type",kind:"enum",T:m.getEnumType(F)},{no:2,name:"value",kind:"scalar",T:12},{no:3,name:"created_at",kind:"message",T:M},{no:4,name:"moved_at",kind:"message",T:M},{no:5,name:"removed_at",kind:"message",T:M}]));let fl=Fi;const zi=class zi extends D{constructor(t){super();d(this,"nodes",[]);d(this,"createdAt");d(this,"movedAt");d(this,"removedAt");m.util.initPartial(t,this)}static fromBinary(t,i){return new zi().fromBinary(t,i)}static fromJson(t,i){return new zi().fromJson(t,i)}static fromJsonString(t,i){return new zi().fromJsonString(t,i)}static equals(t,i){return m.util.equals(zi,t,i)}};d(zi,"runtime",m),d(zi,"typeName","yorkie.v1.JSONElement.Text"),d(zi,"fields",m.util.newFieldList(()=>[{no:1,name:"nodes",kind:"message",T:Gm,repeated:!0},{no:2,name:"created_at",kind:"message",T:M},{no:3,name:"moved_at",kind:"message",T:M},{no:4,name:"removed_at",kind:"message",T:M}]));let dl=zi;const _i=class _i extends D{constructor(t){super();d(this,"type",0);d(this,"value",new Uint8Array(0));d(this,"createdAt");d(this,"movedAt");d(this,"removedAt");m.util.initPartial(t,this)}static fromBinary(t,i){return new _i().fromBinary(t,i)}static fromJson(t,i){return new _i().fromJson(t,i)}static fromJsonString(t,i){return new _i().fromJsonString(t,i)}static equals(t,i){return m.util.equals(_i,t,i)}};d(_i,"runtime",m),d(_i,"typeName","yorkie.v1.JSONElement.Counter"),d(_i,"fields",m.util.newFieldList(()=>[{no:1,name:"type",kind:"enum",T:m.getEnumType(F)},{no:2,name:"value",kind:"scalar",T:12},{no:3,name:"created_at",kind:"message",T:M},{no:4,name:"moved_at",kind:"message",T:M},{no:5,name:"removed_at",kind:"message",T:M}]));let pl=_i;const Gi=class Gi extends D{constructor(t){super();d(this,"nodes",[]);d(this,"createdAt");d(this,"movedAt");d(this,"removedAt");m.util.initPartial(t,this)}static fromBinary(t,i){return new Gi().fromBinary(t,i)}static fromJson(t,i){return new Gi().fromJson(t,i)}static fromJsonString(t,i){return new Gi().fromJsonString(t,i)}static equals(t,i){return m.util.equals(Gi,t,i)}};d(Gi,"runtime",m),d(Gi,"typeName","yorkie.v1.JSONElement.Tree"),d(Gi,"fields",m.util.newFieldList(()=>[{no:1,name:"nodes",kind:"message",T:ju,repeated:!0},{no:2,name:"created_at",kind:"message",T:M},{no:3,name:"moved_at",kind:"message",T:M},{no:4,name:"removed_at",kind:"message",T:M}]));let gl=Gi;var xt;let _m=(xt=class extends D{constructor(t){super();d(this,"key","");d(this,"element");m.util.initPartial(t,this)}static fromBinary(t,i){return new xt().fromBinary(t,i)}static fromJson(t,i){return new xt().fromJson(t,i)}static fromJsonString(t,i){return new xt().fromJsonString(t,i)}static equals(t,i){return m.util.equals(xt,t,i)}},d(xt,"runtime",m),d(xt,"typeName","yorkie.v1.RHTNode"),d(xt,"fields",m.util.newFieldList(()=>[{no:1,name:"key",kind:"scalar",T:9},{no:2,name:"element",kind:"message",T:rt}])),xt);const li=class li extends D{constructor(t){super();d(this,"next");d(this,"element");m.util.initPartial(t,this)}static fromBinary(t,i){return new li().fromBinary(t,i)}static fromJson(t,i){return new li().fromJson(t,i)}static fromJsonString(t,i){return new li().fromJsonString(t,i)}static equals(t,i){return m.util.equals(li,t,i)}};d(li,"runtime",m),d(li,"typeName","yorkie.v1.RGANode"),d(li,"fields",m.util.newFieldList(()=>[{no:1,name:"next",kind:"message",T:li},{no:2,name:"element",kind:"message",T:rt}]));let ml=li;const Ji=class Ji extends D{constructor(t){super();d(this,"value","");d(this,"updatedAt");d(this,"isRemoved",!1);m.util.initPartial(t,this)}static fromBinary(t,i){return new Ji().fromBinary(t,i)}static fromJson(t,i){return new Ji().fromJson(t,i)}static fromJsonString(t,i){return new Ji().fromJsonString(t,i)}static equals(t,i){return m.util.equals(Ji,t,i)}};d(Ji,"runtime",m),d(Ji,"typeName","yorkie.v1.NodeAttr"),d(Ji,"fields",m.util.newFieldList(()=>[{no:1,name:"value",kind:"scalar",T:9},{no:2,name:"updated_at",kind:"message",T:M},{no:3,name:"is_removed",kind:"scalar",T:8}]));let cs=Ji;var Tt;let Gm=(Tt=class extends D{constructor(t){super();d(this,"id");d(this,"value","");d(this,"removedAt");d(this,"insPrevId");d(this,"attributes",{});m.util.initPartial(t,this)}static fromBinary(t,i){return new Tt().fromBinary(t,i)}static fromJson(t,i){return new Tt().fromJson(t,i)}static fromJsonString(t,i){return new Tt().fromJsonString(t,i)}static equals(t,i){return m.util.equals(Tt,t,i)}},d(Tt,"runtime",m),d(Tt,"typeName","yorkie.v1.TextNode"),d(Tt,"fields",m.util.newFieldList(()=>[{no:1,name:"id",kind:"message",T:ho},{no:2,name:"value",kind:"scalar",T:9},{no:3,name:"removed_at",kind:"message",T:M},{no:4,name:"ins_prev_id",kind:"message",T:ho},{no:5,name:"attributes",kind:"map",K:9,V:{kind:"message",T:cs}}])),Tt);const Yi=class Yi extends D{constructor(t){super();d(this,"createdAt");d(this,"offset",0);m.util.initPartial(t,this)}static fromBinary(t,i){return new Yi().fromBinary(t,i)}static fromJson(t,i){return new Yi().fromJson(t,i)}static fromJsonString(t,i){return new Yi().fromJsonString(t,i)}static equals(t,i){return m.util.equals(Yi,t,i)}};d(Yi,"runtime",m),d(Yi,"typeName","yorkie.v1.TextNodeID"),d(Yi,"fields",m.util.newFieldList(()=>[{no:1,name:"created_at",kind:"message",T:M},{no:2,name:"offset",kind:"scalar",T:5}]));let ho=Yi;var Qt;let ju=(Qt=class extends D{constructor(t){super();d(this,"id");d(this,"type","");d(this,"value","");d(this,"removedAt");d(this,"insPrevId");d(this,"insNextId");d(this,"depth",0);d(this,"attributes",{});m.util.initPartial(t,this)}static fromBinary(t,i){return new Qt().fromBinary(t,i)}static fromJson(t,i){return new Qt().fromJson(t,i)}static fromJsonString(t,i){return new Qt().fromJsonString(t,i)}static equals(t,i){return m.util.equals(Qt,t,i)}},d(Qt,"runtime",m),d(Qt,"typeName","yorkie.v1.TreeNode"),d(Qt,"fields",m.util.newFieldList(()=>[{no:1,name:"id",kind:"message",T:nr},{no:2,name:"type",kind:"scalar",T:9},{no:3,name:"value",kind:"scalar",T:9},{no:4,name:"removed_at",kind:"message",T:M},{no:5,name:"ins_prev_id",kind:"message",T:nr},{no:6,name:"ins_next_id",kind:"message",T:nr},{no:7,name:"depth",kind:"scalar",T:5},{no:8,name:"attributes",kind:"map",K:9,V:{kind:"message",T:cs}}])),Qt);const Hi=class Hi extends D{constructor(t){super();d(this,"content",[]);m.util.initPartial(t,this)}static fromBinary(t,i){return new Hi().fromBinary(t,i)}static fromJson(t,i){return new Hi().fromJson(t,i)}static fromJsonString(t,i){return new Hi().fromJsonString(t,i)}static equals(t,i){return m.util.equals(Hi,t,i)}};d(Hi,"runtime",m),d(Hi,"typeName","yorkie.v1.TreeNodes"),d(Hi,"fields",m.util.newFieldList(()=>[{no:1,name:"content",kind:"message",T:ju,repeated:!0}]));let Ol=Hi;const Ki=class Ki extends D{constructor(t){super();d(this,"createdAt");d(this,"offset",0);m.util.initPartial(t,this)}static fromBinary(t,i){return new Ki().fromBinary(t,i)}static fromJson(t,i){return new Ki().fromJson(t,i)}static fromJsonString(t,i){return new Ki().fromJsonString(t,i)}static equals(t,i){return m.util.equals(Ki,t,i)}};d(Ki,"runtime",m),d(Ki,"typeName","yorkie.v1.TreeNodeID"),d(Ki,"fields",m.util.newFieldList(()=>[{no:1,name:"created_at",kind:"message",T:M},{no:2,name:"offset",kind:"scalar",T:5}]));let nr=Ki;const en=class en extends D{constructor(t){super();d(this,"parentId");d(this,"leftSiblingId");m.util.initPartial(t,this)}static fromBinary(t,i){return new en().fromBinary(t,i)}static fromJson(t,i){return new en().fromJson(t,i)}static fromJsonString(t,i){return new en().fromJsonString(t,i)}static equals(t,i){return m.util.equals(en,t,i)}};d(en,"runtime",m),d(en,"typeName","yorkie.v1.TreePos"),d(en,"fields",m.util.newFieldList(()=>[{no:1,name:"parent_id",kind:"message",T:nr},{no:2,name:"left_sibling_id",kind:"message",T:nr}]));let Er=en;const tn=class tn extends D{constructor(t){super();d(this,"id","");d(this,"username","");d(this,"createdAt");m.util.initPartial(t,this)}static fromBinary(t,i){return new tn().fromBinary(t,i)}static fromJson(t,i){return new tn().fromJson(t,i)}static fromJsonString(t,i){return new tn().fromJsonString(t,i)}static equals(t,i){return m.util.equals(tn,t,i)}};d(tn,"runtime",m),d(tn,"typeName","yorkie.v1.User"),d(tn,"fields",m.util.newFieldList(()=>[{no:1,name:"id",kind:"scalar",T:9},{no:2,name:"username",kind:"scalar",T:9},{no:3,name:"created_at",kind:"message",T:Ue}]));let Qd=tn;const nn=class nn extends D{constructor(t){super();d(this,"id","");d(this,"name","");d(this,"publicKey","");d(this,"secretKey","");d(this,"authWebhookUrl","");d(this,"authWebhookMethods",[]);d(this,"clientDeactivateThreshold","");d(this,"createdAt");d(this,"updatedAt");m.util.initPartial(t,this)}static fromBinary(t,i){return new nn().fromBinary(t,i)}static fromJson(t,i){return new nn().fromJson(t,i)}static fromJsonString(t,i){return new nn().fromJsonString(t,i)}static equals(t,i){return m.util.equals(nn,t,i)}};d(nn,"runtime",m),d(nn,"typeName","yorkie.v1.Project"),d(nn,"fields",m.util.newFieldList(()=>[{no:1,name:"id",kind:"scalar",T:9},{no:2,name:"name",kind:"scalar",T:9},{no:3,name:"public_key",kind:"scalar",T:9},{no:4,name:"secret_key",kind:"scalar",T:9},{no:5,name:"auth_webhook_url",kind:"scalar",T:9},{no:6,name:"auth_webhook_methods",kind:"scalar",T:9,repeated:!0},{no:7,name:"client_deactivate_threshold",kind:"scalar",T:9},{no:8,name:"created_at",kind:"message",T:Ue},{no:9,name:"updated_at",kind:"message",T:Ue}]));let Pd=nn;const rn=class rn extends D{constructor(t){super();d(this,"name");d(this,"authWebhookUrl");d(this,"authWebhookMethods");d(this,"clientDeactivateThreshold");m.util.initPartial(t,this)}static fromBinary(t,i){return new rn().fromBinary(t,i)}static fromJson(t,i){return new rn().fromJson(t,i)}static fromJsonString(t,i){return new rn().fromJsonString(t,i)}static equals(t,i){return m.util.equals(rn,t,i)}};d(rn,"runtime",m),d(rn,"typeName","yorkie.v1.UpdatableProjectFields"),d(rn,"fields",m.util.newFieldList(()=>[{no:1,name:"name",kind:"message",T:ct},{no:2,name:"auth_webhook_url",kind:"message",T:ct},{no:3,name:"auth_webhook_methods",kind:"message",T:yc},{no:4,name:"client_deactivate_threshold",kind:"message",T:ct}]));let Ad=rn;const sn=class sn extends D{constructor(t){super();d(this,"methods",[]);m.util.initPartial(t,this)}static fromBinary(t,i){return new sn().fromBinary(t,i)}static fromJson(t,i){return new sn().fromJson(t,i)}static fromJsonString(t,i){return new sn().fromJsonString(t,i)}static equals(t,i){return m.util.equals(sn,t,i)}};d(sn,"runtime",m),d(sn,"typeName","yorkie.v1.UpdatableProjectFields.AuthWebhookMethods"),d(sn,"fields",m.util.newFieldList(()=>[{no:1,name:"methods",kind:"scalar",T:9,repeated:!0}]));let yc=sn;const on=class on extends D{constructor(t){super();d(this,"id","");d(this,"key","");d(this,"snapshot","");d(this,"createdAt");d(this,"accessedAt");d(this,"updatedAt");m.util.initPartial(t,this)}static fromBinary(t,i){return new on().fromBinary(t,i)}static fromJson(t,i){return new on().fromJson(t,i)}static fromJsonString(t,i){return new on().fromJsonString(t,i)}static equals(t,i){return m.util.equals(on,t,i)}};d(on,"runtime",m),d(on,"typeName","yorkie.v1.DocumentSummary"),d(on,"fields",m.util.newFieldList(()=>[{no:1,name:"id",kind:"scalar",T:9},{no:2,name:"key",kind:"scalar",T:9},{no:3,name:"snapshot",kind:"scalar",T:9},{no:4,name:"created_at",kind:"message",T:Ue},{no:5,name:"accessed_at",kind:"message",T:Ue},{no:6,name:"updated_at",kind:"message",T:Ue}]));let $d=on;const an=class an extends D{constructor(t){super();d(this,"type",0);d(this,"presence");m.util.initPartial(t,this)}static fromBinary(t,i){return new an().fromBinary(t,i)}static fromJson(t,i){return new an().fromJson(t,i)}static fromJsonString(t,i){return new an().fromJsonString(t,i)}static equals(t,i){return m.util.equals(an,t,i)}};d(an,"runtime",m),d(an,"typeName","yorkie.v1.PresenceChange"),d(an,"fields",m.util.newFieldList(()=>[{no:1,name:"type",kind:"enum",T:m.getEnumType(Dr)},{no:2,name:"presence",kind:"message",T:Fu}]));let co=an;var Dr=(n=>(n[n.UNSPECIFIED=0]="UNSPECIFIED",n[n.PUT=1]="PUT",n[n.DELETE=2]="DELETE",n[n.CLEAR=3]="CLEAR",n))(Dr||{});m.util.setEnumType(Dr,"yorkie.v1.PresenceChange.ChangeType",[{no:0,name:"CHANGE_TYPE_UNSPECIFIED"},{no:1,name:"CHANGE_TYPE_PUT"},{no:2,name:"CHANGE_TYPE_DELETE"},{no:3,name:"CHANGE_TYPE_CLEAR"}]);var Pt;let Fu=(Pt=class extends D{constructor(t){super();d(this,"data",{});m.util.initPartial(t,this)}static fromBinary(t,i){return new Pt().fromBinary(t,i)}static fromJson(t,i){return new Pt().fromJson(t,i)}static fromJsonString(t,i){return new Pt().fromJsonString(t,i)}static equals(t,i){return m.util.equals(Pt,t,i)}},d(Pt,"runtime",m),d(Pt,"typeName","yorkie.v1.Presence"),d(Pt,"fields",m.util.newFieldList(()=>[{no:1,name:"data",kind:"map",K:9,V:{kind:"scalar",T:9}}])),Pt);var At;let Jm=(At=class extends D{constructor(t){super();d(this,"serverSeq",ue.zero);d(this,"clientSeq",0);m.util.initPartial(t,this)}static fromBinary(t,i){return new At().fromBinary(t,i)}static fromJson(t,i){return new At().fromJson(t,i)}static fromJsonString(t,i){return new At().fromJsonString(t,i)}static equals(t,i){return m.util.equals(At,t,i)}},d(At,"runtime",m),d(At,"typeName","yorkie.v1.Checkpoint"),d(At,"fields",m.util.newFieldList(()=>[{no:1,name:"server_seq",kind:"scalar",T:3},{no:2,name:"client_seq",kind:"scalar",T:13}])),At);const ln=class ln extends D{constructor(t){super();d(this,"createdAt");d(this,"offset",0);d(this,"relativeOffset",0);m.util.initPartial(t,this)}static fromBinary(t,i){return new ln().fromBinary(t,i)}static fromJson(t,i){return new ln().fromJson(t,i)}static fromJsonString(t,i){return new ln().fromJsonString(t,i)}static equals(t,i){return m.util.equals(ln,t,i)}};d(ln,"runtime",m),d(ln,"typeName","yorkie.v1.TextNodePos"),d(ln,"fields",m.util.newFieldList(()=>[{no:1,name:"created_at",kind:"message",T:M},{no:2,name:"offset",kind:"scalar",T:5},{no:3,name:"relative_offset",kind:"scalar",T:5}]));let Mn=ln;var $t;let M=($t=class extends D{constructor(t){super();d(this,"lamport",ue.zero);d(this,"delimiter",0);d(this,"actorId",new Uint8Array(0));m.util.initPartial(t,this)}static fromBinary(t,i){return new $t().fromBinary(t,i)}static fromJson(t,i){return new $t().fromJson(t,i)}static fromJsonString(t,i){return new $t().fromJsonString(t,i)}static equals(t,i){return m.util.equals($t,t,i)}},d($t,"runtime",m),d($t,"typeName","yorkie.v1.TimeTicket"),d($t,"fields",m.util.newFieldList(()=>[{no:1,name:"lamport",kind:"scalar",T:3},{no:2,name:"delimiter",kind:"scalar",T:13},{no:3,name:"actor_id",kind:"scalar",T:12}])),$t);const hn=class hn extends D{constructor(t){super();d(this,"topic","");d(this,"payload",new Uint8Array(0));m.util.initPartial(t,this)}static fromBinary(t,i){return new hn().fromBinary(t,i)}static fromJson(t,i){return new hn().fromJson(t,i)}static fromJsonString(t,i){return new hn().fromJsonString(t,i)}static equals(t,i){return m.util.equals(hn,t,i)}};d(hn,"runtime",m),d(hn,"typeName","yorkie.v1.DocEventBody"),d(hn,"fields",m.util.newFieldList(()=>[{no:1,name:"topic",kind:"scalar",T:9},{no:2,name:"payload",kind:"scalar",T:12}]));let bc=hn;const cn=class cn extends D{constructor(t){super();d(this,"type",0);d(this,"publisher","");d(this,"body");m.util.initPartial(t,this)}static fromBinary(t,i){return new cn().fromBinary(t,i)}static fromJson(t,i){return new cn().fromJson(t,i)}static fromJsonString(t,i){return new cn().fromJsonString(t,i)}static equals(t,i){return m.util.equals(cn,t,i)}};d(cn,"runtime",m),d(cn,"typeName","yorkie.v1.DocEvent"),d(cn,"fields",m.util.newFieldList(()=>[{no:1,name:"type",kind:"enum",T:m.getEnumType(Rr)},{no:2,name:"publisher",kind:"scalar",T:9},{no:3,name:"body",kind:"message",T:bc}]));let Sc=cn;const un=class un extends D{constructor(t){super();d(this,"clientKey","");m.util.initPartial(t,this)}static fromBinary(t,i){return new un().fromBinary(t,i)}static fromJson(t,i){return new un().fromJson(t,i)}static fromJsonString(t,i){return new un().fromJsonString(t,i)}static equals(t,i){return m.util.equals(un,t,i)}};d(un,"runtime",m),d(un,"typeName","yorkie.v1.ActivateClientRequest"),d(un,"fields",m.util.newFieldList(()=>[{no:1,name:"client_key",kind:"scalar",T:9}]));let wc=un;const fn=class fn extends D{constructor(t){super();d(this,"clientId","");m.util.initPartial(t,this)}static fromBinary(t,i){return new fn().fromBinary(t,i)}static fromJson(t,i){return new fn().fromJson(t,i)}static fromJsonString(t,i){return new fn().fromJsonString(t,i)}static equals(t,i){return m.util.equals(fn,t,i)}};d(fn,"runtime",m),d(fn,"typeName","yorkie.v1.ActivateClientResponse"),d(fn,"fields",m.util.newFieldList(()=>[{no:1,name:"client_id",kind:"scalar",T:9}]));let vc=fn;const dn=class dn extends D{constructor(t){super();d(this,"clientId","");m.util.initPartial(t,this)}static fromBinary(t,i){return new dn().fromBinary(t,i)}static fromJson(t,i){return new dn().fromJson(t,i)}static fromJsonString(t,i){return new dn().fromJsonString(t,i)}static equals(t,i){return m.util.equals(dn,t,i)}};d(dn,"runtime",m),d(dn,"typeName","yorkie.v1.DeactivateClientRequest"),d(dn,"fields",m.util.newFieldList(()=>[{no:1,name:"client_id",kind:"scalar",T:9}]));let kc=dn;const pn=class pn extends D{constructor(e){super(),m.util.initPartial(e,this)}static fromBinary(e,t){return new pn().fromBinary(e,t)}static fromJson(e,t){return new pn().fromJson(e,t)}static fromJsonString(e,t){return new pn().fromJsonString(e,t)}static equals(e,t){return m.util.equals(pn,e,t)}};d(pn,"runtime",m),d(pn,"typeName","yorkie.v1.DeactivateClientResponse"),d(pn,"fields",m.util.newFieldList(()=>[]));let xc=pn;const gn=class gn extends D{constructor(t){super();d(this,"clientId","");d(this,"changePack");m.util.initPartial(t,this)}static fromBinary(t,i){return new gn().fromBinary(t,i)}static fromJson(t,i){return new gn().fromJson(t,i)}static fromJsonString(t,i){return new gn().fromJsonString(t,i)}static equals(t,i){return m.util.equals(gn,t,i)}};d(gn,"runtime",m),d(gn,"typeName","yorkie.v1.AttachDocumentRequest"),d(gn,"fields",m.util.newFieldList(()=>[{no:1,name:"client_id",kind:"scalar",T:9},{no:2,name:"change_pack",kind:"message",T:Wn}]));let Tc=gn;const mn=class mn extends D{constructor(t){super();d(this,"documentId","");d(this,"changePack");m.util.initPartial(t,this)}static fromBinary(t,i){return new mn().fromBinary(t,i)}static fromJson(t,i){return new mn().fromJson(t,i)}static fromJsonString(t,i){return new mn().fromJsonString(t,i)}static equals(t,i){return m.util.equals(mn,t,i)}};d(mn,"runtime",m),d(mn,"typeName","yorkie.v1.AttachDocumentResponse"),d(mn,"fields",m.util.newFieldList(()=>[{no:1,name:"document_id",kind:"scalar",T:9},{no:2,name:"change_pack",kind:"message",T:Wn}]));let Qc=mn;const On=class On extends D{constructor(t){super();d(this,"clientId","");d(this,"documentId","");d(this,"changePack");d(this,"removeIfNotAttached",!1);m.util.initPartial(t,this)}static fromBinary(t,i){return new On().fromBinary(t,i)}static fromJson(t,i){return new On().fromJson(t,i)}static fromJsonString(t,i){return new On().fromJsonString(t,i)}static equals(t,i){return m.util.equals(On,t,i)}};d(On,"runtime",m),d(On,"typeName","yorkie.v1.DetachDocumentRequest"),d(On,"fields",m.util.newFieldList(()=>[{no:1,name:"client_id",kind:"scalar",T:9},{no:2,name:"document_id",kind:"scalar",T:9},{no:3,name:"change_pack",kind:"message",T:Wn},{no:4,name:"remove_if_not_attached",kind:"scalar",T:8}]));let Pc=On;const yn=class yn extends D{constructor(t){super();d(this,"changePack");m.util.initPartial(t,this)}static fromBinary(t,i){return new yn().fromBinary(t,i)}static fromJson(t,i){return new yn().fromJson(t,i)}static fromJsonString(t,i){return new yn().fromJsonString(t,i)}static equals(t,i){return m.util.equals(yn,t,i)}};d(yn,"runtime",m),d(yn,"typeName","yorkie.v1.DetachDocumentResponse"),d(yn,"fields",m.util.newFieldList(()=>[{no:2,name:"change_pack",kind:"message",T:Wn}]));let Ac=yn;const bn=class bn extends D{constructor(t){super();d(this,"clientId","");d(this,"documentId","");m.util.initPartial(t,this)}static fromBinary(t,i){return new bn().fromBinary(t,i)}static fromJson(t,i){return new bn().fromJson(t,i)}static fromJsonString(t,i){return new bn().fromJsonString(t,i)}static equals(t,i){return m.util.equals(bn,t,i)}};d(bn,"runtime",m),d(bn,"typeName","yorkie.v1.WatchDocumentRequest"),d(bn,"fields",m.util.newFieldList(()=>[{no:1,name:"client_id",kind:"scalar",T:9},{no:2,name:"document_id",kind:"scalar",T:9}]));let $c=bn;const Sn=class Sn extends D{constructor(t){super();d(this,"body",{case:void 0});m.util.initPartial(t,this)}static fromBinary(t,i){return new Sn().fromBinary(t,i)}static fromJson(t,i){return new Sn().fromJson(t,i)}static fromJsonString(t,i){return new Sn().fromJsonString(t,i)}static equals(t,i){return m.util.equals(Sn,t,i)}};d(Sn,"runtime",m),d(Sn,"typeName","yorkie.v1.WatchDocumentResponse"),d(Sn,"fields",m.util.newFieldList(()=>[{no:1,name:"initialization",kind:"message",T:Ic,oneof:"body"},{no:2,name:"event",kind:"message",T:Sc,oneof:"body"}]));let Cc=Sn;const wn=class wn extends D{constructor(t){super();d(this,"clientIds",[]);m.util.initPartial(t,this)}static fromBinary(t,i){return new wn().fromBinary(t,i)}static fromJson(t,i){return new wn().fromJson(t,i)}static fromJsonString(t,i){return new wn().fromJsonString(t,i)}static equals(t,i){return m.util.equals(wn,t,i)}};d(wn,"runtime",m),d(wn,"typeName","yorkie.v1.WatchDocumentResponse.Initialization"),d(wn,"fields",m.util.newFieldList(()=>[{no:1,name:"client_ids",kind:"scalar",T:9,repeated:!0}]));let Ic=wn;const vn=class vn extends D{constructor(t){super();d(this,"clientId","");d(this,"documentId","");d(this,"changePack");m.util.initPartial(t,this)}static fromBinary(t,i){return new vn().fromBinary(t,i)}static fromJson(t,i){return new vn().fromJson(t,i)}static fromJsonString(t,i){return new vn().fromJsonString(t,i)}static equals(t,i){return m.util.equals(vn,t,i)}};d(vn,"runtime",m),d(vn,"typeName","yorkie.v1.RemoveDocumentRequest"),d(vn,"fields",m.util.newFieldList(()=>[{no:1,name:"client_id",kind:"scalar",T:9},{no:2,name:"document_id",kind:"scalar",T:9},{no:3,name:"change_pack",kind:"message",T:Wn}]));let Rc=vn;const kn=class kn extends D{constructor(t){super();d(this,"changePack");m.util.initPartial(t,this)}static fromBinary(t,i){return new kn().fromBinary(t,i)}static fromJson(t,i){return new kn().fromJson(t,i)}static fromJsonString(t,i){return new kn().fromJsonString(t,i)}static equals(t,i){return m.util.equals(kn,t,i)}};d(kn,"runtime",m),d(kn,"typeName","yorkie.v1.RemoveDocumentResponse"),d(kn,"fields",m.util.newFieldList(()=>[{no:1,name:"change_pack",kind:"message",T:Wn}]));let Ec=kn;const xn=class xn extends D{constructor(t){super();d(this,"clientId","");d(this,"documentId","");d(this,"changePack");d(this,"pushOnly",!1);m.util.initPartial(t,this)}static fromBinary(t,i){return new xn().fromBinary(t,i)}static fromJson(t,i){return new xn().fromJson(t,i)}static fromJsonString(t,i){return new xn().fromJsonString(t,i)}static equals(t,i){return m.util.equals(xn,t,i)}};d(xn,"runtime",m),d(xn,"typeName","yorkie.v1.PushPullChangesRequest"),d(xn,"fields",m.util.newFieldList(()=>[{no:1,name:"client_id",kind:"scalar",T:9},{no:2,name:"document_id",kind:"scalar",T:9},{no:3,name:"change_pack",kind:"message",T:Wn},{no:4,name:"push_only",kind:"scalar",T:8}]));let Dc=xn;const Tn=class Tn extends D{constructor(t){super();d(this,"changePack");m.util.initPartial(t,this)}static fromBinary(t,i){return new Tn().fromBinary(t,i)}static fromJson(t,i){return new Tn().fromJson(t,i)}static fromJsonString(t,i){return new Tn().fromJsonString(t,i)}static equals(t,i){return m.util.equals(Tn,t,i)}};d(Tn,"runtime",m),d(Tn,"typeName","yorkie.v1.PushPullChangesResponse"),d(Tn,"fields",m.util.newFieldList(()=>[{no:1,name:"change_pack",kind:"message",T:Wn}]));let Nc=Tn;const Qn=class Qn extends D{constructor(t){super();d(this,"clientId","");d(this,"documentId","");d(this,"topic","");d(this,"payload",new Uint8Array(0));m.util.initPartial(t,this)}static fromBinary(t,i){return new Qn().fromBinary(t,i)}static fromJson(t,i){return new Qn().fromJson(t,i)}static fromJsonString(t,i){return new Qn().fromJsonString(t,i)}static equals(t,i){return m.util.equals(Qn,t,i)}};d(Qn,"runtime",m),d(Qn,"typeName","yorkie.v1.BroadcastRequest"),d(Qn,"fields",m.util.newFieldList(()=>[{no:1,name:"client_id",kind:"scalar",T:9},{no:2,name:"document_id",kind:"scalar",T:9},{no:3,name:"topic",kind:"scalar",T:9},{no:4,name:"payload",kind:"scalar",T:12}]));let Bc=Qn;const Pn=class Pn extends D{constructor(e){super(),m.util.initPartial(e,this)}static fromBinary(e,t){return new Pn().fromBinary(e,t)}static fromJson(e,t){return new Pn().fromJson(e,t)}static fromJsonString(e,t){return new Pn().fromJsonString(e,t)}static equals(e,t){return m.util.equals(Pn,e,t)}};d(Pn,"runtime",m),d(Pn,"typeName","yorkie.v1.BroadcastResponse"),d(Pn,"fields",m.util.newFieldList(()=>[]));let qc=Pn;const L1={typeName:"yorkie.v1.YorkieService",methods:{activateClient:{name:"ActivateClient",I:wc,O:vc,kind:ze.Unary},deactivateClient:{name:"DeactivateClient",I:kc,O:xc,kind:ze.Unary},attachDocument:{name:"AttachDocument",I:Tc,O:Qc,kind:ze.Unary},detachDocument:{name:"DetachDocument",I:Pc,O:Ac,kind:ze.Unary},removeDocument:{name:"RemoveDocument",I:Rc,O:Ec,kind:ze.Unary},pushPullChanges:{name:"PushPullChanges",I:Dc,O:Nc,kind:ze.Unary},watchDocument:{name:"WatchDocument",I:$c,O:Cc,kind:ze.ServerStreaming},broadcast:{name:"Broadcast",I:Bc,O:qc,kind:ze.Unary}}},U1=m.makeMessageType("google.rpc.ErrorInfo",()=>[{no:1,name:"reason",kind:"scalar",T:9},{no:2,name:"domain",kind:"scalar",T:9},{no:3,name:"metadata",kind:"map",K:9,V:{kind:"scalar",T:9}}]);m.makeMessageType("google.rpc.RetryInfo",()=>[{no:1,name:"retry_delay",kind:"message",T:In}]);m.makeMessageType("google.rpc.DebugInfo",()=>[{no:1,name:"stack_entries",kind:"scalar",T:9,repeated:!0},{no:2,name:"detail",kind:"scalar",T:9}]);m.makeMessageType("google.rpc.QuotaFailure",()=>[{no:1,name:"violations",kind:"message",T:Z1,repeated:!0}]);const Z1=m.makeMessageType("google.rpc.QuotaFailure.Violation",()=>[{no:1,name:"subject",kind:"scalar",T:9},{no:2,name:"description",kind:"scalar",T:9}],{localName:"QuotaFailure_Violation"});m.makeMessageType("google.rpc.PreconditionFailure",()=>[{no:1,name:"violations",kind:"message",T:W1,repeated:!0}]);const W1=m.makeMessageType("google.rpc.PreconditionFailure.Violation",()=>[{no:1,name:"type",kind:"scalar",T:9},{no:2,name:"subject",kind:"scalar",T:9},{no:3,name:"description",kind:"scalar",T:9}],{localName:"PreconditionFailure_Violation"});m.makeMessageType("google.rpc.BadRequest",()=>[{no:1,name:"field_violations",kind:"message",T:j1,repeated:!0}]);const j1=m.makeMessageType("google.rpc.BadRequest.FieldViolation",()=>[{no:1,name:"field",kind:"scalar",T:9},{no:2,name:"description",kind:"scalar",T:9}],{localName:"BadRequest_FieldViolation"});m.makeMessageType("google.rpc.RequestInfo",()=>[{no:1,name:"request_id",kind:"scalar",T:9},{no:2,name:"serving_data",kind:"scalar",T:9}]);m.makeMessageType("google.rpc.ResourceInfo",()=>[{no:1,name:"resource_type",kind:"scalar",T:9},{no:2,name:"resource_name",kind:"scalar",T:9},{no:3,name:"owner",kind:"scalar",T:9},{no:4,name:"description",kind:"scalar",T:9}]);m.makeMessageType("google.rpc.Help",()=>[{no:1,name:"links",kind:"message",T:F1,repeated:!0}]);const F1=m.makeMessageType("google.rpc.Help.Link",()=>[{no:1,name:"description",kind:"scalar",T:9},{no:2,name:"url",kind:"scalar",T:9}],{localName:"Help_Link"});m.makeMessageType("google.rpc.LocalizedMessage",()=>[{no:1,name:"locale",kind:"scalar",T:9},{no:2,name:"message",kind:"scalar",T:9}]);var w=(n=>(n.Ok="ok",n.ErrClientNotActivated="ErrClientNotActivated",n.ErrClientNotFound="ErrClientNotFound",n.ErrUnimplemented="ErrUnimplemented",n.ErrInvalidType="ErrInvalidType",n.ErrDummy="ErrDummy",n.ErrDocumentNotAttached="ErrDocumentNotAttached",n.ErrDocumentNotDetached="ErrDocumentNotDetached",n.ErrDocumentRemoved="ErrDocumentRemoved",n.ErrInvalidObjectKey="ErrInvalidObjectKey",n.ErrInvalidArgument="ErrInvalidArgument",n.ErrNotInitialized="ErrNotInitialized",n.ErrNotReady="ErrNotReady",n.ErrRefused="ErrRefused",n.ErrContextNotProvided="ErrContextNotProvided",n))(w||{});class v extends Error{constructor(t,i){super(i);d(this,"name","YorkieError");d(this,"stack");this.code=t,this.message=i,this.toString=()=>`[code=${this.code}]: ${this.message}`}}function Wt(n){if(n instanceof Map){const e=Array.from(n);return new Map(JSON.parse(JSON.stringify(e)))}return JSON.parse(JSON.stringify(n))}const Ym=n=>n?Object.entries(n).length===0:!0,us=n=>{const e={};for(const[t,i]of Object.entries(n))e[t]=JSON.stringify(i);return e},es=n=>{const e={};for(const[t,i]of Object.entries(n))e[t]=JSON.parse(i);return e};var cr=(n=>(n.Put="put",n.Clear="clear",n))(cr||{});class Ph{constructor(e,t){d(this,"context");d(this,"presence");this.context=e,this.presence=t}set(e,t){for(const i of Object.keys(e))this.presence[i]=e[i];this.context.setPresenceChange({type:"put",presence:Wt(this.presence)}),this.context.setReversePresence(e,t)}get(e){return this.presence[e]}clear(){this.presence={},this.context.setPresenceChange({type:"clear"})}}const zu="000000000000000000000000",z1="FFFFFFFFFFFFFFFFFFFFFFFF";class dt{constructor(e,t,i){d(this,"lamport");d(this,"delimiter");d(this,"actorID");this.lamport=e,this.delimiter=t,this.actorID=i}static of(e,t,i){return new dt(e,t,i)}static fromStruct(e){return dt.of(BigInt(e.lamport),e.delimiter,e.actorID)}toIDString(){return`${this.lamport.toString()}:${this.actorID}:${this.delimiter}`}toStruct(){return{lamport:this.getLamportAsString(),delimiter:this.getDelimiter(),actorID:this.getActorID()}}toTestString(){return`${this.lamport.toString()}:${this.actorID.slice(-2)}:${this.delimiter}`}setActor(e){return new dt(this.lamport,this.delimiter,e)}getLamportAsString(){return this.lamport.toString()}getLamport(){return this.lamport}getDelimiter(){return this.delimiter}getActorID(){return this.actorID}after(e){return this.compare(e)>0}equals(e){return this.compare(e)===0}compare(e){if(this.lamport>e.lamport)return 1;if(e.lamport>this.lamport)return-1;const t=this.actorID.localeCompare(e.actorID);return t!==0?t:this.delimiter>e.delimiter?1:e.delimiter>this.delimiter?-1:0}}const Hm=0,_1=4294967295,G1=9223372036854775807n,Gt=new dt(0n,Hm,zu),Ys=new dt(G1,_1,z1);function wi(n){return n.replace(/["'\\\n\r\f\b\t\u2028\u2029]/g,function(e){switch(e){case'"':case"\\":return"\\"+e;case` +`:case"\r":case" ":case" ":continue;default:throw Error("invalid base64 string.")}switch(r){case 0:o=s,r=1;break;case 1:t[i++]=o<<2|(s&48)>>4,o=s,r=2;break;case 2:t[i++]=(o&15)<<4|(s&60)>>2,o=s,r=3;break;case 3:t[i++]=(o&3)<<6|s,r=0;break}}if(r==1)throw Error("invalid base64 string.");return t.subarray(0,i)},enc(n){let e="",t=0,i,r=0;for(let s=0;s>2],r=(i&3)<<4,t=1;break;case 1:e+=Cn[r|i>>4],r=(i&15)<<2,t=2;break;case 2:e+=Cn[r|i>>6],e+=Cn[i&63],t=0;break}return t&&(e+=Cn[r],e+="=",t==1&&(e+="=")),e}};function VS(n,e,t){Im(e,n);const i=e.runtime.bin.makeReadOptions(t),r=MS(n.getType().runtime.bin.listUnknownFields(n),e.field),[s,o]=$m(e);for(const a of r)e.runtime.bin.readField(s,i.readerFactory(a.data),e.field,a.wireType,i);return o()}function XS(n,e,t,i){Im(e,n);const r=e.runtime.bin.makeReadOptions(i),s=e.runtime.bin.makeWriteOptions(i);if(Cm(n,e)){const h=n.getType().runtime.bin.listUnknownFields(n).filter(c=>c.no!=e.field.no);n.getType().runtime.bin.discardUnknownFields(n);for(const c of h)n.getType().runtime.bin.onUnknownField(n,c.no,c.wireType,c.data)}const o=s.writerFactory();let a=e.field;!a.opt&&!a.repeated&&(a.kind=="enum"||a.kind=="scalar")&&(a=Object.assign(Object.assign({},e.field),{opt:!0})),e.runtime.bin.writeField(a,t,o,s);const l=r.readerFactory(o.finish());for(;l.posi.no==e.field.no)}function Im(n,e){Oe(n.extendee.typeName==e.getType().typeName,`extension ${n.typeName} can only be applied to message ${n.extendee.typeName}`)}function Rm(n,e){const t=n.localName;if(n.repeated)return e[t].length>0;if(n.oneof)return e[n.oneof.localName].case===t;switch(n.kind){case"enum":case"scalar":return n.opt||n.req?e[t]!==void 0:n.kind=="enum"?e[t]!==n.T.values[0].no:!Am(n.T,e[t]);case"message":return e[t]!==void 0;case"map":return Object.keys(e[t]).length>0}}function rd(n,e){const t=n.localName,i=!n.opt&&!n.req;if(n.repeated)e[t]=[];else if(n.oneof)e[n.oneof.localName]={case:void 0};else switch(n.kind){case"map":e[t]={};break;case"enum":e[t]=i?n.T.values[0].no:void 0;break;case"scalar":e[t]=i?ls(n.T,n.L):void 0;break;case"message":e[t]=void 0;break}}function Ir(n,e){if(n===null||typeof n!="object"||!Object.getOwnPropertyNames(D.prototype).every(i=>i in n&&typeof n[i]=="function"))return!1;const t=n.getType();return t===null||typeof t!="function"||!("typeName"in t)||typeof t.typeName!="string"?!1:e===void 0?!0:t.typeName==e.typeName}function Em(n,e){return Ir(e)||!n.fieldWrapper?e:n.fieldWrapper.wrapField(e)}T.DOUBLE,T.FLOAT,T.INT64,T.UINT64,T.INT32,T.UINT32,T.BOOL,T.STRING,T.BYTES;const sd={ignoreUnknownFields:!1},od={emitDefaultValues:!1,enumAsInteger:!1,useProtoFieldName:!1,prettySpaces:0};function LS(n){return n?Object.assign(Object.assign({},sd),n):sd}function US(n){return n?Object.assign(Object.assign({},od),n):od}const Ka=Symbol(),Da=Symbol();function ZS(){return{makeReadOptions:LS,makeWriteOptions:US,readMessage(n,e,t,i){if(e==null||Array.isArray(e)||typeof e!="object")throw new Error(`cannot decode message ${n.typeName} from JSON: ${hi(e)}`);i=i??new n;const r=new Map,s=t.typeRegistry;for(const[o,a]of Object.entries(e)){const l=n.fields.findJsonName(o);if(l){if(l.oneof){if(a===null&&l.kind=="scalar")continue;const h=r.get(l.oneof);if(h!==void 0)throw new Error(`cannot decode message ${n.typeName} from JSON: multiple keys for oneof "${l.oneof.name}" present: "${h}", "${o}"`);r.set(l.oneof,o)}ad(i,a,l,t,n)}else{let h=!1;if(s!=null&&s.findExtension&&o.startsWith("[")&&o.endsWith("]")){const c=s.findExtension(o.substring(1,o.length-1));if(c&&c.extendee.typeName==n.typeName){h=!0;const[u,f]=$m(c);ad(u,a,c.field,t,c),XS(i,c,f(),t)}}if(!h&&!t.ignoreUnknownFields)throw new Error(`cannot decode message ${n.typeName} from JSON: key "${o}" is unknown`)}}return i},writeMessage(n,e){const t=n.getType(),i={};let r;try{for(r of t.fields.byNumber()){if(!Rm(r,n)){if(r.req)throw"required field not set";if(!e.emitDefaultValues||!jS(r))continue}const o=r.oneof?n[r.oneof.localName].value:n[r.localName],a=ld(r,o,e);a!==void 0&&(i[e.useProtoFieldName?r.name:r.jsonName]=a)}const s=e.typeRegistry;if(s!=null&&s.findExtensionFor)for(const o of t.runtime.bin.listUnknownFields(n)){const a=s.findExtensionFor(t.typeName,o.no);if(a&&Cm(n,a)){const l=VS(n,a,e),h=ld(a.field,l,e);h!==void 0&&(i[a.field.jsonName]=h)}}}catch(s){const o=r?`cannot encode field ${t.typeName}.${r.name} to JSON`:`cannot encode message ${t.typeName} to JSON`,a=s instanceof Error?s.message:String(s);throw new Error(o+(a.length>0?`: ${a}`:""))}return i},readScalar(n,e,t){return Gs(n,e,t??hr.BIGINT,!0)},writeScalar(n,e,t){if(e!==void 0&&(t||Am(n,e)))return Na(n,e)},debug:hi}}function hi(n){if(n===null)return"null";switch(typeof n){case"object":return Array.isArray(n)?"array":"object";case"string":return n.length>100?"string":`"${n.split('"').join('\\"')}"`;default:return String(n)}}function ad(n,e,t,i,r){let s=t.localName;if(t.repeated){if(Oe(t.kind!="map"),e===null)return;if(!Array.isArray(e))throw new Error(`cannot decode field ${r.typeName}.${t.name} from JSON: ${hi(e)}`);const o=n[s];for(const a of e){if(a===null)throw new Error(`cannot decode field ${r.typeName}.${t.name} from JSON: ${hi(a)}`);switch(t.kind){case"message":o.push(t.T.fromJson(a,i));break;case"enum":const l=xh(t.T,a,i.ignoreUnknownFields,!0);l!==Da&&o.push(l);break;case"scalar":try{o.push(Gs(t.T,a,t.L,!0))}catch(h){let c=`cannot decode field ${r.typeName}.${t.name} from JSON: ${hi(a)}`;throw h instanceof Error&&h.message.length>0&&(c+=`: ${h.message}`),new Error(c)}break}}}else if(t.kind=="map"){if(e===null)return;if(typeof e!="object"||Array.isArray(e))throw new Error(`cannot decode field ${r.typeName}.${t.name} from JSON: ${hi(e)}`);const o=n[s];for(const[a,l]of Object.entries(e)){if(l===null)throw new Error(`cannot decode field ${r.typeName}.${t.name} from JSON: map value null`);let h;try{h=WS(t.K,a)}catch(c){let u=`cannot decode map key for field ${r.typeName}.${t.name} from JSON: ${hi(e)}`;throw c instanceof Error&&c.message.length>0&&(u+=`: ${c.message}`),new Error(u)}switch(t.V.kind){case"message":o[h]=t.V.T.fromJson(l,i);break;case"enum":const c=xh(t.V.T,l,i.ignoreUnknownFields,!0);c!==Da&&(o[h]=c);break;case"scalar":try{o[h]=Gs(t.V.T,l,hr.BIGINT,!0)}catch(u){let f=`cannot decode map value for field ${r.typeName}.${t.name} from JSON: ${hi(e)}`;throw u instanceof Error&&u.message.length>0&&(f+=`: ${u.message}`),new Error(f)}break}}}else switch(t.oneof&&(n=n[t.oneof.localName]={case:s},s="value"),t.kind){case"message":const o=t.T;if(e===null&&o.typeName!="google.protobuf.Value")return;let a=n[s];Ir(a)?a.fromJson(e,i):(n[s]=a=o.fromJson(e,i),o.fieldWrapper&&!t.oneof&&(n[s]=o.fieldWrapper.unwrapField(a)));break;case"enum":const l=xh(t.T,e,i.ignoreUnknownFields,!1);switch(l){case Ka:rd(t,n);break;case Da:break;default:n[s]=l;break}break;case"scalar":try{const h=Gs(t.T,e,t.L,!1);switch(h){case Ka:rd(t,n);break;default:n[s]=h;break}}catch(h){let c=`cannot decode field ${r.typeName}.${t.name} from JSON: ${hi(e)}`;throw h instanceof Error&&h.message.length>0&&(c+=`: ${h.message}`),new Error(c)}break}}function WS(n,e){if(n===T.BOOL)switch(e){case"true":e=!0;break;case"false":e=!1;break}return Gs(n,e,hr.BIGINT,!0).toString()}function Gs(n,e,t,i){if(e===null)return i?ls(n,t):Ka;switch(n){case T.DOUBLE:case T.FLOAT:if(e==="NaN")return Number.NaN;if(e==="Infinity")return Number.POSITIVE_INFINITY;if(e==="-Infinity")return Number.NEGATIVE_INFINITY;if(e===""||typeof e=="string"&&e.trim().length!==e.length||typeof e!="string"&&typeof e!="number")break;const r=Number(e);if(Number.isNaN(r)||!Number.isFinite(r))break;return n==T.FLOAT&&wm(r),r;case T.INT32:case T.FIXED32:case T.SFIXED32:case T.SINT32:case T.UINT32:let s;if(typeof e=="number"?s=e:typeof e=="string"&&e.length>0&&e.trim().length===e.length&&(s=Number(e)),s===void 0)break;return n==T.UINT32||n==T.FIXED32?pc(s):Ra(s),s;case T.INT64:case T.SFIXED64:case T.SINT64:if(typeof e!="number"&&typeof e!="string")break;const o=ue.parse(e);return t?o.toString():o;case T.FIXED64:case T.UINT64:if(typeof e!="number"&&typeof e!="string")break;const a=ue.uParse(e);return t?a.toString():a;case T.BOOL:if(typeof e!="boolean")break;return e;case T.STRING:if(typeof e!="string")break;try{encodeURIComponent(e)}catch{throw new Error("invalid UTF8")}return e;case T.BYTES:if(e==="")return new Uint8Array(0);if(typeof e!="string")break;return Zu.dec(e)}throw new Error}function xh(n,e,t,i){if(e===null)return n.typeName=="google.protobuf.NullValue"?0:i?n.values[0].no:Ka;switch(typeof e){case"number":if(Number.isInteger(e))return e;break;case"string":const r=n.findName(e);if(r!==void 0)return r.no;if(t)return Da;break}throw new Error(`cannot decode enum ${n.typeName} from JSON: ${hi(e)}`)}function jS(n){return n.repeated||n.kind=="map"?!0:!(n.oneof||n.kind=="message"||n.opt||n.req)}function ld(n,e,t){if(n.kind=="map"){Oe(typeof e=="object"&&e!=null);const i={},r=Object.entries(e);switch(n.V.kind){case"scalar":for(const[o,a]of r)i[o.toString()]=Na(n.V.T,a);break;case"message":for(const[o,a]of r)i[o.toString()]=a.toJson(t);break;case"enum":const s=n.V.T;for(const[o,a]of r)i[o.toString()]=Th(s,a,t.enumAsInteger);break}return t.emitDefaultValues||r.length>0?i:void 0}if(n.repeated){Oe(Array.isArray(e));const i=[];switch(n.kind){case"scalar":for(let r=0;r0?i:void 0}switch(n.kind){case"scalar":return Na(n.T,e);case"enum":return Th(n.T,e,t.enumAsInteger);case"message":return Em(n.T,e).toJson(t)}}function Th(n,e,t){var i;if(Oe(typeof e=="number"),n.typeName=="google.protobuf.NullValue")return null;if(t)return e;const r=n.findNumber(e);return(i=r==null?void 0:r.name)!==null&&i!==void 0?i:e}function Na(n,e){switch(n){case T.INT32:case T.SFIXED32:case T.SINT32:case T.FIXED32:case T.UINT32:return Oe(typeof e=="number"),e;case T.FLOAT:case T.DOUBLE:return Oe(typeof e=="number"),Number.isNaN(e)?"NaN":e===Number.POSITIVE_INFINITY?"Infinity":e===Number.NEGATIVE_INFINITY?"-Infinity":e;case T.STRING:return Oe(typeof e=="string"),e;case T.BOOL:return Oe(typeof e=="boolean"),e;case T.UINT64:case T.FIXED64:case T.INT64:case T.SFIXED64:case T.SINT64:return Oe(typeof e=="bigint"||typeof e=="string"||typeof e=="number"),e.toString();case T.BYTES:return Oe(e instanceof Uint8Array),Zu.enc(e)}}const Zr=Symbol("@bufbuild/protobuf/unknown-fields"),hd={readUnknownFields:!0,readerFactory:n=>new NS(n)},cd={writeUnknownFields:!0,writerFactory:()=>new DS};function FS(n){return n?Object.assign(Object.assign({},hd),n):hd}function zS(n){return n?Object.assign(Object.assign({},cd),n):cd}function _S(){return{makeReadOptions:FS,makeWriteOptions:zS,listUnknownFields(n){var e;return(e=n[Zr])!==null&&e!==void 0?e:[]},discardUnknownFields(n){delete n[Zr]},writeUnknownFields(n,e){const i=n[Zr];if(i)for(const r of i)e.tag(r.no,r.wireType).raw(r.data)},onUnknownField(n,e,t,i){const r=n;Array.isArray(r[Zr])||(r[Zr]=[]),r[Zr].push({no:e,wireType:t,data:i})},readMessage(n,e,t,i,r){const s=n.getType(),o=r?e.len:e.pos+t;let a,l;for(;e.pos0&&(l=JS),s){let f=n[o];if(i==ve.LengthDelimited&&a!=T.STRING&&a!=T.BYTES){let g=e.uint32()+e.pos;for(;e.posIr(f,u)?f:new u(f));else{const f=o[r];u.fieldWrapper?u.typeName==="google.protobuf.BytesValue"?s[r]=Rs(f):s[r]=f:s[r]=Ir(f,u)?f:new u(f)}break}}},equals(n,e,t){return e===t?!0:!e||!t?!1:n.fields.byMember().every(i=>{const r=e[i.localName],s=t[i.localName];if(i.repeated){if(r.length!==s.length)return!1;switch(i.kind){case"message":return r.every((o,a)=>i.T.equals(o,s[a]));case"scalar":return r.every((o,a)=>Fn(i.T,o,s[a]));case"enum":return r.every((o,a)=>Fn(T.INT32,o,s[a]))}throw new Error(`repeated cannot contain ${i.kind}`)}switch(i.kind){case"message":return i.T.equals(r,s);case"enum":return Fn(T.INT32,r,s);case"scalar":return Fn(i.T,r,s);case"oneof":if(r.case!==s.case)return!1;const o=i.findField(r.case);if(o===void 0)return!0;switch(o.kind){case"message":return o.T.equals(r.value,s.value);case"enum":return Fn(T.INT32,r.value,s.value);case"scalar":return Fn(o.T,r.value,s.value)}throw new Error(`oneof cannot contain ${o.kind}`);case"map":const a=Object.keys(r).concat(Object.keys(s));switch(i.V.kind){case"message":const l=i.V.T;return a.every(c=>l.equals(r[c],s[c]));case"enum":return a.every(c=>Fn(T.INT32,r[c],s[c]));case"scalar":const h=i.V.T;return a.every(c=>Fn(h,r[c],s[c]))}break}})},clone(n){const e=n.getType(),t=new e,i=t;for(const r of e.fields.byMember()){const s=n[r.localName];let o;if(r.repeated)o=s.map(Ko);else if(r.kind=="map"){o=i[r.localName];for(const[a,l]of Object.entries(s))o[a]=Ko(l)}else r.kind=="oneof"?o=r.findField(s.case)?{case:s.case,value:Ko(s.value)}:{case:void 0}:o=Ko(s);i[r.localName]=o}for(const r of e.runtime.bin.listUnknownFields(n))e.runtime.bin.onUnknownField(i,r.no,r.wireType,r.data);return t}}}function Ko(n){if(n===void 0)return n;if(Ir(n))return n.clone();if(n instanceof Uint8Array){const e=new Uint8Array(n.byteLength);return e.set(n),e}return n}function Rs(n){return n instanceof Uint8Array?n:new Uint8Array(n)}function e1(n,e,t){return{syntax:n,json:ZS(),bin:_S(),util:Object.assign(Object.assign({},KS()),{newFieldList:e,initFields:t}),makeMessageType(i,r,s){return AS(this,i,r,s)},makeEnum:PS,makeEnumType:xm,getEnumType:QS,makeExtension(i,r,s){return BS(this,i,r,s)}}}class t1{constructor(e,t){this._fields=e,this._normalizer=t}findJsonName(e){if(!this.jsonNames){const t={};for(const i of this.list())t[i.jsonName]=t[i.name]=i;this.jsonNames=t}return this.jsonNames[e]}find(e){if(!this.numbers){const t={};for(const i of this.list())t[i.no]=i;this.numbers=t}return this.numbers[e]}list(){return this.all||(this.all=this._normalizer(this._fields)),this.all}byNumber(){return this.numbersAsc||(this.numbersAsc=this.list().concat().sort((e,t)=>e.no-t.no)),this.numbersAsc}byMember(){if(!this.members){this.members=[];const e=this.members;let t;for(const i of this.list())i.oneof?i.oneof!==t&&(t=i.oneof,e.push(t)):e.push(i)}return this.members}}function Nm(n,e){const t=Bm(n);return e?t:a1(o1(t))}function i1(n){return Nm(n,!1)}const n1=Bm;function Bm(n){let e=!1;const t=[];for(let i=0;i`${n}$`,o1=n=>s1.has(n)?qm(n):n,a1=n=>r1.has(n)?qm(n):n;class l1{constructor(e){this.kind="oneof",this.repeated=!1,this.packed=!1,this.opt=!1,this.req=!1,this.default=void 0,this.fields=[],this.name=e,this.localName=i1(e)}addField(e){Oe(e.oneof===this,`field ${e.name} not one of ${this.name}`),this.fields.push(e)}findField(e){if(!this._lookup){this._lookup=Object.create(null);for(let t=0;tnew t1(n,e=>h1(e)),n=>{for(const e of n.getType().fields.byMember()){if(e.opt)continue;const t=e.localName,i=n;if(e.repeated){i[t]=[];continue}switch(e.kind){case"oneof":i[t]={case:void 0};break;case"enum":i[t]=0;break;case"map":i[t]={};break;case"scalar":i[t]=ls(e.T,e.L);break}}});var ze;(function(n){n[n.Unary=0]="Unary",n[n.ServerStreaming=1]="ServerStreaming",n[n.ClientStreaming=2]="ClientStreaming",n[n.BiDiStreaming=3]="BiDiStreaming"})(ze||(ze={}));var pd;(function(n){n[n.NoSideEffects=1]="NoSideEffects",n[n.Idempotent=2]="Idempotent"})(pd||(pd={}));class Ue extends D{constructor(e){super(),this.seconds=ue.zero,this.nanos=0,m.util.initPartial(e,this)}fromJson(e,t){if(typeof e!="string")throw new Error(`cannot decode google.protobuf.Timestamp from JSON: ${m.json.debug(e)}`);const i=e.match(/^([0-9]{4})-([0-9]{2})-([0-9]{2})T([0-9]{2}):([0-9]{2}):([0-9]{2})(?:Z|\.([0-9]{3,9})Z|([+-][0-9][0-9]:[0-9][0-9]))$/);if(!i)throw new Error("cannot decode google.protobuf.Timestamp from JSON: invalid RFC 3339 string");const r=Date.parse(i[1]+"-"+i[2]+"-"+i[3]+"T"+i[4]+":"+i[5]+":"+i[6]+(i[8]?i[8]:"Z"));if(Number.isNaN(r))throw new Error("cannot decode google.protobuf.Timestamp from JSON: invalid RFC 3339 string");if(rDate.parse("9999-12-31T23:59:59Z"))throw new Error("cannot decode message google.protobuf.Timestamp from JSON: must be from 0001-01-01T00:00:00Z to 9999-12-31T23:59:59Z inclusive");return this.seconds=ue.parse(r/1e3),this.nanos=0,i[7]&&(this.nanos=parseInt("1"+i[7]+"0".repeat(9-i[7].length))-1e9),this}toJson(e){const t=Number(this.seconds)*1e3;if(tDate.parse("9999-12-31T23:59:59Z"))throw new Error("cannot encode google.protobuf.Timestamp to JSON: must be from 0001-01-01T00:00:00Z to 9999-12-31T23:59:59Z inclusive");if(this.nanos<0)throw new Error("cannot encode google.protobuf.Timestamp to JSON: nanos must not be negative");let i="Z";if(this.nanos>0){const r=(this.nanos+1e9).toString().substring(1);r.substring(3)==="000000"?i="."+r.substring(0,3)+"Z":r.substring(6)==="000"?i="."+r.substring(0,6)+"Z":i="."+r+"Z"}return new Date(t).toISOString().replace(".000Z",i)}toDate(){return new Date(Number(this.seconds)*1e3+Math.ceil(this.nanos/1e6))}static now(){return Ue.fromDate(new Date)}static fromDate(e){const t=e.getTime();return new Ue({seconds:ue.parse(Math.floor(t/1e3)),nanos:t%1e3*1e6})}static fromBinary(e,t){return new Ue().fromBinary(e,t)}static fromJson(e,t){return new Ue().fromJson(e,t)}static fromJsonString(e,t){return new Ue().fromJsonString(e,t)}static equals(e,t){return m.util.equals(Ue,e,t)}}Ue.runtime=m;Ue.typeName="google.protobuf.Timestamp";Ue.fields=m.util.newFieldList(()=>[{no:1,name:"seconds",kind:"scalar",T:3},{no:2,name:"nanos",kind:"scalar",T:5}]);class In extends D{constructor(e){super(),this.seconds=ue.zero,this.nanos=0,m.util.initPartial(e,this)}fromJson(e,t){if(typeof e!="string")throw new Error(`cannot decode google.protobuf.Duration from JSON: ${m.json.debug(e)}`);const i=e.match(/^(-?[0-9]+)(?:\.([0-9]+))?s/);if(i===null)throw new Error(`cannot decode google.protobuf.Duration from JSON: ${m.json.debug(e)}`);const r=Number(i[1]);if(r>315576e6||r<-315576e6)throw new Error(`cannot decode google.protobuf.Duration from JSON: ${m.json.debug(e)}`);if(this.seconds=ue.parse(r),typeof i[2]=="string"){const s=i[2]+"0".repeat(9-i[2].length);this.nanos=parseInt(s),(r<0||Object.is(r,-0))&&(this.nanos=-this.nanos)}return this}toJson(e){if(Number(this.seconds)>315576e6||Number(this.seconds)<-315576e6)throw new Error("cannot encode google.protobuf.Duration to JSON: value out of range");let t=this.seconds.toString();if(this.nanos!==0){let i=Math.abs(this.nanos).toString();i="0".repeat(9-i.length)+i,i.substring(3)==="000000"?i=i.substring(0,3):i.substring(6)==="000"&&(i=i.substring(0,6)),t+="."+i,this.nanos<0&&Number(this.seconds)==0&&(t="-"+t)}return t+"s"}static fromBinary(e,t){return new In().fromBinary(e,t)}static fromJson(e,t){return new In().fromJson(e,t)}static fromJsonString(e,t){return new In().fromJsonString(e,t)}static equals(e,t){return m.util.equals(In,e,t)}}In.runtime=m;In.typeName="google.protobuf.Duration";In.fields=m.util.newFieldList(()=>[{no:1,name:"seconds",kind:"scalar",T:3},{no:2,name:"nanos",kind:"scalar",T:5}]);class ci extends D{constructor(e){super(),this.typeUrl="",this.value=new Uint8Array(0),m.util.initPartial(e,this)}toJson(e){var t;if(this.typeUrl==="")return{};const i=this.typeUrlToName(this.typeUrl),r=(t=e==null?void 0:e.typeRegistry)===null||t===void 0?void 0:t.findMessage(i);if(!r)throw new Error(`cannot encode message google.protobuf.Any to JSON: "${this.typeUrl}" is not in the type registry`);let o=r.fromBinary(this.value).toJson(e);return(i.startsWith("google.protobuf.")||o===null||Array.isArray(o)||typeof o!="object")&&(o={value:o}),o["@type"]=this.typeUrl,o}fromJson(e,t){var i;if(e===null||Array.isArray(e)||typeof e!="object")throw new Error(`cannot decode message google.protobuf.Any from JSON: expected object but got ${e===null?"null":Array.isArray(e)?"array":typeof e}`);if(Object.keys(e).length==0)return this;const r=e["@type"];if(typeof r!="string"||r=="")throw new Error('cannot decode message google.protobuf.Any from JSON: "@type" is empty');const s=this.typeUrlToName(r),o=(i=t==null?void 0:t.typeRegistry)===null||i===void 0?void 0:i.findMessage(s);if(!o)throw new Error(`cannot decode message google.protobuf.Any from JSON: ${r} is not in the type registry`);let a;if(s.startsWith("google.protobuf.")&&Object.prototype.hasOwnProperty.call(e,"value"))a=o.fromJson(e.value,t);else{const l=Object.assign({},e);delete l["@type"],a=o.fromJson(l,t)}return this.packFrom(a),this}packFrom(e){this.value=e.toBinary(),this.typeUrl=this.typeNameToUrl(e.getType().typeName)}unpackTo(e){return this.is(e.getType())?(e.fromBinary(this.value),!0):!1}unpack(e){if(this.typeUrl==="")return;const t=e.findMessage(this.typeUrlToName(this.typeUrl));if(t)return t.fromBinary(this.value)}is(e){if(this.typeUrl==="")return!1;const t=this.typeUrlToName(this.typeUrl);let i="";return typeof e=="string"?i=e:i=e.typeName,t===i}typeNameToUrl(e){return`type.googleapis.com/${e}`}typeUrlToName(e){if(!e.length)throw new Error(`invalid type url: ${e}`);const t=e.lastIndexOf("/"),i=t>=0?e.substring(t+1):e;if(!i.length)throw new Error(`invalid type url: ${e}`);return i}static pack(e){const t=new ci;return t.packFrom(e),t}static fromBinary(e,t){return new ci().fromBinary(e,t)}static fromJson(e,t){return new ci().fromJson(e,t)}static fromJsonString(e,t){return new ci().fromJsonString(e,t)}static equals(e,t){return m.util.equals(ci,e,t)}}ci.runtime=m;ci.typeName="google.protobuf.Any";ci.fields=m.util.newFieldList(()=>[{no:1,name:"type_url",kind:"scalar",T:9},{no:2,name:"value",kind:"scalar",T:12}]);class di extends D{constructor(e){super(),this.value=0,m.util.initPartial(e,this)}toJson(e){return m.json.writeScalar(T.DOUBLE,this.value,!0)}fromJson(e,t){try{this.value=m.json.readScalar(T.DOUBLE,e)}catch(i){let r='cannot decode message google.protobuf.DoubleValue from JSON"';throw i instanceof Error&&i.message.length>0&&(r+=`: ${i.message}`),new Error(r)}return this}static fromBinary(e,t){return new di().fromBinary(e,t)}static fromJson(e,t){return new di().fromJson(e,t)}static fromJsonString(e,t){return new di().fromJsonString(e,t)}static equals(e,t){return m.util.equals(di,e,t)}}di.runtime=m;di.typeName="google.protobuf.DoubleValue";di.fields=m.util.newFieldList(()=>[{no:1,name:"value",kind:"scalar",T:1}]);di.fieldWrapper={wrapField(n){return new di({value:n})},unwrapField(n){return n.value}};class pi extends D{constructor(e){super(),this.value=0,m.util.initPartial(e,this)}toJson(e){return m.json.writeScalar(T.FLOAT,this.value,!0)}fromJson(e,t){try{this.value=m.json.readScalar(T.FLOAT,e)}catch(i){let r='cannot decode message google.protobuf.FloatValue from JSON"';throw i instanceof Error&&i.message.length>0&&(r+=`: ${i.message}`),new Error(r)}return this}static fromBinary(e,t){return new pi().fromBinary(e,t)}static fromJson(e,t){return new pi().fromJson(e,t)}static fromJsonString(e,t){return new pi().fromJsonString(e,t)}static equals(e,t){return m.util.equals(pi,e,t)}}pi.runtime=m;pi.typeName="google.protobuf.FloatValue";pi.fields=m.util.newFieldList(()=>[{no:1,name:"value",kind:"scalar",T:2}]);pi.fieldWrapper={wrapField(n){return new pi({value:n})},unwrapField(n){return n.value}};class gi extends D{constructor(e){super(),this.value=ue.zero,m.util.initPartial(e,this)}toJson(e){return m.json.writeScalar(T.INT64,this.value,!0)}fromJson(e,t){try{this.value=m.json.readScalar(T.INT64,e)}catch(i){let r='cannot decode message google.protobuf.Int64Value from JSON"';throw i instanceof Error&&i.message.length>0&&(r+=`: ${i.message}`),new Error(r)}return this}static fromBinary(e,t){return new gi().fromBinary(e,t)}static fromJson(e,t){return new gi().fromJson(e,t)}static fromJsonString(e,t){return new gi().fromJsonString(e,t)}static equals(e,t){return m.util.equals(gi,e,t)}}gi.runtime=m;gi.typeName="google.protobuf.Int64Value";gi.fields=m.util.newFieldList(()=>[{no:1,name:"value",kind:"scalar",T:3}]);gi.fieldWrapper={wrapField(n){return new gi({value:n})},unwrapField(n){return n.value}};class mi extends D{constructor(e){super(),this.value=ue.zero,m.util.initPartial(e,this)}toJson(e){return m.json.writeScalar(T.UINT64,this.value,!0)}fromJson(e,t){try{this.value=m.json.readScalar(T.UINT64,e)}catch(i){let r='cannot decode message google.protobuf.UInt64Value from JSON"';throw i instanceof Error&&i.message.length>0&&(r+=`: ${i.message}`),new Error(r)}return this}static fromBinary(e,t){return new mi().fromBinary(e,t)}static fromJson(e,t){return new mi().fromJson(e,t)}static fromJsonString(e,t){return new mi().fromJsonString(e,t)}static equals(e,t){return m.util.equals(mi,e,t)}}mi.runtime=m;mi.typeName="google.protobuf.UInt64Value";mi.fields=m.util.newFieldList(()=>[{no:1,name:"value",kind:"scalar",T:4}]);mi.fieldWrapper={wrapField(n){return new mi({value:n})},unwrapField(n){return n.value}};class Oi extends D{constructor(e){super(),this.value=0,m.util.initPartial(e,this)}toJson(e){return m.json.writeScalar(T.INT32,this.value,!0)}fromJson(e,t){try{this.value=m.json.readScalar(T.INT32,e)}catch(i){let r='cannot decode message google.protobuf.Int32Value from JSON"';throw i instanceof Error&&i.message.length>0&&(r+=`: ${i.message}`),new Error(r)}return this}static fromBinary(e,t){return new Oi().fromBinary(e,t)}static fromJson(e,t){return new Oi().fromJson(e,t)}static fromJsonString(e,t){return new Oi().fromJsonString(e,t)}static equals(e,t){return m.util.equals(Oi,e,t)}}Oi.runtime=m;Oi.typeName="google.protobuf.Int32Value";Oi.fields=m.util.newFieldList(()=>[{no:1,name:"value",kind:"scalar",T:5}]);Oi.fieldWrapper={wrapField(n){return new Oi({value:n})},unwrapField(n){return n.value}};class yi extends D{constructor(e){super(),this.value=0,m.util.initPartial(e,this)}toJson(e){return m.json.writeScalar(T.UINT32,this.value,!0)}fromJson(e,t){try{this.value=m.json.readScalar(T.UINT32,e)}catch(i){let r='cannot decode message google.protobuf.UInt32Value from JSON"';throw i instanceof Error&&i.message.length>0&&(r+=`: ${i.message}`),new Error(r)}return this}static fromBinary(e,t){return new yi().fromBinary(e,t)}static fromJson(e,t){return new yi().fromJson(e,t)}static fromJsonString(e,t){return new yi().fromJsonString(e,t)}static equals(e,t){return m.util.equals(yi,e,t)}}yi.runtime=m;yi.typeName="google.protobuf.UInt32Value";yi.fields=m.util.newFieldList(()=>[{no:1,name:"value",kind:"scalar",T:13}]);yi.fieldWrapper={wrapField(n){return new yi({value:n})},unwrapField(n){return n.value}};class bi extends D{constructor(e){super(),this.value=!1,m.util.initPartial(e,this)}toJson(e){return m.json.writeScalar(T.BOOL,this.value,!0)}fromJson(e,t){try{this.value=m.json.readScalar(T.BOOL,e)}catch(i){let r='cannot decode message google.protobuf.BoolValue from JSON"';throw i instanceof Error&&i.message.length>0&&(r+=`: ${i.message}`),new Error(r)}return this}static fromBinary(e,t){return new bi().fromBinary(e,t)}static fromJson(e,t){return new bi().fromJson(e,t)}static fromJsonString(e,t){return new bi().fromJsonString(e,t)}static equals(e,t){return m.util.equals(bi,e,t)}}bi.runtime=m;bi.typeName="google.protobuf.BoolValue";bi.fields=m.util.newFieldList(()=>[{no:1,name:"value",kind:"scalar",T:8}]);bi.fieldWrapper={wrapField(n){return new bi({value:n})},unwrapField(n){return n.value}};class ct extends D{constructor(e){super(),this.value="",m.util.initPartial(e,this)}toJson(e){return m.json.writeScalar(T.STRING,this.value,!0)}fromJson(e,t){try{this.value=m.json.readScalar(T.STRING,e)}catch(i){let r='cannot decode message google.protobuf.StringValue from JSON"';throw i instanceof Error&&i.message.length>0&&(r+=`: ${i.message}`),new Error(r)}return this}static fromBinary(e,t){return new ct().fromBinary(e,t)}static fromJson(e,t){return new ct().fromJson(e,t)}static fromJsonString(e,t){return new ct().fromJsonString(e,t)}static equals(e,t){return m.util.equals(ct,e,t)}}ct.runtime=m;ct.typeName="google.protobuf.StringValue";ct.fields=m.util.newFieldList(()=>[{no:1,name:"value",kind:"scalar",T:9}]);ct.fieldWrapper={wrapField(n){return new ct({value:n})},unwrapField(n){return n.value}};class Si extends D{constructor(e){super(),this.value=new Uint8Array(0),m.util.initPartial(e,this)}toJson(e){return m.json.writeScalar(T.BYTES,this.value,!0)}fromJson(e,t){try{this.value=m.json.readScalar(T.BYTES,e)}catch(i){let r='cannot decode message google.protobuf.BytesValue from JSON"';throw i instanceof Error&&i.message.length>0&&(r+=`: ${i.message}`),new Error(r)}return this}static fromBinary(e,t){return new Si().fromBinary(e,t)}static fromJson(e,t){return new Si().fromJson(e,t)}static fromJsonString(e,t){return new Si().fromJsonString(e,t)}static equals(e,t){return m.util.equals(Si,e,t)}}Si.runtime=m;Si.typeName="google.protobuf.BytesValue";Si.fields=m.util.newFieldList(()=>[{no:1,name:"value",kind:"scalar",T:12}]);Si.fieldWrapper={wrapField(n){return new Si({value:n})},unwrapField(n){return n.value}};function c1(n,e,t){try{const i=Zu.dec(n);return e?e.fromBinary(i,t):i}catch(i){throw Te.from(i,ie.DataLoss)}}function u1(n,e){const t={};for(const[i,r]of Object.entries(n.methods)){const s=e(Object.assign(Object.assign({},r),{localName:i,service:n}));s!=null&&(t[i]=s)}return t}function gd(n){let e,t=new Uint8Array(0);function i(r){const s=new Uint8Array(t.length+r.length);s.set(t),s.set(r,t.length),t=s}return new ReadableStream({start(){e=n.getReader()},async pull(r){let s;for(;;){if(s===void 0&&t.byteLength>=5){let l=0;for(let h=1;h<5;h++)l=(l<<8)+t[h];s={flags:t[0],length:l}}if(s!==void 0&&t.byteLength>=s.length+5)break;const a=await e.read();if(a.done)break;i(a.value)}if(s===void 0){if(t.byteLength==0){r.close();return}r.error(new Te("premature end of stream",ie.DataLoss));return}const o=t.subarray(5,5+s.length);t=t.subarray(5+s.length),r.enqueue({flags:s.flags,data:o})}})}function md(n,e){const t=new Uint8Array(e.length+5);t.set(e,5);const i=new DataView(t.buffer,t.byteOffset,t.byteLength);return i.setUint8(0,n),i.setUint32(1,e.length),t}var f1=function(n){if(!Symbol.asyncIterator)throw new TypeError("Symbol.asyncIterator is not defined.");var e=n[Symbol.asyncIterator],t;return e?e.call(n):(n=typeof __values=="function"?__values(n):n[Symbol.iterator](),t={},i("next"),i("throw"),i("return"),t[Symbol.asyncIterator]=function(){return this},t);function i(s){t[s]=n[s]&&function(o){return new Promise(function(a,l){o=n[s](o),r(a,l,o.done,o.value)})}}function r(s,o,a,l){Promise.resolve(l).then(function(h){s({value:h,done:a})},o)}},lo=function(n){return this instanceof lo?(this.v=n,this):new lo(n)},d1=function(n,e,t){if(!Symbol.asyncIterator)throw new TypeError("Symbol.asyncIterator is not defined.");var i=t.apply(n,e||[]),r,s=[];return r={},a("next"),a("throw"),a("return",o),r[Symbol.asyncIterator]=function(){return this},r;function o(p){return function(g){return Promise.resolve(g).then(p,u)}}function a(p,g){i[p]&&(r[p]=function(O){return new Promise(function(y,S){s.push([p,O,y,S])>1||l(p,O)})},g&&(r[p]=g(r[p])))}function l(p,g){try{h(i[p](g))}catch(O){f(s[0][3],O)}}function h(p){p.value instanceof lo?Promise.resolve(p.value.v).then(c,u):f(s[0][2],p)}function c(p){l("next",p)}function u(p){l("throw",p)}function f(p,g){p(g),s.shift(),s.length&&l(s[0][0],s[0][1])}},p1=function(n){var e,t;return e={},i("next"),i("throw",function(r){throw r}),i("return"),e[Symbol.iterator]=function(){return this},e;function i(r,s){e[r]=n[r]?function(o){return(t=!t)?{value:lo(n[r](o)),done:!1}:s?s(o):o}:s}};function g1(n){return d1(this,arguments,function*(){yield lo(yield*p1(f1(n)))})}var Mm=function(n){if(!Symbol.asyncIterator)throw new TypeError("Symbol.asyncIterator is not defined.");var e=n[Symbol.asyncIterator],t;return e?e.call(n):(n=typeof __values=="function"?__values(n):n[Symbol.iterator](),t={},i("next"),i("throw"),i("return"),t[Symbol.asyncIterator]=function(){return this},t);function i(s){t[s]=n[s]&&function(o){return new Promise(function(a,l){o=n[s](o),r(a,l,o.done,o.value)})}}function r(s,o,a,l){Promise.resolve(l).then(function(h){s({value:h,done:a})},o)}},hs=function(n){return this instanceof hs?(this.v=n,this):new hs(n)},m1=function(n){var e,t;return e={},i("next"),i("throw",function(r){throw r}),i("return"),e[Symbol.iterator]=function(){return this},e;function i(r,s){e[r]=n[r]?function(o){return(t=!t)?{value:hs(n[r](o)),done:!1}:s?s(o):o}:s}},O1=function(n,e,t){if(!Symbol.asyncIterator)throw new TypeError("Symbol.asyncIterator is not defined.");var i=t.apply(n,e||[]),r,s=[];return r={},a("next"),a("throw"),a("return",o),r[Symbol.asyncIterator]=function(){return this},r;function o(p){return function(g){return Promise.resolve(g).then(p,u)}}function a(p,g){i[p]&&(r[p]=function(O){return new Promise(function(y,S){s.push([p,O,y,S])>1||l(p,O)})},g&&(r[p]=g(r[p])))}function l(p,g){try{h(i[p](g))}catch(O){f(s[0][3],O)}}function h(p){p.value instanceof hs?Promise.resolve(p.value.v).then(c,u):f(s[0][2],p)}function c(p){l("next",p)}function u(p){l("throw",p)}function f(p,g){p(g),s.shift(),s.length&&l(s[0][0],s[0][1])}};function y1(n,e){return u1(n,t=>{switch(t.kind){case ze.Unary:return b1(e,n,t);case ze.ServerStreaming:return S1(e,n,t);case ze.ClientStreaming:return w1(e,n,t);case ze.BiDiStreaming:return v1(e,n,t);default:return null}})}function b1(n,e,t){return async function(i,r){var s,o;const a=await n.unary(e,t,r==null?void 0:r.signal,r==null?void 0:r.timeoutMs,r==null?void 0:r.headers,i,r==null?void 0:r.contextValues);return(s=r==null?void 0:r.onHeader)===null||s===void 0||s.call(r,a.header),(o=r==null?void 0:r.onTrailer)===null||o===void 0||o.call(r,a.trailer),a.message}}function S1(n,e,t){return function(i,r){return Vm(n.stream(e,t,r==null?void 0:r.signal,r==null?void 0:r.timeoutMs,r==null?void 0:r.headers,g1([i]),r==null?void 0:r.contextValues),r)}}function w1(n,e,t){return async function(i,r){var s,o,a,l,h,c;const u=await n.stream(e,t,r==null?void 0:r.signal,r==null?void 0:r.timeoutMs,r==null?void 0:r.headers,i,r==null?void 0:r.contextValues);(h=r==null?void 0:r.onHeader)===null||h===void 0||h.call(r,u.header);let f;try{for(var p=!0,g=Mm(u.message),O;O=await g.next(),s=O.done,!s;p=!0)l=O.value,p=!1,f=l}catch(y){o={error:y}}finally{try{!p&&!s&&(a=g.return)&&await a.call(g)}finally{if(o)throw o.error}}if(!f)throw new Te("protocol error: missing response message",ie.Internal);return(c=r==null?void 0:r.onTrailer)===null||c===void 0||c.call(r,u.trailer),f}}function v1(n,e,t){return function(i,r){return Vm(n.stream(e,t,r==null?void 0:r.signal,r==null?void 0:r.timeoutMs,r==null?void 0:r.headers,i,r==null?void 0:r.contextValues),r)}}function Vm(n,e){const t=function(){var i,r;return O1(this,arguments,function*(){const s=yield hs(n);(i=e==null?void 0:e.onHeader)===null||i===void 0||i.call(e,s.header),yield hs(yield*m1(Mm(s.message))),(r=e==null?void 0:e.onTrailer)===null||r===void 0||r.call(e,s.trailer)})}()[Symbol.asyncIterator]();return{[Symbol.asyncIterator]:()=>({next:()=>t.next()})}}function k1(...n){const e=new AbortController,t=n.filter(r=>r!==void 0).concat(e.signal);for(const r of t){if(r.aborted){i.apply(r);break}r.addEventListener("abort",i)}function i(){e.signal.aborted||e.abort(Xm(this));for(const r of t)r.removeEventListener("abort",i)}return e}function x1(n){const e=new AbortController,t=()=>{e.abort(new Te("the operation timed out",ie.DeadlineExceeded))};let i;return n!==void 0&&(n<=0?t():i=setTimeout(t,n)),{signal:e.signal,cleanup:()=>clearTimeout(i)}}function Xm(n){if(!n.aborted)return;if(n.reason!==void 0)return n.reason;const e=new Error("This operation was aborted");return e.name="AbortError",e}function Od(){return{get(n){return n.id in this?this[n.id]:n.defaultValue},set(n,e){return this[n.id]=e,this},delete(n){return delete this[n.id],this}}}const Qh=128;function yd(n){const e=new Headers,t=new TextDecoder().decode(n).split(`\r +`);for(const i of t){if(i==="")continue;const r=i.indexOf(":");if(r>0){const s=i.substring(0,r).trim(),o=i.substring(r+1).trim();e.append(s,o)}}return e}const T1="Content-Type",Q1="Grpc-Timeout",Lm="Grpc-Status",Um="Grpc-Message",P1="Grpc-Status-Details-Bin",A1="X-User-Agent",$1="X-Grpc-Web",C1="application/grpc-web+proto",I1="application/grpc-web+json";class Rn extends D{constructor(e){super(),this.code=0,this.message="",this.details=[],m.util.initPartial(e,this)}static fromBinary(e,t){return new Rn().fromBinary(e,t)}static fromJson(e,t){return new Rn().fromJson(e,t)}static fromJsonString(e,t){return new Rn().fromJsonString(e,t)}static equals(e,t){return m.util.equals(Rn,e,t)}}Rn.runtime=m;Rn.typeName="google.rpc.Status";Rn.fields=m.util.newFieldList(()=>[{no:1,name:"code",kind:"scalar",T:5},{no:2,name:"message",kind:"scalar",T:9},{no:3,name:"details",kind:"message",T:ci,repeated:!0}]);const R1="0";function Zm(n){var e;const t=n.get(P1);if(t!=null){const r=c1(t,Rn);if(r.code==0)return;const s=new Te(r.message,r.code,n);return s.details=r.details.map(o=>({type:o.typeUrl.substring(o.typeUrl.lastIndexOf("/")+1),value:o.value})),s}const i=n.get(Lm);if(i!=null){if(i===R1)return;const r=parseInt(i,10);return r in ie?new Te(decodeURIComponent((e=n.get(Um))!==null&&e!==void 0?e:""),r,n):new Te(`invalid grpc-status: ${i}`,ie.Internal,n)}}function bd(n,e,t){const i=typeof e=="string"?e:e.typeName,r=typeof t=="string"?t:t.name;return n.toString().replace(/\/?$/,`/${i}/${r}`)}function Wm(n,e){return e instanceof n?e:new n(e)}function E1(n,e){function t(i){return i.done===!0?i:{done:i.done,value:Wm(n,i.value)}}return{[Symbol.asyncIterator](){const i=e[Symbol.asyncIterator](),r={next:()=>i.next().then(t)};return i.throw!==void 0&&(r.throw=s=>i.throw(s).then(t)),i.return!==void 0&&(r.return=s=>i.return(s).then(t)),r}}}function jm(n,e){var t;return(t=e==null?void 0:e.concat().reverse().reduce((i,r)=>r(i),n))!==null&&t!==void 0?t:n}function D1(n){var e;const t=Object.assign({},n);return(e=t.ignoreUnknownFields)!==null&&e!==void 0||(t.ignoreUnknownFields=!0),t}function Sd(n,e,t,i){const r=e?wd(n.I,i):vd(n.I,t);return{parse:(e?wd(n.O,i):vd(n.O,t)).parse,serialize:r.serialize}}function wd(n,e){return{parse(t){try{return n.fromBinary(t,e)}catch(i){const r=i instanceof Error?i.message:String(i);throw new Te(`parse binary: ${r}`,ie.InvalidArgument)}},serialize(t){try{return t.toBinary(e)}catch(i){const r=i instanceof Error?i.message:String(i);throw new Te(`serialize binary: ${r}`,ie.Internal)}}}}function vd(n,e){var t,i;const r=(t=e==null?void 0:e.textEncoder)!==null&&t!==void 0?t:new TextEncoder,s=(i=e==null?void 0:e.textDecoder)!==null&&i!==void 0?i:new TextDecoder,o=D1(e);return{parse(a){try{const l=s.decode(a);return n.fromJsonString(l,o)}catch(l){throw Te.from(l,ie.InvalidArgument)}},serialize(a){try{const l=a.toJsonString(o);return r.encode(l)}catch(l){throw Te.from(l,ie.Internal)}}}}function N1(n){const e=jm(n.next,n.interceptors),[t,i,r]=Fm(n),s=Object.assign(Object.assign({},n.req),{message:Wm(n.req.method.I,n.req.message),signal:t});return e(s).then(o=>(r(),o),i)}function B1(n){const e=jm(n.next,n.interceptors),[t,i,r]=Fm(n),s=Object.assign(Object.assign({},n.req),{message:E1(n.req.method.I,n.req.message),signal:t});let o=!1;return t.addEventListener("abort",function(){var a,l;const h=n.req.message[Symbol.asyncIterator]();o||(a=h.throw)===null||a===void 0||a.call(h,this.reason).catch(()=>{}),(l=h.return)===null||l===void 0||l.call(h).catch(()=>{})}),e(s).then(a=>Object.assign(Object.assign({},a),{message:{[Symbol.asyncIterator](){const l=a.message[Symbol.asyncIterator]();return{next(){return l.next().then(h=>(h.done==!0&&(o=!0,r()),h),i)}}}}}),i)}function Fm(n){const{signal:e,cleanup:t}=x1(n.timeoutMs),i=k1(n.signal,e);return[i.signal,function(s){const o=Te.from(e.aborted?Xm(e):s);return i.abort(o),t(),Promise.reject(o)},function(){t(),i.abort()}]}function q1(){try{new Headers}catch{throw new Error("connect-web requires the fetch API. Are you running on an old version of Node.js? Node.js is not supported in Connect for Web - please stay tuned for Connect for Node.")}}function kd(n,e){const t=Zm(n);if(t)throw e.forEach((i,r)=>{t.metadata.append(r,i)}),t}function xd(n,e,t,i){const r=new Headers(t??{});return r.set(T1,n?C1:I1),r.set($1,"1"),r.set(A1,"connect-es/1.4.0"),e!==void 0&&r.set(Q1,`${e}m`),r}function M1(n){switch(n){case 400:return ie.Internal;case 401:return ie.Unauthenticated;case 403:return ie.PermissionDenied;case 404:return ie.Unimplemented;case 429:return ie.Unavailable;case 502:return ie.Unavailable;case 503:return ie.Unavailable;case 504:return ie.Unavailable;default:return ie.Unknown}}function Td(n,e){var t;if(n>=200&&n<300){const i=Zm(e);if(i)throw i;return{foundStatus:e.has(Lm)}}throw new Te(decodeURIComponent((t=e.get(Um))!==null&&t!==void 0?t:`HTTP ${n}`),M1(n),e)}var Pr=function(n){return this instanceof Pr?(this.v=n,this):new Pr(n)},V1=function(n,e,t){if(!Symbol.asyncIterator)throw new TypeError("Symbol.asyncIterator is not defined.");var i=t.apply(n,e||[]),r,s=[];return r={},a("next"),a("throw"),a("return",o),r[Symbol.asyncIterator]=function(){return this},r;function o(p){return function(g){return Promise.resolve(g).then(p,u)}}function a(p,g){i[p]&&(r[p]=function(O){return new Promise(function(y,S){s.push([p,O,y,S])>1||l(p,O)})},g&&(r[p]=g(r[p])))}function l(p,g){try{h(i[p](g))}catch(O){f(s[0][3],O)}}function h(p){p.value instanceof Pr?Promise.resolve(p.value.v).then(c,u):f(s[0][2],p)}function c(p){l("next",p)}function u(p){l("throw",p)}function f(p,g){p(g),s.shift(),s.length&&l(s[0][0],s[0][1])}};function X1(n){var e;q1();const t=(e=n.useBinaryFormat)!==null&&e!==void 0?e:!0;return{async unary(i,r,s,o,a,l,h){var c;const{serialize:u,parse:f}=Sd(r,t,n.jsonOptions,n.binaryOptions);return o=o===void 0?n.defaultTimeoutMs:o<=0?void 0:o,await N1({interceptors:n.interceptors,signal:s,timeoutMs:o,req:{stream:!1,service:i,method:r,url:bd(n.baseUrl,i,r),init:{method:"POST",credentials:(c=n.credentials)!==null&&c!==void 0?c:"same-origin",redirect:"error",mode:"cors"},header:xd(t,o,a),contextValues:h??Od(),message:l},next:async p=>{var g;const y=await((g=n.fetch)!==null&&g!==void 0?g:globalThis.fetch)(p.url,Object.assign(Object.assign({},p.init),{headers:p.header,signal:p.signal,body:md(0,u(p.message))}));if(Td(y.status,y.headers),!y.body)throw"missing response body";const S=gd(y.body).getReader();let k,$;for(;;){const x=await S.read();if(x.done)break;const{flags:Q,data:A}=x.value;if(Q===Qh){if(k!==void 0)throw"extra trailer";k=yd(A);continue}if($!==void 0)throw"extra message";$=f(A)}if(k===void 0)throw"missing trailer";if(kd(k,y.headers),$===void 0)throw"missing message";return{stream:!1,service:i,method:r,header:y.headers,message:$,trailer:k}}})},async stream(i,r,s,o,a,l,h){var c;const{serialize:u,parse:f}=Sd(r,t,n.jsonOptions,n.binaryOptions);function p(O,y,S,k){return V1(this,arguments,function*(){const x=gd(O).getReader();if(y){if(!(yield Pr(x.read())).done)throw"extra data for trailers-only";return yield Pr(void 0)}let Q=!1;for(;;){const A=yield Pr(x.read());if(A.done)break;const{flags:R,data:j}=A.value;if((R&Qh)===Qh){if(Q)throw"extra trailer";Q=!0;const W=yd(j);kd(W,k),W.forEach((G,re)=>S.set(re,G));continue}if(Q)throw"extra message";yield yield Pr(f(j))}if(!Q)throw"missing trailer"})}async function g(O){if(r.kind!=ze.ServerStreaming)throw"The fetch API does not support streaming request bodies";const y=await O[Symbol.asyncIterator]().next();if(y.done==!0)throw"missing request message";return md(0,u(y.value))}return o=o===void 0?n.defaultTimeoutMs:o<=0?void 0:o,B1({interceptors:n.interceptors,signal:s,timeoutMs:o,req:{stream:!0,service:i,method:r,url:bd(n.baseUrl,i,r),init:{method:"POST",credentials:(c=n.credentials)!==null&&c!==void 0?c:"same-origin",redirect:"error",mode:"cors"},header:xd(t,o,a),contextValues:h??Od(),message:l},next:async O=>{var y;const k=await((y=n.fetch)!==null&&y!==void 0?y:globalThis.fetch)(O.url,Object.assign(Object.assign({},O.init),{headers:O.header,signal:O.signal,body:await g(O.message)})),{foundStatus:$}=Td(k.status,k.headers);if(!k.body)throw"missing response body";const x=new Headers;return Object.assign(Object.assign({},O),{header:k.headers,trailer:x,message:p(k.body,$,x,k.headers)})}})}}}var F=(n=>(n[n.NULL=0]="NULL",n[n.BOOLEAN=1]="BOOLEAN",n[n.INTEGER=2]="INTEGER",n[n.LONG=3]="LONG",n[n.DOUBLE=4]="DOUBLE",n[n.STRING=5]="STRING",n[n.BYTES=6]="BYTES",n[n.DATE=7]="DATE",n[n.JSON_OBJECT=8]="JSON_OBJECT",n[n.JSON_ARRAY=9]="JSON_ARRAY",n[n.TEXT=10]="TEXT",n[n.INTEGER_CNT=11]="INTEGER_CNT",n[n.LONG_CNT=12]="LONG_CNT",n[n.TREE=13]="TREE",n))(F||{});m.util.setEnumType(F,"yorkie.v1.ValueType",[{no:0,name:"VALUE_TYPE_NULL"},{no:1,name:"VALUE_TYPE_BOOLEAN"},{no:2,name:"VALUE_TYPE_INTEGER"},{no:3,name:"VALUE_TYPE_LONG"},{no:4,name:"VALUE_TYPE_DOUBLE"},{no:5,name:"VALUE_TYPE_STRING"},{no:6,name:"VALUE_TYPE_BYTES"},{no:7,name:"VALUE_TYPE_DATE"},{no:8,name:"VALUE_TYPE_JSON_OBJECT"},{no:9,name:"VALUE_TYPE_JSON_ARRAY"},{no:10,name:"VALUE_TYPE_TEXT"},{no:11,name:"VALUE_TYPE_INTEGER_CNT"},{no:12,name:"VALUE_TYPE_LONG_CNT"},{no:13,name:"VALUE_TYPE_TREE"}]);var Rr=(n=>(n[n.DOCUMENT_CHANGED=0]="DOCUMENT_CHANGED",n[n.DOCUMENT_WATCHED=1]="DOCUMENT_WATCHED",n[n.DOCUMENT_UNWATCHED=2]="DOCUMENT_UNWATCHED",n[n.DOCUMENT_BROADCAST=3]="DOCUMENT_BROADCAST",n))(Rr||{});m.util.setEnumType(Rr,"yorkie.v1.DocEventType",[{no:0,name:"DOC_EVENT_TYPE_DOCUMENT_CHANGED"},{no:1,name:"DOC_EVENT_TYPE_DOCUMENT_WATCHED"},{no:2,name:"DOC_EVENT_TYPE_DOCUMENT_UNWATCHED"},{no:3,name:"DOC_EVENT_TYPE_DOCUMENT_BROADCAST"}]);const Ci=class Ci extends D{constructor(t){super();d(this,"root");d(this,"presences",{});m.util.initPartial(t,this)}static fromBinary(t,i){return new Ci().fromBinary(t,i)}static fromJson(t,i){return new Ci().fromJson(t,i)}static fromJsonString(t,i){return new Ci().fromJsonString(t,i)}static equals(t,i){return m.util.equals(Ci,t,i)}};d(Ci,"runtime",m),d(Ci,"typeName","yorkie.v1.Snapshot"),d(Ci,"fields",m.util.newFieldList(()=>[{no:1,name:"root",kind:"message",T:rt},{no:2,name:"presences",kind:"map",K:9,V:{kind:"message",T:Fu}}]));let gc=Ci;var bt;let Wn=(bt=class extends D{constructor(t){super();d(this,"documentKey","");d(this,"checkpoint");d(this,"snapshot",new Uint8Array(0));d(this,"changes",[]);d(this,"minSyncedTicket");d(this,"isRemoved",!1);d(this,"versionVector");m.util.initPartial(t,this)}static fromBinary(t,i){return new bt().fromBinary(t,i)}static fromJson(t,i){return new bt().fromJson(t,i)}static fromJsonString(t,i){return new bt().fromJsonString(t,i)}static equals(t,i){return m.util.equals(bt,t,i)}},d(bt,"runtime",m),d(bt,"typeName","yorkie.v1.ChangePack"),d(bt,"fields",m.util.newFieldList(()=>[{no:1,name:"document_key",kind:"scalar",T:9},{no:2,name:"checkpoint",kind:"message",T:Jm},{no:3,name:"snapshot",kind:"scalar",T:12},{no:4,name:"changes",kind:"message",T:zm,repeated:!0},{no:5,name:"min_synced_ticket",kind:"message",T:M},{no:6,name:"is_removed",kind:"scalar",T:8},{no:7,name:"version_vector",kind:"message",T:eh}])),bt);var St;let zm=(St=class extends D{constructor(t){super();d(this,"id");d(this,"message","");d(this,"operations",[]);d(this,"presenceChange");m.util.initPartial(t,this)}static fromBinary(t,i){return new St().fromBinary(t,i)}static fromJson(t,i){return new St().fromJson(t,i)}static fromJsonString(t,i){return new St().fromJsonString(t,i)}static equals(t,i){return m.util.equals(St,t,i)}},d(St,"runtime",m),d(St,"typeName","yorkie.v1.Change"),d(St,"fields",m.util.newFieldList(()=>[{no:1,name:"id",kind:"message",T:Kl},{no:2,name:"message",kind:"scalar",T:9},{no:3,name:"operations",kind:"message",T:Wu,repeated:!0},{no:4,name:"presence_change",kind:"message",T:co}])),St);var wt;let Kl=(wt=class extends D{constructor(t){super();d(this,"clientSeq",0);d(this,"serverSeq",ue.zero);d(this,"lamport",ue.zero);d(this,"actorId",new Uint8Array(0));d(this,"versionVector");m.util.initPartial(t,this)}static fromBinary(t,i){return new wt().fromBinary(t,i)}static fromJson(t,i){return new wt().fromJson(t,i)}static fromJsonString(t,i){return new wt().fromJsonString(t,i)}static equals(t,i){return m.util.equals(wt,t,i)}},d(wt,"runtime",m),d(wt,"typeName","yorkie.v1.ChangeID"),d(wt,"fields",m.util.newFieldList(()=>[{no:1,name:"client_seq",kind:"scalar",T:13},{no:2,name:"server_seq",kind:"scalar",T:3},{no:3,name:"lamport",kind:"scalar",T:3},{no:4,name:"actor_id",kind:"scalar",T:12},{no:5,name:"version_vector",kind:"message",T:eh}])),wt);var vt;let eh=(vt=class extends D{constructor(t){super();d(this,"vector",{});m.util.initPartial(t,this)}static fromBinary(t,i){return new vt().fromBinary(t,i)}static fromJson(t,i){return new vt().fromJson(t,i)}static fromJsonString(t,i){return new vt().fromJsonString(t,i)}static equals(t,i){return m.util.equals(vt,t,i)}},d(vt,"runtime",m),d(vt,"typeName","yorkie.v1.VersionVector"),d(vt,"fields",m.util.newFieldList(()=>[{no:1,name:"vector",kind:"map",K:9,V:{kind:"scalar",T:3}}])),vt);var kt;let Wu=(kt=class extends D{constructor(t){super();d(this,"body",{case:void 0});m.util.initPartial(t,this)}static fromBinary(t,i){return new kt().fromBinary(t,i)}static fromJson(t,i){return new kt().fromJson(t,i)}static fromJsonString(t,i){return new kt().fromJsonString(t,i)}static equals(t,i){return m.util.equals(kt,t,i)}},d(kt,"runtime",m),d(kt,"typeName","yorkie.v1.Operation"),d(kt,"fields",m.util.newFieldList(()=>[{no:1,name:"set",kind:"message",T:tl,oneof:"body"},{no:2,name:"add",kind:"message",T:il,oneof:"body"},{no:3,name:"move",kind:"message",T:nl,oneof:"body"},{no:4,name:"remove",kind:"message",T:rl,oneof:"body"},{no:5,name:"edit",kind:"message",T:sl,oneof:"body"},{no:6,name:"select",kind:"message",T:mc,oneof:"body"},{no:7,name:"style",kind:"message",T:ol,oneof:"body"},{no:8,name:"increase",kind:"message",T:al,oneof:"body"},{no:9,name:"tree_edit",kind:"message",T:ll,oneof:"body"},{no:10,name:"tree_style",kind:"message",T:hl,oneof:"body"},{no:11,name:"array_set",kind:"message",T:Oc,oneof:"body"}])),kt);const Ii=class Ii extends D{constructor(t){super();d(this,"parentCreatedAt");d(this,"key","");d(this,"value");d(this,"executedAt");m.util.initPartial(t,this)}static fromBinary(t,i){return new Ii().fromBinary(t,i)}static fromJson(t,i){return new Ii().fromJson(t,i)}static fromJsonString(t,i){return new Ii().fromJsonString(t,i)}static equals(t,i){return m.util.equals(Ii,t,i)}};d(Ii,"runtime",m),d(Ii,"typeName","yorkie.v1.Operation.Set"),d(Ii,"fields",m.util.newFieldList(()=>[{no:1,name:"parent_created_at",kind:"message",T:M},{no:2,name:"key",kind:"scalar",T:9},{no:3,name:"value",kind:"message",T:Ot},{no:4,name:"executed_at",kind:"message",T:M}]));let tl=Ii;const Ri=class Ri extends D{constructor(t){super();d(this,"parentCreatedAt");d(this,"prevCreatedAt");d(this,"value");d(this,"executedAt");m.util.initPartial(t,this)}static fromBinary(t,i){return new Ri().fromBinary(t,i)}static fromJson(t,i){return new Ri().fromJson(t,i)}static fromJsonString(t,i){return new Ri().fromJsonString(t,i)}static equals(t,i){return m.util.equals(Ri,t,i)}};d(Ri,"runtime",m),d(Ri,"typeName","yorkie.v1.Operation.Add"),d(Ri,"fields",m.util.newFieldList(()=>[{no:1,name:"parent_created_at",kind:"message",T:M},{no:2,name:"prev_created_at",kind:"message",T:M},{no:3,name:"value",kind:"message",T:Ot},{no:4,name:"executed_at",kind:"message",T:M}]));let il=Ri;const Ei=class Ei extends D{constructor(t){super();d(this,"parentCreatedAt");d(this,"prevCreatedAt");d(this,"createdAt");d(this,"executedAt");m.util.initPartial(t,this)}static fromBinary(t,i){return new Ei().fromBinary(t,i)}static fromJson(t,i){return new Ei().fromJson(t,i)}static fromJsonString(t,i){return new Ei().fromJsonString(t,i)}static equals(t,i){return m.util.equals(Ei,t,i)}};d(Ei,"runtime",m),d(Ei,"typeName","yorkie.v1.Operation.Move"),d(Ei,"fields",m.util.newFieldList(()=>[{no:1,name:"parent_created_at",kind:"message",T:M},{no:2,name:"prev_created_at",kind:"message",T:M},{no:3,name:"created_at",kind:"message",T:M},{no:4,name:"executed_at",kind:"message",T:M}]));let nl=Ei;const Di=class Di extends D{constructor(t){super();d(this,"parentCreatedAt");d(this,"createdAt");d(this,"executedAt");m.util.initPartial(t,this)}static fromBinary(t,i){return new Di().fromBinary(t,i)}static fromJson(t,i){return new Di().fromJson(t,i)}static fromJsonString(t,i){return new Di().fromJsonString(t,i)}static equals(t,i){return m.util.equals(Di,t,i)}};d(Di,"runtime",m),d(Di,"typeName","yorkie.v1.Operation.Remove"),d(Di,"fields",m.util.newFieldList(()=>[{no:1,name:"parent_created_at",kind:"message",T:M},{no:2,name:"created_at",kind:"message",T:M},{no:3,name:"executed_at",kind:"message",T:M}]));let rl=Di;const Ni=class Ni extends D{constructor(t){super();d(this,"parentCreatedAt");d(this,"from");d(this,"to");d(this,"createdAtMapByActor",{});d(this,"content","");d(this,"executedAt");d(this,"attributes",{});m.util.initPartial(t,this)}static fromBinary(t,i){return new Ni().fromBinary(t,i)}static fromJson(t,i){return new Ni().fromJson(t,i)}static fromJsonString(t,i){return new Ni().fromJsonString(t,i)}static equals(t,i){return m.util.equals(Ni,t,i)}};d(Ni,"runtime",m),d(Ni,"typeName","yorkie.v1.Operation.Edit"),d(Ni,"fields",m.util.newFieldList(()=>[{no:1,name:"parent_created_at",kind:"message",T:M},{no:2,name:"from",kind:"message",T:Mn},{no:3,name:"to",kind:"message",T:Mn},{no:4,name:"created_at_map_by_actor",kind:"map",K:9,V:{kind:"message",T:M}},{no:5,name:"content",kind:"scalar",T:9},{no:6,name:"executed_at",kind:"message",T:M},{no:7,name:"attributes",kind:"map",K:9,V:{kind:"scalar",T:9}}]));let sl=Ni;const Bi=class Bi extends D{constructor(t){super();d(this,"parentCreatedAt");d(this,"from");d(this,"to");d(this,"executedAt");m.util.initPartial(t,this)}static fromBinary(t,i){return new Bi().fromBinary(t,i)}static fromJson(t,i){return new Bi().fromJson(t,i)}static fromJsonString(t,i){return new Bi().fromJsonString(t,i)}static equals(t,i){return m.util.equals(Bi,t,i)}};d(Bi,"runtime",m),d(Bi,"typeName","yorkie.v1.Operation.Select"),d(Bi,"fields",m.util.newFieldList(()=>[{no:1,name:"parent_created_at",kind:"message",T:M},{no:2,name:"from",kind:"message",T:Mn},{no:3,name:"to",kind:"message",T:Mn},{no:4,name:"executed_at",kind:"message",T:M}]));let mc=Bi;const qi=class qi extends D{constructor(t){super();d(this,"parentCreatedAt");d(this,"from");d(this,"to");d(this,"attributes",{});d(this,"executedAt");d(this,"createdAtMapByActor",{});m.util.initPartial(t,this)}static fromBinary(t,i){return new qi().fromBinary(t,i)}static fromJson(t,i){return new qi().fromJson(t,i)}static fromJsonString(t,i){return new qi().fromJsonString(t,i)}static equals(t,i){return m.util.equals(qi,t,i)}};d(qi,"runtime",m),d(qi,"typeName","yorkie.v1.Operation.Style"),d(qi,"fields",m.util.newFieldList(()=>[{no:1,name:"parent_created_at",kind:"message",T:M},{no:2,name:"from",kind:"message",T:Mn},{no:3,name:"to",kind:"message",T:Mn},{no:4,name:"attributes",kind:"map",K:9,V:{kind:"scalar",T:9}},{no:5,name:"executed_at",kind:"message",T:M},{no:6,name:"created_at_map_by_actor",kind:"map",K:9,V:{kind:"message",T:M}}]));let ol=qi;const Mi=class Mi extends D{constructor(t){super();d(this,"parentCreatedAt");d(this,"value");d(this,"executedAt");m.util.initPartial(t,this)}static fromBinary(t,i){return new Mi().fromBinary(t,i)}static fromJson(t,i){return new Mi().fromJson(t,i)}static fromJsonString(t,i){return new Mi().fromJsonString(t,i)}static equals(t,i){return m.util.equals(Mi,t,i)}};d(Mi,"runtime",m),d(Mi,"typeName","yorkie.v1.Operation.Increase"),d(Mi,"fields",m.util.newFieldList(()=>[{no:1,name:"parent_created_at",kind:"message",T:M},{no:2,name:"value",kind:"message",T:Ot},{no:3,name:"executed_at",kind:"message",T:M}]));let al=Mi;const Vi=class Vi extends D{constructor(t){super();d(this,"parentCreatedAt");d(this,"from");d(this,"to");d(this,"createdAtMapByActor",{});d(this,"contents",[]);d(this,"splitLevel",0);d(this,"executedAt");m.util.initPartial(t,this)}static fromBinary(t,i){return new Vi().fromBinary(t,i)}static fromJson(t,i){return new Vi().fromJson(t,i)}static fromJsonString(t,i){return new Vi().fromJsonString(t,i)}static equals(t,i){return m.util.equals(Vi,t,i)}};d(Vi,"runtime",m),d(Vi,"typeName","yorkie.v1.Operation.TreeEdit"),d(Vi,"fields",m.util.newFieldList(()=>[{no:1,name:"parent_created_at",kind:"message",T:M},{no:2,name:"from",kind:"message",T:Er},{no:3,name:"to",kind:"message",T:Er},{no:4,name:"created_at_map_by_actor",kind:"map",K:9,V:{kind:"message",T:M}},{no:5,name:"contents",kind:"message",T:Ol,repeated:!0},{no:7,name:"split_level",kind:"scalar",T:5},{no:6,name:"executed_at",kind:"message",T:M}]));let ll=Vi;const Xi=class Xi extends D{constructor(t){super();d(this,"parentCreatedAt");d(this,"from");d(this,"to");d(this,"attributes",{});d(this,"executedAt");d(this,"attributesToRemove",[]);d(this,"createdAtMapByActor",{});m.util.initPartial(t,this)}static fromBinary(t,i){return new Xi().fromBinary(t,i)}static fromJson(t,i){return new Xi().fromJson(t,i)}static fromJsonString(t,i){return new Xi().fromJsonString(t,i)}static equals(t,i){return m.util.equals(Xi,t,i)}};d(Xi,"runtime",m),d(Xi,"typeName","yorkie.v1.Operation.TreeStyle"),d(Xi,"fields",m.util.newFieldList(()=>[{no:1,name:"parent_created_at",kind:"message",T:M},{no:2,name:"from",kind:"message",T:Er},{no:3,name:"to",kind:"message",T:Er},{no:4,name:"attributes",kind:"map",K:9,V:{kind:"scalar",T:9}},{no:5,name:"executed_at",kind:"message",T:M},{no:6,name:"attributes_to_remove",kind:"scalar",T:9,repeated:!0},{no:7,name:"created_at_map_by_actor",kind:"map",K:9,V:{kind:"message",T:M}}]));let hl=Xi;const Li=class Li extends D{constructor(t){super();d(this,"parentCreatedAt");d(this,"createdAt");d(this,"value");d(this,"executedAt");m.util.initPartial(t,this)}static fromBinary(t,i){return new Li().fromBinary(t,i)}static fromJson(t,i){return new Li().fromJson(t,i)}static fromJsonString(t,i){return new Li().fromJsonString(t,i)}static equals(t,i){return m.util.equals(Li,t,i)}};d(Li,"runtime",m),d(Li,"typeName","yorkie.v1.Operation.ArraySet"),d(Li,"fields",m.util.newFieldList(()=>[{no:1,name:"parent_created_at",kind:"message",T:M},{no:2,name:"created_at",kind:"message",T:M},{no:3,name:"value",kind:"message",T:Ot},{no:4,name:"executed_at",kind:"message",T:M}]));let Oc=Li;const Ui=class Ui extends D{constructor(t){super();d(this,"createdAt");d(this,"movedAt");d(this,"removedAt");d(this,"type",0);d(this,"value",new Uint8Array(0));m.util.initPartial(t,this)}static fromBinary(t,i){return new Ui().fromBinary(t,i)}static fromJson(t,i){return new Ui().fromJson(t,i)}static fromJsonString(t,i){return new Ui().fromJsonString(t,i)}static equals(t,i){return m.util.equals(Ui,t,i)}};d(Ui,"runtime",m),d(Ui,"typeName","yorkie.v1.JSONElementSimple"),d(Ui,"fields",m.util.newFieldList(()=>[{no:1,name:"created_at",kind:"message",T:M},{no:2,name:"moved_at",kind:"message",T:M},{no:3,name:"removed_at",kind:"message",T:M},{no:4,name:"type",kind:"enum",T:m.getEnumType(F)},{no:5,name:"value",kind:"scalar",T:12}]));let Ot=Ui;const Zi=class Zi extends D{constructor(t){super();d(this,"body",{case:void 0});m.util.initPartial(t,this)}static fromBinary(t,i){return new Zi().fromBinary(t,i)}static fromJson(t,i){return new Zi().fromJson(t,i)}static fromJsonString(t,i){return new Zi().fromJsonString(t,i)}static equals(t,i){return m.util.equals(Zi,t,i)}};d(Zi,"runtime",m),d(Zi,"typeName","yorkie.v1.JSONElement"),d(Zi,"fields",m.util.newFieldList(()=>[{no:1,name:"json_object",kind:"message",T:cl,oneof:"body"},{no:2,name:"json_array",kind:"message",T:ul,oneof:"body"},{no:3,name:"primitive",kind:"message",T:fl,oneof:"body"},{no:5,name:"text",kind:"message",T:dl,oneof:"body"},{no:6,name:"counter",kind:"message",T:pl,oneof:"body"},{no:7,name:"tree",kind:"message",T:gl,oneof:"body"}]));let rt=Zi;const Wi=class Wi extends D{constructor(t){super();d(this,"nodes",[]);d(this,"createdAt");d(this,"movedAt");d(this,"removedAt");m.util.initPartial(t,this)}static fromBinary(t,i){return new Wi().fromBinary(t,i)}static fromJson(t,i){return new Wi().fromJson(t,i)}static fromJsonString(t,i){return new Wi().fromJsonString(t,i)}static equals(t,i){return m.util.equals(Wi,t,i)}};d(Wi,"runtime",m),d(Wi,"typeName","yorkie.v1.JSONElement.JSONObject"),d(Wi,"fields",m.util.newFieldList(()=>[{no:1,name:"nodes",kind:"message",T:_m,repeated:!0},{no:2,name:"created_at",kind:"message",T:M},{no:3,name:"moved_at",kind:"message",T:M},{no:4,name:"removed_at",kind:"message",T:M}]));let cl=Wi;const ji=class ji extends D{constructor(t){super();d(this,"nodes",[]);d(this,"createdAt");d(this,"movedAt");d(this,"removedAt");m.util.initPartial(t,this)}static fromBinary(t,i){return new ji().fromBinary(t,i)}static fromJson(t,i){return new ji().fromJson(t,i)}static fromJsonString(t,i){return new ji().fromJsonString(t,i)}static equals(t,i){return m.util.equals(ji,t,i)}};d(ji,"runtime",m),d(ji,"typeName","yorkie.v1.JSONElement.JSONArray"),d(ji,"fields",m.util.newFieldList(()=>[{no:1,name:"nodes",kind:"message",T:ml,repeated:!0},{no:2,name:"created_at",kind:"message",T:M},{no:3,name:"moved_at",kind:"message",T:M},{no:4,name:"removed_at",kind:"message",T:M}]));let ul=ji;const Fi=class Fi extends D{constructor(t){super();d(this,"type",0);d(this,"value",new Uint8Array(0));d(this,"createdAt");d(this,"movedAt");d(this,"removedAt");m.util.initPartial(t,this)}static fromBinary(t,i){return new Fi().fromBinary(t,i)}static fromJson(t,i){return new Fi().fromJson(t,i)}static fromJsonString(t,i){return new Fi().fromJsonString(t,i)}static equals(t,i){return m.util.equals(Fi,t,i)}};d(Fi,"runtime",m),d(Fi,"typeName","yorkie.v1.JSONElement.Primitive"),d(Fi,"fields",m.util.newFieldList(()=>[{no:1,name:"type",kind:"enum",T:m.getEnumType(F)},{no:2,name:"value",kind:"scalar",T:12},{no:3,name:"created_at",kind:"message",T:M},{no:4,name:"moved_at",kind:"message",T:M},{no:5,name:"removed_at",kind:"message",T:M}]));let fl=Fi;const zi=class zi extends D{constructor(t){super();d(this,"nodes",[]);d(this,"createdAt");d(this,"movedAt");d(this,"removedAt");m.util.initPartial(t,this)}static fromBinary(t,i){return new zi().fromBinary(t,i)}static fromJson(t,i){return new zi().fromJson(t,i)}static fromJsonString(t,i){return new zi().fromJsonString(t,i)}static equals(t,i){return m.util.equals(zi,t,i)}};d(zi,"runtime",m),d(zi,"typeName","yorkie.v1.JSONElement.Text"),d(zi,"fields",m.util.newFieldList(()=>[{no:1,name:"nodes",kind:"message",T:Gm,repeated:!0},{no:2,name:"created_at",kind:"message",T:M},{no:3,name:"moved_at",kind:"message",T:M},{no:4,name:"removed_at",kind:"message",T:M}]));let dl=zi;const _i=class _i extends D{constructor(t){super();d(this,"type",0);d(this,"value",new Uint8Array(0));d(this,"createdAt");d(this,"movedAt");d(this,"removedAt");m.util.initPartial(t,this)}static fromBinary(t,i){return new _i().fromBinary(t,i)}static fromJson(t,i){return new _i().fromJson(t,i)}static fromJsonString(t,i){return new _i().fromJsonString(t,i)}static equals(t,i){return m.util.equals(_i,t,i)}};d(_i,"runtime",m),d(_i,"typeName","yorkie.v1.JSONElement.Counter"),d(_i,"fields",m.util.newFieldList(()=>[{no:1,name:"type",kind:"enum",T:m.getEnumType(F)},{no:2,name:"value",kind:"scalar",T:12},{no:3,name:"created_at",kind:"message",T:M},{no:4,name:"moved_at",kind:"message",T:M},{no:5,name:"removed_at",kind:"message",T:M}]));let pl=_i;const Gi=class Gi extends D{constructor(t){super();d(this,"nodes",[]);d(this,"createdAt");d(this,"movedAt");d(this,"removedAt");m.util.initPartial(t,this)}static fromBinary(t,i){return new Gi().fromBinary(t,i)}static fromJson(t,i){return new Gi().fromJson(t,i)}static fromJsonString(t,i){return new Gi().fromJsonString(t,i)}static equals(t,i){return m.util.equals(Gi,t,i)}};d(Gi,"runtime",m),d(Gi,"typeName","yorkie.v1.JSONElement.Tree"),d(Gi,"fields",m.util.newFieldList(()=>[{no:1,name:"nodes",kind:"message",T:ju,repeated:!0},{no:2,name:"created_at",kind:"message",T:M},{no:3,name:"moved_at",kind:"message",T:M},{no:4,name:"removed_at",kind:"message",T:M}]));let gl=Gi;var xt;let _m=(xt=class extends D{constructor(t){super();d(this,"key","");d(this,"element");m.util.initPartial(t,this)}static fromBinary(t,i){return new xt().fromBinary(t,i)}static fromJson(t,i){return new xt().fromJson(t,i)}static fromJsonString(t,i){return new xt().fromJsonString(t,i)}static equals(t,i){return m.util.equals(xt,t,i)}},d(xt,"runtime",m),d(xt,"typeName","yorkie.v1.RHTNode"),d(xt,"fields",m.util.newFieldList(()=>[{no:1,name:"key",kind:"scalar",T:9},{no:2,name:"element",kind:"message",T:rt}])),xt);const li=class li extends D{constructor(t){super();d(this,"next");d(this,"element");m.util.initPartial(t,this)}static fromBinary(t,i){return new li().fromBinary(t,i)}static fromJson(t,i){return new li().fromJson(t,i)}static fromJsonString(t,i){return new li().fromJsonString(t,i)}static equals(t,i){return m.util.equals(li,t,i)}};d(li,"runtime",m),d(li,"typeName","yorkie.v1.RGANode"),d(li,"fields",m.util.newFieldList(()=>[{no:1,name:"next",kind:"message",T:li},{no:2,name:"element",kind:"message",T:rt}]));let ml=li;const Ji=class Ji extends D{constructor(t){super();d(this,"value","");d(this,"updatedAt");d(this,"isRemoved",!1);m.util.initPartial(t,this)}static fromBinary(t,i){return new Ji().fromBinary(t,i)}static fromJson(t,i){return new Ji().fromJson(t,i)}static fromJsonString(t,i){return new Ji().fromJsonString(t,i)}static equals(t,i){return m.util.equals(Ji,t,i)}};d(Ji,"runtime",m),d(Ji,"typeName","yorkie.v1.NodeAttr"),d(Ji,"fields",m.util.newFieldList(()=>[{no:1,name:"value",kind:"scalar",T:9},{no:2,name:"updated_at",kind:"message",T:M},{no:3,name:"is_removed",kind:"scalar",T:8}]));let cs=Ji;var Tt;let Gm=(Tt=class extends D{constructor(t){super();d(this,"id");d(this,"value","");d(this,"removedAt");d(this,"insPrevId");d(this,"attributes",{});m.util.initPartial(t,this)}static fromBinary(t,i){return new Tt().fromBinary(t,i)}static fromJson(t,i){return new Tt().fromJson(t,i)}static fromJsonString(t,i){return new Tt().fromJsonString(t,i)}static equals(t,i){return m.util.equals(Tt,t,i)}},d(Tt,"runtime",m),d(Tt,"typeName","yorkie.v1.TextNode"),d(Tt,"fields",m.util.newFieldList(()=>[{no:1,name:"id",kind:"message",T:ho},{no:2,name:"value",kind:"scalar",T:9},{no:3,name:"removed_at",kind:"message",T:M},{no:4,name:"ins_prev_id",kind:"message",T:ho},{no:5,name:"attributes",kind:"map",K:9,V:{kind:"message",T:cs}}])),Tt);const Yi=class Yi extends D{constructor(t){super();d(this,"createdAt");d(this,"offset",0);m.util.initPartial(t,this)}static fromBinary(t,i){return new Yi().fromBinary(t,i)}static fromJson(t,i){return new Yi().fromJson(t,i)}static fromJsonString(t,i){return new Yi().fromJsonString(t,i)}static equals(t,i){return m.util.equals(Yi,t,i)}};d(Yi,"runtime",m),d(Yi,"typeName","yorkie.v1.TextNodeID"),d(Yi,"fields",m.util.newFieldList(()=>[{no:1,name:"created_at",kind:"message",T:M},{no:2,name:"offset",kind:"scalar",T:5}]));let ho=Yi;var Qt;let ju=(Qt=class extends D{constructor(t){super();d(this,"id");d(this,"type","");d(this,"value","");d(this,"removedAt");d(this,"insPrevId");d(this,"insNextId");d(this,"depth",0);d(this,"attributes",{});m.util.initPartial(t,this)}static fromBinary(t,i){return new Qt().fromBinary(t,i)}static fromJson(t,i){return new Qt().fromJson(t,i)}static fromJsonString(t,i){return new Qt().fromJsonString(t,i)}static equals(t,i){return m.util.equals(Qt,t,i)}},d(Qt,"runtime",m),d(Qt,"typeName","yorkie.v1.TreeNode"),d(Qt,"fields",m.util.newFieldList(()=>[{no:1,name:"id",kind:"message",T:nr},{no:2,name:"type",kind:"scalar",T:9},{no:3,name:"value",kind:"scalar",T:9},{no:4,name:"removed_at",kind:"message",T:M},{no:5,name:"ins_prev_id",kind:"message",T:nr},{no:6,name:"ins_next_id",kind:"message",T:nr},{no:7,name:"depth",kind:"scalar",T:5},{no:8,name:"attributes",kind:"map",K:9,V:{kind:"message",T:cs}}])),Qt);const Hi=class Hi extends D{constructor(t){super();d(this,"content",[]);m.util.initPartial(t,this)}static fromBinary(t,i){return new Hi().fromBinary(t,i)}static fromJson(t,i){return new Hi().fromJson(t,i)}static fromJsonString(t,i){return new Hi().fromJsonString(t,i)}static equals(t,i){return m.util.equals(Hi,t,i)}};d(Hi,"runtime",m),d(Hi,"typeName","yorkie.v1.TreeNodes"),d(Hi,"fields",m.util.newFieldList(()=>[{no:1,name:"content",kind:"message",T:ju,repeated:!0}]));let Ol=Hi;const Ki=class Ki extends D{constructor(t){super();d(this,"createdAt");d(this,"offset",0);m.util.initPartial(t,this)}static fromBinary(t,i){return new Ki().fromBinary(t,i)}static fromJson(t,i){return new Ki().fromJson(t,i)}static fromJsonString(t,i){return new Ki().fromJsonString(t,i)}static equals(t,i){return m.util.equals(Ki,t,i)}};d(Ki,"runtime",m),d(Ki,"typeName","yorkie.v1.TreeNodeID"),d(Ki,"fields",m.util.newFieldList(()=>[{no:1,name:"created_at",kind:"message",T:M},{no:2,name:"offset",kind:"scalar",T:5}]));let nr=Ki;const en=class en extends D{constructor(t){super();d(this,"parentId");d(this,"leftSiblingId");m.util.initPartial(t,this)}static fromBinary(t,i){return new en().fromBinary(t,i)}static fromJson(t,i){return new en().fromJson(t,i)}static fromJsonString(t,i){return new en().fromJsonString(t,i)}static equals(t,i){return m.util.equals(en,t,i)}};d(en,"runtime",m),d(en,"typeName","yorkie.v1.TreePos"),d(en,"fields",m.util.newFieldList(()=>[{no:1,name:"parent_id",kind:"message",T:nr},{no:2,name:"left_sibling_id",kind:"message",T:nr}]));let Er=en;const tn=class tn extends D{constructor(t){super();d(this,"id","");d(this,"username","");d(this,"createdAt");m.util.initPartial(t,this)}static fromBinary(t,i){return new tn().fromBinary(t,i)}static fromJson(t,i){return new tn().fromJson(t,i)}static fromJsonString(t,i){return new tn().fromJsonString(t,i)}static equals(t,i){return m.util.equals(tn,t,i)}};d(tn,"runtime",m),d(tn,"typeName","yorkie.v1.User"),d(tn,"fields",m.util.newFieldList(()=>[{no:1,name:"id",kind:"scalar",T:9},{no:2,name:"username",kind:"scalar",T:9},{no:3,name:"created_at",kind:"message",T:Ue}]));let Qd=tn;const nn=class nn extends D{constructor(t){super();d(this,"id","");d(this,"name","");d(this,"publicKey","");d(this,"secretKey","");d(this,"authWebhookUrl","");d(this,"authWebhookMethods",[]);d(this,"clientDeactivateThreshold","");d(this,"createdAt");d(this,"updatedAt");m.util.initPartial(t,this)}static fromBinary(t,i){return new nn().fromBinary(t,i)}static fromJson(t,i){return new nn().fromJson(t,i)}static fromJsonString(t,i){return new nn().fromJsonString(t,i)}static equals(t,i){return m.util.equals(nn,t,i)}};d(nn,"runtime",m),d(nn,"typeName","yorkie.v1.Project"),d(nn,"fields",m.util.newFieldList(()=>[{no:1,name:"id",kind:"scalar",T:9},{no:2,name:"name",kind:"scalar",T:9},{no:3,name:"public_key",kind:"scalar",T:9},{no:4,name:"secret_key",kind:"scalar",T:9},{no:5,name:"auth_webhook_url",kind:"scalar",T:9},{no:6,name:"auth_webhook_methods",kind:"scalar",T:9,repeated:!0},{no:7,name:"client_deactivate_threshold",kind:"scalar",T:9},{no:8,name:"created_at",kind:"message",T:Ue},{no:9,name:"updated_at",kind:"message",T:Ue}]));let Pd=nn;const rn=class rn extends D{constructor(t){super();d(this,"name");d(this,"authWebhookUrl");d(this,"authWebhookMethods");d(this,"clientDeactivateThreshold");m.util.initPartial(t,this)}static fromBinary(t,i){return new rn().fromBinary(t,i)}static fromJson(t,i){return new rn().fromJson(t,i)}static fromJsonString(t,i){return new rn().fromJsonString(t,i)}static equals(t,i){return m.util.equals(rn,t,i)}};d(rn,"runtime",m),d(rn,"typeName","yorkie.v1.UpdatableProjectFields"),d(rn,"fields",m.util.newFieldList(()=>[{no:1,name:"name",kind:"message",T:ct},{no:2,name:"auth_webhook_url",kind:"message",T:ct},{no:3,name:"auth_webhook_methods",kind:"message",T:yc},{no:4,name:"client_deactivate_threshold",kind:"message",T:ct}]));let Ad=rn;const sn=class sn extends D{constructor(t){super();d(this,"methods",[]);m.util.initPartial(t,this)}static fromBinary(t,i){return new sn().fromBinary(t,i)}static fromJson(t,i){return new sn().fromJson(t,i)}static fromJsonString(t,i){return new sn().fromJsonString(t,i)}static equals(t,i){return m.util.equals(sn,t,i)}};d(sn,"runtime",m),d(sn,"typeName","yorkie.v1.UpdatableProjectFields.AuthWebhookMethods"),d(sn,"fields",m.util.newFieldList(()=>[{no:1,name:"methods",kind:"scalar",T:9,repeated:!0}]));let yc=sn;const on=class on extends D{constructor(t){super();d(this,"id","");d(this,"key","");d(this,"snapshot","");d(this,"createdAt");d(this,"accessedAt");d(this,"updatedAt");m.util.initPartial(t,this)}static fromBinary(t,i){return new on().fromBinary(t,i)}static fromJson(t,i){return new on().fromJson(t,i)}static fromJsonString(t,i){return new on().fromJsonString(t,i)}static equals(t,i){return m.util.equals(on,t,i)}};d(on,"runtime",m),d(on,"typeName","yorkie.v1.DocumentSummary"),d(on,"fields",m.util.newFieldList(()=>[{no:1,name:"id",kind:"scalar",T:9},{no:2,name:"key",kind:"scalar",T:9},{no:3,name:"snapshot",kind:"scalar",T:9},{no:4,name:"created_at",kind:"message",T:Ue},{no:5,name:"accessed_at",kind:"message",T:Ue},{no:6,name:"updated_at",kind:"message",T:Ue}]));let $d=on;const an=class an extends D{constructor(t){super();d(this,"type",0);d(this,"presence");m.util.initPartial(t,this)}static fromBinary(t,i){return new an().fromBinary(t,i)}static fromJson(t,i){return new an().fromJson(t,i)}static fromJsonString(t,i){return new an().fromJsonString(t,i)}static equals(t,i){return m.util.equals(an,t,i)}};d(an,"runtime",m),d(an,"typeName","yorkie.v1.PresenceChange"),d(an,"fields",m.util.newFieldList(()=>[{no:1,name:"type",kind:"enum",T:m.getEnumType(Dr)},{no:2,name:"presence",kind:"message",T:Fu}]));let co=an;var Dr=(n=>(n[n.UNSPECIFIED=0]="UNSPECIFIED",n[n.PUT=1]="PUT",n[n.DELETE=2]="DELETE",n[n.CLEAR=3]="CLEAR",n))(Dr||{});m.util.setEnumType(Dr,"yorkie.v1.PresenceChange.ChangeType",[{no:0,name:"CHANGE_TYPE_UNSPECIFIED"},{no:1,name:"CHANGE_TYPE_PUT"},{no:2,name:"CHANGE_TYPE_DELETE"},{no:3,name:"CHANGE_TYPE_CLEAR"}]);var Pt;let Fu=(Pt=class extends D{constructor(t){super();d(this,"data",{});m.util.initPartial(t,this)}static fromBinary(t,i){return new Pt().fromBinary(t,i)}static fromJson(t,i){return new Pt().fromJson(t,i)}static fromJsonString(t,i){return new Pt().fromJsonString(t,i)}static equals(t,i){return m.util.equals(Pt,t,i)}},d(Pt,"runtime",m),d(Pt,"typeName","yorkie.v1.Presence"),d(Pt,"fields",m.util.newFieldList(()=>[{no:1,name:"data",kind:"map",K:9,V:{kind:"scalar",T:9}}])),Pt);var At;let Jm=(At=class extends D{constructor(t){super();d(this,"serverSeq",ue.zero);d(this,"clientSeq",0);m.util.initPartial(t,this)}static fromBinary(t,i){return new At().fromBinary(t,i)}static fromJson(t,i){return new At().fromJson(t,i)}static fromJsonString(t,i){return new At().fromJsonString(t,i)}static equals(t,i){return m.util.equals(At,t,i)}},d(At,"runtime",m),d(At,"typeName","yorkie.v1.Checkpoint"),d(At,"fields",m.util.newFieldList(()=>[{no:1,name:"server_seq",kind:"scalar",T:3},{no:2,name:"client_seq",kind:"scalar",T:13}])),At);const ln=class ln extends D{constructor(t){super();d(this,"createdAt");d(this,"offset",0);d(this,"relativeOffset",0);m.util.initPartial(t,this)}static fromBinary(t,i){return new ln().fromBinary(t,i)}static fromJson(t,i){return new ln().fromJson(t,i)}static fromJsonString(t,i){return new ln().fromJsonString(t,i)}static equals(t,i){return m.util.equals(ln,t,i)}};d(ln,"runtime",m),d(ln,"typeName","yorkie.v1.TextNodePos"),d(ln,"fields",m.util.newFieldList(()=>[{no:1,name:"created_at",kind:"message",T:M},{no:2,name:"offset",kind:"scalar",T:5},{no:3,name:"relative_offset",kind:"scalar",T:5}]));let Mn=ln;var $t;let M=($t=class extends D{constructor(t){super();d(this,"lamport",ue.zero);d(this,"delimiter",0);d(this,"actorId",new Uint8Array(0));m.util.initPartial(t,this)}static fromBinary(t,i){return new $t().fromBinary(t,i)}static fromJson(t,i){return new $t().fromJson(t,i)}static fromJsonString(t,i){return new $t().fromJsonString(t,i)}static equals(t,i){return m.util.equals($t,t,i)}},d($t,"runtime",m),d($t,"typeName","yorkie.v1.TimeTicket"),d($t,"fields",m.util.newFieldList(()=>[{no:1,name:"lamport",kind:"scalar",T:3},{no:2,name:"delimiter",kind:"scalar",T:13},{no:3,name:"actor_id",kind:"scalar",T:12}])),$t);const hn=class hn extends D{constructor(t){super();d(this,"topic","");d(this,"payload",new Uint8Array(0));m.util.initPartial(t,this)}static fromBinary(t,i){return new hn().fromBinary(t,i)}static fromJson(t,i){return new hn().fromJson(t,i)}static fromJsonString(t,i){return new hn().fromJsonString(t,i)}static equals(t,i){return m.util.equals(hn,t,i)}};d(hn,"runtime",m),d(hn,"typeName","yorkie.v1.DocEventBody"),d(hn,"fields",m.util.newFieldList(()=>[{no:1,name:"topic",kind:"scalar",T:9},{no:2,name:"payload",kind:"scalar",T:12}]));let bc=hn;const cn=class cn extends D{constructor(t){super();d(this,"type",0);d(this,"publisher","");d(this,"body");m.util.initPartial(t,this)}static fromBinary(t,i){return new cn().fromBinary(t,i)}static fromJson(t,i){return new cn().fromJson(t,i)}static fromJsonString(t,i){return new cn().fromJsonString(t,i)}static equals(t,i){return m.util.equals(cn,t,i)}};d(cn,"runtime",m),d(cn,"typeName","yorkie.v1.DocEvent"),d(cn,"fields",m.util.newFieldList(()=>[{no:1,name:"type",kind:"enum",T:m.getEnumType(Rr)},{no:2,name:"publisher",kind:"scalar",T:9},{no:3,name:"body",kind:"message",T:bc}]));let Sc=cn;const un=class un extends D{constructor(t){super();d(this,"clientKey","");m.util.initPartial(t,this)}static fromBinary(t,i){return new un().fromBinary(t,i)}static fromJson(t,i){return new un().fromJson(t,i)}static fromJsonString(t,i){return new un().fromJsonString(t,i)}static equals(t,i){return m.util.equals(un,t,i)}};d(un,"runtime",m),d(un,"typeName","yorkie.v1.ActivateClientRequest"),d(un,"fields",m.util.newFieldList(()=>[{no:1,name:"client_key",kind:"scalar",T:9}]));let wc=un;const fn=class fn extends D{constructor(t){super();d(this,"clientId","");m.util.initPartial(t,this)}static fromBinary(t,i){return new fn().fromBinary(t,i)}static fromJson(t,i){return new fn().fromJson(t,i)}static fromJsonString(t,i){return new fn().fromJsonString(t,i)}static equals(t,i){return m.util.equals(fn,t,i)}};d(fn,"runtime",m),d(fn,"typeName","yorkie.v1.ActivateClientResponse"),d(fn,"fields",m.util.newFieldList(()=>[{no:1,name:"client_id",kind:"scalar",T:9}]));let vc=fn;const dn=class dn extends D{constructor(t){super();d(this,"clientId","");m.util.initPartial(t,this)}static fromBinary(t,i){return new dn().fromBinary(t,i)}static fromJson(t,i){return new dn().fromJson(t,i)}static fromJsonString(t,i){return new dn().fromJsonString(t,i)}static equals(t,i){return m.util.equals(dn,t,i)}};d(dn,"runtime",m),d(dn,"typeName","yorkie.v1.DeactivateClientRequest"),d(dn,"fields",m.util.newFieldList(()=>[{no:1,name:"client_id",kind:"scalar",T:9}]));let kc=dn;const pn=class pn extends D{constructor(e){super(),m.util.initPartial(e,this)}static fromBinary(e,t){return new pn().fromBinary(e,t)}static fromJson(e,t){return new pn().fromJson(e,t)}static fromJsonString(e,t){return new pn().fromJsonString(e,t)}static equals(e,t){return m.util.equals(pn,e,t)}};d(pn,"runtime",m),d(pn,"typeName","yorkie.v1.DeactivateClientResponse"),d(pn,"fields",m.util.newFieldList(()=>[]));let xc=pn;const gn=class gn extends D{constructor(t){super();d(this,"clientId","");d(this,"changePack");m.util.initPartial(t,this)}static fromBinary(t,i){return new gn().fromBinary(t,i)}static fromJson(t,i){return new gn().fromJson(t,i)}static fromJsonString(t,i){return new gn().fromJsonString(t,i)}static equals(t,i){return m.util.equals(gn,t,i)}};d(gn,"runtime",m),d(gn,"typeName","yorkie.v1.AttachDocumentRequest"),d(gn,"fields",m.util.newFieldList(()=>[{no:1,name:"client_id",kind:"scalar",T:9},{no:2,name:"change_pack",kind:"message",T:Wn}]));let Tc=gn;const mn=class mn extends D{constructor(t){super();d(this,"documentId","");d(this,"changePack");m.util.initPartial(t,this)}static fromBinary(t,i){return new mn().fromBinary(t,i)}static fromJson(t,i){return new mn().fromJson(t,i)}static fromJsonString(t,i){return new mn().fromJsonString(t,i)}static equals(t,i){return m.util.equals(mn,t,i)}};d(mn,"runtime",m),d(mn,"typeName","yorkie.v1.AttachDocumentResponse"),d(mn,"fields",m.util.newFieldList(()=>[{no:1,name:"document_id",kind:"scalar",T:9},{no:2,name:"change_pack",kind:"message",T:Wn}]));let Qc=mn;const On=class On extends D{constructor(t){super();d(this,"clientId","");d(this,"documentId","");d(this,"changePack");d(this,"removeIfNotAttached",!1);m.util.initPartial(t,this)}static fromBinary(t,i){return new On().fromBinary(t,i)}static fromJson(t,i){return new On().fromJson(t,i)}static fromJsonString(t,i){return new On().fromJsonString(t,i)}static equals(t,i){return m.util.equals(On,t,i)}};d(On,"runtime",m),d(On,"typeName","yorkie.v1.DetachDocumentRequest"),d(On,"fields",m.util.newFieldList(()=>[{no:1,name:"client_id",kind:"scalar",T:9},{no:2,name:"document_id",kind:"scalar",T:9},{no:3,name:"change_pack",kind:"message",T:Wn},{no:4,name:"remove_if_not_attached",kind:"scalar",T:8}]));let Pc=On;const yn=class yn extends D{constructor(t){super();d(this,"changePack");m.util.initPartial(t,this)}static fromBinary(t,i){return new yn().fromBinary(t,i)}static fromJson(t,i){return new yn().fromJson(t,i)}static fromJsonString(t,i){return new yn().fromJsonString(t,i)}static equals(t,i){return m.util.equals(yn,t,i)}};d(yn,"runtime",m),d(yn,"typeName","yorkie.v1.DetachDocumentResponse"),d(yn,"fields",m.util.newFieldList(()=>[{no:2,name:"change_pack",kind:"message",T:Wn}]));let Ac=yn;const bn=class bn extends D{constructor(t){super();d(this,"clientId","");d(this,"documentId","");m.util.initPartial(t,this)}static fromBinary(t,i){return new bn().fromBinary(t,i)}static fromJson(t,i){return new bn().fromJson(t,i)}static fromJsonString(t,i){return new bn().fromJsonString(t,i)}static equals(t,i){return m.util.equals(bn,t,i)}};d(bn,"runtime",m),d(bn,"typeName","yorkie.v1.WatchDocumentRequest"),d(bn,"fields",m.util.newFieldList(()=>[{no:1,name:"client_id",kind:"scalar",T:9},{no:2,name:"document_id",kind:"scalar",T:9}]));let $c=bn;const Sn=class Sn extends D{constructor(t){super();d(this,"body",{case:void 0});m.util.initPartial(t,this)}static fromBinary(t,i){return new Sn().fromBinary(t,i)}static fromJson(t,i){return new Sn().fromJson(t,i)}static fromJsonString(t,i){return new Sn().fromJsonString(t,i)}static equals(t,i){return m.util.equals(Sn,t,i)}};d(Sn,"runtime",m),d(Sn,"typeName","yorkie.v1.WatchDocumentResponse"),d(Sn,"fields",m.util.newFieldList(()=>[{no:1,name:"initialization",kind:"message",T:Ic,oneof:"body"},{no:2,name:"event",kind:"message",T:Sc,oneof:"body"}]));let Cc=Sn;const wn=class wn extends D{constructor(t){super();d(this,"clientIds",[]);m.util.initPartial(t,this)}static fromBinary(t,i){return new wn().fromBinary(t,i)}static fromJson(t,i){return new wn().fromJson(t,i)}static fromJsonString(t,i){return new wn().fromJsonString(t,i)}static equals(t,i){return m.util.equals(wn,t,i)}};d(wn,"runtime",m),d(wn,"typeName","yorkie.v1.WatchDocumentResponse.Initialization"),d(wn,"fields",m.util.newFieldList(()=>[{no:1,name:"client_ids",kind:"scalar",T:9,repeated:!0}]));let Ic=wn;const vn=class vn extends D{constructor(t){super();d(this,"clientId","");d(this,"documentId","");d(this,"changePack");m.util.initPartial(t,this)}static fromBinary(t,i){return new vn().fromBinary(t,i)}static fromJson(t,i){return new vn().fromJson(t,i)}static fromJsonString(t,i){return new vn().fromJsonString(t,i)}static equals(t,i){return m.util.equals(vn,t,i)}};d(vn,"runtime",m),d(vn,"typeName","yorkie.v1.RemoveDocumentRequest"),d(vn,"fields",m.util.newFieldList(()=>[{no:1,name:"client_id",kind:"scalar",T:9},{no:2,name:"document_id",kind:"scalar",T:9},{no:3,name:"change_pack",kind:"message",T:Wn}]));let Rc=vn;const kn=class kn extends D{constructor(t){super();d(this,"changePack");m.util.initPartial(t,this)}static fromBinary(t,i){return new kn().fromBinary(t,i)}static fromJson(t,i){return new kn().fromJson(t,i)}static fromJsonString(t,i){return new kn().fromJsonString(t,i)}static equals(t,i){return m.util.equals(kn,t,i)}};d(kn,"runtime",m),d(kn,"typeName","yorkie.v1.RemoveDocumentResponse"),d(kn,"fields",m.util.newFieldList(()=>[{no:1,name:"change_pack",kind:"message",T:Wn}]));let Ec=kn;const xn=class xn extends D{constructor(t){super();d(this,"clientId","");d(this,"documentId","");d(this,"changePack");d(this,"pushOnly",!1);m.util.initPartial(t,this)}static fromBinary(t,i){return new xn().fromBinary(t,i)}static fromJson(t,i){return new xn().fromJson(t,i)}static fromJsonString(t,i){return new xn().fromJsonString(t,i)}static equals(t,i){return m.util.equals(xn,t,i)}};d(xn,"runtime",m),d(xn,"typeName","yorkie.v1.PushPullChangesRequest"),d(xn,"fields",m.util.newFieldList(()=>[{no:1,name:"client_id",kind:"scalar",T:9},{no:2,name:"document_id",kind:"scalar",T:9},{no:3,name:"change_pack",kind:"message",T:Wn},{no:4,name:"push_only",kind:"scalar",T:8}]));let Dc=xn;const Tn=class Tn extends D{constructor(t){super();d(this,"changePack");m.util.initPartial(t,this)}static fromBinary(t,i){return new Tn().fromBinary(t,i)}static fromJson(t,i){return new Tn().fromJson(t,i)}static fromJsonString(t,i){return new Tn().fromJsonString(t,i)}static equals(t,i){return m.util.equals(Tn,t,i)}};d(Tn,"runtime",m),d(Tn,"typeName","yorkie.v1.PushPullChangesResponse"),d(Tn,"fields",m.util.newFieldList(()=>[{no:1,name:"change_pack",kind:"message",T:Wn}]));let Nc=Tn;const Qn=class Qn extends D{constructor(t){super();d(this,"clientId","");d(this,"documentId","");d(this,"topic","");d(this,"payload",new Uint8Array(0));m.util.initPartial(t,this)}static fromBinary(t,i){return new Qn().fromBinary(t,i)}static fromJson(t,i){return new Qn().fromJson(t,i)}static fromJsonString(t,i){return new Qn().fromJsonString(t,i)}static equals(t,i){return m.util.equals(Qn,t,i)}};d(Qn,"runtime",m),d(Qn,"typeName","yorkie.v1.BroadcastRequest"),d(Qn,"fields",m.util.newFieldList(()=>[{no:1,name:"client_id",kind:"scalar",T:9},{no:2,name:"document_id",kind:"scalar",T:9},{no:3,name:"topic",kind:"scalar",T:9},{no:4,name:"payload",kind:"scalar",T:12}]));let Bc=Qn;const Pn=class Pn extends D{constructor(e){super(),m.util.initPartial(e,this)}static fromBinary(e,t){return new Pn().fromBinary(e,t)}static fromJson(e,t){return new Pn().fromJson(e,t)}static fromJsonString(e,t){return new Pn().fromJsonString(e,t)}static equals(e,t){return m.util.equals(Pn,e,t)}};d(Pn,"runtime",m),d(Pn,"typeName","yorkie.v1.BroadcastResponse"),d(Pn,"fields",m.util.newFieldList(()=>[]));let qc=Pn;const L1={typeName:"yorkie.v1.YorkieService",methods:{activateClient:{name:"ActivateClient",I:wc,O:vc,kind:ze.Unary},deactivateClient:{name:"DeactivateClient",I:kc,O:xc,kind:ze.Unary},attachDocument:{name:"AttachDocument",I:Tc,O:Qc,kind:ze.Unary},detachDocument:{name:"DetachDocument",I:Pc,O:Ac,kind:ze.Unary},removeDocument:{name:"RemoveDocument",I:Rc,O:Ec,kind:ze.Unary},pushPullChanges:{name:"PushPullChanges",I:Dc,O:Nc,kind:ze.Unary},watchDocument:{name:"WatchDocument",I:$c,O:Cc,kind:ze.ServerStreaming},broadcast:{name:"Broadcast",I:Bc,O:qc,kind:ze.Unary}}},U1=m.makeMessageType("google.rpc.ErrorInfo",()=>[{no:1,name:"reason",kind:"scalar",T:9},{no:2,name:"domain",kind:"scalar",T:9},{no:3,name:"metadata",kind:"map",K:9,V:{kind:"scalar",T:9}}]);m.makeMessageType("google.rpc.RetryInfo",()=>[{no:1,name:"retry_delay",kind:"message",T:In}]);m.makeMessageType("google.rpc.DebugInfo",()=>[{no:1,name:"stack_entries",kind:"scalar",T:9,repeated:!0},{no:2,name:"detail",kind:"scalar",T:9}]);m.makeMessageType("google.rpc.QuotaFailure",()=>[{no:1,name:"violations",kind:"message",T:Z1,repeated:!0}]);const Z1=m.makeMessageType("google.rpc.QuotaFailure.Violation",()=>[{no:1,name:"subject",kind:"scalar",T:9},{no:2,name:"description",kind:"scalar",T:9}],{localName:"QuotaFailure_Violation"});m.makeMessageType("google.rpc.PreconditionFailure",()=>[{no:1,name:"violations",kind:"message",T:W1,repeated:!0}]);const W1=m.makeMessageType("google.rpc.PreconditionFailure.Violation",()=>[{no:1,name:"type",kind:"scalar",T:9},{no:2,name:"subject",kind:"scalar",T:9},{no:3,name:"description",kind:"scalar",T:9}],{localName:"PreconditionFailure_Violation"});m.makeMessageType("google.rpc.BadRequest",()=>[{no:1,name:"field_violations",kind:"message",T:j1,repeated:!0}]);const j1=m.makeMessageType("google.rpc.BadRequest.FieldViolation",()=>[{no:1,name:"field",kind:"scalar",T:9},{no:2,name:"description",kind:"scalar",T:9}],{localName:"BadRequest_FieldViolation"});m.makeMessageType("google.rpc.RequestInfo",()=>[{no:1,name:"request_id",kind:"scalar",T:9},{no:2,name:"serving_data",kind:"scalar",T:9}]);m.makeMessageType("google.rpc.ResourceInfo",()=>[{no:1,name:"resource_type",kind:"scalar",T:9},{no:2,name:"resource_name",kind:"scalar",T:9},{no:3,name:"owner",kind:"scalar",T:9},{no:4,name:"description",kind:"scalar",T:9}]);m.makeMessageType("google.rpc.Help",()=>[{no:1,name:"links",kind:"message",T:F1,repeated:!0}]);const F1=m.makeMessageType("google.rpc.Help.Link",()=>[{no:1,name:"description",kind:"scalar",T:9},{no:2,name:"url",kind:"scalar",T:9}],{localName:"Help_Link"});m.makeMessageType("google.rpc.LocalizedMessage",()=>[{no:1,name:"locale",kind:"scalar",T:9},{no:2,name:"message",kind:"scalar",T:9}]);var w=(n=>(n.Ok="ok",n.ErrClientNotActivated="ErrClientNotActivated",n.ErrClientNotFound="ErrClientNotFound",n.ErrUnimplemented="ErrUnimplemented",n.ErrInvalidType="ErrInvalidType",n.ErrDummy="ErrDummy",n.ErrDocumentNotAttached="ErrDocumentNotAttached",n.ErrDocumentNotDetached="ErrDocumentNotDetached",n.ErrDocumentRemoved="ErrDocumentRemoved",n.ErrInvalidObjectKey="ErrInvalidObjectKey",n.ErrInvalidArgument="ErrInvalidArgument",n.ErrNotInitialized="ErrNotInitialized",n.ErrNotReady="ErrNotReady",n.ErrRefused="ErrRefused",n.ErrContextNotProvided="ErrContextNotProvided",n))(w||{});class v extends Error{constructor(t,i){super(i);d(this,"name","YorkieError");d(this,"stack");this.code=t,this.message=i,this.toString=()=>`[code=${this.code}]: ${this.message}`}}function Wt(n){if(n instanceof Map){const e=Array.from(n);return new Map(JSON.parse(JSON.stringify(e)))}return JSON.parse(JSON.stringify(n))}const Ym=n=>n?Object.entries(n).length===0:!0,us=n=>{const e={};for(const[t,i]of Object.entries(n))e[t]=JSON.stringify(i);return e},es=n=>{const e={};for(const[t,i]of Object.entries(n))e[t]=JSON.parse(i);return e};var cr=(n=>(n.Put="put",n.Clear="clear",n))(cr||{});class Ph{constructor(e,t){d(this,"context");d(this,"presence");this.context=e,this.presence=t}set(e,t){for(const i of Object.keys(e))this.presence[i]=e[i];this.context.setPresenceChange({type:"put",presence:Wt(this.presence)}),this.context.setReversePresence(e,t)}get(e){return this.presence[e]}clear(){this.presence={},this.context.setPresenceChange({type:"clear"})}}const zu="000000000000000000000000",z1="FFFFFFFFFFFFFFFFFFFFFFFF";class dt{constructor(e,t,i){d(this,"lamport");d(this,"delimiter");d(this,"actorID");this.lamport=e,this.delimiter=t,this.actorID=i}static of(e,t,i){return new dt(e,t,i)}static fromStruct(e){return dt.of(BigInt(e.lamport),e.delimiter,e.actorID)}toIDString(){return`${this.lamport.toString()}:${this.actorID}:${this.delimiter}`}toStruct(){return{lamport:this.getLamportAsString(),delimiter:this.getDelimiter(),actorID:this.getActorID()}}toTestString(){return`${this.lamport.toString()}:${this.actorID.slice(-2)}:${this.delimiter}`}setActor(e){return new dt(this.lamport,this.delimiter,e)}getLamportAsString(){return this.lamport.toString()}getLamport(){return this.lamport}getDelimiter(){return this.delimiter}getActorID(){return this.actorID}after(e){return this.compare(e)>0}equals(e){return this.compare(e)===0}compare(e){if(this.lamport>e.lamport)return 1;if(e.lamport>this.lamport)return-1;const t=this.actorID.localeCompare(e.actorID);return t!==0?t:this.delimiter>e.delimiter?1:e.delimiter>this.delimiter?-1:0}}const Hm=0,_1=4294967295,G1=9223372036854775807n,Gt=new dt(0n,Hm,zu),Ys=new dt(G1,_1,z1);function wi(n){return n.replace(/["'\\\n\r\f\b\t\u2028\u2029]/g,function(e){switch(e){case'"':case"\\":return"\\"+e;case` `:return"\\n";case"\r":return"\\r";case"\f":return"\\f";case"\b":return"\\b";case" ":return"\\t";case"\u2028":return"\\u2028";case"\u2029":return"\\u2029";default:return e}})}class qo{constructor(e){d(this,"createdAt");d(this,"movedAt");d(this,"removedAt");this.createdAt=e}getCreatedAt(){return this.createdAt}getID(){return this.createdAt}getMovedAt(){return this.movedAt}getRemovedAt(){return this.removedAt}getPositionedAt(){return this.movedAt?this.movedAt:this.createdAt}setMovedAt(e){return!this.movedAt||e&&e.after(this.movedAt)?(this.movedAt=e,!0):!1}setRemovedAt(e){this.removedAt=e}remove(e){return e&&e.after(this.getPositionedAt())&&(!this.removedAt||e.after(this.removedAt))?(this.removedAt=e,!0):!1}isRemoved(){return!!this.removedAt}}class rr extends qo{constructor(e){super(e)}}class _u{constructor(e,t){d(this,"strKey");d(this,"value");this.strKey=e,this.value=t}static of(e,t){return new _u(e,t)}isRemoved(){return this.value.isRemoved()}getStrKey(){return this.strKey}getValue(){return this.value}remove(e){return this.value.remove(e)}}class uo{constructor(){d(this,"nodeMapByKey");d(this,"nodeMapByCreatedAt");this.nodeMapByKey=new Map,this.nodeMapByCreatedAt=new Map}static create(){return new uo}set(e,t,i){let r;const s=this.nodeMapByKey.get(e);s!=null&&!s.isRemoved()&&s.remove(i)&&(r=s.getValue());const o=_u.of(e,t);return this.nodeMapByCreatedAt.set(t.getCreatedAt().toIDString(),o),(s==null||i.after(s.getValue().getPositionedAt()))&&(this.nodeMapByKey.set(e,o),t.setMovedAt(i)),r}delete(e,t){if(!this.nodeMapByCreatedAt.has(e.toIDString()))throw new v(w.ErrInvalidArgument,`fail to find ${e.toIDString()}`);const i=this.nodeMapByCreatedAt.get(e.toIDString());return i.remove(t),i.getValue()}subPathOf(e){const t=this.nodeMapByCreatedAt.get(e.toIDString());if(t)return t.getStrKey()}purge(e){const t=this.nodeMapByCreatedAt.get(e.getCreatedAt().toIDString());if(!t)throw new v(w.ErrInvalidArgument,`fail to find ${e.getCreatedAt().toIDString()}`);const i=this.nodeMapByKey.get(t.getStrKey());t===i&&this.nodeMapByKey.delete(i.getStrKey()),this.nodeMapByCreatedAt.delete(t.getValue().getCreatedAt().toIDString())}deleteByKey(e,t){const i=this.nodeMapByKey.get(e);if(i!=null&&i.remove(t))return i.getValue()}has(e){const t=this.nodeMapByKey.get(e);return t==null?!1:!t.isRemoved()}getByID(e){return this.nodeMapByCreatedAt.get(e.toIDString())}get(e){const t=this.nodeMapByKey.get(e);if(!(!t||t.isRemoved()))return t}*[Symbol.iterator](){for(const[,e]of this.nodeMapByKey)yield e}}class nt extends rr{constructor(t,i){super(t);d(this,"memberNodes");this.memberNodes=i}static create(t,i){if(!i)return new nt(t,uo.create());const r=uo.create();for(const[s,o]of Object.entries(i))r.set(s,o.deepcopy(),o.getCreatedAt());return new nt(t,r)}subPathOf(t){return this.memberNodes.subPathOf(t)}purge(t){this.memberNodes.purge(t)}set(t,i,r){return this.memberNodes.set(t,i,r)}delete(t,i){return this.memberNodes.delete(t,i)}deleteByKey(t,i){return this.memberNodes.deleteByKey(t,i)}get(t){const i=this.memberNodes.get(t);return i==null?void 0:i.getValue()}getByID(t){const i=this.memberNodes.getByID(t);return i==null?void 0:i.getValue()}has(t){return this.memberNodes.has(t)}toJSON(){const t=[];for(const[i,r]of this)t.push(`"${wi(i)}":${r.toJSON()}`);return`{${t.join(",")}}`}toJS(){return JSON.parse(this.toJSON())}toJSForTest(){const t={};for(const[i,r]of this){const{createdAt:s,value:o,type:a}=r.toJSForTest();t[i]={key:i,createdAt:s,value:o,type:a}}return{createdAt:this.getCreatedAt().toTestString(),value:t,type:"YORKIE_OBJECT"}}getKeys(){const t=Array();for(const[i]of this)t.push(i);return t}toSortedJSON(){var r;const t=Array();for(const[s]of this)t.push(s);const i=[];for(const s of t.sort()){const o=(r=this.memberNodes.get(s))==null?void 0:r.getValue();i.push(`"${wi(s)}":${o.toSortedJSON()}`)}return`{${i.join(",")}}`}getRHT(){return this.memberNodes}deepcopy(){const t=nt.create(this.getCreatedAt());for(const i of this.memberNodes)t.memberNodes.set(i.getStrKey(),i.getValue().deepcopy(),this.getPositionedAt());return t.remove(this.getRemovedAt()),t}getDescendants(t){for(const i of this.memberNodes){const r=i.getValue();if(t(r,this))return;r instanceof rr&&r.getDescendants(t)}}*[Symbol.iterator](){const t=new Set;for(const i of this.memberNodes)t.has(i.getStrKey())||(t.add(i.getStrKey()),i.isRemoved()||(yield[i.getStrKey(),i.getValue()]))}}var se=(n=>(n.Local="local",n.Remote="remote",n.UndoRedo="undoredo",n))(se||{});class Yt{constructor(e,t){d(this,"parentCreatedAt");d(this,"executedAt");this.parentCreatedAt=e,this.executedAt=t}getParentCreatedAt(){return this.parentCreatedAt}getExecutedAt(){if(!this.executedAt)throw new v(w.ErrNotReady,"executedAt is not set yet");return this.executedAt}setActor(e){this.executedAt&&(this.executedAt=this.executedAt.setActor(e))}setExecutedAt(e){this.executedAt=e}}class Km{constructor(e){d(this,"value");d(this,"left");d(this,"right");d(this,"parent");d(this,"weight");this.value=e,this.initWeight()}getNodeString(){return`${this.weight}${this.value}`}getValue(){return this.value}getLeftWeight(){return this.hasLeft()?this.left.getWeight():0}getRightWeight(){return this.hasRight()?this.right.getWeight():0}getWeight(){return this.weight}getLeft(){return this.left}getRight(){return this.right}getParent(){return this.parent}hasLeft(){return!!this.left}hasRight(){return!!this.right}hasParent(){return!!this.parent}setLeft(e){this.left=e}setRight(e){this.right=e}setParent(e){this.parent=e}unlink(){this.parent=void 0,this.right=void 0,this.left=void 0}hasLinks(){return this.hasParent()||this.hasLeft()||this.hasRight()}increaseWeight(e){this.weight+=e}initWeight(){this.weight=this.getLength()}}class fo{constructor(e){d(this,"root");this.root=e}get length(){return this.root?this.root.getWeight():0}find(e){if(!this.root||e<0)return[void 0,0];let t=this.root;for(;;)if(t.hasLeft()&&e<=t.getLeftWeight())t=t.getLeft();else if(t.hasRight()&&t.getLeftWeight()+t.getLength()t.getLength())throw new v(w.ErrInvalidArgument,`out of index range: pos: ${e} > node.length: ${t.getLength()}`);return this.splayNode(t),[t,e]}indexOf(e){return!e||e!==this.root&&!e.hasLinks()?-1:(this.splayNode(e),this.root.getLeftWeight())}getRoot(){return this.root}insert(e){return this.insertAfter(this.root,e)}insertAfter(e,t){return e?(this.splayNode(e),this.root=t,t.setRight(e.getRight()),e.hasRight()&&e.getRight().setParent(t),t.setLeft(e),e.setParent(t),e.setRight(),this.updateWeight(e),this.updateWeight(t),t):(this.root=t,t)}updateWeight(e){e.initWeight(),e.hasLeft()&&e.increaseWeight(e.getLeftWeight()),e.hasRight()&&e.increaseWeight(e.getRightWeight())}updateTreeWeight(e){for(;e;)this.updateWeight(e),e=e.getParent()}splayNode(e){if(e)for(;;)if(this.isLeftChild(e.getParent())&&this.isRightChild(e))this.rotateLeft(e),this.rotateRight(e);else if(this.isRightChild(e.getParent())&&this.isLeftChild(e))this.rotateRight(e),this.rotateLeft(e);else if(this.isLeftChild(e.getParent())&&this.isLeftChild(e))this.rotateRight(e.getParent()),this.rotateRight(e);else if(this.isRightChild(e.getParent())&&this.isRightChild(e))this.rotateLeft(e.getParent()),this.rotateLeft(e);else{this.isLeftChild(e)?this.rotateRight(e):this.isRightChild(e)&&this.rotateLeft(e),this.updateWeight(e);return}}delete(e){this.splayNode(e);const t=new fo(e.getLeft());t.root&&t.root.setParent();const i=new fo(e.getRight());if(i.root&&i.root.setParent(),t.root){const r=t.getRightmost();t.splayNode(r),t.root.setRight(i.root),i.root&&i.root.setParent(t.root),this.root=t.root}else this.root=i.root;e.unlink(),this.root&&this.updateWeight(this.root)}deleteRange(e,t){if(!t){this.splayNode(e),this.cutOffRight(e);return}this.splayNode(e),this.splayNode(t),t.getLeft()!=e&&this.rotateRight(e),this.cutOffRight(e)}cutOffRight(e){const t=[];this.traversePostorder(e.getRight(),t);for(const i of t)i.initWeight();this.updateTreeWeight(e)}toTestString(){const e=[];return this.traverseInorder(this.root,e),e.map(t=>`[${t.getWeight()},${t.getLength()}]${t.getValue()||""}`).join("")}checkWeight(){const e=[];this.traverseInorder(this.root,e);for(const t of e)if(t.getWeight()!=t.getLength()+t.getLeftWeight()+t.getRightWeight())return!1;return!0}getRightmost(){let e=this.root;for(;e.hasRight();)e=e.getRight();return e}traverseInorder(e,t){e&&(this.traverseInorder(e.getLeft(),t),t.push(e),this.traverseInorder(e.getRight(),t))}traversePostorder(e,t){e&&(this.traversePostorder(e.getLeft(),t),this.traversePostorder(e.getRight(),t),t.push(e))}rotateLeft(e){const t=e.getParent();t.hasParent()?t===t.getParent().getLeft()?t.getParent().setLeft(e):t.getParent().setRight(e):this.root=e,e.setParent(t.getParent()),t.setRight(e.getLeft()),t.hasRight()&&t.getRight().setParent(t),e.setLeft(t),e.getLeft().setParent(e),this.updateWeight(t),this.updateWeight(e)}rotateRight(e){const t=e.getParent();t.hasParent()?t===t.getParent().getLeft()?t.getParent().setLeft(e):t.getParent().setRight(e):this.root=e,e.setParent(t.getParent()),t.setLeft(e.getRight()),t.hasLeft()&&t.getLeft().setParent(t),e.setRight(t),e.getRight().setParent(e),this.updateWeight(t),this.updateWeight(e)}isLeftChild(e){return e&&e.hasParent()?e.getParent().getLeft()===e:!1}isRightChild(e){return e&&e.hasParent()?e.getParent().getRight()===e:!1}}/** * @license * Copyright 2009 The Closure Library Authors @@ -19,25 +19,25 @@ var yS=Object.defineProperty;var bS=(n,e,t)=>e in n?yS(n,e,{enumerable:!0,config * limitations under the License. * * SPDX-License-Identifier: Apache-2.0 - */var Ct=null;try{Ct=new WebAssembly.Instance(new WebAssembly.Module(new Uint8Array([0,97,115,109,1,0,0,0,1,13,2,96,0,1,127,96,4,127,127,127,127,1,127,3,7,6,0,1,1,1,1,1,6,6,1,127,1,65,0,11,7,50,6,3,109,117,108,0,1,5,100,105,118,95,115,0,2,5,100,105,118,95,117,0,3,5,114,101,109,95,115,0,4,5,114,101,109,95,117,0,5,8,103,101,116,95,104,105,103,104,0,0,10,191,1,6,4,0,35,0,11,36,1,1,126,32,0,173,32,1,173,66,32,134,132,32,2,173,32,3,173,66,32,134,132,126,34,4,66,32,135,167,36,0,32,4,167,11,36,1,1,126,32,0,173,32,1,173,66,32,134,132,32,2,173,32,3,173,66,32,134,132,127,34,4,66,32,135,167,36,0,32,4,167,11,36,1,1,126,32,0,173,32,1,173,66,32,134,132,32,2,173,32,3,173,66,32,134,132,128,34,4,66,32,135,167,36,0,32,4,167,11,36,1,1,126,32,0,173,32,1,173,66,32,134,132,32,2,173,32,3,173,66,32,134,132,129,34,4,66,32,135,167,36,0,32,4,167,11,36,1,1,126,32,0,173,32,1,173,66,32,134,132,32,2,173,32,3,173,66,32,134,132,130,34,4,66,32,135,167,36,0,32,4,167,11])),{}).exports}catch{}function Y(n,e,t){this.low=n|0,this.high=e|0,this.unsigned=!!t}Y.prototype.__isLong__;Object.defineProperty(Y.prototype,"__isLong__",{value:!0});function je(n){return(n&&n.__isLong__)===!0}function Cd(n){var e=Math.clz32(n&-n);return n?31-e:e}Y.isLong=je;var Id={},Rd={};function Xr(n,e){var t,i,r;return e?(n>>>=0,(r=0<=n&&n<256)&&(i=Rd[n],i)?i:(t=ee(n,0,!0),r&&(Rd[n]=t),t)):(n|=0,(r=-128<=n&&n<128)&&(i=Id[n],i)?i:(t=ee(n,n<0?-1:0,!1),r&&(Id[n]=t),t))}Y.fromInt=Xr;function It(n,e){if(isNaN(n))return e?En:zt;if(e){if(n<0)return En;if(n>=eO)return nO}else{if(n<=-Dd)return tt;if(n+1>=Dd)return iO}return n<0?It(-n,e).neg():ee(n%fs|0,n/fs|0,e)}Y.fromNumber=It;function ee(n,e,t){return new Y(n,e,t)}Y.fromBits=ee;var yl=Math.pow;function Gu(n,e,t){if(n.length===0)throw Error("empty string");if(typeof e=="number"?(t=e,e=!1):e=!!e,n==="NaN"||n==="Infinity"||n==="+Infinity"||n==="-Infinity")return e?En:zt;if(t=t||10,t<2||360)throw Error("interior hyphen");if(i===0)return Gu(n.substring(1),e,t).neg();for(var r=It(yl(t,8)),s=zt,o=0;o>>0:this.low};C.toNumber=function(){return this.unsigned?(this.high>>>0)*fs+(this.low>>>0):this.high*fs+(this.low>>>0)};C.toString=function(e){if(e=e||10,e<2||36>>0,c=h.toString(e);if(o=l,o.isZero())return c+a;for(;c.length<6;)c="0"+c;a=""+c+a}};C.getHighBits=function(){return this.high};C.getHighBitsUnsigned=function(){return this.high>>>0};C.getLowBits=function(){return this.low};C.getLowBitsUnsigned=function(){return this.low>>>0};C.getNumBitsAbs=function(){if(this.isNegative())return this.eq(tt)?64:this.neg().getNumBitsAbs();for(var e=this.high!=0?this.high:this.low,t=31;t>0&&!(e&1<=0};C.isOdd=function(){return(this.low&1)===1};C.isEven=function(){return(this.low&1)===0};C.equals=function(e){return je(e)||(e=ei(e)),this.unsigned!==e.unsigned&&this.high>>>31===1&&e.high>>>31===1?!1:this.high===e.high&&this.low===e.low};C.eq=C.equals;C.notEquals=function(e){return!this.eq(e)};C.neq=C.notEquals;C.ne=C.notEquals;C.lessThan=function(e){return this.comp(e)<0};C.lt=C.lessThan;C.lessThanOrEqual=function(e){return this.comp(e)<=0};C.lte=C.lessThanOrEqual;C.le=C.lessThanOrEqual;C.greaterThan=function(e){return this.comp(e)>0};C.gt=C.greaterThan;C.greaterThanOrEqual=function(e){return this.comp(e)>=0};C.gte=C.greaterThanOrEqual;C.ge=C.greaterThanOrEqual;C.compare=function(e){if(je(e)||(e=ei(e)),this.eq(e))return 0;var t=this.isNegative(),i=e.isNegative();return t&&!i?-1:!t&&i?1:this.unsigned?e.high>>>0>this.high>>>0||e.high===this.high&&e.low>>>0>this.low>>>0?-1:1:this.sub(e).isNegative()?-1:1};C.comp=C.compare;C.negate=function(){return!this.unsigned&&this.eq(tt)?tt:this.not().add(Gr)};C.neg=C.negate;C.add=function(e){je(e)||(e=ei(e));var t=this.high>>>16,i=this.high&65535,r=this.low>>>16,s=this.low&65535,o=e.high>>>16,a=e.high&65535,l=e.low>>>16,h=e.low&65535,c=0,u=0,f=0,p=0;return p+=s+h,f+=p>>>16,p&=65535,f+=r+l,u+=f>>>16,f&=65535,u+=i+a,c+=u>>>16,u&=65535,c+=t+o,c&=65535,ee(f<<16|p,c<<16|u,this.unsigned)};C.subtract=function(e){return je(e)||(e=ei(e)),this.add(e.neg())};C.sub=C.subtract;C.multiply=function(e){if(this.isZero())return this;if(je(e)||(e=ei(e)),Ct){var t=Ct.mul(this.low,this.high,e.low,e.high);return ee(t,Ct.get_high(),this.unsigned)}if(e.isZero())return this.unsigned?En:zt;if(this.eq(tt))return e.isOdd()?tt:zt;if(e.eq(tt))return this.isOdd()?tt:zt;if(this.isNegative())return e.isNegative()?this.neg().mul(e.neg()):this.neg().mul(e).neg();if(e.isNegative())return this.mul(e.neg()).neg();if(this.lt(Nd)&&e.lt(Nd))return It(this.toNumber()*e.toNumber(),this.unsigned);var i=this.high>>>16,r=this.high&65535,s=this.low>>>16,o=this.low&65535,a=e.high>>>16,l=e.high&65535,h=e.low>>>16,c=e.low&65535,u=0,f=0,p=0,g=0;return g+=o*c,p+=g>>>16,g&=65535,p+=s*c,f+=p>>>16,p&=65535,p+=o*h,f+=p>>>16,p&=65535,f+=r*c,u+=f>>>16,f&=65535,f+=s*h,u+=f>>>16,f&=65535,f+=o*l,u+=f>>>16,f&=65535,u+=i*c+r*h+s*l+o*a,u&=65535,ee(p<<16|g,u<<16|f,this.unsigned)};C.mul=C.multiply;C.divide=function(e){if(je(e)||(e=ei(e)),e.isZero())throw Error("division by zero");if(Ct){if(!this.unsigned&&this.high===-2147483648&&e.low===-1&&e.high===-1)return this;var t=(this.unsigned?Ct.div_u:Ct.div_s)(this.low,this.high,e.low,e.high);return ee(t,Ct.get_high(),this.unsigned)}if(this.isZero())return this.unsigned?En:zt;var i,r,s;if(this.unsigned){if(e.unsigned||(e=e.toUnsigned()),e.gt(this))return En;if(e.gt(this.shru(1)))return tO;s=En}else{if(this.eq(tt)){if(e.eq(Gr)||e.eq(Mc))return tt;if(e.eq(tt))return Gr;var o=this.shr(1);return i=o.div(e).shl(1),i.eq(zt)?e.isNegative()?Gr:Mc:(r=this.sub(e.mul(i)),s=i.add(r.div(e)),s)}else if(e.eq(tt))return this.unsigned?En:zt;if(this.isNegative())return e.isNegative()?this.neg().div(e.neg()):this.neg().div(e).neg();if(e.isNegative())return this.div(e.neg()).neg();s=zt}for(r=this;r.gte(e);){i=Math.max(1,Math.floor(r.toNumber()/e.toNumber()));for(var a=Math.ceil(Math.log(i)/Math.LN2),l=a<=48?1:yl(2,a-48),h=It(i),c=h.mul(e);c.isNegative()||c.gt(r);)i-=l,h=It(i,this.unsigned),c=h.mul(e);h.isZero()&&(h=Gr),s=s.add(h),r=r.sub(c)}return s};C.div=C.divide;C.modulo=function(e){if(je(e)||(e=ei(e)),Ct){var t=(this.unsigned?Ct.rem_u:Ct.rem_s)(this.low,this.high,e.low,e.high);return ee(t,Ct.get_high(),this.unsigned)}return this.sub(this.div(e).mul(e))};C.mod=C.modulo;C.rem=C.modulo;C.not=function(){return ee(~this.low,~this.high,this.unsigned)};C.countLeadingZeros=function(){return this.high?Math.clz32(this.high):Math.clz32(this.low)+32};C.clz=C.countLeadingZeros;C.countTrailingZeros=function(){return this.low?Cd(this.low):Cd(this.high)+32};C.ctz=C.countTrailingZeros;C.and=function(e){return je(e)||(e=ei(e)),ee(this.low&e.low,this.high&e.high,this.unsigned)};C.or=function(e){return je(e)||(e=ei(e)),ee(this.low|e.low,this.high|e.high,this.unsigned)};C.xor=function(e){return je(e)||(e=ei(e)),ee(this.low^e.low,this.high^e.high,this.unsigned)};C.shiftLeft=function(e){return je(e)&&(e=e.toInt()),(e&=63)===0?this:e<32?ee(this.low<>>32-e,this.unsigned):ee(0,this.low<>>e|this.high<<32-e,this.high>>e,this.unsigned):ee(this.high>>e-32,this.high>=0?0:-1,this.unsigned)};C.shr=C.shiftRight;C.shiftRightUnsigned=function(e){return je(e)&&(e=e.toInt()),(e&=63)===0?this:e<32?ee(this.low>>>e|this.high<<32-e,this.high>>>e,this.unsigned):e===32?ee(this.high,0,this.unsigned):ee(this.high>>>e-32,0,this.unsigned)};C.shru=C.shiftRightUnsigned;C.shr_u=C.shiftRightUnsigned;C.rotateLeft=function(e){var t;return je(e)&&(e=e.toInt()),(e&=63)===0?this:e===32?ee(this.high,this.low,this.unsigned):e<32?(t=32-e,ee(this.low<>>t,this.high<>>t,this.unsigned)):(e-=32,t=32-e,ee(this.high<>>t,this.low<>>t,this.unsigned))};C.rotl=C.rotateLeft;C.rotateRight=function(e){var t;return je(e)&&(e=e.toInt()),(e&=63)===0?this:e===32?ee(this.high,this.low,this.unsigned):e<32?(t=32-e,ee(this.high<>>e,this.low<>>e,this.unsigned)):(e-=32,t=32-e,ee(this.low<>>e,this.high<>>e,this.unsigned))};C.rotr=C.rotateRight;C.toSigned=function(){return this.unsigned?ee(this.low,this.high,!1):this};C.toUnsigned=function(){return this.unsigned?this:ee(this.low,this.high,!0)};C.toBytes=function(e){return e?this.toBytesLE():this.toBytesBE()};C.toBytesLE=function(){var e=this.high,t=this.low;return[t&255,t>>>8&255,t>>>16&255,t>>>24,e&255,e>>>8&255,e>>>16&255,e>>>24]};C.toBytesBE=function(){var e=this.high,t=this.low;return[e>>>24,e>>>16&255,e>>>8&255,e&255,t>>>24,t>>>16&255,t>>>8&255,t&255]};Y.fromBytes=function(e,t,i){return i?Y.fromBytesLE(e,t):Y.fromBytesBE(e,t)};Y.fromBytesLE=function(e,t){return new Y(e[0]|e[1]<<8|e[2]<<16|e[3]<<24,e[4]|e[5]<<8|e[6]<<16|e[7]<<24,t)};Y.fromBytesBE=function(e,t){return new Y(e[4]<<24|e[5]<<16|e[6]<<8|e[7],e[0]<<24|e[1]<<16|e[2]<<8|e[3],t)};var $e=(n=>(n[n.Null=0]="Null",n[n.Boolean=1]="Boolean",n[n.Integer=2]="Integer",n[n.Long=3]="Long",n[n.Double=4]="Double",n[n.String=5]="String",n[n.Bytes=6]="Bytes",n[n.Date=7]="Date",n))($e||{});class pe extends qo{constructor(t,i){super(i);d(this,"valueType");d(this,"value");this.valueType=pe.getPrimitiveType(t),this.value=t===void 0?null:t}static of(t,i){return new pe(t,i)}static valueFromBytes(t,i){switch(t){case 0:return null;case 1:return!!i[0];case 2:return i[0]|i[1]<<8|i[2]<<16|i[3]<<24;case 4:{const r=new DataView(i.buffer);return i.forEach(function(s,o){r.setUint8(o,s)}),r.getFloat64(0,!0)}case 5:return new TextDecoder("utf-8").decode(i);case 3:return Y.fromBytesLE(Array.from(i));case 6:return i;case 7:return new Date(Y.fromBytesLE(Array.from(i),!0).toNumber());default:throw new v(w.ErrUnimplemented,`unimplemented type: ${t}`)}}toJSON(){return this.valueType===5?`"${wi(this.value)}"`:`${this.value}`}toSortedJSON(){return this.toJSON()}toJSForTest(){return{createdAt:this.getCreatedAt().toTestString(),value:this.value,type:"YORKIE_PRIMITIVE"}}deepcopy(){const t=pe.of(this.value,this.getCreatedAt());return t.setMovedAt(this.getMovedAt()),t.setRemovedAt(this.getRemovedAt()),t}getType(){return this.valueType}static getPrimitiveType(t){switch(typeof t){case"undefined":return 0;case"boolean":return 1;case"number":return this.isInteger(t)?2:4;case"string":return 5;case"object":if(t===null)return 0;if(t instanceof Y)return 3;if(t instanceof Uint8Array)return 6;if(t instanceof Date)return 7}}static isSupport(t){return pe.getPrimitiveType(t)!==void 0}static isInteger(t){return t%1===0}isNumericType(){const t=this.valueType;return t===2||t===3||t===4}getValue(){return this.value}toBytes(){switch(this.valueType){case 0:return new Uint8Array;case 1:return this.value?new Uint8Array([1]):new Uint8Array([0]);case 2:{const t=this.value;return new Uint8Array([t&255,t>>8&255,t>>16&255,t>>24&255])}case 4:{const t=this.value,i=new Uint8Array(8);return new DataView(i.buffer).setFloat64(0,t,!0),i}case 5:return new TextEncoder().encode(this.value);case 3:{const i=this.value.toBytesLE();return Uint8Array.from(i)}case 6:return this.value;case 7:{const t=this.value,i=Y.fromNumber(t.getTime(),!0).toBytesLE();return Uint8Array.from(i)}default:throw new v(w.ErrUnimplemented,`unimplemented type: ${this.valueType}`)}}}class bl extends Km{constructor(t){super(t);d(this,"prev");d(this,"next");this.value=t}static createAfter(t,i){const r=new bl(i),s=t.next;return t.next=r,r.prev=t,r.next=s,s&&(s.prev=r),r}remove(t){return this.value.remove(t)}getCreatedAt(){return this.value.getCreatedAt()}getPositionedAt(){return this.value.getPositionedAt()}release(){this.prev&&(this.prev.next=this.next),this.next&&(this.next.prev=this.prev),this.prev=void 0,this.next=void 0}getLength(){return this.value.isRemoved()?0:1}getPrev(){return this.prev}getNext(){return this.next}getValue(){return this.value}isRemoved(){return this.value.isRemoved()}}class po{constructor(){d(this,"dummyHead");d(this,"last");d(this,"nodeMapByIndex");d(this,"nodeMapByCreatedAt");const e=pe.of(0,Gt);e.setRemovedAt(Gt),this.dummyHead=new bl(e),this.last=this.dummyHead,this.nodeMapByIndex=new fo,this.nodeMapByCreatedAt=new Map,this.nodeMapByIndex.insert(this.dummyHead),this.nodeMapByCreatedAt.set(this.dummyHead.getCreatedAt().toIDString(),this.dummyHead)}static create(){return new po}get length(){return this.nodeMapByIndex.length}findNextBeforeExecutedAt(e,t){let i=this.nodeMapByCreatedAt.get(e.toIDString());if(!i)throw new v(w.ErrInvalidArgument,`cant find the given node: ${e.toIDString()}`);for(;i.getNext()&&i.getNext().getPositionedAt().after(t);)i=i.getNext();return i}release(e){this.last===e&&(this.last=e.getPrev()),e.release(),this.nodeMapByIndex.delete(e),this.nodeMapByCreatedAt.delete(e.getValue().getCreatedAt().toIDString())}insertAfter(e,t,i=t.getCreatedAt()){const r=this.findNextBeforeExecutedAt(e,i),s=bl.createAfter(r,t);r===this.last&&(this.last=s),this.nodeMapByIndex.insertAfter(r,s),this.nodeMapByCreatedAt.set(s.getCreatedAt().toIDString(),s)}moveAfter(e,t,i){const r=this.nodeMapByCreatedAt.get(e.toIDString());if(!r)throw new v(w.ErrInvalidArgument,`cant find the given node: ${e.toIDString()}`);const s=this.nodeMapByCreatedAt.get(t.toIDString());if(!s)throw new v(w.ErrInvalidArgument,`cant find the given node: ${t.toIDString()}`);r!==s&&(!s.getValue().getMovedAt()||i.after(s.getValue().getMovedAt()))&&(this.release(s),this.insertAfter(r.getCreatedAt(),s.getValue(),i),s.getValue().setMovedAt(i))}insert(e){this.insertAfter(this.last.getCreatedAt(),e)}getByID(e){return this.nodeMapByCreatedAt.get(e.toIDString())}subPathOf(e){const t=this.nodeMapByCreatedAt.get(e.toIDString());if(t)return String(this.nodeMapByIndex.indexOf(t))}purge(e){const t=this.nodeMapByCreatedAt.get(e.getCreatedAt().toIDString());if(!t)throw new v(w.ErrInvalidArgument,`fail to find the given createdAt: ${e.getCreatedAt().toIDString()}`);this.release(t)}getByIndex(e){if(e>=this.length)return;const[t,i]=this.nodeMapByIndex.find(e);let r=t;if(e===0&&t===this.dummyHead||i>0)do r&&(r=r.getNext());while(r&&r.isRemoved());return r}getPrevCreatedAt(e){let t=this.nodeMapByCreatedAt.get(e.toIDString());do t=t.getPrev();while(this.dummyHead!==t&&t.isRemoved());return t.getValue().getCreatedAt()}delete(e,t){const i=this.nodeMapByCreatedAt.get(e.toIDString()),r=i.isRemoved();return i.remove(t)&&!r&&this.nodeMapByIndex.splayNode(i),i.getValue()}deleteByIndex(e,t){const i=this.getByIndex(e);if(i)return i.remove(t)&&this.nodeMapByIndex.splayNode(i),i.getValue()}getHead(){return this.dummyHead.getValue()}getLast(){return this.last.getValue()}getLastCreatedAt(){return this.last.getCreatedAt()}toTestString(){const e=[];for(const t of this){const i=`${t.getCreatedAt().toIDString()}:${t.getValue().toJSON()}`;t.isRemoved()?e.push(`{${i}}`):e.push(`[${i}]`)}return e.join("")}*[Symbol.iterator](){let e=this.dummyHead.getNext();for(;e;)yield e,e=e.getNext()}}class pt extends rr{constructor(t,i){super(t);d(this,"elements");this.elements=i}static create(t,i){if(!i)return new pt(t,po.create());const r=po.create();for(const s of i)r.insertAfter(r.getLastCreatedAt(),s.deepcopy());return new pt(t,r)}subPathOf(t){return this.elements.subPathOf(t)}purge(t){this.elements.purge(t)}insertAfter(t,i){this.elements.insertAfter(t,i)}moveAfter(t,i,r){this.elements.moveAfter(t,i,r)}get(t){const i=this.elements.getByIndex(t);return i==null?void 0:i.getValue()}getByID(t){const i=this.elements.getByID(t);return i==null?void 0:i.getValue()}getHead(){return this.elements.getHead()}getLast(){return this.elements.getLast()}getPrevCreatedAt(t){return this.elements.getPrevCreatedAt(t)}delete(t,i){return this.elements.delete(t,i)}deleteByIndex(t,i){return this.elements.deleteByIndex(t,i)}getLastCreatedAt(){return this.elements.getLastCreatedAt()}get length(){return this.elements.length}*[Symbol.iterator](){for(const t of this.elements)t.isRemoved()||(yield t.getValue())}toTestString(){return this.elements.toTestString()}getDescendants(t){for(const i of this.elements){const r=i.getValue();if(t(r,this))return;r instanceof rr&&r.getDescendants(t)}}toJSON(){const t=[];for(const i of this)t.push(i.toJSON());return`[${t.join(",")}]`}toJS(){return JSON.parse(this.toJSON())}toJSForTest(){const t={};for(let i=0;i({...p,value:p.value?{attributes:es(p.value.getAttributes()),content:p.value.getContent()}:{attributes:void 0,content:""},type:"content"}));return[h,f,c,[l,l]]}setStyle(t,i,r,s){const[,o]=this.rgaTreeSplit.findNodeWithSplit(t[1],r),[,a]=this.rgaTreeSplit.findNodeWithSplit(t[0],r),l=[],h=this.rgaTreeSplit.findBetween(a,o),c=new Map,u=[];for(const p of h){const g=p.getCreatedAt().getActorID(),y=s!=null&&s.size?s.has(g)?s.get(g):Gt:Ys;if(p.canStyle(r,y)){const O=c.get(g),S=p.getCreatedAt();(!O||S.after(O))&&c.set(g,S),u.push(p)}}const f=[];for(const p of u){if(p.isRemoved())continue;const[g,y]=this.rgaTreeSplit.findIndexesFromRange(p.createPosRange());l.push({type:"style",actor:r.getActorID(),from:g,to:y,value:{attributes:es(i)}});for(const[O,S]of Object.entries(i)){const[k]=p.getValue().setAttr(O,S,r);k!==void 0&&f.push({parent:p.getValue(),child:k})}}return[c,f,l]}indexRangeToPosRange(t,i){const r=this.rgaTreeSplit.indexToPos(t);return t===i?[r,r]:[r,this.rgaTreeSplit.indexToPos(i)]}get length(){return this.rgaTreeSplit.length}getTreeByIndex(){return this.rgaTreeSplit.getTreeByIndex()}getTreeByID(){return this.rgaTreeSplit.getTreeByID()}toJSON(){const t=[];for(const i of this.rgaTreeSplit)i.isRemoved()||t.push(i.getValue().toJSON());return`[${t.join(",")}]`}toSortedJSON(){return this.toJSON()}toJSForTest(){return{createdAt:this.getCreatedAt().toTestString(),value:JSON.parse(this.toJSON()),type:"YORKIE_TEXT"}}toString(){return this.rgaTreeSplit.toString()}values(){const t=[];for(const i of this.rgaTreeSplit)if(!i.isRemoved()){const r=i.getValue();t.push({attributes:es(r.getAttributes()),content:r.getContent()})}return t}getRGATreeSplit(){return this.rgaTreeSplit}toTestString(){return this.rgaTreeSplit.toTestString()}deepcopy(){const t=new qt(this.rgaTreeSplit.deepcopy(),this.getCreatedAt());return t.remove(this.getRemovedAt()),t}findIndexesFromRange(t){return this.rgaTreeSplit.findIndexesFromRange(t)}getGCPairs(){const t=[];for(const i of this.rgaTreeSplit){i.getRemovedAt()&&t.push({parent:this.rgaTreeSplit,child:i});for(const r of i.getValue().getGCPairs())t.push(r)}return t}}class Vo extends Yt{constructor(t,i,r,s,o,a,l){super(t,l);d(this,"fromPos");d(this,"toPos");d(this,"maxCreatedAtMapByActor");d(this,"content");d(this,"attributes");this.fromPos=i,this.toPos=r,this.maxCreatedAtMapByActor=s,this.content=o,this.attributes=a}static create(t,i,r,s,o,a,l){return new Vo(t,i,r,s,o,a,l)}execute(t){const i=t.findByCreatedAt(this.getParentCreatedAt());if(!i)throw new v(w.ErrInvalidArgument,`fail to find ${this.getParentCreatedAt()}`);if(!(i instanceof qt))throw new v(w.ErrInvalidArgument,"fail to execute, only Text can execute edit");const r=i,[,s,o]=r.edit([this.fromPos,this.toPos],this.content,this.getExecutedAt(),Object.fromEntries(this.attributes),this.maxCreatedAtMapByActor);for(const a of o)t.registerGCPair(a);return{opInfos:s.map(({from:a,to:l,value:h})=>({type:"edit",from:a,to:l,value:h,path:t.createPath(this.getParentCreatedAt())}))}}getEffectedCreatedAt(){return this.getParentCreatedAt()}toTestString(){const t=this.getParentCreatedAt().toTestString(),i=this.fromPos.toTestString(),r=this.toPos.toTestString(),s=this.content;return`${t}.EDIT(${i},${r},${s})`}getFromPos(){return this.fromPos}getToPos(){return this.toPos}getContent(){return this.content}getAttributes(){return this.attributes||new Map}getMaxCreatedAtMapByActor(){return this.maxCreatedAtMapByActor}}class Xo extends Yt{constructor(t,i,r,s,o,a){super(t,a);d(this,"fromPos");d(this,"toPos");d(this,"maxCreatedAtMapByActor");d(this,"attributes");this.fromPos=i,this.toPos=r,this.maxCreatedAtMapByActor=s,this.attributes=o}static create(t,i,r,s,o,a){return new Xo(t,i,r,s,o,a)}execute(t){const i=t.findByCreatedAt(this.getParentCreatedAt());if(!i)throw new v(w.ErrInvalidArgument,`fail to find ${this.getParentCreatedAt()}`);if(!(i instanceof qt))throw new v(w.ErrInvalidArgument,"fail to execute, only Text can execute edit");const r=i,[,s,o]=r.setStyle([this.fromPos,this.toPos],this.attributes?Object.fromEntries(this.attributes):{},this.getExecutedAt(),this.maxCreatedAtMapByActor);for(const a of s)t.registerGCPair(a);return{opInfos:o.map(({from:a,to:l,value:h})=>({type:"style",from:a,to:l,value:h,path:t.createPath(this.getParentCreatedAt())}))}}getEffectedCreatedAt(){return this.getParentCreatedAt()}toTestString(){const t=this.getParentCreatedAt().toTestString(),i=this.fromPos.toTestString(),r=this.toPos.toTestString(),s=this.attributes;return`${t}.STYL(${i},${r},${JSON.stringify(s)})`}getFromPos(){return this.fromPos}getToPos(){return this.toPos}getAttributes(){return this.attributes}getMaxCreatedAtMapByActor(){return this.maxCreatedAtMapByActor}}const Y1=2,H1="root",Dn="text";function Es(n,e){let t=0;const i=n.children;for(let r=0;r0)throw new v(w.ErrRefused,"Text node cannot have children")}updateAncestorsSize(){let e=this.parent;const t=this.isRemoved?-1:1;for(;e&&(e.size+=this.paddedSize*t,!e.isRemoved);)e=e.parent}updateDescendantsSize(){let e=0;for(const t of this._children){const i=t.updateDescendantsSize();t.isRemoved||(e+=i)}return this.size+=e,this.paddedSize}get isText(){return this.type===Dn}get paddedSize(){return this.size+(this.isText?0:Y1)}isAncestorOf(e){return ew(this,e)}get nextSibling(){const e=this.parent.findOffset(this),t=this.parent.children[e+1];if(t)return t}get prevSibling(){const e=this.parent.findOffset(this),t=this.parent.children[e-1];if(t)return t}splitText(e,t){if(e===0||e===this.size)return;const i=this.value.slice(0,e),r=this.value.slice(e);if(!r.length)return;this.value=i;const s=this.cloneText(e+t);return s.value=r,this.parent.insertAfterInternal(s,this),s}get children(){return this._children.filter(e=>!e.isRemoved)}get allChildren(){return[...this._children]}hasTextChild(){return this.children.length>0&&this.children.every(e=>e.isText)}append(...e){if(this.isText)throw new v(w.ErrRefused,"Text node cannot have children");this._children.push(...e);for(const t of e)t.parent=this,t.updateAncestorsSize()}prepend(...e){if(this.isText)throw new v(w.ErrRefused,"Text node cannot have children");this._children.unshift(...e);for(const t of e)t.parent=this}insertBefore(e,t){if(this.isText)throw new v(w.ErrRefused,"Text node cannot have children");const i=this._children.indexOf(t);if(i===-1)throw new v(w.ErrInvalidArgument,"child not found");this.insertAtInternal(e,i),e.updateAncestorsSize()}insertAfter(e,t){if(this.isText)throw new v(w.ErrRefused,"Text node cannot have children");const i=this._children.indexOf(t);if(i===-1)throw new v(w.ErrInvalidArgument,"child not found");this.insertAtInternal(e,i+1),e.updateAncestorsSize()}insertAt(e,t){if(this.isText)throw new v(w.ErrRefused,"Text node cannot have children");this.insertAtInternal(e,t),e.updateAncestorsSize()}removeChild(e){if(this.isText)throw new v(w.ErrRefused,"Text node cannot have children");const t=this._children.indexOf(e);if(t===-1)throw new v(w.ErrInvalidArgument,"child not found");this._children.splice(t,1),e.parent=void 0}splitElement(e,t){const i=this.cloneElement(t);this.parent.insertAfterInternal(i,this),i.updateAncestorsSize();const r=this.children.slice(0,e),s=this.children.slice(e);this._children=r,i._children=s,this.size=this._children.reduce((o,a)=>o+a.paddedSize,0),i.size=i._children.reduce((o,a)=>o+a.paddedSize,0);for(const o of i._children)o.parent=i;return i}insertAfterInternal(e,t){if(this.isText)throw new v(w.ErrRefused,"Text node cannot have children");const i=this._children.indexOf(t);if(i===-1)throw new v(w.ErrInvalidArgument,"child not found");this.insertAtInternal(e,i+1)}insertAtInternal(e,t){if(this.isText)throw new v(w.ErrRefused,"Text node cannot have children");this._children.splice(t,0,e),e.parent=this}findOffset(e){if(this.isText)throw new v(w.ErrRefused,"Text node cannot have children");if(e.isRemoved){const t=this._children.indexOf(e);return this.allChildren.splice(0,t).filter(r=>!r.isRemoved).length}return this.children.indexOf(e)}findBranchOffset(e){if(this.isText)throw new v(w.ErrRefused,"Text node cannot have children");let t=e;for(;t;){const i=this._children.indexOf(t);if(i!==-1)return i;t=t.parent}return-1}}function ew(n,e){if(n===e)return!1;for(;e.parent;){if(e.parent===n)return!0;e=e.parent}return!1}var xe=(n=>(n.Start="Start",n.End="End",n.Text="Text",n))(xe||{});function rO(n,e,t,i){if(e>t)throw new v(w.ErrInvalidArgument,`from is greater than to: ${e} > ${t}`);if(e>n.size)throw new v(w.ErrInvalidArgument,`from is out of range: ${e} > ${n.size}`);if(t>n.size)throw new v(w.ErrInvalidArgument,`to is out of range: ${t} > ${n.size}`);if(e===t)return;let r=0;for(const s of n.children){if(e-s.paddedSizes.size;(s.isText||l)&&i([s,s.isText?"Text":"Start"],h),rO(s,Math.max(0,o),Math.min(a,s.size),i),h&&i([s,"End"],h)}r+=s.paddedSize}}function sO(n,e,t=0){for(const i of n.children)sO(i,e,t+1);e(n,t)}function th(n,e,t=0){for(const i of n._children)th(i,e,t+1);e(n,t)}function Vc(n,e,t=!0){if(e>n.size)throw new v(w.ErrInvalidArgument,`index is out of range: ${e} > ${n.size}`);if(n.isText)return{node:n,offset:e};let i=0,r=0;for(const s of n.children){if(t&&s.isText&&s.size>=e-r)return Vc(s,e-r,t);if(e===r)return{node:n,offset:i};if(!t&&s.paddedSize===e-r)return{node:n,offset:i+1};if(s.paddedSize>e-r)return Vc(s,e-r-1,t);r+=s.paddedSize,i+=1}return{node:n,offset:i}}function oO(n){return n.isText||n.children.length===0?n:oO(n.children[0])}function tw(n,e){if(n.sizen===e?0:n0)if(t.right)t.right.parent=t,t=t.right;else return t;else if(i<0)if(t.left)t.left.parent=t,t=t.left;else{let r=t.parent,s=t;for(;r&&s===r.left;)s=r,r=r.parent;return r}else return t}}lastEntry(){if(!this.root)return this.root;let e=this.root;for(;e.right;)e=e.right;return e}size(){return this.counter}isEmpty(){return this.counter===0}getInternal(e,t){for(;t;){const i=this.comparator(e,t.key);if(i===0)return t;i<0?t=t.left:i>0&&(t=t.right)}}putInternal(e,t,i){if(!i)return this.counter+=1,new rw(e,t,!0);const r=this.comparator(e,i.key);return r<0?i.left=this.putInternal(e,t,i.left):r>0?i.right=this.putInternal(e,t,i.right):i.value=t,this.isRed(i.right)&&!this.isRed(i.left)&&(i=this.rotateLeft(i)),this.isRed(i.left)&&this.isRed(i.left.left)&&(i=this.rotateRight(i)),this.isRed(i.left)&&this.isRed(i.right)&&this.flipColors(i),i}removeInternal(e,t){if(this.comparator(t,e.key)<0)!this.isRed(e.left)&&!this.isRed(e.left.left)&&(e=this.moveRedLeft(e)),e.left=this.removeInternal(e.left,t);else{if(this.isRed(e.left)&&(e=this.rotateRight(e)),this.comparator(t,e.key)===0&&!e.right){this.counter-=1;return}if(!this.isRed(e.right)&&!this.isRed(e.right.left)&&(e=this.moveRedRight(e)),this.comparator(t,e.key)===0){this.counter-=1;const i=this.min(e.right);e.value=i.value,e.key=i.key,e.right=this.removeMin(e.right)}else e.right=this.removeInternal(e.right,t)}return this.fixUp(e)}min(e){return e.left?this.min(e.left):e}removeMin(e){if(e.left)return!this.isRed(e.left)&&!this.isRed(e.left.left)&&(e=this.moveRedLeft(e)),e.left=this.removeMin(e.left),this.fixUp(e)}fixUp(e){return this.isRed(e.right)&&(e=this.rotateLeft(e)),this.isRed(e.left)&&this.isRed(e.left.left)&&(e=this.rotateRight(e)),this.isRed(e.left)&&this.isRed(e.right)&&this.flipColors(e),e}moveRedLeft(e){return this.flipColors(e),this.isRed(e.right.left)&&(e.right=this.rotateRight(e.right),e=this.rotateLeft(e),this.flipColors(e)),e}moveRedRight(e){return this.flipColors(e),this.isRed(e.left.left)&&(e=this.rotateRight(e),this.flipColors(e)),e}isRed(e){return e&&e.isRed}rotateLeft(e){const t=e.right;return e.right=t.left,t.left=e,t.isRed=t.left.isRed,t.left.isRed=!0,t}rotateRight(e){const t=e.left;return e.left=t.right,t.right=e,t.isRed=t.right.isRed,t.right.isRed=!0,t}flipColors(e){e.isRed=!e.isRed,e.left.isRed=!e.left.isRed,e.right.isRed=!e.right.isRed}}class _t{constructor(e,t){d(this,"parentID");d(this,"leftSiblingID");this.parentID=e,this.leftSiblingID=t}static of(e,t){return new _t(e,t)}static fromTreePos(e){const{offset:t}=e;let{node:i}=e,r;return i.isText?(i.parent.children[0]===i&&t===0?r=i.parent:r=i,i=i.parent):t===0?r=i:r=i.children[t-1],_t.of(i.id,Me.of(r.getCreatedAt(),r.getOffset()+t))}getParentID(){return this.parentID}static fromStruct(e){return _t.of(Me.of(dt.fromStruct(e.parentID.createdAt),e.parentID.offset),Me.of(dt.fromStruct(e.leftSiblingID.createdAt),e.leftSiblingID.offset))}toStruct(){return{parentID:{createdAt:this.getParentID().getCreatedAt().toStruct(),offset:this.getParentID().getOffset()},leftSiblingID:{createdAt:this.getLeftSiblingID().getCreatedAt().toStruct(),offset:this.getLeftSiblingID().getOffset()}}}toTreeNodePair(e){const t=this.getParentID(),i=this.getLeftSiblingID(),r=e.findFloorNode(t);let s=e.findFloorNode(i);if(!r||!s)throw new v(w.ErrRefused,`cannot find node of CRDTTreePos(${t.toTestString()}, ${i.toTestString()})`);return!i.equals(t)&&i.getOffset()>0&&i.getOffset()===s.id.getOffset()&&s.insPrevID&&(s=e.findFloorNode(s.insPrevID)),[r,s]}getLeftSiblingID(){return this.leftSiblingID}equals(e){return this.getParentID().getCreatedAt().equals(e.getParentID().getCreatedAt())&&this.getParentID().getOffset()===e.getParentID().getOffset()&&this.getLeftSiblingID().getCreatedAt().equals(e.getLeftSiblingID().getCreatedAt())&&this.getLeftSiblingID().getOffset()===e.getLeftSiblingID().getOffset()}}class Me{constructor(e,t){d(this,"createdAt");d(this,"offset");this.createdAt=e,this.offset=t}static of(e,t){return new Me(e,t)}static fromStruct(e){return Me.of(dt.fromStruct(e.createdAt),e.offset)}static createComparator(){return(e,t)=>{const i=e.getCreatedAt().compare(t.getCreatedAt());return i!==0?i:e.getOffset()>t.getOffset()?1:e.getOffset(){const s=r.deepcopy();return s.parent=t,s}),t.insPrevID=this.insPrevID,t.insNextID=this.insNextID,t}get value(){if(!this.isText)throw new v(w.ErrInvalidType,`cannot get value of element node: ${this.type}`);return this._value}set value(t){if(!this.isText)throw new v(w.ErrInvalidType,`cannot set value of element node: ${this.type}`);this._value=t,this.size=t.length}get isRemoved(){return!!this.removedAt}remove(t){const i=!this.removedAt;(!this.removedAt||this.removedAt.compare(t)>0)&&(this.removedAt=t),i&&this.updateAncestorsSize()}cloneText(t){return new ut(Me.of(this.id.getCreatedAt(),t),this.type,void 0,void 0,this.removedAt)}cloneElement(t){return new ut(Me.of(t(),0),this.type,void 0,void 0,this.removedAt)}split(t,i,r){const s=this.isText?this.splitText(i,this.id.getOffset()):this.splitElement(i,r);if(s){if(s.insPrevID=this.id,this.insNextID){const o=t.findFloorNode(this.insNextID);o.insPrevID=s.id,s.insNextID=this.insNextID}this.insNextID=s.id,t.registerNode(s)}return s}getCreatedAt(){return this.id.getCreatedAt()}getOffset(){return this.id.getOffset()}canDelete(t,i){return!this.getCreatedAt().after(i)&&(!this.removedAt||t.after(this.removedAt))}canStyle(t,i){return this.isText?!1:!this.getCreatedAt().after(i)&&(!this.removedAt||t.after(this.removedAt))}setAttrs(t,i){this.attrs||(this.attrs=new Vn);const r=new Array;for(const[s,o]of Object.entries(t))r.push(this.attrs.set(s,o,i));return r}purge(t){this.attrs&&this.attrs.purge(t)}getGCPairs(){const t=[];if(!this.attrs)return t;for(const i of this.attrs)i.getRemovedAt()&&t.push({parent:this,child:i});return t}}function Xc(n){var t;if(n.isText){const i=n;return{type:i.type,value:i.value}}const e={type:n.type,children:n.children.map(Xc)};return n.attrs&&(e.attributes=es((t=n.attrs)==null?void 0:t.toObject())),e}function Ju(n){if(n.isText)return n.value;let e="";return n.attrs&&n.attrs.size()&&(e=" "+Array.from(n.attrs).filter(t=>!t.isRemoved()).sort((t,i)=>t.getKey().localeCompare(i.getKey())).map(t=>{const i=JSON.parse(t.getValue());return typeof i=="string"?`${t.getKey()}="${i}"`:`${t.getKey()}="${wi(t.getValue())}"`}).join(" ")),`<${n.type}${e}>${n.children.map(t=>Ju(t)).join("")}`}function lO(n){if(n.isText){const e=n;return{type:e.type,value:e.value,size:e.size,isRemoved:e.isRemoved}}return{type:n.type,children:n.children.map(lO),size:n.size,isRemoved:n.isRemoved}}class Mt extends qo{constructor(t,i){super(i);d(this,"indexTree");d(this,"nodeMapByID");this.indexTree=new iw(t),this.nodeMapByID=new aO(Me.createComparator()),this.indexTree.traverseAll(r=>{this.nodeMapByID.put(r.id,r)})}static create(t,i){return new Mt(t,i)}findFloorNode(t){const i=this.nodeMapByID.floorEntry(t);if(!(!i||!i.key.getCreatedAt().equals(t.getCreatedAt())))return i.value}registerNode(t){this.nodeMapByID.put(t.id,t)}findNodesAndSplitText(t,i){const[r,s]=t.toTreeNodePair(this);let o=s;const a=r===o,l=o.parent&&!a?o.parent:r;if(o.isText&&o.split(this,t.getLeftSiblingID().getOffset()-o.id.getOffset()),i){const h=l.allChildren,c=a?0:h.indexOf(o)+1;for(let u=c;u{const y=g.getCreatedAt().getActorID(),O=s?s.has(y)?s.get(y):Gt:Ys;if(g.canStyle(r,O)&&i){const S=f.get(y),k=g.getCreatedAt();(!S||k.after(S))&&f.set(y,k);const $=g.setAttrs(i,r),x=$.reduce((R,[,j])=>(j&&(R[j.getKey()]=u[j.getKey()]),R),{}),Q=g.parent,A=g.prevSibling||g.parent;Object.keys(x).length>0&&c.push({type:"style",from:this.toIndex(Q,A),to:this.toIndex(g,g),fromPath:this.toPath(Q,A),toPath:this.toPath(g,g),actor:r.getActorID(),value:x});for(const[R]of $)R&&p.push({parent:g,child:R})}}),[f,p,c]}removeStyle(t,i,r,s){const[o,a]=this.findNodesAndSplitText(t[0],r),[l,h]=this.findNodesAndSplitText(t[1],r),c=[],u=new Map,f=[];return this.traverseInPosRange(o,a,l,h,([p])=>{const g=p.getCreatedAt().getActorID(),y=s?s.has(g)?s.get(g):Gt:Ys;if(p.canStyle(r,y)&&i){const O=u.get(g),S=p.getCreatedAt();(!O||S.after(O))&&u.set(g,S),p.attrs||(p.attrs=new Vn);for(const x of i){const Q=p.attrs.remove(x,r);for(const A of Q)f.push({parent:p,child:A})}const k=p.parent,$=p.prevSibling||p.parent;c.push({actor:r.getActorID(),type:"removeStyle",from:this.toIndex(k,$),to:this.toIndex(p,p),fromPath:this.toPath(k,$),toPath:this.toPath(p,p),value:i})}}),[u,f,c]}edit(t,i,r,s,o,a){const[l,h]=this.findNodesAndSplitText(t[0],s),[c,u]=this.findNodesAndSplitText(t[1],s),f=this.toIndex(l,h),p=this.toPath(l,h),g=[],y=[],O=[],S=new Map;this.traverseInPosRange(l,h,c,u,([x,Q],A)=>{if(Q===xe.Start&&!A)for(const W of x.children)O.push(W);const R=x.getCreatedAt().getActorID(),j=a?a.has(R)?a.get(R):Gt:Ys;if(x.canDelete(s,j)||g.includes(x.parent)){const W=S.get(R),G=x.getCreatedAt();(!W||G.after(W))&&S.set(R,G),(Q===xe.Text||Q===xe.Start)&&g.push(x),y.push([x,Q])}});const k=this.makeDeletionChanges(y,s),$=[];for(const x of g)x.remove(s),x.isRemoved&&$.push({parent:this,child:x});for(const x of O)x.removedAt||l.append(x);if(r>0){let x=0,Q=l,A=h;for(;x{l.isRemoved&&(R.remove(s),$.push({parent:this,child:R})),this.nodeMapByID.put(R.id,R)}),A.isRemoved||x.push(A);if(x.length){const A=x.map(R=>Xc(R));k.length&&k[k.length-1].from===f?k[k.length-1].value=A:k.push({type:"content",from:f,to:f,fromPath:p,toPath:p,actor:s.getActorID(),value:A})}}return[k,$,S]}editT(t,i,r,s,o){const a=this.findPos(t[0]),l=this.findPos(t[1]);this.edit([a,l],i,r,s,o)}move(t,i,r){throw new v(w.ErrUnimplemented,`not implemented: ${t}, ${i}, ${r}`)}purge(t){var s;(s=t.parent)==null||s.removeChild(t),this.nodeMapByID.remove(t.id);const i=t.insPrevID,r=t.insNextID;if(i){const o=this.findFloorNode(i);o.insNextID=r}if(r){const o=this.findFloorNode(r);o.insPrevID=i}t.insPrevID=void 0,t.insNextID=void 0}getGCPairs(){const t=[];return this.indexTree.traverse(i=>{i.getRemovedAt()&&t.push({parent:this,child:i});for(const r of i.getGCPairs())t.push(r)}),t}findPos(t,i=!0){const r=this.indexTree.findTreePos(t,i);return _t.fromTreePos(r)}pathToPosRange(t){const i=this.pathToIndex(t);return[this.findPos(i),this.findPos(i+1)]}pathToPos(t){const i=this.indexTree.pathToIndex(t);return this.findPos(i)}getRoot(){return this.indexTree.getRoot()}getSize(){return this.indexTree.size}getNodeSize(){return this.nodeMapByID.size()}getIndexTree(){return this.indexTree}toXML(){return Ju(this.indexTree.getRoot())}toJSON(){return JSON.stringify(this.getRootTreeNode())}toJSForTest(){return{createdAt:this.getCreatedAt().toTestString(),value:JSON.parse(this.toJSON()),type:"YORKIE_TREE"}}toJSInfoForTest(){const t=this.indexTree.getRoot(),i=(r,s=void 0,o=void 0,a=0)=>{var p,g,y,O;let l,h,c;const u=r.isText?{node:r,offset:0}:s&&o?this.toTreePos(s,o):null;u&&(l=this.indexTree.indexOf(u),h=this.indexTree.treePosToPath(u),c=_t.fromTreePos(u).toStruct());const f={type:r.type,parent:s==null?void 0:s.id.toTestString(),size:r.size,id:r.id.toTestString(),removedAt:(p=r.removedAt)==null?void 0:p.toTestString(),insPrev:(g=r.insPrevID)==null?void 0:g.toTestString(),insNext:(y=r.insNextID)==null?void 0:y.toTestString(),value:r.isText?r.value:void 0,isRemoved:r.isRemoved,children:[],depth:a,attributes:r.attrs?es((O=r.attrs)==null?void 0:O.toObject()):void 0,index:l,path:h,pos:c};for(let S=0;S0&&S===r[r.length-1].to?(r[r.length-1].to=k,r[r.length-1].toPath=this.toPath(O,p)):r.push({type:"content",from:S,to:k,fromPath:this.toPath(y,u),toPath:this.toPath(O,p),actor:i.getActorID()}))}return r.reverse()}findRightToken([t,i]){if(i===xe.Start){const l=t.allChildren;return l.length>0?[l[0],l[0].isText?xe.Text:xe.Start]:[t,xe.End]}const r=t.parent,s=r.allChildren,o=s.indexOf(t);if(r&&o===s.length-1)return[r,xe.End];const a=s[o+1];return[a,a.isText?xe.Text:xe.Start]}findLeftToken([t,i]){if(i===xe.End){const l=t.allChildren;if(l.length>0){const h=l[l.length-1];return[h,h.isText?xe.Text:xe.End]}return[t,xe.Start]}const r=t.parent,s=r.allChildren,o=s.indexOf(t);if(r&&o===0)return[r,xe.Start];const a=s[o-1];return[a,a.isText?xe.Text:xe.End]}}class Lo extends Yt{constructor(t,i,r,s,o,a,l){super(t,l);d(this,"fromPos");d(this,"toPos");d(this,"contents");d(this,"splitLevel");d(this,"maxCreatedAtMapByActor");this.fromPos=i,this.toPos=r,this.contents=s,this.splitLevel=o,this.maxCreatedAtMapByActor=a}static create(t,i,r,s,o,a,l){return new Lo(t,i,r,s,o,a,l)}execute(t){var l;const i=t.findByCreatedAt(this.getParentCreatedAt());if(!i)throw new v(w.ErrInvalidArgument,`fail to find ${this.getParentCreatedAt()}`);if(!(i instanceof Mt))throw new v(w.ErrInvalidArgument,"fail to execute, only Tree can execute edit");const r=this.getExecutedAt(),s=i,[o,a]=s.edit([this.fromPos,this.toPos],(l=this.contents)==null?void 0:l.map(h=>h.deepcopy()),this.splitLevel,r,(()=>{let h=r.getDelimiter();return this.contents!==void 0&&(h+=this.contents.length),()=>dt.of(r.getLamport(),++h,r.getActorID())})(),this.maxCreatedAtMapByActor);for(const h of a)t.registerGCPair(h);return{opInfos:o.map(({from:h,to:c,value:u,splitLevel:f,fromPath:p,toPath:g})=>({type:"tree-edit",path:t.createPath(this.getParentCreatedAt()),from:h,to:c,value:u,splitLevel:f,fromPath:p,toPath:g}))}}getEffectedCreatedAt(){return this.getParentCreatedAt()}toTestString(){const t=this.getParentCreatedAt().toTestString(),i=`${this.fromPos.getLeftSiblingID().getCreatedAt().toTestString()}/${this.fromPos.getLeftSiblingID().getOffset()}`,r=`${this.toPos.getLeftSiblingID().getCreatedAt().toTestString()}/${this.toPos.getLeftSiblingID().getOffset()}`,s=this.contents||[];return`${t}.EDIT(${i},${r},${s.map(o=>Ju(o)).join("")})`}getFromPos(){return this.fromPos}getToPos(){return this.toPos}getContents(){return this.contents}getSplitLevel(){return this.splitLevel}getMaxCreatedAtMapByActor(){return this.maxCreatedAtMapByActor}}class ts{constructor(e){d(this,"vector");this.vector=e||new Map}set(e,t){this.vector.set(e,t)}get(e){return this.vector.get(e)}maxLamport(){let e=BigInt(0);for(const[,t]of this)t>e&&(e=t);return e}max(e){const t=new Map;for(const[i,r]of e){const s=this.vector.get(i),o=s&&s>r?s:r;t.set(i,o)}for(const[i,r]of this){const s=e.get(i),o=s&&s>r?s:r;t.set(i,o)}return new ts(t)}afterOrEqual(e){const t=this.vector.get(e.getActorID());return t===void 0?!1:t>=e.getLamport()}deepcopy(){const e=new Map;for(const[t,i]of this.vector)e.set(t,i);return new ts(e)}filter(e){const t=new Map;for(const[i]of e){const r=this.vector.get(i);r!==void 0&&t.set(i,r)}return new ts(t)}size(){return this.vector.size}*[Symbol.iterator](){for(const[e,t]of this.vector)yield[e,t]}}const ow=new ts(new Map);class An{constructor(e,t,i,r,s){d(this,"clientSeq");d(this,"serverSeq");d(this,"lamport");d(this,"actor");d(this,"versionVector");this.clientSeq=e,this.serverSeq=s,this.lamport=t,this.versionVector=r,this.actor=i}static of(e,t,i,r,s){return new An(e,t,i,r,s)}next(){const e=this.versionVector.deepcopy();return e.set(this.actor,this.lamport+1n),new An(this.clientSeq+1,this.lamport+1n,this.actor,e)}syncClocks(e){const t=e.lamport>this.lamport?e.lamport+1n:this.lamport+1n,i=this.versionVector.max(e.versionVector),r=new An(this.clientSeq,t,this.actor,i);return r.versionVector.set(this.actor,t),r}setClocks(e,t){const i=e>this.lamport?e:this.lamport+1n,r=this.versionVector.max(t);return r.set(this.actor,i),An.of(this.clientSeq,i,this.actor,r)}createTimeTicket(e){return dt.of(this.lamport,e,this.actor)}setActor(e){return new An(this.clientSeq,this.lamport,e,this.versionVector,this.serverSeq)}setVersionVector(e){return new An(this.clientSeq,this.lamport,this.actor,e,this.serverSeq)}getClientSeq(){return this.clientSeq}getServerSeq(){return this.serverSeq?this.serverSeq.toString():""}getLamport(){return this.lamport}getLamportAsString(){return this.lamport.toString()}getActorID(){return this.actor}getVersionVector(){return this.versionVector}toTestString(){return`${this.lamport.toString()}:${this.actor.slice(-2)}:${this.clientSeq}`}}const aw=new An(0,0n,zu,ow);class ds{constructor({id:e,operations:t,presenceChange:i,message:r}){d(this,"id");d(this,"operations");d(this,"presenceChange");d(this,"message");this.id=e,this.operations=t||[],this.presenceChange=i,this.message=r}static create({id:e,operations:t,presenceChange:i,message:r}){return new ds({id:e,operations:t,presenceChange:i,message:r})}getID(){return this.id}getMessage(){return this.message}hasOperations(){return this.operations.length>0}getOperations(){return this.operations}setActor(e){for(const t of this.operations)t.setActor(e);this.id=this.id.setActor(e)}hasPresenceChange(){return this.presenceChange!==void 0}getPresenceChange(){return this.presenceChange}execute(e,t,i){const r=[],s=[];for(const o of this.operations){const a=o.execute(e,i);if(!a)continue;const{opInfos:l,reverseOp:h}=a;r.push(...l),h&&s.unshift(h)}return this.presenceChange&&(this.presenceChange.type===cr.Put?t.set(this.id.getActorID(),Wt(this.presenceChange.presence)):t.delete(this.id.getActorID())),{opInfos:r,reverseOps:s}}toTestString(){return`${this.operations.map(e=>e.toTestString()).join(",")}`}toStruct(){return{changeID:we.bytesToHex(we.toChangeID(this.getID()).toBinary()),message:this.getMessage(),operations:this.getOperations().map(e=>we.bytesToHex(we.toOperation(e).toBinary())),presenceChange:this.getPresenceChange()}}static fromStruct(e){const{changeID:t,operations:i,presenceChange:r,message:s}=e;return ds.create({id:we.bytesToChangeID(we.hexToBytes(t)),operations:i==null?void 0:i.map(o=>we.bytesToOperation(we.hexToBytes(o))),presenceChange:r,message:s})}}class ih{constructor(e,t,i,r,s,o,a){d(this,"documentKey");d(this,"checkpoint");d(this,"isRemoved");d(this,"changes");d(this,"snapshot");d(this,"minSyncedTicket");d(this,"versionVector");this.documentKey=e,this.checkpoint=t,this.isRemoved=i,this.changes=r,this.snapshot=o,this.minSyncedTicket=a,this.versionVector=s}static create(e,t,i,r,s,o,a){return new ih(e,t,i,r,s,o,a)}getDocumentKey(){return this.documentKey}getCheckpoint(){return this.checkpoint}getIsRemoved(){return this.isRemoved}getChanges(){return this.changes}hasChanges(){return this.changes.length>0}getChangeSize(){return this.changes.length}hasSnapshot(){return!!this.snapshot&&!!this.snapshot.length}getSnapshot(){return this.snapshot}getMinSyncedTicket(){return this.minSyncedTicket}getVersionVector(){return this.versionVector}}class is{constructor(e,t){d(this,"serverSeq");d(this,"clientSeq");this.serverSeq=e,this.clientSeq=t}static of(e,t){return new is(e,t)}increaseClientSeq(e){return e===0?this:new is(this.serverSeq,this.clientSeq+e)}forward(e){if(this.equals(e))return this;const t=this.serverSeq>e.serverSeq?this.serverSeq:e.serverSeq,i=Math.max(this.clientSeq,e.clientSeq);return is.of(t,i)}getServerSeqAsString(){return this.serverSeq.toString()}getClientSeq(){return this.clientSeq}getServerSeq(){return this.serverSeq}equals(e){return this.clientSeq===e.clientSeq&&this.serverSeq==e.serverSeq}toTestString(){return`serverSeq=${this.serverSeq}, clientSeq=${this.clientSeq}`}}const lw=new is(0n,0);class Ti{constructor(e,t){d(this,"createdAt");d(this,"offset");this.createdAt=e,this.offset=t}static of(e,t){return new Ti(e,t)}static fromStruct(e){return Ti.of(dt.fromStruct(e.createdAt),e.offset)}getCreatedAt(){return this.createdAt}getOffset(){return this.offset}equals(e){return this.createdAt.compare(e.createdAt)===0&&this.offset===e.offset}hasSameCreatedAt(e){return this.createdAt.compare(e.createdAt)===0}split(e){return new Ti(this.createdAt,this.offset+e)}toStruct(){return{createdAt:this.createdAt.toStruct(),offset:this.offset}}toTestString(){return`${this.createdAt.toTestString()}:${this.offset}`}toIDString(){return`${this.createdAt.toIDString()}:${this.offset}`}}const hw=Ti.of(Gt,0);class Jt{constructor(e,t){d(this,"id");d(this,"relativeOffset");this.id=e,this.relativeOffset=t}static of(e,t){return new Jt(e,t)}static fromStruct(e){const t=Ti.fromStruct(e.id);return Jt.of(t,e.relativeOffset)}getID(){return this.id}getRelativeOffset(){return this.relativeOffset}getAbsoluteID(){return Ti.of(this.id.getCreatedAt(),this.id.getOffset()+this.relativeOffset)}toTestString(){return`${this.id.toTestString()}:${this.relativeOffset}`}toStruct(){return{id:this.id.toStruct(),relativeOffset:this.relativeOffset}}equals(e){return this.id.equals(e.id)?this.relativeOffset===e.relativeOffset:!1}}class sr extends Km{constructor(t,i,r){super(i);d(this,"id");d(this,"removedAt");d(this,"prev");d(this,"next");d(this,"insPrev");d(this,"insNext");this.id=t,this.removedAt=r}static create(t,i){return new sr(t,i)}static createComparator(){return(t,i)=>{const r=t.getCreatedAt().compare(i.getCreatedAt());return r!==0?r:t.getOffset()>i.getOffset()?1:t.getOffset()0&&t.getID().getOffset()==e.getOffset()){if(!t.hasInsPrev())return t;t=t.getInsPrev()}return t}findFloorNode(e){const t=this.treeByID.floorEntry(e);if(t&&!(!t.key.equals(e)&&!t.key.hasSameCreatedAt(e)))return t.value}findBetween(e,t){const i=[];let r=e;for(;r&&r!==t;)i.push(r),r=r.getNext();return i}splitNode(e,t){if(t>e.getContentLength())throw new v(w.ErrInvalidArgument,"offset should be less than or equal to length");if(t===0)return e;if(t===e.getContentLength())return e.getNext();const i=e.split(t);this.treeByIndex.updateWeight(i),this.insertAfter(e,i);const r=e.getInsNext();return r&&r.setInsPrev(i),i.setInsPrev(e),i}deleteNodes(e,t,i){if(!e.length)return[[],new Map,new Map];const[r,s]=this.filterNodes(e,t,i),o=new Map,a=new Map,l=this.makeChanges(s,t);for(const h of r){const c=h.getCreatedAt().getActorID();(!o.has(c)||h.getID().getCreatedAt().after(o.get(c)))&&o.set(c,h.getID().getCreatedAt()),a.set(h.getID().toIDString(),h),h.remove(t)}return this.deleteIndexNodes(s),[l,o,a]}filterNodes(e,t,i){const r=!!i,s=[],o=[],[a,l]=this.findEdgesOfCandidates(e);o.push(a);for(const h of e){const c=h.getCreatedAt().getActorID(),u=r?i.has(c)?i.get(c):Gt:Ys;h.canDelete(t,u)?s.push(h):o.push(h)}return o.push(l),[s,o]}findEdgesOfCandidates(e){return[e[0].getPrev(),e[e.length-1].getNext()]}makeChanges(e,t){const i=[];let r,s;for(let o=0;on<0?Math.ceil(n):Math.floor(n);var Pi=(n=>(n[n.IntegerCnt=0]="IntegerCnt",n[n.LongCnt=1]="LongCnt",n))(Pi||{});class gt extends qo{constructor(t,i,r){super(r);d(this,"valueType");d(this,"value");switch(this.valueType=t,t){case 0:typeof i=="number"?i>Math.pow(2,31)-1||i<-Math.pow(2,31)?this.value=Y.fromNumber(i).toInt():this.value=Bd(i):this.value=i.toInt();break;case 1:typeof i=="number"?this.value=Y.fromNumber(i):this.value=i;break;default:throw new v(w.ErrUnimplemented,`unimplemented type: ${t}`)}}static create(t,i,r){return new gt(t,i,r)}static valueFromBytes(t,i){switch(t){case 0:return i[0]|i[1]<<8|i[2]<<16|i[3]<<24;case 1:return Y.fromBytesLE(Array.from(i));default:throw new v(w.ErrUnimplemented,`unimplemented type: ${t}`)}}toJSON(){return`${this.value}`}toSortedJSON(){return this.toJSON()}toJSForTest(){return{createdAt:this.getCreatedAt().toTestString(),value:this.value,type:"YORKIE_COUNTER"}}deepcopy(){const t=gt.create(this.valueType,this.value,this.getCreatedAt());return t.setMovedAt(this.getMovedAt()),t}getType(){return this.valueType}static getCounterType(t){switch(typeof t){case"object":return t instanceof Y?1:void 0;case"number":return t>Math.pow(2,31)-1||t<-Math.pow(2,31)?1:0;default:return}}static isSupport(t){return!!gt.getCounterType(t)}static isInteger(t){return t%1===0}isNumericType(){const t=this.valueType;return t===0||t===1}getValueType(){return this.valueType}getValue(){return this.value}toBytes(){switch(this.valueType){case 0:{const t=this.value;return new Uint8Array([t&255,t>>8&255,t>>16&255,t>>24&255])}case 1:{const i=this.value.toBytesLE();return Uint8Array.from(i)}default:throw new v(w.ErrUnimplemented,`unimplemented type: ${this.valueType}`)}}increase(t){function i(r){if(!r.isNumericType())throw new TypeError(`Unsupported type of value: ${typeof r.getValue()}`)}return i(this),i(t),this.valueType===1?this.value=this.value.add(t.getValue()):t.getType()===$e.Long?this.value=this.value+t.getValue().toInt():this.value=Y.fromNumber(this.value+Bd(t.getValue())).toInt(),this}}class gs extends Yt{constructor(t,i,r){super(t,r);d(this,"value");this.value=i}static create(t,i,r){return new gs(t,i,r)}execute(t){const i=t.findByCreatedAt(this.getParentCreatedAt());if(!i)throw new v(w.ErrInvalidArgument,`fail to find ${this.getParentCreatedAt()}`);if(!(i instanceof gt))throw new v(w.ErrInvalidArgument,"fail to execute, only Counter can execute increase");const r=i,s=this.value.deepcopy();return r.increase(s),{opInfos:[{type:"increase",path:t.createPath(this.getParentCreatedAt()),value:s.getValue()}],reverseOp:this.toReverseOperation()}}toReverseOperation(){const t=this.value.deepcopy(),r=t.getType()===$e.Long?t.getValue().multiply(-1):t.getValue()*-1;return gs.create(this.getParentCreatedAt(),pe.of(r,t.getCreatedAt()))}getEffectedCreatedAt(){return this.getParentCreatedAt()}toTestString(){return`${this.getParentCreatedAt().toTestString()}.INCREASE.${this.value.toJSON()}`}getValue(){return this.value}}class Nn extends Yt{constructor(t,i,r,s,o,a,l){super(t,l);d(this,"fromPos");d(this,"toPos");d(this,"maxCreatedAtMapByActor");d(this,"attributes");d(this,"attributesToRemove");this.fromPos=i,this.toPos=r,this.maxCreatedAtMapByActor=s,this.attributes=o,this.attributesToRemove=a}static create(t,i,r,s,o,a){return new Nn(t,i,r,s,o,new Array,a)}static createTreeRemoveStyleOperation(t,i,r,s,o,a){return new Nn(t,i,r,s,new Map,o,a)}execute(t){const i=t.findByCreatedAt(this.getParentCreatedAt());if(!i)throw new v(w.ErrInvalidArgument,`fail to find ${this.getParentCreatedAt()}`);if(!(i instanceof Mt))throw new v(w.ErrInvalidArgument,"fail to execute, only Tree can execute edit");const r=i;let s,o;if(this.attributes.size){const a={};[...this.attributes].forEach(([l,h])=>a[l]=h),[,o,s]=r.style([this.fromPos,this.toPos],a,this.getExecutedAt(),this.maxCreatedAtMapByActor)}else{const a=this.attributesToRemove;[,o,s]=r.removeStyle([this.fromPos,this.toPos],a,this.getExecutedAt(),this.maxCreatedAtMapByActor)}for(const a of o)t.registerGCPair(a);return{opInfos:s.map(({from:a,to:l,value:h,fromPath:c,toPath:u})=>({type:"tree-style",from:a,to:l,value:this.attributes.size?{attributes:h}:{attributesToRemove:h},fromPath:c,toPath:u,path:t.createPath(this.getParentCreatedAt())}))}}getEffectedCreatedAt(){return this.getParentCreatedAt()}toTestString(){const t=this.getParentCreatedAt().toTestString(),i=`${this.fromPos.getLeftSiblingID().getCreatedAt().toTestString()}:${this.fromPos.getLeftSiblingID().getOffset()}`,r=`${this.toPos.getLeftSiblingID().getCreatedAt().toTestString()}:${this.toPos.getLeftSiblingID().getOffset()}`;return`${t}.STYLE(${i},${r},${Object.entries(this.attributes||{}).map(([s,o])=>`${s}:"${o}"`).join(" ")})`}getFromPos(){return this.fromPos}getToPos(){return this.toPos}getAttributes(){return this.attributes}getAttributesToRemove(){return this.attributesToRemove}getMaxCreatedAtMapByActor(){return this.maxCreatedAtMapByActor}}function cw(n){const e=new Fu,t=e.data;for(const[i,r]of Object.entries(n))t[i]=JSON.stringify(r);return e}function uw(n){if(n.type===cr.Put)return new co({type:Dr.PUT,presence:cw(n.presence)});if(n.type===cr.Clear)return new co({type:Dr.CLEAR});throw new v(w.ErrUnimplemented,"unimplemented type")}function fw(n){return new Jm({serverSeq:n.getServerSeq(),clientSeq:n.getClientSeq()})}function hO(n){return new Kl({clientSeq:n.getClientSeq(),lamport:n.getLamport(),actorId:lf(n.getActorID()),versionVector:Yu(n.getVersionVector())})}function X(n){if(n)return new M({lamport:n.getLamport(),delimiter:n.getDelimiter(),actorId:lf(n.getActorID())})}function Yu(n){if(!n)return;const e=new eh;for(const[t,i]of n)e.vector[t]=BigInt(i.toString());return e}function cO(n){switch(n){case $e.Null:return F.NULL;case $e.Boolean:return F.BOOLEAN;case $e.Integer:return F.INTEGER;case $e.Long:return F.LONG;case $e.Double:return F.DOUBLE;case $e.String:return F.STRING;case $e.Bytes:return F.BYTES;case $e.Date:return F.DATE;default:throw new v(w.ErrInvalidType,`unsupported type: ${n}`)}}function uO(n){switch(n){case Pi.IntegerCnt:return F.INTEGER_CNT;case Pi.LongCnt:return F.LONG_CNT;default:throw new v(w.ErrInvalidType,`unsupported type: ${n}`)}}function Ah(n){if(n instanceof nt)return new Ot({type:F.JSON_OBJECT,createdAt:X(n.getCreatedAt()),value:xO(n)});if(n instanceof pt)return new Ot({type:F.JSON_ARRAY,createdAt:X(n.getCreatedAt()),value:Zw(n)});if(n instanceof qt)return new Ot({type:F.TEXT,createdAt:X(n.getCreatedAt())});if(n instanceof pe)return new Ot({type:cO(n.getType()),createdAt:X(n.getCreatedAt()),value:n.toBytes()});if(n instanceof gt)return new Ot({type:uO(n.getType()),createdAt:X(n.getCreatedAt()),value:n.toBytes()});if(n instanceof Mt)return new Ot({type:F.TREE,createdAt:X(n.getCreatedAt()),value:jw(n)});throw new v(w.ErrUnimplemented,"unimplemented element")}function dw(n){return new ho({createdAt:X(n.getCreatedAt()),offset:n.getOffset()})}function ea(n){return new Mn({createdAt:X(n.getID().getCreatedAt()),offset:n.getID().getOffset(),relativeOffset:n.getRelativeOffset()})}function ta(n){return new Er({parentId:Hs(n.getParentID()),leftSiblingId:Hs(n.getLeftSiblingID())})}function Hs(n){return new nr({createdAt:X(n.getCreatedAt()),offset:n.getOffset()})}function fO(n){const e=new Wu;if(n instanceof Nr){const t=n,i=new tl;i.parentCreatedAt=X(t.getParentCreatedAt()),i.key=t.getKey(),i.value=Ah(t.getValue()),i.executedAt=X(t.getExecutedAt()),e.body.case="set",e.body.value=i}else if(n instanceof Mo){const t=n,i=new il;i.parentCreatedAt=X(t.getParentCreatedAt()),i.prevCreatedAt=X(t.getPrevCreatedAt()),i.value=Ah(t.getValue()),i.executedAt=X(t.getExecutedAt()),e.body.case="add",e.body.value=i}else if(n instanceof Kn){const t=n,i=new nl;i.parentCreatedAt=X(t.getParentCreatedAt()),i.prevCreatedAt=X(t.getPrevCreatedAt()),i.createdAt=X(t.getCreatedAt()),i.executedAt=X(t.getExecutedAt()),e.body.case="move",e.body.value=i}else if(n instanceof ur){const t=n,i=new rl;i.parentCreatedAt=X(t.getParentCreatedAt()),i.createdAt=X(t.getCreatedAt()),i.executedAt=X(t.getExecutedAt()),e.body.case="remove",e.body.value=i}else if(n instanceof Vo){const t=n,i=new sl;i.parentCreatedAt=X(t.getParentCreatedAt()),i.from=ea(t.getFromPos()),i.to=ea(t.getToPos());const r=i.createdAtMapByActor;for(const[o,a]of t.getMaxCreatedAtMapByActor())r[o]=X(a);i.content=t.getContent();const s=i.attributes;for(const[o,a]of t.getAttributes())s[o]=a;i.executedAt=X(t.getExecutedAt()),e.body.case="edit",e.body.value=i}else if(n instanceof Xo){const t=n,i=new ol;i.parentCreatedAt=X(t.getParentCreatedAt()),i.from=ea(t.getFromPos()),i.to=ea(t.getToPos());const r=i.createdAtMapByActor;for(const[o,a]of t.getMaxCreatedAtMapByActor())r[o]=X(a);const s=i.attributes;for(const[o,a]of t.getAttributes())s[o]=a;i.executedAt=X(t.getExecutedAt()),e.body.case="style",e.body.value=i}else if(n instanceof gs){const t=n,i=new al;i.parentCreatedAt=X(t.getParentCreatedAt()),i.value=Ah(t.getValue()),i.executedAt=X(t.getExecutedAt()),e.body.case="increase",e.body.value=i}else if(n instanceof Lo){const t=n,i=new ll,r=i.createdAtMapByActor;for(const[s,o]of t.getMaxCreatedAtMapByActor())r[s]=X(o);i.parentCreatedAt=X(t.getParentCreatedAt()),i.from=ta(t.getFromPos()),i.to=ta(t.getToPos()),i.contents=Sw(t.getContents()),i.splitLevel=t.getSplitLevel(),i.executedAt=X(t.getExecutedAt()),e.body.case="treeEdit",e.body.value=i}else if(n instanceof Nn){const t=n,i=new hl;i.parentCreatedAt=X(t.getParentCreatedAt()),i.from=ta(t.getFromPos()),i.to=ta(t.getToPos());const r=i.createdAtMapByActor;for(const[o,a]of t.getMaxCreatedAtMapByActor())r[o]=X(a);const s=t.getAttributesToRemove();if(s.length>0)i.attributesToRemove=s;else{const o=i.attributes;for(const[a,l]of t.getAttributes())o[a]=l}i.executedAt=X(t.getExecutedAt()),e.body.case="treeStyle",e.body.value=i}else throw new v(w.ErrUnimplemented,"unimplemented operation");return e}function pw(n){const e=[];for(const t of n)e.push(fO(t));return e}function gw(n){const e=new zm({id:hO(n.getID()),message:n.getMessage()});return n.hasOperations()&&(e.operations=pw(n.getOperations())),n.hasPresenceChange()&&(e.presenceChange=uw(n.getPresenceChange())),e}function mw(n){const e=[];for(const t of n)e.push(gw(t));return e}function Ow(n){const e=[];for(const t of n)e.push(new _m({key:t.getStrKey(),element:Ku(t.getValue())}));return e}function yw(n){const e=[];for(const t of n)e.push(new ml({element:Ku(t.getValue())}));return e}function bw(n){const e=[];for(const t of n){const i=new Gm;i.id=dw(t.getID()),i.value=t.getValue().getContent(),i.removedAt=X(t.getRemovedAt());const r=i.attributes,s=t.getValue().getAttrs();for(const o of s){const a=new cs;a.value=o.getValue(),a.updatedAt=X(o.getUpdatedAt()),r[o.getKey()]=a}e.push(i)}return e}function Sw(n){const e=[];if(!n||!n.length)return e;for(const t of n)e.push(new Ol({content:Hu(t)}));return e}function ww(n){const e={};for(const t of n)e[t.getKey()]=new cs({value:t.getValue(),updatedAt:X(t.getUpdatedAt()),isRemoved:t.isRemoved()});return e}function Hu(n){if(!n)return[];const e=[];return th(n,(t,i)=>{const r=new ju({id:Hs(t.id),type:t.type,removedAt:X(t.removedAt),depth:i});t.isText&&(r.value=t.value),t.insPrevID&&(r.insPrevId=Hs(t.insPrevID)),t.insNextID&&(r.insNextId=Hs(t.insNextID)),t.attrs&&(r.attributes=ww(t.attrs)),e.push(r)}),e}function vw(n){const e=new rt;return e.body.case="jsonObject",e.body.value=new cl({nodes:Ow(n.getRHT()),createdAt:X(n.getCreatedAt()),movedAt:X(n.getMovedAt()),removedAt:X(n.getRemovedAt())}),e}function dO(n){const e=new rt;return e.body.case="jsonArray",e.body.value=new ul({nodes:yw(n.getElements()),createdAt:X(n.getCreatedAt()),movedAt:X(n.getMovedAt()),removedAt:X(n.getRemovedAt())}),e}function kw(n){const e=new rt;return e.body.case="primitive",e.body.value=new fl({type:cO(n.getType()),value:n.toBytes(),createdAt:X(n.getCreatedAt()),movedAt:X(n.getMovedAt()),removedAt:X(n.getRemovedAt())}),e}function xw(n){const e=new rt;return e.body.case="text",e.body.value=new dl({nodes:bw(n.getRGATreeSplit()),createdAt:X(n.getCreatedAt()),movedAt:X(n.getMovedAt()),removedAt:X(n.getRemovedAt())}),e}function Tw(n){const e=new rt;return e.body.case="counter",e.body.value=new pl({type:uO(n.getType()),value:n.toBytes(),createdAt:X(n.getCreatedAt()),movedAt:X(n.getMovedAt()),removedAt:X(n.getRemovedAt())}),e}function pO(n){const e=new rt;return e.body.case="tree",e.body.value=new gl({nodes:Hu(n.getRoot()),createdAt:X(n.getCreatedAt()),movedAt:X(n.getMovedAt()),removedAt:X(n.getRemovedAt())}),e}function Ku(n){if(n instanceof nt)return vw(n);if(n instanceof pt)return dO(n);if(n instanceof pe)return kw(n);if(n instanceof qt)return xw(n);if(n instanceof gt)return Tw(n);if(n instanceof Mt)return pO(n);throw new v(w.ErrUnimplemented,"unimplemented element")}function Qw(n){return new Wn({documentKey:n.getDocumentKey(),checkpoint:fw(n.getCheckpoint()),isRemoved:n.getIsRemoved(),changes:mw(n.getChanges()),snapshot:n.getSnapshot(),versionVector:Yu(n.getVersionVector()),minSyncedTicket:X(n.getMinSyncedTicket())})}function qd(n){const e=n.findDetails(U1);for(const t of e)if(t.metadata.code)return t.metadata.code;return""}function gO(n){return An.of(n.clientSeq,BigInt(n.lamport),of(n.actorId),ef(n.versionVector),BigInt(n.serverSeq))}function ef(n){if(!n)return;const e=new ts;return Object.entries(n.vector).forEach(([t,i])=>{e.set(t,BigInt(i.toString()))}),e}function L(n){if(n)return dt.of(BigInt(n.lamport),n.delimiter,of(n.actorId))}function tf(n){const e={};return Object.entries(n.data).forEach(([t,i])=>{e[t]=JSON.parse(i)}),e}function Pw(n){const e=n.type;if(e===Dr.PUT){const t=tf(n.presence);return{type:cr.Put,presence:t}}if(e===Dr.CLEAR)return{type:cr.Clear};throw new v(w.ErrInvalidType,`unsupported type: ${e}`)}function Aw(n){const e=new Map;return Object.entries(n).forEach(([t,i])=>{e.set(t,tf(i))}),e}function mO(n){switch(n){case F.NULL:return $e.Null;case F.BOOLEAN:return $e.Boolean;case F.INTEGER:return $e.Integer;case F.LONG:return $e.Long;case F.DOUBLE:return $e.Double;case F.STRING:return $e.String;case F.BYTES:return $e.Bytes;case F.DATE:return $e.Date}throw new v(w.ErrUnimplemented,`unimplemented value type: ${n}`)}function Sl(n){switch(n){case F.INTEGER_CNT:return Pi.IntegerCnt;case F.LONG_CNT:return Pi.LongCnt}throw new v(w.ErrUnimplemented,`unimplemented value type: ${n}`)}function $h(n){switch(n.type){case F.JSON_OBJECT:return n.value?kO(n.value):nt.create(L(n.createdAt));case F.JSON_ARRAY:return n.value?Uw(n.value):pt.create(L(n.createdAt));case F.TEXT:return qt.create(ps.create(),L(n.createdAt));case F.TREE:return Ww(n.value);case F.NULL:case F.BOOLEAN:case F.INTEGER:case F.LONG:case F.DOUBLE:case F.STRING:case F.BYTES:case F.DATE:return pe.of(pe.valueFromBytes(mO(n.type),n.value),L(n.createdAt));case F.INTEGER_CNT:case F.LONG_CNT:return gt.create(Sl(n.type),gt.valueFromBytes(Sl(n.type),n.value),L(n.createdAt))}}function ia(n){return Jt.of(Ti.of(L(n.createdAt),n.offset),n.relativeOffset)}function OO(n){return Ti.of(L(n.createdAt),n.offset)}function $w(n){const e=go.create(n.value);Object.entries(n.attributes).forEach(([i,r])=>{e.setAttr(i,r.value,L(r.updatedAt))});const t=sr.create(OO(n.id),e);return t.remove(L(n.removedAt)),t}function Wr(n){return _t.of(Ks(n.parentId),Ks(n.leftSiblingId))}function Ks(n){return Me.of(L(n.createdAt),n.offset)}function Cw(n){if(!n.length)return;const e=[];return n.forEach(t=>{const i=nf(t.content);e.push(i)}),e}function nf(n){if(n.length===0)return;const e=[];for(const r of n)e.push(Rw(r));const t=e[e.length-1],i=new Map;i.set(n[e.length-1].depth,e[e.length-1]);for(let r=e.length-2;r>=0;r--)i.get(n[r].depth-1).prepend(e[r]),i.set(n[r].depth,e[r]);return t.updateDescendantsSize(),Mt.create(t,Gt).getRoot()}function Iw(n){const e=Vn.create();for(const[t,i]of Object.entries(n))e.setInternal(t,i.value,L(i.updatedAt),i.isRemoved);return e}function Rw(n){const e=Ks(n.id),t=ut.create(e,n.type),i=Object.entries(n.attributes);return t.isText?t.value=n.value:i.length&&(t.attrs=Iw(n.attributes)),n.insPrevId&&(t.insPrevID=Ks(n.insPrevId)),n.insNextId&&(t.insNextID=Ks(n.insNextId)),t.removedAt=L(n.removedAt),t}function yO(n){if(n.body.case==="set"){const e=n.body.value;return Nr.create(e.key,$h(e.value),L(e.parentCreatedAt),L(e.executedAt))}else if(n.body.case==="add"){const e=n.body.value;return Mo.create(L(e.parentCreatedAt),L(e.prevCreatedAt),$h(e.value),L(e.executedAt))}else if(n.body.case==="move"){const e=n.body.value;return Kn.create(L(e.parentCreatedAt),L(e.prevCreatedAt),L(e.createdAt),L(e.executedAt))}else if(n.body.case==="remove"){const e=n.body.value;return ur.create(L(e.parentCreatedAt),L(e.createdAt),L(e.executedAt))}else if(n.body.case==="edit"){const e=n.body.value,t=new Map;Object.entries(e.createdAtMapByActor).forEach(([r,s])=>{t.set(r,L(s))});const i=new Map;return Object.entries(e.attributes).forEach(([r,s])=>{i.set(r,s)}),Vo.create(L(e.parentCreatedAt),ia(e.from),ia(e.to),t,e.content,i,L(e.executedAt))}else if(n.body.case==="style"){const e=n.body.value,t=new Map;Object.entries(e.createdAtMapByActor).forEach(([r,s])=>{t.set(r,L(s))});const i=new Map;return Object.entries(e.attributes).forEach(([r,s])=>{i.set(r,s)}),Xo.create(L(e.parentCreatedAt),ia(e.from),ia(e.to),t,i,L(e.executedAt))}else{if(n.body.case==="select")return;if(n.body.case==="increase"){const e=n.body.value;return gs.create(L(e.parentCreatedAt),$h(e.value),L(e.executedAt))}else if(n.body.case==="treeEdit"){const e=n.body.value,t=new Map;return Object.entries(e.createdAtMapByActor).forEach(([i,r])=>{t.set(i,L(r))}),Lo.create(L(e.parentCreatedAt),Wr(e.from),Wr(e.to),Cw(e.contents),e.splitLevel,t,L(e.executedAt))}else if(n.body.case==="treeStyle"){const e=n.body.value,t=new Map,i=e.attributesToRemove,r=new Map;return e!=null&&e.createdAtMapByActor&&Object.entries(e.createdAtMapByActor).forEach(([s,o])=>{r.set(s,L(o))}),(i==null?void 0:i.length)>0?Nn.createTreeRemoveStyleOperation(L(e.parentCreatedAt),Wr(e.from),Wr(e.to),r,i,L(e.executedAt)):(Object.entries(e.attributes).forEach(([s,o])=>{t.set(s,o)}),Nn.create(L(e.parentCreatedAt),Wr(e.from),Wr(e.to),r,t,L(e.executedAt)))}else throw new v(w.ErrUnimplemented,"unimplemented operation")}}function Ew(n){const e=[];for(const t of n){const i=yO(t);i&&e.push(i)}return e}function bO(n){const e=[];for(const t of n)e.push(ds.create({id:gO(t.id),operations:Ew(t.operations),presenceChange:t.presenceChange?Pw(t.presenceChange):void 0,message:t.message}));return e}function Dw(n){return is.of(BigInt(n.serverSeq),n.clientSeq)}function Nw(n){return ih.create(n.documentKey,Dw(n.checkpoint),n.isRemoved,bO(n.changes),ef(n.versionVector),n.snapshot,L(n.minSyncedTicket))}function SO(n){const e=new uo;for(const i of n.nodes){const r=rf(i.element);e.set(i.key,r,r.getPositionedAt())}const t=new nt(L(n.createdAt),e);return t.setMovedAt(L(n.movedAt)),t.setRemovedAt(L(n.removedAt)),t}function wO(n){const e=new po;for(const i of n.nodes)e.insert(rf(i.element));const t=new pt(L(n.createdAt),e);return t.setMovedAt(L(n.movedAt)),t.setRemovedAt(L(n.removedAt)),t}function Bw(n){const e=pe.of(pe.valueFromBytes(mO(n.type),n.value),L(n.createdAt));return e.setMovedAt(L(n.movedAt)),e.setRemovedAt(L(n.removedAt)),e}function qw(n){const e=new ps;let t=e.getHead();for(const r of n.nodes){const s=e.insertAfter(t,$w(r));r.insPrevId&&s.setInsPrev(e.findNode(OO(r.insPrevId))),t=s}const i=new qt(e,L(n.createdAt));return i.setMovedAt(L(n.movedAt)),i.setRemovedAt(L(n.removedAt)),i}function Mw(n){const e=gt.create(Sl(n.type),gt.valueFromBytes(Sl(n.type),n.value),L(n.createdAt));return e.setMovedAt(L(n.movedAt)),e.setRemovedAt(L(n.removedAt)),e}function vO(n){const e=nf(n.nodes);return Mt.create(e,L(n.createdAt))}function rf(n){if(n.body.case==="jsonObject")return SO(n.body.value);if(n.body.case==="jsonArray")return wO(n.body.value);if(n.body.case==="primitive")return Bw(n.body.value);if(n.body.case==="text")return qw(n.body.value);if(n.body.case==="counter")return Mw(n.body.value);if(n.body.case==="tree")return vO(n.body.value);throw new v(w.ErrUnimplemented,"unimplemented element")}function Vw(n){if(!n)return{root:nt.create(Gt),presences:new Map};const e=gc.fromBinary(n);return{root:rf(e.root),presences:Aw(e.presences)}}function Xw(n){const e=Yu(n);return sf(e.toBinary())}function Lw(n){const e=af(n),t=eh.fromBinary(e);return ef(t)}function kO(n){if(!n)throw new v(w.ErrInvalidArgument,"bytes is empty");const e=rt.fromBinary(n);return SO(e.body.value)}function xO(n){return Ku(n).toBinary()}function Uw(n){if(!n)throw new v(w.ErrInvalidArgument,"bytes is empty");const e=rt.fromBinary(n);return wO(e.body.value)}function Zw(n){return dO(n).toBinary()}function Ww(n){if(!n)throw new v(w.ErrInvalidArgument,"bytes is empty");const e=rt.fromBinary(n);return vO(e.body.value)}function jw(n){return pO(n).toBinary()}function sf(n){return n?Array.from(n).map(e=>e.toString(16).padStart(2,"0")).join(""):""}function of(n){return sf(n)}function af(n){return new Uint8Array(n.match(/.{1,2}/g).map(e=>parseInt(e,16)))}function lf(n){return af(n)}function Fw(n){const e=Kl.fromBinary(n);return gO(e)}function zw(n){const e=Wu.fromBinary(n);return yO(e)}const we={fromPresence:tf,toChangePack:Qw,fromChangePack:Nw,fromChanges:bO,toTreeNodes:Hu,fromTreeNodes:nf,objectToBytes:xO,bytesToObject:kO,bytesToSnapshot:Vw,bytesToHex:sf,hexToBytes:af,toHexString:of,toUint8Array:lf,toOperation:fO,toChangeID:hO,PbChangeID:Kl,bytesToChangeID:Fw,bytesToOperation:zw,versionVectorToHex:Xw,hexToVersionVector:Lw};var Ge=(n=>(n[n.Trivial=0]="Trivial",n[n.Debug=1]="Debug",n[n.Info=2]="Info",n[n.Warn=3]="Warn",n[n.Error=4]="Error",n[n.Fatal=5]="Fatal",n))(Ge||{});let vr=3;function TO(n){vr=n}const U={trivial:(...n)=>{vr>0||typeof console<"u"&&console.log("YORKIE T:",...n)},debug:(...n)=>{vr>1||typeof console<"u"&&console.log("YORKIE D:",...n)},info:(...n)=>{vr>2||typeof console<"u"&&console.log("YORKIE I:",...n)},warn:(...n)=>{vr>3||typeof console<"u"&&(typeof console.warn<"u"?console.warn("YORKIE W:",...n):console.log("YORKIE W:",...n))},error:(...n)=>{vr>4||typeof console<"u"&&(typeof console.error<"u"?console.error("YORKIE E:",...n):console.log("YORKIE E:",...n))},fatal:(...n)=>{typeof console<"u"&&(typeof console.error<"u"?console.error("YORKIE F:",...n):console.log("YORKIE F:",...n))},isEnabled:n=>vr<=n};function QO(){return"xxxxxxxx-xxxx-4xxxy-xxxx-xxxxxxxxxxx".replace(/[xy]/g,n=>{const e=Math.random()*16|0;return(n==="x"?e:e&3|8).toString(16)})}class _w{constructor(e,t,i,r,s){d(this,"reconnectStreamDelay");d(this,"doc");d(this,"docID");d(this,"syncMode");d(this,"remoteChangeEventReceived");d(this,"watchStream");d(this,"watchLoopTimerID");d(this,"watchAbortController");d(this,"unsubscribeBroadcastEvent");this.reconnectStreamDelay=e,this.doc=t,this.docID=i,this.syncMode=r,this.remoteChangeEventReceived=!1,this.unsubscribeBroadcastEvent=s}changeSyncMode(e){this.syncMode=e}needRealtimeSync(){return this.syncMode===Ma.RealtimeSyncOff?!1:this.syncMode===Ma.RealtimePushOnly?this.doc.hasLocalChanges():this.syncMode!==Ma.Manual&&(this.doc.hasLocalChanges()||this.remoteChangeEventReceived)}async runWatchLoop(e){const t=async()=>{if(this.watchStream)return Promise.resolve();this.watchLoopTimerID&&(clearTimeout(this.watchLoopTimerID),this.watchLoopTimerID=void 0);try{[this.watchStream,this.watchAbortController]=await e(()=>{this.watchStream=void 0,this.watchAbortController=void 0,this.watchLoopTimerID=setTimeout(t,this.reconnectStreamDelay)})}catch{}};await t()}cancelWatchStream(){this.watchStream&&this.watchAbortController&&(this.watchAbortController.abort(),this.watchStream=void 0,this.watchAbortController=void 0),clearTimeout(this.watchLoopTimerID),this.watchLoopTimerID=void 0}}const Ch=()=>{};class Gw{constructor(e){d(this,"finalized",!1);d(this,"observers",[]);d(this,"finalError");try{e(this)}catch(t){this.error(t)}}next(e){this.forEachObserver(t=>{t.next(e)})}error(e){this.forEachObserver(t=>{t.error(e)}),this.close(e)}complete(){this.forEachObserver(e=>{e.complete()}),this.close()}subscribe(e,t,i){let r;if(!e)throw new v(w.ErrInvalidArgument,"missing observer");if(this.finalized)throw new v(w.ErrRefused,"observable is finalized due to previous error");typeof e=="object"?r=e:r={next:e,error:t,complete:i},r.next===void 0&&(r.next=Ch),r.error===void 0&&(r.error=Ch),r.complete===void 0&&(r.complete=Ch);const s=QO(),o=this.unsubscribeOne.bind(this,s);if(this.observers.push({subscriptionID:s,observer:r}),this.finalized)try{this.finalError?r.error(this.finalError):r.complete()}catch(a){U.warn(a)}return o}unsubscribeOne(e){var t;this.observers=(t=this.observers)==null?void 0:t.filter(i=>i.subscriptionID!==e)}forEachObserver(e){if(!this.finalized)for(let t=0;te}}class Jr{constructor(e,t,i,r){d(this,"id");d(this,"delimiter");d(this,"message");d(this,"root");d(this,"operations");d(this,"presenceChange");d(this,"previousPresence");d(this,"reversePresenceKeys");this.id=e,this.delimiter=Hm,this.root=t,this.operations=[],this.previousPresence=Wt(i),this.presenceChange=void 0,this.reversePresenceKeys=new Set,this.message=r}static create(e,t,i,r){return new Jr(e,t,i,r)}push(e){this.operations.push(e)}registerElement(e,t){this.root.registerElement(e,t)}registerRemovedElement(e){this.root.registerRemovedElement(e)}registerGCPair(e){this.root.registerGCPair(e)}getChange(){return ds.create({id:this.id,operations:this.operations,presenceChange:this.presenceChange,message:this.message})}hasChange(){return this.operations.length>0||this.presenceChange!==void 0}setPresenceChange(e){this.presenceChange=e}setReversePresence(e,t){for(const i of Object.keys(e))t!=null&&t.addToHistory?this.reversePresenceKeys.add(i):this.reversePresenceKeys.delete(i)}getReversePresence(){if(this.reversePresenceKeys.size===0)return;const e={};for(const t of this.reversePresenceKeys)e[t]=this.previousPresence[t];return e}issueTimeTicket(){return this.delimiter+=1,this.id.createTimeTicket(this.delimiter)}getLastTimeTicket(){return this.id.createTimeTicket(this.delimiter)}}class mo{constructor(e){d(this,"rootObject");d(this,"elementPairMapByCreatedAt");d(this,"gcElementSetByCreatedAt");d(this,"gcPairMap");this.rootObject=e,this.elementPairMapByCreatedAt=new Map,this.gcElementSetByCreatedAt=new Set,this.gcPairMap=new Map,this.registerElement(e,void 0),e.getDescendants(t=>{if(t.getRemovedAt()&&this.registerRemovedElement(t),t instanceof qt||t instanceof Mt)for(const i of t.getGCPairs())this.registerGCPair(i);return!1})}static create(){return new mo(nt.create(Gt))}findByCreatedAt(e){const t=this.elementPairMapByCreatedAt.get(e.toIDString());if(t)return t.element}findElementPairByCreatedAt(e){return this.elementPairMapByCreatedAt.get(e.toIDString())}createSubPaths(e){let t=this.elementPairMapByCreatedAt.get(e.toIDString());if(!t)return[];const i=[];for(;t.parent;){const r=t.element.getCreatedAt(),s=t.parent.subPathOf(r);if(s===void 0)throw new v(w.ErrInvalidArgument,`cant find the given element: ${r.toIDString()}`);i.unshift(s),t=this.elementPairMapByCreatedAt.get(t.parent.getCreatedAt().toIDString())}return i.unshift("$"),i}createPath(e){return this.createSubPaths(e).join(".")}registerElement(e,t){this.elementPairMapByCreatedAt.set(e.getCreatedAt().toIDString(),{parent:t,element:e}),e instanceof rr&&e.getDescendants((i,r)=>(this.registerElement(i,r),!1))}deregisterElement(e){let t=0;const i=r=>{const s=r.getCreatedAt().toIDString();this.elementPairMapByCreatedAt.delete(s),this.gcElementSetByCreatedAt.delete(s),t++};return i(e),e instanceof rr&&e.getDescendants(r=>(i(r),!1)),t}registerRemovedElement(e){this.gcElementSetByCreatedAt.add(e.getCreatedAt().toIDString())}registerGCPair(e){if(this.gcPairMap.get(e.child.toIDString())){this.gcPairMap.delete(e.child.toIDString());return}this.gcPairMap.set(e.child.toIDString(),e)}getElementMapSize(){return this.elementPairMapByCreatedAt.size}getGarbageElementSetSize(){const e=new Set;for(const t of this.gcElementSetByCreatedAt){e.add(t);const i=this.elementPairMapByCreatedAt.get(t);i.element instanceof rr&&i.element.getDescendants(r=>(e.add(r.getCreatedAt().toIDString()),!1))}return e.size}getObject(){return this.rootObject}getGarbageLen(){return this.getGarbageElementSetSize()+this.gcPairMap.size}deepcopy(){return new mo(this.rootObject.deepcopy())}garbageCollect(e){let t=0;for(const i of this.gcElementSetByCreatedAt){const r=this.elementPairMapByCreatedAt.get(i),s=r.element.getRemovedAt();s&&(e!=null&&e.afterOrEqual(s))&&(r.parent.purge(r.element),t+=this.deregisterElement(r.element))}for(const[,i]of this.gcPairMap){const r=i.child.getRemovedAt();r&&(e!=null&&e.afterOrEqual(r))&&(i.parent.purge(i.child),this.gcPairMap.delete(i.child.toIDString()),t+=1)}return t}toJSON(){return this.rootObject.toJSON()}toSortedJSON(){return this.rootObject.toSortedJSON()}getStats(){return{elements:this.getElementMapSize(),gcPairs:this.gcPairMap.size,gcElements:this.getGarbageElementSetSize()}}}function PO(n,e){const t=new Oo(n);return new Proxy(e,t.getHandlers())}class Oo{constructor(e){d(this,"context");d(this,"handlers");this.context=e,this.handlers={set:(t,i,r)=>(U.isEnabled(Ge.Trivial)&&U.trivial(`obj[${i}]=${JSON.stringify(r)}`),Oo.setInternal(e,t,i,r),!0),get:(t,i)=>(U.isEnabled(Ge.Trivial)&&U.trivial(`obj[${i}]`),i==="getID"?()=>t.getCreatedAt():i==="toJSON"||i==="toString"?()=>t.toJSON():i==="toJS"?()=>t.toJS():i==="toJSForTest"?()=>t.toJSForTest():kr(e,t.get(i))),ownKeys:t=>t.getKeys(),getOwnPropertyDescriptor:()=>({enumerable:!0,configurable:!0}),deleteProperty:(t,i)=>(U.isEnabled(Ge.Trivial)&&U.trivial(`obj[${i}]`),Oo.deleteInternal(e,t,i),!0)}}static setInternal(e,t,i,r){if(i.includes("."))throw new v(w.ErrInvalidObjectKey,"key must not contain the '.'.");const s=e.issueTimeTicket(),o=wl(e,r,s),a=t.set(i,o,s);e.registerElement(o,t),a&&e.registerRemovedElement(a),e.push(Nr.create(i,o.deepcopy(),t.getCreatedAt(),s))}static buildObjectMembers(e,t){const i={};for(const[r,s]of Object.entries(t)){if(r.includes("."))throw new v(w.ErrInvalidObjectKey,"key must not contain the '.'.");const o=e.issueTimeTicket(),a=wl(e,s,o);i[r]=a}return i}static deleteInternal(e,t,i){const r=e.issueTimeTicket(),s=t.deleteByKey(i,r);s&&(e.push(ur.create(t.getCreatedAt(),s.getCreatedAt(),r)),e.registerRemovedElement(s))}getHandlers(){return this.handlers}}function Yw(n,e){const t=new me(n,e);return new Proxy(e,t.getHandlers())}function Hw(n){return typeof n=="string"||n instanceof String?!isNaN(n):!1}function Kw(n){return["concat","entries","every","filter","find","findIndex","forEach","join","keys","map","reduce","reduceRight","slice","some","toLocaleString","toString","values"].includes(n)}class me{constructor(e,t){d(this,"context");d(this,"handlers");d(this,"array");this.context=e,this.array=t,this.handlers={get:(i,r,s)=>r==="getID"?()=>i.getCreatedAt():r==="getElementByID"?o=>{const a=i.getByID(o);if(!(!a||a.isRemoved()))return _n(e,a)}:r==="getElementByIndex"?o=>{const a=i.get(o);return _n(e,a)}:r==="getLast"?()=>_n(e,i.getLast()):r==="deleteByID"?o=>{const a=me.deleteInternalByID(e,i,o);return _n(e,a)}:r==="insertAfter"?(o,a)=>{const l=me.insertAfterInternal(e,i,o,a);return _n(e,l)}:r==="insertBefore"?(o,a)=>{const l=me.insertBeforeInternal(e,i,o,a);return _n(e,l)}:r==="moveBefore"?(o,a)=>{me.moveBeforeInternal(e,i,o,a)}:r==="moveAfter"?(o,a)=>{me.moveAfterInternal(e,i,o,a)}:r==="moveFront"?o=>{me.moveFrontInternal(e,i,o)}:r==="moveLast"?o=>{me.moveLastInternal(e,i,o)}:Hw(r)?kr(e,i.get(Number(r))):r==="push"?o=>me.pushInternal(e,i,o):r==="splice"?(o,a,...l)=>me.splice(e,i,o,a,...l):r==="length"?i.length:typeof r=="symbol"&&r===Symbol.iterator?me.iteratorInternal.bind(this,e,i):r==="includes"?(o,a)=>me.includes(e,i,o,a):r==="indexOf"?(o,a)=>me.indexOf(e,i,o,a):r==="lastIndexOf"?(o,a)=>me.lastIndexOf(e,i,o,a):r==="toJSForTest"?()=>i.toJSForTest():r==="toTestString"?()=>me.toTestString(i):typeof r=="string"&&Kw(r)?(...o)=>{const a=Array.from(i).map(l=>kr(e,l));return Array.prototype[r].apply(a,o)}:Reflect.get(i,r,s),deleteProperty:(i,r)=>(U.isEnabled(Ge.Trivial)&&U.trivial(`array[${r}]`),me.deleteInternalByIndex(e,i,Number.parseInt(r)),!0)}}static*iteratorInternal(e,t){for(const i of t)yield _n(e,i)}static buildArrayElements(e,t){const i=[];for(const r of t){const s=e.issueTimeTicket(),o=wl(e,r,s);i.push(o)}return i}static pushInternal(e,t,i){return me.insertAfterInternal(e,t,t.getLastCreatedAt(),i),t.length}static moveBeforeInternal(e,t,i,r){const s=e.issueTimeTicket(),o=t.getPrevCreatedAt(i);t.moveAfter(o,r,s),e.push(Kn.create(t.getCreatedAt(),o,r,s))}static moveAfterInternal(e,t,i,r){const s=e.issueTimeTicket();t.moveAfter(i,r,s),e.push(Kn.create(t.getCreatedAt(),i,r,s))}static moveFrontInternal(e,t,i){const r=e.issueTimeTicket(),s=t.getHead();t.moveAfter(s.getCreatedAt(),i,r),e.push(Kn.create(t.getCreatedAt(),s.getCreatedAt(),i,r))}static moveLastInternal(e,t,i){const r=e.issueTimeTicket(),s=t.getLastCreatedAt();t.moveAfter(s,i,r),e.push(Kn.create(t.getCreatedAt(),s,i,r))}static insertAfterInternal(e,t,i,r){const s=e.issueTimeTicket(),o=wl(e,r,s);return t.insertAfter(i,o),e.registerElement(o,t),e.push(Mo.create(t.getCreatedAt(),i,o.deepcopy(),s)),o}static insertBeforeInternal(e,t,i,r){return me.insertAfterInternal(e,t,t.getPrevCreatedAt(i),r)}static deleteInternalByIndex(e,t,i){const r=e.issueTimeTicket(),s=t.deleteByIndex(i,r);if(s)return e.push(ur.create(t.getCreatedAt(),s.getCreatedAt(),r)),e.registerRemovedElement(s),s}static deleteInternalByID(e,t,i){const r=e.issueTimeTicket(),s=t.delete(i,r);return e.push(ur.create(t.getCreatedAt(),s.getCreatedAt(),r)),e.registerRemovedElement(s),s}static splice(e,t,i,r,...s){const o=t.length,a=i>=0?Math.min(i,o):Math.max(o+i,0),l=r===void 0?o:r<0?a:Math.min(a+r,o),h=[];for(let c=a;c=s)return!1;if(pe.isSupport(i))return Array.from(t).map(h=>kr(e,h)).includes(i,o);for(let l=o;l=s)return-1;if(pe.isSupport(i))return Array.from(t).map(h=>kr(e,h)).indexOf(i,o);for(let l=o;l=s?s-1:r<0?r+s:r;if(o<0)return-1;if(pe.isSupport(i))return Array.from(t).map(h=>kr(e,h)).lastIndexOf(i,o);for(let l=o;l>0;l--)if(((a=t.get(l))==null?void 0:a.getID())===i.getID())return l;return-1}static toTestString(e){return e.toTestString()}getHandlers(){return this.handlers}}let nh=class{constructor(e,t){d(this,"context");d(this,"text");this.context=e,this.text=t}initialize(e,t){this.context=e,this.text=t}getID(){return this.text.getID()}edit(e,t,i,r){if(!this.context||!this.text)throw new v(w.ErrNotInitialized,"Text is not initialized yet");if(e>t)throw new v(w.ErrInvalidArgument,"from should be less than or equal to to");const s=this.text.indexRangeToPosRange(e,t);U.isEnabled(Ge.Debug)&&U.debug(`EDIT: f:${e}->${s[0].toTestString()}, t:${t}->${s[1].toTestString()} c:${i}`);const o=r?us(r):void 0,a=this.context.issueTimeTicket(),[l,,h,c]=this.text.edit(s,i,a,o);for(const u of h)this.context.registerGCPair(u);return this.context.push(new Vo(this.text.getCreatedAt(),s[0],s[1],l,i,o?new Map(Object.entries(o)):new Map,a)),this.text.findIndexesFromRange(c)}delete(e,t){return this.edit(e,t,"")}empty(){return this.edit(0,this.length,"")}setStyle(e,t,i){if(!this.context||!this.text)throw new v(w.ErrNotInitialized,"Text is not initialized yet");if(e>t)throw new v(w.ErrInvalidArgument,"from should be less than or equal to to");const r=this.text.indexRangeToPosRange(e,t);U.isEnabled(Ge.Debug)&&U.debug(`STYL: f:${e}->${r[0].toTestString()}, t:${t}->${r[1].toTestString()} a:${JSON.stringify(i)}`);const s=us(i),o=this.context.issueTimeTicket(),[a,l]=this.text.setStyle(r,s,o);for(const h of l)this.context.registerGCPair(h);return this.context.push(new Xo(this.text.getCreatedAt(),r[0],r[1],a,new Map(Object.entries(s)),o)),!0}indexRangeToPosRange(e){if(!this.context||!this.text)throw new v(w.ErrNotInitialized,"Text is not initialized yet");const t=this.text.indexRangeToPosRange(e[0],e[1]);return[t[0].toStruct(),t[1].toStruct()]}posRangeToIndexRange(e){if(!this.context||!this.text)throw new v(w.ErrNotInitialized,"Text is not initialized yet");const t=this.text.findIndexesFromRange([Jt.fromStruct(e[0]),Jt.fromStruct(e[1])]);return[t[0],t[1]]}toTestString(){if(!this.context||!this.text)throw new v(w.ErrNotInitialized,"Text is not initialized yet");return this.text.toTestString()}values(){if(!this.context||!this.text)throw new v(w.ErrNotInitialized,"Text is not initialized yet");return this.text.values()}get length(){return this.text.length}getTreeByIndex(){return this.text.getTreeByIndex()}getTreeByID(){return this.text.getTreeByID()}toString(){if(!this.context||!this.text)throw new v(w.ErrNotInitialized,"Text is not initialized yet");return this.text.toString()}toJSON(){if(!this.context||!this.text)throw new v(w.ErrNotInitialized,"Text is not initialized yet");return this.text.toJSON()}toJSForTest(){if(!this.context||!this.text)throw new v(w.ErrNotInitialized,"Text is not initialized yet");return this.text.toJSForTest()}createRangeForTest(e,t){if(!this.context||!this.text)throw new v(w.ErrNotInitialized,"Text is not initialized yet");return this.text.indexRangeToPosRange(e,t)}};class rh{constructor(e,t){d(this,"valueType");d(this,"value");d(this,"context");d(this,"counter");this.valueType=e,this.value=t}initialize(e,t){this.valueType=t.getValueType(),this.context=e,this.counter=t,this.value=t.getValue()}getID(){return this.counter.getID()}getValue(){return this.value}getValueType(){return this.valueType}increase(e){if(!this.context||!this.counter)throw new v(w.ErrNotInitialized,"Counter is not initialized yet");const t=this.context.issueTimeTicket(),i=pe.of(e,t);if(!i.isNumericType())throw new TypeError(`Unsupported type of value: ${typeof i.getValue()}`);return this.counter.increase(i),this.context.push(gs.create(this.counter.getCreatedAt(),i,t)),this}toJSForTest(){if(!this.context||!this.counter)throw new v(w.ErrNotInitialized,"Counter is not initialized yet");return this.counter.toJSForTest()}}function hf(n,e,t){const{type:i}=n,r=t.issueTimeTicket();if(i===Dn){AO(n);const{value:s}=n,o=ut.create(Me.of(r,0),i,s);e.append(o)}else{const{children:s=[]}=n,{attributes:o}=n;let a;if(typeof o=="object"&&!Ym(o)){const h=us(o);a=new Vn;for(const[c,u]of Object.entries(h))a.set(c,u,r)}const l=ut.create(Me.of(r,0),i,void 0,a);e.append(l);for(const h of s)hf(h,l,t)}}function ev(n,e){const{type:t}=e,i=n.issueTimeTicket();let r;if(e.type===Dn){const{value:s}=e;r=ut.create(Me.of(i,0),t,s)}else if(e){const{children:s=[]}=e,{attributes:o}=e;let a;if(typeof o=="object"&&!Ym(o)){const l=us(o);a=new Vn;for(const[h,c]of Object.entries(l))a.set(h,c,i)}r=ut.create(Me.of(n.issueTimeTicket(),0),t,void 0,a);for(const l of s)hf(l,r,n)}return r}function AO(n){if(!n.value.length)throw new v(w.ErrInvalidArgument,"text node cannot have empty value");return!0}function Md(n){if(!n.length)return!0;if(n[0].type===Dn)for(const t of n){const{type:i}=t;if(i!==Dn)throw new v(w.ErrInvalidArgument,"element node and text node cannot be passed together");AO(t)}else for(const t of n){const{type:i}=t;if(i===Dn)throw new v(w.ErrInvalidArgument,"element node and text node cannot be passed together")}return!0}let sh=class{constructor(e){d(this,"initialRoot");d(this,"context");d(this,"tree");this.initialRoot=e}initialize(e,t){this.context=e,this.tree=t}getID(){return this.tree.getID()}buildRoot(e){if(!this.initialRoot)return ut.create(Me.of(e.issueTimeTicket(),0),H1);const t=ut.create(Me.of(e.issueTimeTicket(),0),this.initialRoot.type);for(const i of this.initialRoot.children)hf(i,t,e);return t}getSize(){if(!this.context||!this.tree)throw new v(w.ErrNotInitialized,"Tree is not initialized yet");return this.tree.getSize()}getNodeSize(){if(!this.context||!this.tree)throw new v(w.ErrNotInitialized,"Tree is not initialized yet");return this.tree.getNodeSize()}getIndexTree(){if(!this.context||!this.tree)throw new v(w.ErrNotInitialized,"Tree is not initialized yet");return this.tree.getIndexTree()}styleByPath(e,t){if(!this.context||!this.tree)throw new v(w.ErrNotInitialized,"Tree is not initialized yet");if(!e.length)throw new v(w.ErrInvalidArgument,"path should not be empty");const[i,r]=this.tree.pathToPosRange(e),s=this.context.issueTimeTicket(),o=t?us(t):void 0,[a]=this.tree.style([i,r],o,s);this.context.push(Nn.create(this.tree.getCreatedAt(),i,r,a,o?new Map(Object.entries(o)):new Map,s))}style(e,t,i){if(!this.context||!this.tree)throw new v(w.ErrNotInitialized,"Tree is not initialized yet");if(e>t)throw new v(w.ErrInvalidArgument,"from should be less than or equal to to");const r=this.tree.findPos(e),s=this.tree.findPos(t),o=this.context.issueTimeTicket(),a=i?us(i):void 0,[l,h]=this.tree.style([r,s],a,o);for(const c of h)this.context.registerGCPair(c);this.context.push(Nn.create(this.tree.getCreatedAt(),r,s,l,a?new Map(Object.entries(a)):new Map,o))}removeStyle(e,t,i){if(!this.context||!this.tree)throw new v(w.ErrNotInitialized,"Tree is not initialized yet");if(e>t)throw new v(w.ErrInvalidArgument,"from should be less than or equal to to");const r=this.tree.findPos(e),s=this.tree.findPos(t),o=this.context.issueTimeTicket(),[a,l]=this.tree.removeStyle([r,s],i,o);for(const h of l)this.context.registerGCPair(h);this.context.push(Nn.createTreeRemoveStyleOperation(this.tree.getCreatedAt(),r,s,a,i,o))}editInternal(e,t,i,r=0){var h;if(i.length!==0&&i[0]&&(Md(i),i[0].type!==Dn))for(const c of i){const{children:u=[]}=c;Md(u)}const s=this.context.getLastTimeTicket();let o=new Array;if(((h=i[0])==null?void 0:h.type)===Dn){let c="";for(const u of i){const{value:f}=u;c+=f}o.push(ut.create(Me.of(this.context.issueTimeTicket(),0),Dn,c))}else o=i.map(c=>c&&ev(this.context,c)).filter(c=>c);const[,a,l]=this.tree.edit([e,t],o.length?o.map(c=>c==null?void 0:c.deepcopy()):void 0,r,s,()=>this.context.issueTimeTicket());for(const c of a)this.context.registerGCPair(c);return this.context.push(Lo.create(this.tree.getCreatedAt(),e,t,o.length?o:void 0,r,l,s)),!0}editByPath(e,t,i,r=0){if(!this.context||!this.tree)throw new v(w.ErrNotInitialized,"Tree is not initialized yet");if(e.length!==t.length)throw new v(w.ErrInvalidArgument,"path length should be equal");if(!e.length||!t.length)throw new v(w.ErrInvalidArgument,"path should not be empty");const s=this.tree.pathToPos(e),o=this.tree.pathToPos(t);return this.editInternal(s,o,i?[i]:[],r)}editBulkByPath(e,t,i,r=0){if(!this.context||!this.tree)throw new v(w.ErrNotInitialized,"Tree is not initialized yet");if(e.length!==t.length)throw new v(w.ErrInvalidArgument,"path length should be equal");if(!e.length||!t.length)throw new v(w.ErrInvalidArgument,"path should not be empty");const s=this.tree.pathToPos(e),o=this.tree.pathToPos(t);return this.editInternal(s,o,i,r)}edit(e,t,i,r=0){if(!this.context||!this.tree)throw new v(w.ErrNotInitialized,"Tree is not initialized yet");if(e>t)throw new v(w.ErrInvalidArgument,"from should be less than or equal to to");const s=this.tree.findPos(e),o=this.tree.findPos(t);return this.editInternal(s,o,i?[i]:[],r)}editBulk(e,t,i,r=0){if(!this.context||!this.tree)throw new v(w.ErrNotInitialized,"Tree is not initialized yet");if(e>t)throw new v(w.ErrInvalidArgument,"from should be less than or equal to to");const s=this.tree.findPos(e),o=this.tree.findPos(t);return this.editInternal(s,o,i,r)}toXML(){if(!this.context||!this.tree)throw new v(w.ErrNotInitialized,"Tree is not initialized yet");return this.tree.toXML()}toJSON(){if(!this.context||!this.tree)throw new v(w.ErrNotInitialized,"Tree is not initialized yet");return this.tree.toJSON()}toJSForTest(){if(!this.context||!this.tree)throw new v(w.ErrNotInitialized,"Tree is not initialized yet");return this.tree.toJSForTest()}toJSInfoForTest(){if(!this.context||!this.tree)throw new v(w.ErrNotInitialized,"Tree is not initialized yet");return this.tree.toJSInfoForTest()}getRootTreeNode(){if(!this.context||!this.tree)throw new v(w.ErrNotInitialized,"Tree is not initialized yet");return this.tree.getRootTreeNode()}indexToPath(e){if(!this.context||!this.tree)throw new v(w.ErrNotInitialized,"Tree is not initialized yet");return this.tree.indexToPath(e)}pathToIndex(e){if(!this.context||!this.tree)throw new v(w.ErrNotInitialized,"Tree is not initialized yet");return this.tree.pathToIndex(e)}pathRangeToPosRange(e){if(!this.context||!this.tree)throw new v(w.ErrNotInitialized,"Tree is not initialized yet");const t=[this.tree.pathToIndex(e[0]),this.tree.pathToIndex(e[1])],i=this.tree.indexRangeToPosRange(t);return[i[0].toStruct(),i[1].toStruct()]}indexRangeToPosRange(e){if(!this.context||!this.tree)throw new v(w.ErrNotInitialized,"Tree is not initialized yet");return this.tree.indexRangeToPosStructRange(e)}posRangeToIndexRange(e){if(!this.context||!this.tree)throw new v(w.ErrNotInitialized,"Tree is not initialized yet");const t=[_t.fromStruct(e[0]),_t.fromStruct(e[1])];return this.tree.posRangeToIndexRange(t)}posRangeToPathRange(e){if(!this.context||!this.tree)throw new v(w.ErrNotInitialized,"Tree is not initialized yet");const t=[_t.fromStruct(e[0]),_t.fromStruct(e[1])];return this.tree.posRangeToPathRange(t)}};function Vd(n,e){return PO(n,e)}function _n(n,e){if(e){if(e instanceof pe)return e;if(e instanceof nt)return PO(n,e);if(e instanceof pt)return Yw(n,e);if(e instanceof qt)return new nh(n,e);if(e instanceof gt){const t=new rh(Pi.IntegerCnt,0);return t.initialize(n,e),t}else if(e instanceof Mt){const t=new sh;return t.initialize(n,e),t}}else return;throw new TypeError(`Unsupported type of element: ${typeof e}`)}function kr(n,e){const t=_n(n,e);return t instanceof pe?t.getValue():t}function wl(n,e,t){let i;if(pe.isSupport(e))i=pe.of(e,t);else if(Array.isArray(e))i=pt.create(t,me.buildArrayElements(n,e));else if(typeof e=="object")e instanceof nh?(i=qt.create(ps.create(),t),e.initialize(n,i)):e instanceof rh?(i=gt.create(e.getValueType(),e.getValue(),t),e.initialize(n,i)):e instanceof sh?(i=Mt.create(e.buildRoot(n),t),e.initialize(n,i)):i=nt.create(t,Oo.buildObjectMembers(n,e));else throw new TypeError(`Unsupported type of value: ${typeof e}`);return i}const Xd=50;class tv{constructor(){d(this,"undoStack",[]);d(this,"redoStack",[])}hasUndo(){return this.undoStack.length>0}hasRedo(){return this.redoStack.length>0}pushUndo(e){this.undoStack.length>=Xd&&this.undoStack.shift(),this.undoStack.push(e)}popUndo(){return this.undoStack.pop()}pushRedo(e){this.redoStack.length>=Xd&&this.redoStack.shift(),this.redoStack.push(e)}popRedo(){return this.redoStack.pop()}clearRedo(){this.redoStack=[]}getUndoStackForTest(){return this.undoStack}getRedoStackForTest(){return this.redoStack}}const iv="yorkie-devtools-panel",nv="yorkie-devtools-sdk";let Fr="disconnected";const Ld=new Map,qa=new Map;typeof window<"u"&&(window.transactionEventsByDocKey=qa);function na(n,e){(e!=null&&e.force||Fr!=="disconnected")&&window.postMessage({source:nv,...n},"*")}function rv(n){if(!n.isEnableDevtools()||typeof window>"u"||Ld.has(n.getKey()))return;qa.set(n.getKey(),[]);const e=n.subscribe("all",t=>{t.some(i=>i.type!==_e.StatusChanged&&i.type!==_e.Snapshot&&i.type!==_e.LocalChange&&i.type!==_e.RemoteChange&&i.type!==_e.Initialized&&i.type!==_e.Watched&&i.type!==_e.Unwatched&&i.type!==_e.PresenceChanged)||(qa.get(n.getKey()).push(t),Fr==="synced"&&na({msg:"doc::sync::partial",docKey:n.getKey(),event:t}))});Ld.set(n.getKey(),[e]),na({msg:"refresh-devtools"},{force:!0}),window.addEventListener("message",t=>{var r;if(((r=t.data)==null?void 0:r.source)!==iv)return;switch(t.data.msg){case"devtools::connect":if(Fr!=="disconnected")break;Fr="connected",na({msg:"doc::available",docKey:n.getKey()}),U.info(`[YD] Devtools connected. Doc: ${n.getKey()}`);break;case"devtools::disconnect":Fr="disconnected",U.info(`[YD] Devtools disconnected. Doc: ${n.getKey()}`);break;case"devtools::subscribe":Fr="synced",na({msg:"doc::sync::full",docKey:n.getKey(),events:qa.get(n.getKey())}),U.info(`[YD] Devtools subscribed. Doc: ${n.getKey()}`);break}})}var Gn=(n=>(n.Detached="detached",n.Attached="attached",n.Removed="removed",n))(Gn||{}),_e=(n=>(n.StatusChanged="status-changed",n.ConnectionChanged="connection-changed",n.SyncStatusChanged="sync-status-changed",n.Snapshot="snapshot",n.LocalChange="local-change",n.RemoteChange="remote-change",n.Initialized="initialized",n.Watched="watched",n.Unwatched="unwatched",n.PresenceChanged="presence-changed",n.Broadcast="broadcast",n.LocalBroadcast="local-broadcast",n))(_e||{}),yo=(n=>(n.Connected="connected",n.Disconnected="disconnected",n))(yo||{}),Lc=(n=>(n.Synced="synced",n.SyncFailed="sync-failed",n))(Lc||{});class $O{constructor(e,t){d(this,"key");d(this,"status");d(this,"opts");d(this,"changeID");d(this,"checkpoint");d(this,"localChanges");d(this,"root");d(this,"clone");d(this,"eventStream");d(this,"eventStreamObserver");d(this,"onlineClients");d(this,"presences");d(this,"history");d(this,"internalHistory");d(this,"isUpdating");this.opts=t||{},this.key=e,this.status="detached",this.root=mo.create(),this.changeID=aw,this.checkpoint=lw,this.localChanges=[],this.eventStream=Jw(i=>{this.eventStreamObserver=i}),this.onlineClients=new Set,this.presences=new Map,this.isUpdating=!1,this.internalHistory=new tv,this.history={canUndo:this.canUndo.bind(this),canRedo:this.canRedo.bind(this),undo:this.undo.bind(this),redo:this.redo.bind(this)},rv(this)}update(e,t){if(this.getStatus()==="removed")throw new v(w.ErrDocumentRemoved,`${this.key} is removed`);this.ensureClone();const i=this.changeID.getActorID(),r=Jr.create(this.changeID.next(),this.clone.root,this.clone.presences.get(i)||{},t);try{const s=Vd(r,this.clone.root.getObject());this.presences.has(i)||this.clone.presences.set(i,{}),this.isUpdating=!0,e(s,new Ph(r,this.clone.presences.get(i)))}catch(s){throw this.clone=void 0,s}finally{this.isUpdating=!1}if(r.hasChange()){U.isEnabled(Ge.Trivial)&&U.trivial(`trying to update a local change: ${this.toJSON()}`);const s=r.getChange(),{opInfos:o,reverseOps:a}=s.execute(this.root,this.presences,se.Local),l=r.getReversePresence();l&&a.push({type:"presence",value:l}),this.localChanges.push(s),a.length>0&&this.internalHistory.pushUndo(a),o.length>0&&this.internalHistory.clearRedo(),this.changeID=s.getID();const h=[];o.length>0&&h.push({type:"local-change",source:se.Local,value:{message:s.getMessage()||"",operations:o,actor:i,clientSeq:s.getID().getClientSeq(),serverSeq:s.getID().getServerSeq()},rawChange:this.isEnableDevtools()?s.toStruct():void 0}),s.hasPresenceChange()&&h.push({type:"presence-changed",source:se.Local,value:{clientID:i,presence:this.getPresence(i)}}),this.publish(h),U.isEnabled(Ge.Trivial)&&U.trivial(`after update a local change: ${this.toJSON()}`)}}subscribe(e,t,i,r){if(typeof e=="string"){if(typeof t!="function")throw new v(w.ErrInvalidArgument,"Second argument must be a callback function");if(e==="presence"){const a=t;return this.eventStream.subscribe(l=>{for(const h of l)h.type!=="initialized"&&h.type!=="watched"&&h.type!=="unwatched"&&h.type!=="presence-changed"||a(h)},i,r)}if(e==="my-presence"){const a=t;return this.eventStream.subscribe(l=>{for(const h of l)h.type!=="initialized"&&h.type!=="presence-changed"||h.type==="presence-changed"&&h.value.clientID!==this.changeID.getActorID()||a(h)},i,r)}if(e==="others"){const a=t;return this.eventStream.subscribe(l=>{for(const h of l)h.type!=="watched"&&h.type!=="unwatched"&&h.type!=="presence-changed"||h.value.clientID!==this.changeID.getActorID()&&a(h)},i,r)}if(e==="connection"){const a=t;return this.eventStream.subscribe(l=>{for(const h of l)h.type==="connection-changed"&&a(h)},i,r)}if(e==="status"){const a=t;return this.eventStream.subscribe(l=>{for(const h of l)h.type==="status-changed"&&a(h)},i,r)}if(e==="sync"){const a=t;return this.eventStream.subscribe(l=>{for(const h of l)h.type==="sync-status-changed"&&a(h)},i,r)}if(e==="local-broadcast"){const a=t;return this.eventStream.subscribe(l=>{for(const h of l)h.type==="local-broadcast"&&a(h)},i)}if(e==="broadcast"){const a=t;return this.eventStream.subscribe(l=>{for(const h of l)h.type==="broadcast"&&a(h)},i)}if(e==="all"){const a=t;return this.eventStream.subscribe(a,i,r)}const s=e,o=t;return this.eventStream.subscribe(a=>{for(const l of a){if(l.type!=="local-change"&&l.type!=="remote-change")continue;const h=[];for(const c of l.value.operations)this.isSameElementOrChildOf(c.path,s)&&h.push(c);h.length&&o({...l,value:{...l.value,operations:h}})}},i,r)}if(typeof e=="function"){const s=e,o=t,a=i;return this.eventStream.subscribe(l=>{for(const h of l)h.type!=="snapshot"&&h.type!=="local-change"&&h.type!=="remote-change"||s(h)},o,a)}throw new v(w.ErrInvalidArgument,`"${e}" is not a valid`)}publish(e){this.eventStreamObserver&&this.eventStreamObserver.next(e)}isSameElementOrChildOf(e,t){if(t===e)return!0;const i=e.split(".");return t.split(".").every((s,o)=>s===i[o])}applyChangePack(e){const t=e.hasSnapshot();for(t?this.applySnapshot(e.getCheckpoint().getServerSeq(),e.getVersionVector(),e.getSnapshot()):e.hasChanges()&&this.applyChanges(e.getChanges(),se.Remote);this.localChanges.length&&!(this.localChanges[0].getID().getClientSeq()>e.getCheckpoint().getClientSeq());)this.localChanges.shift();t&&this.applyChanges(this.localChanges,se.Remote),this.checkpoint=this.checkpoint.forward(e.getCheckpoint()),t||this.garbageCollect(e.getVersionVector()),t||this.filterVersionVector(e.getVersionVector()),e.getIsRemoved()&&this.applyStatus("removed"),U.isEnabled(Ge.Trivial)&&U.trivial(`${this.root.toJSON()}`)}getCheckpoint(){return this.checkpoint}getChangeID(){return this.changeID}hasLocalChanges(){return this.localChanges.length>0}ensureClone(){this.clone||(this.clone={root:this.root.deepcopy(),presences:Wt(this.presences)})}createChangePack(){const e=Array.from(this.localChanges),t=this.checkpoint.increaseClientSeq(e.length);return ih.create(this.key,t,!1,e,this.getVersionVector())}setActor(e){for(const t of this.localChanges)t.setActor(e);this.changeID=this.changeID.setActor(e)}isEnableDevtools(){return!!this.opts.enableDevtools}getKey(){return this.key}getStatus(){return this.status}getCloneRoot(){if(this.clone)return this.clone.root.getObject()}getRoot(){this.ensureClone();const e=Jr.create(this.changeID.next(),this.clone.root,this.clone.presences.get(this.changeID.getActorID())||{});return Vd(e,this.clone.root.getObject())}garbageCollect(e){return this.opts.disableGC?0:(this.clone&&this.clone.root.garbageCollect(e),this.root.garbageCollect(e))}getRootObject(){return this.root.getObject()}getGarbageLen(){return this.root.getGarbageLen()}getGarbageLenFromClone(){return this.clone.root.getGarbageLen()}toJSON(){return this.root.toJSON()}toSortedJSON(){return this.root.toSortedJSON()}getStats(){return this.root.getStats()}toJSForTest(){return{...this.getRoot().toJSForTest(),key:"root"}}applySnapshot(e,t,i){const{root:r,presences:s}=we.bytesToSnapshot(i);this.root=new mo(r),this.presences=s,this.changeID=this.changeID.setClocks(e,t),this.clone=void 0,this.publish([{type:"snapshot",source:se.Remote,value:{serverSeq:e.toString(),snapshot:this.isEnableDevtools()?we.bytesToHex(i):void 0,snapshotVector:we.versionVectorToHex(t)}}])}applyChanges(e,t){U.isEnabled(Ge.Debug)&&U.debug(`trying to apply ${e.length} remote changes.elements:${this.root.getElementMapSize()}, removeds:${this.root.getGarbageElementSetSize()}`),U.isEnabled(Ge.Trivial)&&U.trivial(e.map(i=>`${i.getID().toTestString()} ${i.toTestString()}`).join(` + */var Ct=null;try{Ct=new WebAssembly.Instance(new WebAssembly.Module(new Uint8Array([0,97,115,109,1,0,0,0,1,13,2,96,0,1,127,96,4,127,127,127,127,1,127,3,7,6,0,1,1,1,1,1,6,6,1,127,1,65,0,11,7,50,6,3,109,117,108,0,1,5,100,105,118,95,115,0,2,5,100,105,118,95,117,0,3,5,114,101,109,95,115,0,4,5,114,101,109,95,117,0,5,8,103,101,116,95,104,105,103,104,0,0,10,191,1,6,4,0,35,0,11,36,1,1,126,32,0,173,32,1,173,66,32,134,132,32,2,173,32,3,173,66,32,134,132,126,34,4,66,32,135,167,36,0,32,4,167,11,36,1,1,126,32,0,173,32,1,173,66,32,134,132,32,2,173,32,3,173,66,32,134,132,127,34,4,66,32,135,167,36,0,32,4,167,11,36,1,1,126,32,0,173,32,1,173,66,32,134,132,32,2,173,32,3,173,66,32,134,132,128,34,4,66,32,135,167,36,0,32,4,167,11,36,1,1,126,32,0,173,32,1,173,66,32,134,132,32,2,173,32,3,173,66,32,134,132,129,34,4,66,32,135,167,36,0,32,4,167,11,36,1,1,126,32,0,173,32,1,173,66,32,134,132,32,2,173,32,3,173,66,32,134,132,130,34,4,66,32,135,167,36,0,32,4,167,11])),{}).exports}catch{}function Y(n,e,t){this.low=n|0,this.high=e|0,this.unsigned=!!t}Y.prototype.__isLong__;Object.defineProperty(Y.prototype,"__isLong__",{value:!0});function je(n){return(n&&n.__isLong__)===!0}function Cd(n){var e=Math.clz32(n&-n);return n?31-e:e}Y.isLong=je;var Id={},Rd={};function Xr(n,e){var t,i,r;return e?(n>>>=0,(r=0<=n&&n<256)&&(i=Rd[n],i)?i:(t=ee(n,0,!0),r&&(Rd[n]=t),t)):(n|=0,(r=-128<=n&&n<128)&&(i=Id[n],i)?i:(t=ee(n,n<0?-1:0,!1),r&&(Id[n]=t),t))}Y.fromInt=Xr;function It(n,e){if(isNaN(n))return e?En:zt;if(e){if(n<0)return En;if(n>=eO)return nO}else{if(n<=-Dd)return tt;if(n+1>=Dd)return iO}return n<0?It(-n,e).neg():ee(n%fs|0,n/fs|0,e)}Y.fromNumber=It;function ee(n,e,t){return new Y(n,e,t)}Y.fromBits=ee;var yl=Math.pow;function Gu(n,e,t){if(n.length===0)throw Error("empty string");if(typeof e=="number"?(t=e,e=!1):e=!!e,n==="NaN"||n==="Infinity"||n==="+Infinity"||n==="-Infinity")return e?En:zt;if(t=t||10,t<2||360)throw Error("interior hyphen");if(i===0)return Gu(n.substring(1),e,t).neg();for(var r=It(yl(t,8)),s=zt,o=0;o>>0:this.low};C.toNumber=function(){return this.unsigned?(this.high>>>0)*fs+(this.low>>>0):this.high*fs+(this.low>>>0)};C.toString=function(e){if(e=e||10,e<2||36>>0,c=h.toString(e);if(o=l,o.isZero())return c+a;for(;c.length<6;)c="0"+c;a=""+c+a}};C.getHighBits=function(){return this.high};C.getHighBitsUnsigned=function(){return this.high>>>0};C.getLowBits=function(){return this.low};C.getLowBitsUnsigned=function(){return this.low>>>0};C.getNumBitsAbs=function(){if(this.isNegative())return this.eq(tt)?64:this.neg().getNumBitsAbs();for(var e=this.high!=0?this.high:this.low,t=31;t>0&&!(e&1<=0};C.isOdd=function(){return(this.low&1)===1};C.isEven=function(){return(this.low&1)===0};C.equals=function(e){return je(e)||(e=ei(e)),this.unsigned!==e.unsigned&&this.high>>>31===1&&e.high>>>31===1?!1:this.high===e.high&&this.low===e.low};C.eq=C.equals;C.notEquals=function(e){return!this.eq(e)};C.neq=C.notEquals;C.ne=C.notEquals;C.lessThan=function(e){return this.comp(e)<0};C.lt=C.lessThan;C.lessThanOrEqual=function(e){return this.comp(e)<=0};C.lte=C.lessThanOrEqual;C.le=C.lessThanOrEqual;C.greaterThan=function(e){return this.comp(e)>0};C.gt=C.greaterThan;C.greaterThanOrEqual=function(e){return this.comp(e)>=0};C.gte=C.greaterThanOrEqual;C.ge=C.greaterThanOrEqual;C.compare=function(e){if(je(e)||(e=ei(e)),this.eq(e))return 0;var t=this.isNegative(),i=e.isNegative();return t&&!i?-1:!t&&i?1:this.unsigned?e.high>>>0>this.high>>>0||e.high===this.high&&e.low>>>0>this.low>>>0?-1:1:this.sub(e).isNegative()?-1:1};C.comp=C.compare;C.negate=function(){return!this.unsigned&&this.eq(tt)?tt:this.not().add(Gr)};C.neg=C.negate;C.add=function(e){je(e)||(e=ei(e));var t=this.high>>>16,i=this.high&65535,r=this.low>>>16,s=this.low&65535,o=e.high>>>16,a=e.high&65535,l=e.low>>>16,h=e.low&65535,c=0,u=0,f=0,p=0;return p+=s+h,f+=p>>>16,p&=65535,f+=r+l,u+=f>>>16,f&=65535,u+=i+a,c+=u>>>16,u&=65535,c+=t+o,c&=65535,ee(f<<16|p,c<<16|u,this.unsigned)};C.subtract=function(e){return je(e)||(e=ei(e)),this.add(e.neg())};C.sub=C.subtract;C.multiply=function(e){if(this.isZero())return this;if(je(e)||(e=ei(e)),Ct){var t=Ct.mul(this.low,this.high,e.low,e.high);return ee(t,Ct.get_high(),this.unsigned)}if(e.isZero())return this.unsigned?En:zt;if(this.eq(tt))return e.isOdd()?tt:zt;if(e.eq(tt))return this.isOdd()?tt:zt;if(this.isNegative())return e.isNegative()?this.neg().mul(e.neg()):this.neg().mul(e).neg();if(e.isNegative())return this.mul(e.neg()).neg();if(this.lt(Nd)&&e.lt(Nd))return It(this.toNumber()*e.toNumber(),this.unsigned);var i=this.high>>>16,r=this.high&65535,s=this.low>>>16,o=this.low&65535,a=e.high>>>16,l=e.high&65535,h=e.low>>>16,c=e.low&65535,u=0,f=0,p=0,g=0;return g+=o*c,p+=g>>>16,g&=65535,p+=s*c,f+=p>>>16,p&=65535,p+=o*h,f+=p>>>16,p&=65535,f+=r*c,u+=f>>>16,f&=65535,f+=s*h,u+=f>>>16,f&=65535,f+=o*l,u+=f>>>16,f&=65535,u+=i*c+r*h+s*l+o*a,u&=65535,ee(p<<16|g,u<<16|f,this.unsigned)};C.mul=C.multiply;C.divide=function(e){if(je(e)||(e=ei(e)),e.isZero())throw Error("division by zero");if(Ct){if(!this.unsigned&&this.high===-2147483648&&e.low===-1&&e.high===-1)return this;var t=(this.unsigned?Ct.div_u:Ct.div_s)(this.low,this.high,e.low,e.high);return ee(t,Ct.get_high(),this.unsigned)}if(this.isZero())return this.unsigned?En:zt;var i,r,s;if(this.unsigned){if(e.unsigned||(e=e.toUnsigned()),e.gt(this))return En;if(e.gt(this.shru(1)))return tO;s=En}else{if(this.eq(tt)){if(e.eq(Gr)||e.eq(Mc))return tt;if(e.eq(tt))return Gr;var o=this.shr(1);return i=o.div(e).shl(1),i.eq(zt)?e.isNegative()?Gr:Mc:(r=this.sub(e.mul(i)),s=i.add(r.div(e)),s)}else if(e.eq(tt))return this.unsigned?En:zt;if(this.isNegative())return e.isNegative()?this.neg().div(e.neg()):this.neg().div(e).neg();if(e.isNegative())return this.div(e.neg()).neg();s=zt}for(r=this;r.gte(e);){i=Math.max(1,Math.floor(r.toNumber()/e.toNumber()));for(var a=Math.ceil(Math.log(i)/Math.LN2),l=a<=48?1:yl(2,a-48),h=It(i),c=h.mul(e);c.isNegative()||c.gt(r);)i-=l,h=It(i,this.unsigned),c=h.mul(e);h.isZero()&&(h=Gr),s=s.add(h),r=r.sub(c)}return s};C.div=C.divide;C.modulo=function(e){if(je(e)||(e=ei(e)),Ct){var t=(this.unsigned?Ct.rem_u:Ct.rem_s)(this.low,this.high,e.low,e.high);return ee(t,Ct.get_high(),this.unsigned)}return this.sub(this.div(e).mul(e))};C.mod=C.modulo;C.rem=C.modulo;C.not=function(){return ee(~this.low,~this.high,this.unsigned)};C.countLeadingZeros=function(){return this.high?Math.clz32(this.high):Math.clz32(this.low)+32};C.clz=C.countLeadingZeros;C.countTrailingZeros=function(){return this.low?Cd(this.low):Cd(this.high)+32};C.ctz=C.countTrailingZeros;C.and=function(e){return je(e)||(e=ei(e)),ee(this.low&e.low,this.high&e.high,this.unsigned)};C.or=function(e){return je(e)||(e=ei(e)),ee(this.low|e.low,this.high|e.high,this.unsigned)};C.xor=function(e){return je(e)||(e=ei(e)),ee(this.low^e.low,this.high^e.high,this.unsigned)};C.shiftLeft=function(e){return je(e)&&(e=e.toInt()),(e&=63)===0?this:e<32?ee(this.low<>>32-e,this.unsigned):ee(0,this.low<>>e|this.high<<32-e,this.high>>e,this.unsigned):ee(this.high>>e-32,this.high>=0?0:-1,this.unsigned)};C.shr=C.shiftRight;C.shiftRightUnsigned=function(e){return je(e)&&(e=e.toInt()),(e&=63)===0?this:e<32?ee(this.low>>>e|this.high<<32-e,this.high>>>e,this.unsigned):e===32?ee(this.high,0,this.unsigned):ee(this.high>>>e-32,0,this.unsigned)};C.shru=C.shiftRightUnsigned;C.shr_u=C.shiftRightUnsigned;C.rotateLeft=function(e){var t;return je(e)&&(e=e.toInt()),(e&=63)===0?this:e===32?ee(this.high,this.low,this.unsigned):e<32?(t=32-e,ee(this.low<>>t,this.high<>>t,this.unsigned)):(e-=32,t=32-e,ee(this.high<>>t,this.low<>>t,this.unsigned))};C.rotl=C.rotateLeft;C.rotateRight=function(e){var t;return je(e)&&(e=e.toInt()),(e&=63)===0?this:e===32?ee(this.high,this.low,this.unsigned):e<32?(t=32-e,ee(this.high<>>e,this.low<>>e,this.unsigned)):(e-=32,t=32-e,ee(this.low<>>e,this.high<>>e,this.unsigned))};C.rotr=C.rotateRight;C.toSigned=function(){return this.unsigned?ee(this.low,this.high,!1):this};C.toUnsigned=function(){return this.unsigned?this:ee(this.low,this.high,!0)};C.toBytes=function(e){return e?this.toBytesLE():this.toBytesBE()};C.toBytesLE=function(){var e=this.high,t=this.low;return[t&255,t>>>8&255,t>>>16&255,t>>>24,e&255,e>>>8&255,e>>>16&255,e>>>24]};C.toBytesBE=function(){var e=this.high,t=this.low;return[e>>>24,e>>>16&255,e>>>8&255,e&255,t>>>24,t>>>16&255,t>>>8&255,t&255]};Y.fromBytes=function(e,t,i){return i?Y.fromBytesLE(e,t):Y.fromBytesBE(e,t)};Y.fromBytesLE=function(e,t){return new Y(e[0]|e[1]<<8|e[2]<<16|e[3]<<24,e[4]|e[5]<<8|e[6]<<16|e[7]<<24,t)};Y.fromBytesBE=function(e,t){return new Y(e[4]<<24|e[5]<<16|e[6]<<8|e[7],e[0]<<24|e[1]<<16|e[2]<<8|e[3],t)};var $e=(n=>(n[n.Null=0]="Null",n[n.Boolean=1]="Boolean",n[n.Integer=2]="Integer",n[n.Long=3]="Long",n[n.Double=4]="Double",n[n.String=5]="String",n[n.Bytes=6]="Bytes",n[n.Date=7]="Date",n))($e||{});class pe extends qo{constructor(t,i){super(i);d(this,"valueType");d(this,"value");this.valueType=pe.getPrimitiveType(t),this.value=t===void 0?null:t}static of(t,i){return new pe(t,i)}static valueFromBytes(t,i){switch(t){case 0:return null;case 1:return!!i[0];case 2:return i[0]|i[1]<<8|i[2]<<16|i[3]<<24;case 4:{const r=new DataView(i.buffer);return i.forEach(function(s,o){r.setUint8(o,s)}),r.getFloat64(0,!0)}case 5:return new TextDecoder("utf-8").decode(i);case 3:return Y.fromBytesLE(Array.from(i));case 6:return i;case 7:return new Date(Y.fromBytesLE(Array.from(i),!0).toNumber());default:throw new v(w.ErrUnimplemented,`unimplemented type: ${t}`)}}toJSON(){return this.valueType===5?`"${wi(this.value)}"`:`${this.value}`}toSortedJSON(){return this.toJSON()}toJSForTest(){return{createdAt:this.getCreatedAt().toTestString(),value:this.value,type:"YORKIE_PRIMITIVE"}}deepcopy(){const t=pe.of(this.value,this.getCreatedAt());return t.setMovedAt(this.getMovedAt()),t.setRemovedAt(this.getRemovedAt()),t}getType(){return this.valueType}static getPrimitiveType(t){switch(typeof t){case"undefined":return 0;case"boolean":return 1;case"number":return this.isInteger(t)?2:4;case"string":return 5;case"object":if(t===null)return 0;if(t instanceof Y)return 3;if(t instanceof Uint8Array)return 6;if(t instanceof Date)return 7}}static isSupport(t){return pe.getPrimitiveType(t)!==void 0}static isInteger(t){return t%1===0}isNumericType(){const t=this.valueType;return t===2||t===3||t===4}getValue(){return this.value}toBytes(){switch(this.valueType){case 0:return new Uint8Array;case 1:return this.value?new Uint8Array([1]):new Uint8Array([0]);case 2:{const t=this.value;return new Uint8Array([t&255,t>>8&255,t>>16&255,t>>24&255])}case 4:{const t=this.value,i=new Uint8Array(8);return new DataView(i.buffer).setFloat64(0,t,!0),i}case 5:return new TextEncoder().encode(this.value);case 3:{const i=this.value.toBytesLE();return Uint8Array.from(i)}case 6:return this.value;case 7:{const t=this.value,i=Y.fromNumber(t.getTime(),!0).toBytesLE();return Uint8Array.from(i)}default:throw new v(w.ErrUnimplemented,`unimplemented type: ${this.valueType}`)}}}class bl extends Km{constructor(t){super(t);d(this,"prev");d(this,"next");this.value=t}static createAfter(t,i){const r=new bl(i),s=t.next;return t.next=r,r.prev=t,r.next=s,s&&(s.prev=r),r}remove(t){return this.value.remove(t)}getCreatedAt(){return this.value.getCreatedAt()}getPositionedAt(){return this.value.getPositionedAt()}release(){this.prev&&(this.prev.next=this.next),this.next&&(this.next.prev=this.prev),this.prev=void 0,this.next=void 0}getLength(){return this.value.isRemoved()?0:1}getPrev(){return this.prev}getNext(){return this.next}getValue(){return this.value}isRemoved(){return this.value.isRemoved()}}class po{constructor(){d(this,"dummyHead");d(this,"last");d(this,"nodeMapByIndex");d(this,"nodeMapByCreatedAt");const e=pe.of(0,Gt);e.setRemovedAt(Gt),this.dummyHead=new bl(e),this.last=this.dummyHead,this.nodeMapByIndex=new fo,this.nodeMapByCreatedAt=new Map,this.nodeMapByIndex.insert(this.dummyHead),this.nodeMapByCreatedAt.set(this.dummyHead.getCreatedAt().toIDString(),this.dummyHead)}static create(){return new po}get length(){return this.nodeMapByIndex.length}findNextBeforeExecutedAt(e,t){let i=this.nodeMapByCreatedAt.get(e.toIDString());if(!i)throw new v(w.ErrInvalidArgument,`cant find the given node: ${e.toIDString()}`);for(;i.getNext()&&i.getNext().getPositionedAt().after(t);)i=i.getNext();return i}release(e){this.last===e&&(this.last=e.getPrev()),e.release(),this.nodeMapByIndex.delete(e),this.nodeMapByCreatedAt.delete(e.getValue().getCreatedAt().toIDString())}insertAfter(e,t,i=t.getCreatedAt()){const r=this.findNextBeforeExecutedAt(e,i),s=bl.createAfter(r,t);r===this.last&&(this.last=s),this.nodeMapByIndex.insertAfter(r,s),this.nodeMapByCreatedAt.set(s.getCreatedAt().toIDString(),s)}moveAfter(e,t,i){const r=this.nodeMapByCreatedAt.get(e.toIDString());if(!r)throw new v(w.ErrInvalidArgument,`cant find the given node: ${e.toIDString()}`);const s=this.nodeMapByCreatedAt.get(t.toIDString());if(!s)throw new v(w.ErrInvalidArgument,`cant find the given node: ${t.toIDString()}`);r!==s&&(!s.getValue().getMovedAt()||i.after(s.getValue().getMovedAt()))&&(this.release(s),this.insertAfter(r.getCreatedAt(),s.getValue(),i),s.getValue().setMovedAt(i))}insert(e){this.insertAfter(this.last.getCreatedAt(),e)}getByID(e){return this.nodeMapByCreatedAt.get(e.toIDString())}subPathOf(e){const t=this.nodeMapByCreatedAt.get(e.toIDString());if(t)return String(this.nodeMapByIndex.indexOf(t))}purge(e){const t=this.nodeMapByCreatedAt.get(e.getCreatedAt().toIDString());if(!t)throw new v(w.ErrInvalidArgument,`fail to find the given createdAt: ${e.getCreatedAt().toIDString()}`);this.release(t)}getByIndex(e){if(e>=this.length)return;const[t,i]=this.nodeMapByIndex.find(e);let r=t;if(e===0&&t===this.dummyHead||i>0)do r&&(r=r.getNext());while(r&&r.isRemoved());return r}getPrevCreatedAt(e){let t=this.nodeMapByCreatedAt.get(e.toIDString());do t=t.getPrev();while(this.dummyHead!==t&&t.isRemoved());return t.getValue().getCreatedAt()}delete(e,t){const i=this.nodeMapByCreatedAt.get(e.toIDString()),r=i.isRemoved();return i.remove(t)&&!r&&this.nodeMapByIndex.splayNode(i),i.getValue()}deleteByIndex(e,t){const i=this.getByIndex(e);if(i)return i.remove(t)&&this.nodeMapByIndex.splayNode(i),i.getValue()}getHead(){return this.dummyHead.getValue()}getLast(){return this.last.getValue()}getLastCreatedAt(){return this.last.getCreatedAt()}toTestString(){const e=[];for(const t of this){const i=`${t.getCreatedAt().toIDString()}:${t.getValue().toJSON()}`;t.isRemoved()?e.push(`{${i}}`):e.push(`[${i}]`)}return e.join("")}*[Symbol.iterator](){let e=this.dummyHead.getNext();for(;e;)yield e,e=e.getNext()}}class pt extends rr{constructor(t,i){super(t);d(this,"elements");this.elements=i}static create(t,i){if(!i)return new pt(t,po.create());const r=po.create();for(const s of i)r.insertAfter(r.getLastCreatedAt(),s.deepcopy());return new pt(t,r)}subPathOf(t){return this.elements.subPathOf(t)}purge(t){this.elements.purge(t)}insertAfter(t,i){this.elements.insertAfter(t,i)}moveAfter(t,i,r){this.elements.moveAfter(t,i,r)}get(t){const i=this.elements.getByIndex(t);return i==null?void 0:i.getValue()}getByID(t){const i=this.elements.getByID(t);return i==null?void 0:i.getValue()}getHead(){return this.elements.getHead()}getLast(){return this.elements.getLast()}getPrevCreatedAt(t){return this.elements.getPrevCreatedAt(t)}delete(t,i){return this.elements.delete(t,i)}deleteByIndex(t,i){return this.elements.deleteByIndex(t,i)}getLastCreatedAt(){return this.elements.getLastCreatedAt()}get length(){return this.elements.length}*[Symbol.iterator](){for(const t of this.elements)t.isRemoved()||(yield t.getValue())}toTestString(){return this.elements.toTestString()}getDescendants(t){for(const i of this.elements){const r=i.getValue();if(t(r,this))return;r instanceof rr&&r.getDescendants(t)}}toJSON(){const t=[];for(const i of this)t.push(i.toJSON());return`[${t.join(",")}]`}toJS(){return JSON.parse(this.toJSON())}toJSForTest(){const t={};for(let i=0;i({...p,value:p.value?{attributes:es(p.value.getAttributes()),content:p.value.getContent()}:{attributes:void 0,content:""},type:"content"}));return[h,f,c,[l,l]]}setStyle(t,i,r,s){const[,o]=this.rgaTreeSplit.findNodeWithSplit(t[1],r),[,a]=this.rgaTreeSplit.findNodeWithSplit(t[0],r),l=[],h=this.rgaTreeSplit.findBetween(a,o),c=new Map,u=[];for(const p of h){const g=p.getCreatedAt().getActorID(),O=s!=null&&s.size?s.has(g)?s.get(g):Gt:Ys;if(p.canStyle(r,O)){const y=c.get(g),S=p.getCreatedAt();(!y||S.after(y))&&c.set(g,S),u.push(p)}}const f=[];for(const p of u){if(p.isRemoved())continue;const[g,O]=this.rgaTreeSplit.findIndexesFromRange(p.createPosRange());l.push({type:"style",actor:r.getActorID(),from:g,to:O,value:{attributes:es(i)}});for(const[y,S]of Object.entries(i)){const[k]=p.getValue().setAttr(y,S,r);k!==void 0&&f.push({parent:p.getValue(),child:k})}}return[c,f,l]}indexRangeToPosRange(t,i){const r=this.rgaTreeSplit.indexToPos(t);return t===i?[r,r]:[r,this.rgaTreeSplit.indexToPos(i)]}get length(){return this.rgaTreeSplit.length}getTreeByIndex(){return this.rgaTreeSplit.getTreeByIndex()}getTreeByID(){return this.rgaTreeSplit.getTreeByID()}toJSON(){const t=[];for(const i of this.rgaTreeSplit)i.isRemoved()||t.push(i.getValue().toJSON());return`[${t.join(",")}]`}toSortedJSON(){return this.toJSON()}toJSForTest(){return{createdAt:this.getCreatedAt().toTestString(),value:JSON.parse(this.toJSON()),type:"YORKIE_TEXT"}}toString(){return this.rgaTreeSplit.toString()}values(){const t=[];for(const i of this.rgaTreeSplit)if(!i.isRemoved()){const r=i.getValue();t.push({attributes:es(r.getAttributes()),content:r.getContent()})}return t}getRGATreeSplit(){return this.rgaTreeSplit}toTestString(){return this.rgaTreeSplit.toTestString()}deepcopy(){const t=new qt(this.rgaTreeSplit.deepcopy(),this.getCreatedAt());return t.remove(this.getRemovedAt()),t}findIndexesFromRange(t){return this.rgaTreeSplit.findIndexesFromRange(t)}getGCPairs(){const t=[];for(const i of this.rgaTreeSplit){i.getRemovedAt()&&t.push({parent:this.rgaTreeSplit,child:i});for(const r of i.getValue().getGCPairs())t.push(r)}return t}}class Vo extends Yt{constructor(t,i,r,s,o,a,l){super(t,l);d(this,"fromPos");d(this,"toPos");d(this,"maxCreatedAtMapByActor");d(this,"content");d(this,"attributes");this.fromPos=i,this.toPos=r,this.maxCreatedAtMapByActor=s,this.content=o,this.attributes=a}static create(t,i,r,s,o,a,l){return new Vo(t,i,r,s,o,a,l)}execute(t){const i=t.findByCreatedAt(this.getParentCreatedAt());if(!i)throw new v(w.ErrInvalidArgument,`fail to find ${this.getParentCreatedAt()}`);if(!(i instanceof qt))throw new v(w.ErrInvalidArgument,"fail to execute, only Text can execute edit");const r=i,[,s,o]=r.edit([this.fromPos,this.toPos],this.content,this.getExecutedAt(),Object.fromEntries(this.attributes),this.maxCreatedAtMapByActor);for(const a of o)t.registerGCPair(a);return{opInfos:s.map(({from:a,to:l,value:h})=>({type:"edit",from:a,to:l,value:h,path:t.createPath(this.getParentCreatedAt())}))}}getEffectedCreatedAt(){return this.getParentCreatedAt()}toTestString(){const t=this.getParentCreatedAt().toTestString(),i=this.fromPos.toTestString(),r=this.toPos.toTestString(),s=this.content;return`${t}.EDIT(${i},${r},${s})`}getFromPos(){return this.fromPos}getToPos(){return this.toPos}getContent(){return this.content}getAttributes(){return this.attributes||new Map}getMaxCreatedAtMapByActor(){return this.maxCreatedAtMapByActor}}class Xo extends Yt{constructor(t,i,r,s,o,a){super(t,a);d(this,"fromPos");d(this,"toPos");d(this,"maxCreatedAtMapByActor");d(this,"attributes");this.fromPos=i,this.toPos=r,this.maxCreatedAtMapByActor=s,this.attributes=o}static create(t,i,r,s,o,a){return new Xo(t,i,r,s,o,a)}execute(t){const i=t.findByCreatedAt(this.getParentCreatedAt());if(!i)throw new v(w.ErrInvalidArgument,`fail to find ${this.getParentCreatedAt()}`);if(!(i instanceof qt))throw new v(w.ErrInvalidArgument,"fail to execute, only Text can execute edit");const r=i,[,s,o]=r.setStyle([this.fromPos,this.toPos],this.attributes?Object.fromEntries(this.attributes):{},this.getExecutedAt(),this.maxCreatedAtMapByActor);for(const a of s)t.registerGCPair(a);return{opInfos:o.map(({from:a,to:l,value:h})=>({type:"style",from:a,to:l,value:h,path:t.createPath(this.getParentCreatedAt())}))}}getEffectedCreatedAt(){return this.getParentCreatedAt()}toTestString(){const t=this.getParentCreatedAt().toTestString(),i=this.fromPos.toTestString(),r=this.toPos.toTestString(),s=this.attributes;return`${t}.STYL(${i},${r},${JSON.stringify(s)})`}getFromPos(){return this.fromPos}getToPos(){return this.toPos}getAttributes(){return this.attributes}getMaxCreatedAtMapByActor(){return this.maxCreatedAtMapByActor}}const Y1=2,H1="root",Dn="text";function Es(n,e){let t=0;const i=n.children;for(let r=0;r0)throw new v(w.ErrRefused,"Text node cannot have children")}updateAncestorsSize(){let e=this.parent;const t=this.isRemoved?-1:1;for(;e&&(e.size+=this.paddedSize*t,!e.isRemoved);)e=e.parent}updateDescendantsSize(){let e=0;for(const t of this._children){const i=t.updateDescendantsSize();t.isRemoved||(e+=i)}return this.size+=e,this.paddedSize}get isText(){return this.type===Dn}get paddedSize(){return this.size+(this.isText?0:Y1)}isAncestorOf(e){return ew(this,e)}get nextSibling(){const e=this.parent.findOffset(this),t=this.parent.children[e+1];if(t)return t}get prevSibling(){const e=this.parent.findOffset(this),t=this.parent.children[e-1];if(t)return t}splitText(e,t){if(e===0||e===this.size)return;const i=this.value.slice(0,e),r=this.value.slice(e);if(!r.length)return;this.value=i;const s=this.cloneText(e+t);return s.value=r,this.parent.insertAfterInternal(s,this),s}get children(){return this._children.filter(e=>!e.isRemoved)}get allChildren(){return[...this._children]}hasTextChild(){return this.children.length>0&&this.children.every(e=>e.isText)}append(...e){if(this.isText)throw new v(w.ErrRefused,"Text node cannot have children");this._children.push(...e);for(const t of e)t.parent=this,t.updateAncestorsSize()}prepend(...e){if(this.isText)throw new v(w.ErrRefused,"Text node cannot have children");this._children.unshift(...e);for(const t of e)t.parent=this}insertBefore(e,t){if(this.isText)throw new v(w.ErrRefused,"Text node cannot have children");const i=this._children.indexOf(t);if(i===-1)throw new v(w.ErrInvalidArgument,"child not found");this.insertAtInternal(e,i),e.updateAncestorsSize()}insertAfter(e,t){if(this.isText)throw new v(w.ErrRefused,"Text node cannot have children");const i=this._children.indexOf(t);if(i===-1)throw new v(w.ErrInvalidArgument,"child not found");this.insertAtInternal(e,i+1),e.updateAncestorsSize()}insertAt(e,t){if(this.isText)throw new v(w.ErrRefused,"Text node cannot have children");this.insertAtInternal(e,t),e.updateAncestorsSize()}removeChild(e){if(this.isText)throw new v(w.ErrRefused,"Text node cannot have children");const t=this._children.indexOf(e);if(t===-1)throw new v(w.ErrInvalidArgument,"child not found");this._children.splice(t,1),e.parent=void 0}splitElement(e,t){const i=this.cloneElement(t);this.parent.insertAfterInternal(i,this),i.updateAncestorsSize();const r=this.children.slice(0,e),s=this.children.slice(e);this._children=r,i._children=s,this.size=this._children.reduce((o,a)=>o+a.paddedSize,0),i.size=i._children.reduce((o,a)=>o+a.paddedSize,0);for(const o of i._children)o.parent=i;return i}insertAfterInternal(e,t){if(this.isText)throw new v(w.ErrRefused,"Text node cannot have children");const i=this._children.indexOf(t);if(i===-1)throw new v(w.ErrInvalidArgument,"child not found");this.insertAtInternal(e,i+1)}insertAtInternal(e,t){if(this.isText)throw new v(w.ErrRefused,"Text node cannot have children");this._children.splice(t,0,e),e.parent=this}findOffset(e){if(this.isText)throw new v(w.ErrRefused,"Text node cannot have children");if(e.isRemoved){const t=this._children.indexOf(e);return this.allChildren.splice(0,t).filter(r=>!r.isRemoved).length}return this.children.indexOf(e)}findBranchOffset(e){if(this.isText)throw new v(w.ErrRefused,"Text node cannot have children");let t=e;for(;t;){const i=this._children.indexOf(t);if(i!==-1)return i;t=t.parent}return-1}}function ew(n,e){if(n===e)return!1;for(;e.parent;){if(e.parent===n)return!0;e=e.parent}return!1}var xe=(n=>(n.Start="Start",n.End="End",n.Text="Text",n))(xe||{});function rO(n,e,t,i){if(e>t)throw new v(w.ErrInvalidArgument,`from is greater than to: ${e} > ${t}`);if(e>n.size)throw new v(w.ErrInvalidArgument,`from is out of range: ${e} > ${n.size}`);if(t>n.size)throw new v(w.ErrInvalidArgument,`to is out of range: ${t} > ${n.size}`);if(e===t)return;let r=0;for(const s of n.children){if(e-s.paddedSizes.size;(s.isText||l)&&i([s,s.isText?"Text":"Start"],h),rO(s,Math.max(0,o),Math.min(a,s.size),i),h&&i([s,"End"],h)}r+=s.paddedSize}}function sO(n,e,t=0){for(const i of n.children)sO(i,e,t+1);e(n,t)}function th(n,e,t=0){for(const i of n._children)th(i,e,t+1);e(n,t)}function Vc(n,e,t=!0){if(e>n.size)throw new v(w.ErrInvalidArgument,`index is out of range: ${e} > ${n.size}`);if(n.isText)return{node:n,offset:e};let i=0,r=0;for(const s of n.children){if(t&&s.isText&&s.size>=e-r)return Vc(s,e-r,t);if(e===r)return{node:n,offset:i};if(!t&&s.paddedSize===e-r)return{node:n,offset:i+1};if(s.paddedSize>e-r)return Vc(s,e-r-1,t);r+=s.paddedSize,i+=1}return{node:n,offset:i}}function oO(n){return n.isText||n.children.length===0?n:oO(n.children[0])}function tw(n,e){if(n.sizen===e?0:n0)if(t.right)t.right.parent=t,t=t.right;else return t;else if(i<0)if(t.left)t.left.parent=t,t=t.left;else{let r=t.parent,s=t;for(;r&&s===r.left;)s=r,r=r.parent;return r}else return t}}lastEntry(){if(!this.root)return this.root;let e=this.root;for(;e.right;)e=e.right;return e}size(){return this.counter}isEmpty(){return this.counter===0}getInternal(e,t){for(;t;){const i=this.comparator(e,t.key);if(i===0)return t;i<0?t=t.left:i>0&&(t=t.right)}}putInternal(e,t,i){if(!i)return this.counter+=1,new rw(e,t,!0);const r=this.comparator(e,i.key);return r<0?i.left=this.putInternal(e,t,i.left):r>0?i.right=this.putInternal(e,t,i.right):i.value=t,this.isRed(i.right)&&!this.isRed(i.left)&&(i=this.rotateLeft(i)),this.isRed(i.left)&&this.isRed(i.left.left)&&(i=this.rotateRight(i)),this.isRed(i.left)&&this.isRed(i.right)&&this.flipColors(i),i}removeInternal(e,t){if(this.comparator(t,e.key)<0)!this.isRed(e.left)&&!this.isRed(e.left.left)&&(e=this.moveRedLeft(e)),e.left=this.removeInternal(e.left,t);else{if(this.isRed(e.left)&&(e=this.rotateRight(e)),this.comparator(t,e.key)===0&&!e.right){this.counter-=1;return}if(!this.isRed(e.right)&&!this.isRed(e.right.left)&&(e=this.moveRedRight(e)),this.comparator(t,e.key)===0){this.counter-=1;const i=this.min(e.right);e.value=i.value,e.key=i.key,e.right=this.removeMin(e.right)}else e.right=this.removeInternal(e.right,t)}return this.fixUp(e)}min(e){return e.left?this.min(e.left):e}removeMin(e){if(e.left)return!this.isRed(e.left)&&!this.isRed(e.left.left)&&(e=this.moveRedLeft(e)),e.left=this.removeMin(e.left),this.fixUp(e)}fixUp(e){return this.isRed(e.right)&&(e=this.rotateLeft(e)),this.isRed(e.left)&&this.isRed(e.left.left)&&(e=this.rotateRight(e)),this.isRed(e.left)&&this.isRed(e.right)&&this.flipColors(e),e}moveRedLeft(e){return this.flipColors(e),this.isRed(e.right.left)&&(e.right=this.rotateRight(e.right),e=this.rotateLeft(e),this.flipColors(e)),e}moveRedRight(e){return this.flipColors(e),this.isRed(e.left.left)&&(e=this.rotateRight(e),this.flipColors(e)),e}isRed(e){return e&&e.isRed}rotateLeft(e){const t=e.right;return e.right=t.left,t.left=e,t.isRed=t.left.isRed,t.left.isRed=!0,t}rotateRight(e){const t=e.left;return e.left=t.right,t.right=e,t.isRed=t.right.isRed,t.right.isRed=!0,t}flipColors(e){e.isRed=!e.isRed,e.left.isRed=!e.left.isRed,e.right.isRed=!e.right.isRed}}class _t{constructor(e,t){d(this,"parentID");d(this,"leftSiblingID");this.parentID=e,this.leftSiblingID=t}static of(e,t){return new _t(e,t)}static fromTreePos(e){const{offset:t}=e;let{node:i}=e,r;return i.isText?(i.parent.children[0]===i&&t===0?r=i.parent:r=i,i=i.parent):t===0?r=i:r=i.children[t-1],_t.of(i.id,Me.of(r.getCreatedAt(),r.getOffset()+t))}getParentID(){return this.parentID}static fromStruct(e){return _t.of(Me.of(dt.fromStruct(e.parentID.createdAt),e.parentID.offset),Me.of(dt.fromStruct(e.leftSiblingID.createdAt),e.leftSiblingID.offset))}toStruct(){return{parentID:{createdAt:this.getParentID().getCreatedAt().toStruct(),offset:this.getParentID().getOffset()},leftSiblingID:{createdAt:this.getLeftSiblingID().getCreatedAt().toStruct(),offset:this.getLeftSiblingID().getOffset()}}}toTreeNodePair(e){const t=this.getParentID(),i=this.getLeftSiblingID(),r=e.findFloorNode(t);let s=e.findFloorNode(i);if(!r||!s)throw new v(w.ErrRefused,`cannot find node of CRDTTreePos(${t.toTestString()}, ${i.toTestString()})`);return!i.equals(t)&&i.getOffset()>0&&i.getOffset()===s.id.getOffset()&&s.insPrevID&&(s=e.findFloorNode(s.insPrevID)),[r,s]}getLeftSiblingID(){return this.leftSiblingID}equals(e){return this.getParentID().getCreatedAt().equals(e.getParentID().getCreatedAt())&&this.getParentID().getOffset()===e.getParentID().getOffset()&&this.getLeftSiblingID().getCreatedAt().equals(e.getLeftSiblingID().getCreatedAt())&&this.getLeftSiblingID().getOffset()===e.getLeftSiblingID().getOffset()}}class Me{constructor(e,t){d(this,"createdAt");d(this,"offset");this.createdAt=e,this.offset=t}static of(e,t){return new Me(e,t)}static fromStruct(e){return Me.of(dt.fromStruct(e.createdAt),e.offset)}static createComparator(){return(e,t)=>{const i=e.getCreatedAt().compare(t.getCreatedAt());return i!==0?i:e.getOffset()>t.getOffset()?1:e.getOffset(){const s=r.deepcopy();return s.parent=t,s}),t.insPrevID=this.insPrevID,t.insNextID=this.insNextID,t}get value(){if(!this.isText)throw new v(w.ErrInvalidType,`cannot get value of element node: ${this.type}`);return this._value}set value(t){if(!this.isText)throw new v(w.ErrInvalidType,`cannot set value of element node: ${this.type}`);this._value=t,this.size=t.length}get isRemoved(){return!!this.removedAt}remove(t){const i=!this.removedAt;(!this.removedAt||this.removedAt.compare(t)>0)&&(this.removedAt=t),i&&this.updateAncestorsSize()}cloneText(t){return new ut(Me.of(this.id.getCreatedAt(),t),this.type,void 0,void 0,this.removedAt)}cloneElement(t){return new ut(Me.of(t(),0),this.type,void 0,void 0,this.removedAt)}split(t,i,r){const s=this.isText?this.splitText(i,this.id.getOffset()):this.splitElement(i,r);if(s){if(s.insPrevID=this.id,this.insNextID){const o=t.findFloorNode(this.insNextID);o.insPrevID=s.id,s.insNextID=this.insNextID}this.insNextID=s.id,t.registerNode(s)}return s}getCreatedAt(){return this.id.getCreatedAt()}getOffset(){return this.id.getOffset()}canDelete(t,i){return!this.getCreatedAt().after(i)&&(!this.removedAt||t.after(this.removedAt))}canStyle(t,i){return this.isText?!1:!this.getCreatedAt().after(i)&&(!this.removedAt||t.after(this.removedAt))}setAttrs(t,i){this.attrs||(this.attrs=new Vn);const r=new Array;for(const[s,o]of Object.entries(t))r.push(this.attrs.set(s,o,i));return r}purge(t){this.attrs&&this.attrs.purge(t)}getGCPairs(){const t=[];if(!this.attrs)return t;for(const i of this.attrs)i.getRemovedAt()&&t.push({parent:this,child:i});return t}}function Xc(n){var t;if(n.isText){const i=n;return{type:i.type,value:i.value}}const e={type:n.type,children:n.children.map(Xc)};return n.attrs&&(e.attributes=es((t=n.attrs)==null?void 0:t.toObject())),e}function Ju(n){if(n.isText)return n.value;let e="";return n.attrs&&n.attrs.size()&&(e=" "+Array.from(n.attrs).filter(t=>!t.isRemoved()).sort((t,i)=>t.getKey().localeCompare(i.getKey())).map(t=>{const i=JSON.parse(t.getValue());return typeof i=="string"?`${t.getKey()}="${i}"`:`${t.getKey()}="${wi(t.getValue())}"`}).join(" ")),`<${n.type}${e}>${n.children.map(t=>Ju(t)).join("")}`}function lO(n){if(n.isText){const e=n;return{type:e.type,value:e.value,size:e.size,isRemoved:e.isRemoved}}return{type:n.type,children:n.children.map(lO),size:n.size,isRemoved:n.isRemoved}}class Mt extends qo{constructor(t,i){super(i);d(this,"indexTree");d(this,"nodeMapByID");this.indexTree=new iw(t),this.nodeMapByID=new aO(Me.createComparator()),this.indexTree.traverseAll(r=>{this.nodeMapByID.put(r.id,r)})}static create(t,i){return new Mt(t,i)}findFloorNode(t){const i=this.nodeMapByID.floorEntry(t);if(!(!i||!i.key.getCreatedAt().equals(t.getCreatedAt())))return i.value}registerNode(t){this.nodeMapByID.put(t.id,t)}findNodesAndSplitText(t,i){const[r,s]=t.toTreeNodePair(this);let o=s;const a=r===o,l=o.parent&&!a?o.parent:r;if(o.isText&&o.split(this,t.getLeftSiblingID().getOffset()-o.id.getOffset()),i){const h=l.allChildren,c=a?0:h.indexOf(o)+1;for(let u=c;u{const O=g.getCreatedAt().getActorID(),y=s?s.has(O)?s.get(O):Gt:Ys;if(g.canStyle(r,y)&&i){const S=f.get(O),k=g.getCreatedAt();(!S||k.after(S))&&f.set(O,k);const $=g.setAttrs(i,r),x=$.reduce((R,[,j])=>(j&&(R[j.getKey()]=u[j.getKey()]),R),{}),Q=g.parent,A=g.prevSibling||g.parent;Object.keys(x).length>0&&c.push({type:"style",from:this.toIndex(Q,A),to:this.toIndex(g,g),fromPath:this.toPath(Q,A),toPath:this.toPath(g,g),actor:r.getActorID(),value:x});for(const[R]of $)R&&p.push({parent:g,child:R})}}),[f,p,c]}removeStyle(t,i,r,s){const[o,a]=this.findNodesAndSplitText(t[0],r),[l,h]=this.findNodesAndSplitText(t[1],r),c=[],u=new Map,f=[];return this.traverseInPosRange(o,a,l,h,([p])=>{const g=p.getCreatedAt().getActorID(),O=s?s.has(g)?s.get(g):Gt:Ys;if(p.canStyle(r,O)&&i){const y=u.get(g),S=p.getCreatedAt();(!y||S.after(y))&&u.set(g,S),p.attrs||(p.attrs=new Vn);for(const x of i){const Q=p.attrs.remove(x,r);for(const A of Q)f.push({parent:p,child:A})}const k=p.parent,$=p.prevSibling||p.parent;c.push({actor:r.getActorID(),type:"removeStyle",from:this.toIndex(k,$),to:this.toIndex(p,p),fromPath:this.toPath(k,$),toPath:this.toPath(p,p),value:i})}}),[u,f,c]}edit(t,i,r,s,o,a){const[l,h]=this.findNodesAndSplitText(t[0],s),[c,u]=this.findNodesAndSplitText(t[1],s),f=this.toIndex(l,h),p=this.toPath(l,h),g=[],O=[],y=[],S=new Map;this.traverseInPosRange(l,h,c,u,([x,Q],A)=>{if(Q===xe.Start&&!A)for(const W of x.children)y.push(W);const R=x.getCreatedAt().getActorID(),j=a?a.has(R)?a.get(R):Gt:Ys;if(x.canDelete(s,j)||g.includes(x.parent)){const W=S.get(R),G=x.getCreatedAt();(!W||G.after(W))&&S.set(R,G),(Q===xe.Text||Q===xe.Start)&&g.push(x),O.push([x,Q])}});const k=this.makeDeletionChanges(O,s),$=[];for(const x of g)x.remove(s),x.isRemoved&&$.push({parent:this,child:x});for(const x of y)x.removedAt||l.append(x);if(r>0){let x=0,Q=l,A=h;for(;x{l.isRemoved&&(R.remove(s),$.push({parent:this,child:R})),this.nodeMapByID.put(R.id,R)}),A.isRemoved||x.push(A);if(x.length){const A=x.map(R=>Xc(R));k.length&&k[k.length-1].from===f?k[k.length-1].value=A:k.push({type:"content",from:f,to:f,fromPath:p,toPath:p,actor:s.getActorID(),value:A})}}return[k,$,S]}editT(t,i,r,s,o){const a=this.findPos(t[0]),l=this.findPos(t[1]);this.edit([a,l],i,r,s,o)}move(t,i,r){throw new v(w.ErrUnimplemented,`not implemented: ${t}, ${i}, ${r}`)}purge(t){var s;(s=t.parent)==null||s.removeChild(t),this.nodeMapByID.remove(t.id);const i=t.insPrevID,r=t.insNextID;if(i){const o=this.findFloorNode(i);o.insNextID=r}if(r){const o=this.findFloorNode(r);o.insPrevID=i}t.insPrevID=void 0,t.insNextID=void 0}getGCPairs(){const t=[];return this.indexTree.traverse(i=>{i.getRemovedAt()&&t.push({parent:this,child:i});for(const r of i.getGCPairs())t.push(r)}),t}findPos(t,i=!0){const r=this.indexTree.findTreePos(t,i);return _t.fromTreePos(r)}pathToPosRange(t){const i=this.pathToIndex(t);return[this.findPos(i),this.findPos(i+1)]}pathToPos(t){const i=this.indexTree.pathToIndex(t);return this.findPos(i)}getRoot(){return this.indexTree.getRoot()}getSize(){return this.indexTree.size}getNodeSize(){return this.nodeMapByID.size()}getIndexTree(){return this.indexTree}toXML(){return Ju(this.indexTree.getRoot())}toJSON(){return JSON.stringify(this.getRootTreeNode())}toJSForTest(){return{createdAt:this.getCreatedAt().toTestString(),value:JSON.parse(this.toJSON()),type:"YORKIE_TREE"}}toJSInfoForTest(){const t=this.indexTree.getRoot(),i=(r,s=void 0,o=void 0,a=0)=>{var p,g,O,y;let l,h,c;const u=r.isText?{node:r,offset:0}:s&&o?this.toTreePos(s,o):null;u&&(l=this.indexTree.indexOf(u),h=this.indexTree.treePosToPath(u),c=_t.fromTreePos(u).toStruct());const f={type:r.type,parent:s==null?void 0:s.id.toTestString(),size:r.size,id:r.id.toTestString(),removedAt:(p=r.removedAt)==null?void 0:p.toTestString(),insPrev:(g=r.insPrevID)==null?void 0:g.toTestString(),insNext:(O=r.insNextID)==null?void 0:O.toTestString(),value:r.isText?r.value:void 0,isRemoved:r.isRemoved,children:[],depth:a,attributes:r.attrs?es((y=r.attrs)==null?void 0:y.toObject()):void 0,index:l,path:h,pos:c};for(let S=0;S0&&S===r[r.length-1].to?(r[r.length-1].to=k,r[r.length-1].toPath=this.toPath(y,p)):r.push({type:"content",from:S,to:k,fromPath:this.toPath(O,u),toPath:this.toPath(y,p),actor:i.getActorID()}))}return r.reverse()}findRightToken([t,i]){if(i===xe.Start){const l=t.allChildren;return l.length>0?[l[0],l[0].isText?xe.Text:xe.Start]:[t,xe.End]}const r=t.parent,s=r.allChildren,o=s.indexOf(t);if(r&&o===s.length-1)return[r,xe.End];const a=s[o+1];return[a,a.isText?xe.Text:xe.Start]}findLeftToken([t,i]){if(i===xe.End){const l=t.allChildren;if(l.length>0){const h=l[l.length-1];return[h,h.isText?xe.Text:xe.End]}return[t,xe.Start]}const r=t.parent,s=r.allChildren,o=s.indexOf(t);if(r&&o===0)return[r,xe.Start];const a=s[o-1];return[a,a.isText?xe.Text:xe.End]}}class Lo extends Yt{constructor(t,i,r,s,o,a,l){super(t,l);d(this,"fromPos");d(this,"toPos");d(this,"contents");d(this,"splitLevel");d(this,"maxCreatedAtMapByActor");this.fromPos=i,this.toPos=r,this.contents=s,this.splitLevel=o,this.maxCreatedAtMapByActor=a}static create(t,i,r,s,o,a,l){return new Lo(t,i,r,s,o,a,l)}execute(t){var l;const i=t.findByCreatedAt(this.getParentCreatedAt());if(!i)throw new v(w.ErrInvalidArgument,`fail to find ${this.getParentCreatedAt()}`);if(!(i instanceof Mt))throw new v(w.ErrInvalidArgument,"fail to execute, only Tree can execute edit");const r=this.getExecutedAt(),s=i,[o,a]=s.edit([this.fromPos,this.toPos],(l=this.contents)==null?void 0:l.map(h=>h.deepcopy()),this.splitLevel,r,(()=>{let h=r.getDelimiter();return this.contents!==void 0&&(h+=this.contents.length),()=>dt.of(r.getLamport(),++h,r.getActorID())})(),this.maxCreatedAtMapByActor);for(const h of a)t.registerGCPair(h);return{opInfos:o.map(({from:h,to:c,value:u,splitLevel:f,fromPath:p,toPath:g})=>({type:"tree-edit",path:t.createPath(this.getParentCreatedAt()),from:h,to:c,value:u,splitLevel:f,fromPath:p,toPath:g}))}}getEffectedCreatedAt(){return this.getParentCreatedAt()}toTestString(){const t=this.getParentCreatedAt().toTestString(),i=`${this.fromPos.getLeftSiblingID().getCreatedAt().toTestString()}/${this.fromPos.getLeftSiblingID().getOffset()}`,r=`${this.toPos.getLeftSiblingID().getCreatedAt().toTestString()}/${this.toPos.getLeftSiblingID().getOffset()}`,s=this.contents||[];return`${t}.EDIT(${i},${r},${s.map(o=>Ju(o)).join("")})`}getFromPos(){return this.fromPos}getToPos(){return this.toPos}getContents(){return this.contents}getSplitLevel(){return this.splitLevel}getMaxCreatedAtMapByActor(){return this.maxCreatedAtMapByActor}}class ts{constructor(e){d(this,"vector");this.vector=e||new Map}set(e,t){this.vector.set(e,t)}get(e){return this.vector.get(e)}maxLamport(){let e=BigInt(0);for(const[,t]of this)t>e&&(e=t);return e}max(e){const t=new Map;for(const[i,r]of e){const s=this.vector.get(i),o=s&&s>r?s:r;t.set(i,o)}for(const[i,r]of this){const s=e.get(i),o=s&&s>r?s:r;t.set(i,o)}return new ts(t)}afterOrEqual(e){const t=this.vector.get(e.getActorID());return t===void 0?!1:t>=e.getLamport()}deepcopy(){const e=new Map;for(const[t,i]of this.vector)e.set(t,i);return new ts(e)}filter(e){const t=new Map;for(const[i]of e){const r=this.vector.get(i);r!==void 0&&t.set(i,r)}return new ts(t)}size(){return this.vector.size}*[Symbol.iterator](){for(const[e,t]of this.vector)yield[e,t]}}const ow=new ts(new Map);class An{constructor(e,t,i,r,s){d(this,"clientSeq");d(this,"serverSeq");d(this,"lamport");d(this,"actor");d(this,"versionVector");this.clientSeq=e,this.serverSeq=s,this.lamport=t,this.versionVector=r,this.actor=i}static of(e,t,i,r,s){return new An(e,t,i,r,s)}next(){const e=this.versionVector.deepcopy();return e.set(this.actor,this.lamport+1n),new An(this.clientSeq+1,this.lamport+1n,this.actor,e)}syncClocks(e){const t=e.lamport>this.lamport?e.lamport+1n:this.lamport+1n,i=this.versionVector.max(e.versionVector),r=new An(this.clientSeq,t,this.actor,i);return r.versionVector.set(this.actor,t),r}setClocks(e,t){const i=e>this.lamport?e:this.lamport+1n,r=this.versionVector.max(t);return r.set(this.actor,i),An.of(this.clientSeq,i,this.actor,r)}createTimeTicket(e){return dt.of(this.lamport,e,this.actor)}setActor(e){return new An(this.clientSeq,this.lamport,e,this.versionVector,this.serverSeq)}setVersionVector(e){return new An(this.clientSeq,this.lamport,this.actor,e,this.serverSeq)}getClientSeq(){return this.clientSeq}getServerSeq(){return this.serverSeq?this.serverSeq.toString():""}getLamport(){return this.lamport}getLamportAsString(){return this.lamport.toString()}getActorID(){return this.actor}getVersionVector(){return this.versionVector}toTestString(){return`${this.lamport.toString()}:${this.actor.slice(-2)}:${this.clientSeq}`}}const aw=new An(0,0n,zu,ow);class ds{constructor({id:e,operations:t,presenceChange:i,message:r}){d(this,"id");d(this,"operations");d(this,"presenceChange");d(this,"message");this.id=e,this.operations=t||[],this.presenceChange=i,this.message=r}static create({id:e,operations:t,presenceChange:i,message:r}){return new ds({id:e,operations:t,presenceChange:i,message:r})}getID(){return this.id}getMessage(){return this.message}hasOperations(){return this.operations.length>0}getOperations(){return this.operations}setActor(e){for(const t of this.operations)t.setActor(e);this.id=this.id.setActor(e)}hasPresenceChange(){return this.presenceChange!==void 0}getPresenceChange(){return this.presenceChange}execute(e,t,i){const r=[],s=[];for(const o of this.operations){const a=o.execute(e,i);if(!a)continue;const{opInfos:l,reverseOp:h}=a;r.push(...l),h&&s.unshift(h)}return this.presenceChange&&(this.presenceChange.type===cr.Put?t.set(this.id.getActorID(),Wt(this.presenceChange.presence)):t.delete(this.id.getActorID())),{opInfos:r,reverseOps:s}}toTestString(){return`${this.operations.map(e=>e.toTestString()).join(",")}`}toStruct(){return{changeID:we.bytesToHex(we.toChangeID(this.getID()).toBinary()),message:this.getMessage(),operations:this.getOperations().map(e=>we.bytesToHex(we.toOperation(e).toBinary())),presenceChange:this.getPresenceChange()}}static fromStruct(e){const{changeID:t,operations:i,presenceChange:r,message:s}=e;return ds.create({id:we.bytesToChangeID(we.hexToBytes(t)),operations:i==null?void 0:i.map(o=>we.bytesToOperation(we.hexToBytes(o))),presenceChange:r,message:s})}}class ih{constructor(e,t,i,r,s,o,a){d(this,"documentKey");d(this,"checkpoint");d(this,"isRemoved");d(this,"changes");d(this,"snapshot");d(this,"minSyncedTicket");d(this,"versionVector");this.documentKey=e,this.checkpoint=t,this.isRemoved=i,this.changes=r,this.snapshot=o,this.minSyncedTicket=a,this.versionVector=s}static create(e,t,i,r,s,o,a){return new ih(e,t,i,r,s,o,a)}getDocumentKey(){return this.documentKey}getCheckpoint(){return this.checkpoint}getIsRemoved(){return this.isRemoved}getChanges(){return this.changes}hasChanges(){return this.changes.length>0}getChangeSize(){return this.changes.length}hasSnapshot(){return!!this.snapshot&&!!this.snapshot.length}getSnapshot(){return this.snapshot}getMinSyncedTicket(){return this.minSyncedTicket}getVersionVector(){return this.versionVector}}class is{constructor(e,t){d(this,"serverSeq");d(this,"clientSeq");this.serverSeq=e,this.clientSeq=t}static of(e,t){return new is(e,t)}increaseClientSeq(e){return e===0?this:new is(this.serverSeq,this.clientSeq+e)}forward(e){if(this.equals(e))return this;const t=this.serverSeq>e.serverSeq?this.serverSeq:e.serverSeq,i=Math.max(this.clientSeq,e.clientSeq);return is.of(t,i)}getServerSeqAsString(){return this.serverSeq.toString()}getClientSeq(){return this.clientSeq}getServerSeq(){return this.serverSeq}equals(e){return this.clientSeq===e.clientSeq&&this.serverSeq==e.serverSeq}toTestString(){return`serverSeq=${this.serverSeq}, clientSeq=${this.clientSeq}`}}const lw=new is(0n,0);class Ti{constructor(e,t){d(this,"createdAt");d(this,"offset");this.createdAt=e,this.offset=t}static of(e,t){return new Ti(e,t)}static fromStruct(e){return Ti.of(dt.fromStruct(e.createdAt),e.offset)}getCreatedAt(){return this.createdAt}getOffset(){return this.offset}equals(e){return this.createdAt.compare(e.createdAt)===0&&this.offset===e.offset}hasSameCreatedAt(e){return this.createdAt.compare(e.createdAt)===0}split(e){return new Ti(this.createdAt,this.offset+e)}toStruct(){return{createdAt:this.createdAt.toStruct(),offset:this.offset}}toTestString(){return`${this.createdAt.toTestString()}:${this.offset}`}toIDString(){return`${this.createdAt.toIDString()}:${this.offset}`}}const hw=Ti.of(Gt,0);class Jt{constructor(e,t){d(this,"id");d(this,"relativeOffset");this.id=e,this.relativeOffset=t}static of(e,t){return new Jt(e,t)}static fromStruct(e){const t=Ti.fromStruct(e.id);return Jt.of(t,e.relativeOffset)}getID(){return this.id}getRelativeOffset(){return this.relativeOffset}getAbsoluteID(){return Ti.of(this.id.getCreatedAt(),this.id.getOffset()+this.relativeOffset)}toTestString(){return`${this.id.toTestString()}:${this.relativeOffset}`}toStruct(){return{id:this.id.toStruct(),relativeOffset:this.relativeOffset}}equals(e){return this.id.equals(e.id)?this.relativeOffset===e.relativeOffset:!1}}class sr extends Km{constructor(t,i,r){super(i);d(this,"id");d(this,"removedAt");d(this,"prev");d(this,"next");d(this,"insPrev");d(this,"insNext");this.id=t,this.removedAt=r}static create(t,i){return new sr(t,i)}static createComparator(){return(t,i)=>{const r=t.getCreatedAt().compare(i.getCreatedAt());return r!==0?r:t.getOffset()>i.getOffset()?1:t.getOffset()0&&t.getID().getOffset()==e.getOffset()){if(!t.hasInsPrev())return t;t=t.getInsPrev()}return t}findFloorNode(e){const t=this.treeByID.floorEntry(e);if(t&&!(!t.key.equals(e)&&!t.key.hasSameCreatedAt(e)))return t.value}findBetween(e,t){const i=[];let r=e;for(;r&&r!==t;)i.push(r),r=r.getNext();return i}splitNode(e,t){if(t>e.getContentLength())throw new v(w.ErrInvalidArgument,"offset should be less than or equal to length");if(t===0)return e;if(t===e.getContentLength())return e.getNext();const i=e.split(t);this.treeByIndex.updateWeight(i),this.insertAfter(e,i);const r=e.getInsNext();return r&&r.setInsPrev(i),i.setInsPrev(e),i}deleteNodes(e,t,i){if(!e.length)return[[],new Map,new Map];const[r,s]=this.filterNodes(e,t,i),o=new Map,a=new Map,l=this.makeChanges(s,t);for(const h of r){const c=h.getCreatedAt().getActorID();(!o.has(c)||h.getID().getCreatedAt().after(o.get(c)))&&o.set(c,h.getID().getCreatedAt()),a.set(h.getID().toIDString(),h),h.remove(t)}return this.deleteIndexNodes(s),[l,o,a]}filterNodes(e,t,i){const r=!!i,s=[],o=[],[a,l]=this.findEdgesOfCandidates(e);o.push(a);for(const h of e){const c=h.getCreatedAt().getActorID(),u=r?i.has(c)?i.get(c):Gt:Ys;h.canDelete(t,u)?s.push(h):o.push(h)}return o.push(l),[s,o]}findEdgesOfCandidates(e){return[e[0].getPrev(),e[e.length-1].getNext()]}makeChanges(e,t){const i=[];let r,s;for(let o=0;on<0?Math.ceil(n):Math.floor(n);var Pi=(n=>(n[n.IntegerCnt=0]="IntegerCnt",n[n.LongCnt=1]="LongCnt",n))(Pi||{});class gt extends qo{constructor(t,i,r){super(r);d(this,"valueType");d(this,"value");switch(this.valueType=t,t){case 0:typeof i=="number"?i>Math.pow(2,31)-1||i<-Math.pow(2,31)?this.value=Y.fromNumber(i).toInt():this.value=Bd(i):this.value=i.toInt();break;case 1:typeof i=="number"?this.value=Y.fromNumber(i):this.value=i;break;default:throw new v(w.ErrUnimplemented,`unimplemented type: ${t}`)}}static create(t,i,r){return new gt(t,i,r)}static valueFromBytes(t,i){switch(t){case 0:return i[0]|i[1]<<8|i[2]<<16|i[3]<<24;case 1:return Y.fromBytesLE(Array.from(i));default:throw new v(w.ErrUnimplemented,`unimplemented type: ${t}`)}}toJSON(){return`${this.value}`}toSortedJSON(){return this.toJSON()}toJSForTest(){return{createdAt:this.getCreatedAt().toTestString(),value:this.value,type:"YORKIE_COUNTER"}}deepcopy(){const t=gt.create(this.valueType,this.value,this.getCreatedAt());return t.setMovedAt(this.getMovedAt()),t}getType(){return this.valueType}static getCounterType(t){switch(typeof t){case"object":return t instanceof Y?1:void 0;case"number":return t>Math.pow(2,31)-1||t<-Math.pow(2,31)?1:0;default:return}}static isSupport(t){return!!gt.getCounterType(t)}static isInteger(t){return t%1===0}isNumericType(){const t=this.valueType;return t===0||t===1}getValueType(){return this.valueType}getValue(){return this.value}toBytes(){switch(this.valueType){case 0:{const t=this.value;return new Uint8Array([t&255,t>>8&255,t>>16&255,t>>24&255])}case 1:{const i=this.value.toBytesLE();return Uint8Array.from(i)}default:throw new v(w.ErrUnimplemented,`unimplemented type: ${this.valueType}`)}}increase(t){function i(r){if(!r.isNumericType())throw new TypeError(`Unsupported type of value: ${typeof r.getValue()}`)}return i(this),i(t),this.valueType===1?this.value=this.value.add(t.getValue()):t.getType()===$e.Long?this.value=this.value+t.getValue().toInt():this.value=Y.fromNumber(this.value+Bd(t.getValue())).toInt(),this}}class gs extends Yt{constructor(t,i,r){super(t,r);d(this,"value");this.value=i}static create(t,i,r){return new gs(t,i,r)}execute(t){const i=t.findByCreatedAt(this.getParentCreatedAt());if(!i)throw new v(w.ErrInvalidArgument,`fail to find ${this.getParentCreatedAt()}`);if(!(i instanceof gt))throw new v(w.ErrInvalidArgument,"fail to execute, only Counter can execute increase");const r=i,s=this.value.deepcopy();return r.increase(s),{opInfos:[{type:"increase",path:t.createPath(this.getParentCreatedAt()),value:s.getValue()}],reverseOp:this.toReverseOperation()}}toReverseOperation(){const t=this.value.deepcopy(),r=t.getType()===$e.Long?t.getValue().multiply(-1):t.getValue()*-1;return gs.create(this.getParentCreatedAt(),pe.of(r,t.getCreatedAt()))}getEffectedCreatedAt(){return this.getParentCreatedAt()}toTestString(){return`${this.getParentCreatedAt().toTestString()}.INCREASE.${this.value.toJSON()}`}getValue(){return this.value}}class Nn extends Yt{constructor(t,i,r,s,o,a,l){super(t,l);d(this,"fromPos");d(this,"toPos");d(this,"maxCreatedAtMapByActor");d(this,"attributes");d(this,"attributesToRemove");this.fromPos=i,this.toPos=r,this.maxCreatedAtMapByActor=s,this.attributes=o,this.attributesToRemove=a}static create(t,i,r,s,o,a){return new Nn(t,i,r,s,o,new Array,a)}static createTreeRemoveStyleOperation(t,i,r,s,o,a){return new Nn(t,i,r,s,new Map,o,a)}execute(t){const i=t.findByCreatedAt(this.getParentCreatedAt());if(!i)throw new v(w.ErrInvalidArgument,`fail to find ${this.getParentCreatedAt()}`);if(!(i instanceof Mt))throw new v(w.ErrInvalidArgument,"fail to execute, only Tree can execute edit");const r=i;let s,o;if(this.attributes.size){const a={};[...this.attributes].forEach(([l,h])=>a[l]=h),[,o,s]=r.style([this.fromPos,this.toPos],a,this.getExecutedAt(),this.maxCreatedAtMapByActor)}else{const a=this.attributesToRemove;[,o,s]=r.removeStyle([this.fromPos,this.toPos],a,this.getExecutedAt(),this.maxCreatedAtMapByActor)}for(const a of o)t.registerGCPair(a);return{opInfos:s.map(({from:a,to:l,value:h,fromPath:c,toPath:u})=>({type:"tree-style",from:a,to:l,value:this.attributes.size?{attributes:h}:{attributesToRemove:h},fromPath:c,toPath:u,path:t.createPath(this.getParentCreatedAt())}))}}getEffectedCreatedAt(){return this.getParentCreatedAt()}toTestString(){const t=this.getParentCreatedAt().toTestString(),i=`${this.fromPos.getLeftSiblingID().getCreatedAt().toTestString()}:${this.fromPos.getLeftSiblingID().getOffset()}`,r=`${this.toPos.getLeftSiblingID().getCreatedAt().toTestString()}:${this.toPos.getLeftSiblingID().getOffset()}`;return`${t}.STYLE(${i},${r},${Object.entries(this.attributes||{}).map(([s,o])=>`${s}:"${o}"`).join(" ")})`}getFromPos(){return this.fromPos}getToPos(){return this.toPos}getAttributes(){return this.attributes}getAttributesToRemove(){return this.attributesToRemove}getMaxCreatedAtMapByActor(){return this.maxCreatedAtMapByActor}}function cw(n){const e=new Fu,t=e.data;for(const[i,r]of Object.entries(n))t[i]=JSON.stringify(r);return e}function uw(n){if(n.type===cr.Put)return new co({type:Dr.PUT,presence:cw(n.presence)});if(n.type===cr.Clear)return new co({type:Dr.CLEAR});throw new v(w.ErrUnimplemented,"unimplemented type")}function fw(n){return new Jm({serverSeq:n.getServerSeq(),clientSeq:n.getClientSeq()})}function hO(n){return new Kl({clientSeq:n.getClientSeq(),lamport:n.getLamport(),actorId:lf(n.getActorID()),versionVector:Yu(n.getVersionVector())})}function X(n){if(n)return new M({lamport:n.getLamport(),delimiter:n.getDelimiter(),actorId:lf(n.getActorID())})}function Yu(n){if(!n)return;const e=new eh;for(const[t,i]of n)e.vector[t]=BigInt(i.toString());return e}function cO(n){switch(n){case $e.Null:return F.NULL;case $e.Boolean:return F.BOOLEAN;case $e.Integer:return F.INTEGER;case $e.Long:return F.LONG;case $e.Double:return F.DOUBLE;case $e.String:return F.STRING;case $e.Bytes:return F.BYTES;case $e.Date:return F.DATE;default:throw new v(w.ErrInvalidType,`unsupported type: ${n}`)}}function uO(n){switch(n){case Pi.IntegerCnt:return F.INTEGER_CNT;case Pi.LongCnt:return F.LONG_CNT;default:throw new v(w.ErrInvalidType,`unsupported type: ${n}`)}}function Ah(n){if(n instanceof nt)return new Ot({type:F.JSON_OBJECT,createdAt:X(n.getCreatedAt()),value:xO(n)});if(n instanceof pt)return new Ot({type:F.JSON_ARRAY,createdAt:X(n.getCreatedAt()),value:Zw(n)});if(n instanceof qt)return new Ot({type:F.TEXT,createdAt:X(n.getCreatedAt())});if(n instanceof pe)return new Ot({type:cO(n.getType()),createdAt:X(n.getCreatedAt()),value:n.toBytes()});if(n instanceof gt)return new Ot({type:uO(n.getType()),createdAt:X(n.getCreatedAt()),value:n.toBytes()});if(n instanceof Mt)return new Ot({type:F.TREE,createdAt:X(n.getCreatedAt()),value:jw(n)});throw new v(w.ErrUnimplemented,"unimplemented element")}function dw(n){return new ho({createdAt:X(n.getCreatedAt()),offset:n.getOffset()})}function ea(n){return new Mn({createdAt:X(n.getID().getCreatedAt()),offset:n.getID().getOffset(),relativeOffset:n.getRelativeOffset()})}function ta(n){return new Er({parentId:Hs(n.getParentID()),leftSiblingId:Hs(n.getLeftSiblingID())})}function Hs(n){return new nr({createdAt:X(n.getCreatedAt()),offset:n.getOffset()})}function fO(n){const e=new Wu;if(n instanceof Nr){const t=n,i=new tl;i.parentCreatedAt=X(t.getParentCreatedAt()),i.key=t.getKey(),i.value=Ah(t.getValue()),i.executedAt=X(t.getExecutedAt()),e.body.case="set",e.body.value=i}else if(n instanceof Mo){const t=n,i=new il;i.parentCreatedAt=X(t.getParentCreatedAt()),i.prevCreatedAt=X(t.getPrevCreatedAt()),i.value=Ah(t.getValue()),i.executedAt=X(t.getExecutedAt()),e.body.case="add",e.body.value=i}else if(n instanceof Kn){const t=n,i=new nl;i.parentCreatedAt=X(t.getParentCreatedAt()),i.prevCreatedAt=X(t.getPrevCreatedAt()),i.createdAt=X(t.getCreatedAt()),i.executedAt=X(t.getExecutedAt()),e.body.case="move",e.body.value=i}else if(n instanceof ur){const t=n,i=new rl;i.parentCreatedAt=X(t.getParentCreatedAt()),i.createdAt=X(t.getCreatedAt()),i.executedAt=X(t.getExecutedAt()),e.body.case="remove",e.body.value=i}else if(n instanceof Vo){const t=n,i=new sl;i.parentCreatedAt=X(t.getParentCreatedAt()),i.from=ea(t.getFromPos()),i.to=ea(t.getToPos());const r=i.createdAtMapByActor;for(const[o,a]of t.getMaxCreatedAtMapByActor())r[o]=X(a);i.content=t.getContent();const s=i.attributes;for(const[o,a]of t.getAttributes())s[o]=a;i.executedAt=X(t.getExecutedAt()),e.body.case="edit",e.body.value=i}else if(n instanceof Xo){const t=n,i=new ol;i.parentCreatedAt=X(t.getParentCreatedAt()),i.from=ea(t.getFromPos()),i.to=ea(t.getToPos());const r=i.createdAtMapByActor;for(const[o,a]of t.getMaxCreatedAtMapByActor())r[o]=X(a);const s=i.attributes;for(const[o,a]of t.getAttributes())s[o]=a;i.executedAt=X(t.getExecutedAt()),e.body.case="style",e.body.value=i}else if(n instanceof gs){const t=n,i=new al;i.parentCreatedAt=X(t.getParentCreatedAt()),i.value=Ah(t.getValue()),i.executedAt=X(t.getExecutedAt()),e.body.case="increase",e.body.value=i}else if(n instanceof Lo){const t=n,i=new ll,r=i.createdAtMapByActor;for(const[s,o]of t.getMaxCreatedAtMapByActor())r[s]=X(o);i.parentCreatedAt=X(t.getParentCreatedAt()),i.from=ta(t.getFromPos()),i.to=ta(t.getToPos()),i.contents=Sw(t.getContents()),i.splitLevel=t.getSplitLevel(),i.executedAt=X(t.getExecutedAt()),e.body.case="treeEdit",e.body.value=i}else if(n instanceof Nn){const t=n,i=new hl;i.parentCreatedAt=X(t.getParentCreatedAt()),i.from=ta(t.getFromPos()),i.to=ta(t.getToPos());const r=i.createdAtMapByActor;for(const[o,a]of t.getMaxCreatedAtMapByActor())r[o]=X(a);const s=t.getAttributesToRemove();if(s.length>0)i.attributesToRemove=s;else{const o=i.attributes;for(const[a,l]of t.getAttributes())o[a]=l}i.executedAt=X(t.getExecutedAt()),e.body.case="treeStyle",e.body.value=i}else throw new v(w.ErrUnimplemented,"unimplemented operation");return e}function pw(n){const e=[];for(const t of n)e.push(fO(t));return e}function gw(n){const e=new zm({id:hO(n.getID()),message:n.getMessage()});return n.hasOperations()&&(e.operations=pw(n.getOperations())),n.hasPresenceChange()&&(e.presenceChange=uw(n.getPresenceChange())),e}function mw(n){const e=[];for(const t of n)e.push(gw(t));return e}function Ow(n){const e=[];for(const t of n)e.push(new _m({key:t.getStrKey(),element:Ku(t.getValue())}));return e}function yw(n){const e=[];for(const t of n)e.push(new ml({element:Ku(t.getValue())}));return e}function bw(n){const e=[];for(const t of n){const i=new Gm;i.id=dw(t.getID()),i.value=t.getValue().getContent(),i.removedAt=X(t.getRemovedAt());const r=i.attributes,s=t.getValue().getAttrs();for(const o of s){const a=new cs;a.value=o.getValue(),a.updatedAt=X(o.getUpdatedAt()),r[o.getKey()]=a}e.push(i)}return e}function Sw(n){const e=[];if(!n||!n.length)return e;for(const t of n)e.push(new Ol({content:Hu(t)}));return e}function ww(n){const e={};for(const t of n)e[t.getKey()]=new cs({value:t.getValue(),updatedAt:X(t.getUpdatedAt()),isRemoved:t.isRemoved()});return e}function Hu(n){if(!n)return[];const e=[];return th(n,(t,i)=>{const r=new ju({id:Hs(t.id),type:t.type,removedAt:X(t.removedAt),depth:i});t.isText&&(r.value=t.value),t.insPrevID&&(r.insPrevId=Hs(t.insPrevID)),t.insNextID&&(r.insNextId=Hs(t.insNextID)),t.attrs&&(r.attributes=ww(t.attrs)),e.push(r)}),e}function vw(n){const e=new rt;return e.body.case="jsonObject",e.body.value=new cl({nodes:Ow(n.getRHT()),createdAt:X(n.getCreatedAt()),movedAt:X(n.getMovedAt()),removedAt:X(n.getRemovedAt())}),e}function dO(n){const e=new rt;return e.body.case="jsonArray",e.body.value=new ul({nodes:yw(n.getElements()),createdAt:X(n.getCreatedAt()),movedAt:X(n.getMovedAt()),removedAt:X(n.getRemovedAt())}),e}function kw(n){const e=new rt;return e.body.case="primitive",e.body.value=new fl({type:cO(n.getType()),value:n.toBytes(),createdAt:X(n.getCreatedAt()),movedAt:X(n.getMovedAt()),removedAt:X(n.getRemovedAt())}),e}function xw(n){const e=new rt;return e.body.case="text",e.body.value=new dl({nodes:bw(n.getRGATreeSplit()),createdAt:X(n.getCreatedAt()),movedAt:X(n.getMovedAt()),removedAt:X(n.getRemovedAt())}),e}function Tw(n){const e=new rt;return e.body.case="counter",e.body.value=new pl({type:uO(n.getType()),value:n.toBytes(),createdAt:X(n.getCreatedAt()),movedAt:X(n.getMovedAt()),removedAt:X(n.getRemovedAt())}),e}function pO(n){const e=new rt;return e.body.case="tree",e.body.value=new gl({nodes:Hu(n.getRoot()),createdAt:X(n.getCreatedAt()),movedAt:X(n.getMovedAt()),removedAt:X(n.getRemovedAt())}),e}function Ku(n){if(n instanceof nt)return vw(n);if(n instanceof pt)return dO(n);if(n instanceof pe)return kw(n);if(n instanceof qt)return xw(n);if(n instanceof gt)return Tw(n);if(n instanceof Mt)return pO(n);throw new v(w.ErrUnimplemented,"unimplemented element")}function Qw(n){return new Wn({documentKey:n.getDocumentKey(),checkpoint:fw(n.getCheckpoint()),isRemoved:n.getIsRemoved(),changes:mw(n.getChanges()),snapshot:n.getSnapshot(),versionVector:Yu(n.getVersionVector()),minSyncedTicket:X(n.getMinSyncedTicket())})}function qd(n){const e=n.findDetails(U1);for(const t of e)if(t.metadata.code)return t.metadata.code;return""}function gO(n){return An.of(n.clientSeq,BigInt(n.lamport),of(n.actorId),ef(n.versionVector),BigInt(n.serverSeq))}function ef(n){if(!n)return;const e=new ts;return Object.entries(n.vector).forEach(([t,i])=>{e.set(t,BigInt(i.toString()))}),e}function L(n){if(n)return dt.of(BigInt(n.lamport),n.delimiter,of(n.actorId))}function tf(n){const e={};return Object.entries(n.data).forEach(([t,i])=>{e[t]=JSON.parse(i)}),e}function Pw(n){const e=n.type;if(e===Dr.PUT){const t=tf(n.presence);return{type:cr.Put,presence:t}}if(e===Dr.CLEAR)return{type:cr.Clear};throw new v(w.ErrInvalidType,`unsupported type: ${e}`)}function Aw(n){const e=new Map;return Object.entries(n).forEach(([t,i])=>{e.set(t,tf(i))}),e}function mO(n){switch(n){case F.NULL:return $e.Null;case F.BOOLEAN:return $e.Boolean;case F.INTEGER:return $e.Integer;case F.LONG:return $e.Long;case F.DOUBLE:return $e.Double;case F.STRING:return $e.String;case F.BYTES:return $e.Bytes;case F.DATE:return $e.Date}throw new v(w.ErrUnimplemented,`unimplemented value type: ${n}`)}function Sl(n){switch(n){case F.INTEGER_CNT:return Pi.IntegerCnt;case F.LONG_CNT:return Pi.LongCnt}throw new v(w.ErrUnimplemented,`unimplemented value type: ${n}`)}function $h(n){switch(n.type){case F.JSON_OBJECT:return n.value?kO(n.value):nt.create(L(n.createdAt));case F.JSON_ARRAY:return n.value?Uw(n.value):pt.create(L(n.createdAt));case F.TEXT:return qt.create(ps.create(),L(n.createdAt));case F.TREE:return Ww(n.value);case F.NULL:case F.BOOLEAN:case F.INTEGER:case F.LONG:case F.DOUBLE:case F.STRING:case F.BYTES:case F.DATE:return pe.of(pe.valueFromBytes(mO(n.type),n.value),L(n.createdAt));case F.INTEGER_CNT:case F.LONG_CNT:return gt.create(Sl(n.type),gt.valueFromBytes(Sl(n.type),n.value),L(n.createdAt))}}function ia(n){return Jt.of(Ti.of(L(n.createdAt),n.offset),n.relativeOffset)}function OO(n){return Ti.of(L(n.createdAt),n.offset)}function $w(n){const e=go.create(n.value);Object.entries(n.attributes).forEach(([i,r])=>{e.setAttr(i,r.value,L(r.updatedAt))});const t=sr.create(OO(n.id),e);return t.remove(L(n.removedAt)),t}function Wr(n){return _t.of(Ks(n.parentId),Ks(n.leftSiblingId))}function Ks(n){return Me.of(L(n.createdAt),n.offset)}function Cw(n){if(!n.length)return;const e=[];return n.forEach(t=>{const i=nf(t.content);e.push(i)}),e}function nf(n){if(n.length===0)return;const e=[];for(const r of n)e.push(Rw(r));const t=e[e.length-1],i=new Map;i.set(n[e.length-1].depth,e[e.length-1]);for(let r=e.length-2;r>=0;r--)i.get(n[r].depth-1).prepend(e[r]),i.set(n[r].depth,e[r]);return t.updateDescendantsSize(),Mt.create(t,Gt).getRoot()}function Iw(n){const e=Vn.create();for(const[t,i]of Object.entries(n))e.setInternal(t,i.value,L(i.updatedAt),i.isRemoved);return e}function Rw(n){const e=Ks(n.id),t=ut.create(e,n.type),i=Object.entries(n.attributes);return t.isText?t.value=n.value:i.length&&(t.attrs=Iw(n.attributes)),n.insPrevId&&(t.insPrevID=Ks(n.insPrevId)),n.insNextId&&(t.insNextID=Ks(n.insNextId)),t.removedAt=L(n.removedAt),t}function yO(n){if(n.body.case==="set"){const e=n.body.value;return Nr.create(e.key,$h(e.value),L(e.parentCreatedAt),L(e.executedAt))}else if(n.body.case==="add"){const e=n.body.value;return Mo.create(L(e.parentCreatedAt),L(e.prevCreatedAt),$h(e.value),L(e.executedAt))}else if(n.body.case==="move"){const e=n.body.value;return Kn.create(L(e.parentCreatedAt),L(e.prevCreatedAt),L(e.createdAt),L(e.executedAt))}else if(n.body.case==="remove"){const e=n.body.value;return ur.create(L(e.parentCreatedAt),L(e.createdAt),L(e.executedAt))}else if(n.body.case==="edit"){const e=n.body.value,t=new Map;Object.entries(e.createdAtMapByActor).forEach(([r,s])=>{t.set(r,L(s))});const i=new Map;return Object.entries(e.attributes).forEach(([r,s])=>{i.set(r,s)}),Vo.create(L(e.parentCreatedAt),ia(e.from),ia(e.to),t,e.content,i,L(e.executedAt))}else if(n.body.case==="style"){const e=n.body.value,t=new Map;Object.entries(e.createdAtMapByActor).forEach(([r,s])=>{t.set(r,L(s))});const i=new Map;return Object.entries(e.attributes).forEach(([r,s])=>{i.set(r,s)}),Xo.create(L(e.parentCreatedAt),ia(e.from),ia(e.to),t,i,L(e.executedAt))}else{if(n.body.case==="select")return;if(n.body.case==="increase"){const e=n.body.value;return gs.create(L(e.parentCreatedAt),$h(e.value),L(e.executedAt))}else if(n.body.case==="treeEdit"){const e=n.body.value,t=new Map;return Object.entries(e.createdAtMapByActor).forEach(([i,r])=>{t.set(i,L(r))}),Lo.create(L(e.parentCreatedAt),Wr(e.from),Wr(e.to),Cw(e.contents),e.splitLevel,t,L(e.executedAt))}else if(n.body.case==="treeStyle"){const e=n.body.value,t=new Map,i=e.attributesToRemove,r=new Map;return e!=null&&e.createdAtMapByActor&&Object.entries(e.createdAtMapByActor).forEach(([s,o])=>{r.set(s,L(o))}),(i==null?void 0:i.length)>0?Nn.createTreeRemoveStyleOperation(L(e.parentCreatedAt),Wr(e.from),Wr(e.to),r,i,L(e.executedAt)):(Object.entries(e.attributes).forEach(([s,o])=>{t.set(s,o)}),Nn.create(L(e.parentCreatedAt),Wr(e.from),Wr(e.to),r,t,L(e.executedAt)))}else throw new v(w.ErrUnimplemented,"unimplemented operation")}}function Ew(n){const e=[];for(const t of n){const i=yO(t);i&&e.push(i)}return e}function bO(n){const e=[];for(const t of n)e.push(ds.create({id:gO(t.id),operations:Ew(t.operations),presenceChange:t.presenceChange?Pw(t.presenceChange):void 0,message:t.message}));return e}function Dw(n){return is.of(BigInt(n.serverSeq),n.clientSeq)}function Nw(n){return ih.create(n.documentKey,Dw(n.checkpoint),n.isRemoved,bO(n.changes),ef(n.versionVector),n.snapshot,L(n.minSyncedTicket))}function SO(n){const e=new uo;for(const i of n.nodes){const r=rf(i.element);e.set(i.key,r,r.getPositionedAt())}const t=new nt(L(n.createdAt),e);return t.setMovedAt(L(n.movedAt)),t.setRemovedAt(L(n.removedAt)),t}function wO(n){const e=new po;for(const i of n.nodes)e.insert(rf(i.element));const t=new pt(L(n.createdAt),e);return t.setMovedAt(L(n.movedAt)),t.setRemovedAt(L(n.removedAt)),t}function Bw(n){const e=pe.of(pe.valueFromBytes(mO(n.type),n.value),L(n.createdAt));return e.setMovedAt(L(n.movedAt)),e.setRemovedAt(L(n.removedAt)),e}function qw(n){const e=new ps;let t=e.getHead();for(const r of n.nodes){const s=e.insertAfter(t,$w(r));r.insPrevId&&s.setInsPrev(e.findNode(OO(r.insPrevId))),t=s}const i=new qt(e,L(n.createdAt));return i.setMovedAt(L(n.movedAt)),i.setRemovedAt(L(n.removedAt)),i}function Mw(n){const e=gt.create(Sl(n.type),gt.valueFromBytes(Sl(n.type),n.value),L(n.createdAt));return e.setMovedAt(L(n.movedAt)),e.setRemovedAt(L(n.removedAt)),e}function vO(n){const e=nf(n.nodes);return Mt.create(e,L(n.createdAt))}function rf(n){if(n.body.case==="jsonObject")return SO(n.body.value);if(n.body.case==="jsonArray")return wO(n.body.value);if(n.body.case==="primitive")return Bw(n.body.value);if(n.body.case==="text")return qw(n.body.value);if(n.body.case==="counter")return Mw(n.body.value);if(n.body.case==="tree")return vO(n.body.value);throw new v(w.ErrUnimplemented,"unimplemented element")}function Vw(n){if(!n)return{root:nt.create(Gt),presences:new Map};const e=gc.fromBinary(n);return{root:rf(e.root),presences:Aw(e.presences)}}function Xw(n){const e=Yu(n);return sf(e.toBinary())}function Lw(n){const e=af(n),t=eh.fromBinary(e);return ef(t)}function kO(n){if(!n)throw new v(w.ErrInvalidArgument,"bytes is empty");const e=rt.fromBinary(n);return SO(e.body.value)}function xO(n){return Ku(n).toBinary()}function Uw(n){if(!n)throw new v(w.ErrInvalidArgument,"bytes is empty");const e=rt.fromBinary(n);return wO(e.body.value)}function Zw(n){return dO(n).toBinary()}function Ww(n){if(!n)throw new v(w.ErrInvalidArgument,"bytes is empty");const e=rt.fromBinary(n);return vO(e.body.value)}function jw(n){return pO(n).toBinary()}function sf(n){return n?Array.from(n).map(e=>e.toString(16).padStart(2,"0")).join(""):""}function of(n){return sf(n)}function af(n){return new Uint8Array(n.match(/.{1,2}/g).map(e=>parseInt(e,16)))}function lf(n){return af(n)}function Fw(n){const e=Kl.fromBinary(n);return gO(e)}function zw(n){const e=Wu.fromBinary(n);return yO(e)}const we={fromPresence:tf,toChangePack:Qw,fromChangePack:Nw,fromChanges:bO,toTreeNodes:Hu,fromTreeNodes:nf,objectToBytes:xO,bytesToObject:kO,bytesToSnapshot:Vw,bytesToHex:sf,hexToBytes:af,toHexString:of,toUint8Array:lf,toOperation:fO,toChangeID:hO,PbChangeID:Kl,bytesToChangeID:Fw,bytesToOperation:zw,versionVectorToHex:Xw,hexToVersionVector:Lw};var Ge=(n=>(n[n.Trivial=0]="Trivial",n[n.Debug=1]="Debug",n[n.Info=2]="Info",n[n.Warn=3]="Warn",n[n.Error=4]="Error",n[n.Fatal=5]="Fatal",n))(Ge||{});let vr=3;function TO(n){vr=n}const U={trivial:(...n)=>{vr>0||typeof console<"u"&&console.log("YORKIE T:",...n)},debug:(...n)=>{vr>1||typeof console<"u"&&console.log("YORKIE D:",...n)},info:(...n)=>{vr>2||typeof console<"u"&&console.log("YORKIE I:",...n)},warn:(...n)=>{vr>3||typeof console<"u"&&(typeof console.warn<"u"?console.warn("YORKIE W:",...n):console.log("YORKIE W:",...n))},error:(...n)=>{vr>4||typeof console<"u"&&(typeof console.error<"u"?console.error("YORKIE E:",...n):console.log("YORKIE E:",...n))},fatal:(...n)=>{typeof console<"u"&&(typeof console.error<"u"?console.error("YORKIE F:",...n):console.log("YORKIE F:",...n))},isEnabled:n=>vr<=n};function QO(){return"xxxxxxxx-xxxx-4xxxy-xxxx-xxxxxxxxxxx".replace(/[xy]/g,n=>{const e=Math.random()*16|0;return(n==="x"?e:e&3|8).toString(16)})}class _w{constructor(e,t,i,r,s){d(this,"reconnectStreamDelay");d(this,"doc");d(this,"docID");d(this,"syncMode");d(this,"remoteChangeEventReceived");d(this,"watchStream");d(this,"watchLoopTimerID");d(this,"watchAbortController");d(this,"unsubscribeBroadcastEvent");this.reconnectStreamDelay=e,this.doc=t,this.docID=i,this.syncMode=r,this.remoteChangeEventReceived=!1,this.unsubscribeBroadcastEvent=s}changeSyncMode(e){this.syncMode=e}needRealtimeSync(){return this.syncMode===Ma.RealtimeSyncOff?!1:this.syncMode===Ma.RealtimePushOnly?this.doc.hasLocalChanges():this.syncMode!==Ma.Manual&&(this.doc.hasLocalChanges()||this.remoteChangeEventReceived)}async runWatchLoop(e){const t=async()=>{if(this.watchStream)return Promise.resolve();this.watchLoopTimerID&&(clearTimeout(this.watchLoopTimerID),this.watchLoopTimerID=void 0);try{[this.watchStream,this.watchAbortController]=await e(()=>{this.watchStream=void 0,this.watchAbortController=void 0,this.watchLoopTimerID=setTimeout(t,this.reconnectStreamDelay)})}catch{}};await t()}cancelWatchStream(){this.watchStream&&this.watchAbortController&&(this.watchAbortController.abort(),this.watchStream=void 0,this.watchAbortController=void 0),clearTimeout(this.watchLoopTimerID),this.watchLoopTimerID=void 0}}const Ch=()=>{};class Gw{constructor(e){d(this,"finalized",!1);d(this,"observers",[]);d(this,"finalError");try{e(this)}catch(t){this.error(t)}}next(e){this.forEachObserver(t=>{t.next(e)})}error(e){this.forEachObserver(t=>{t.error(e)}),this.close(e)}complete(){this.forEachObserver(e=>{e.complete()}),this.close()}subscribe(e,t,i){let r;if(!e)throw new v(w.ErrInvalidArgument,"missing observer");if(this.finalized)throw new v(w.ErrRefused,"observable is finalized due to previous error");typeof e=="object"?r=e:r={next:e,error:t,complete:i},r.next===void 0&&(r.next=Ch),r.error===void 0&&(r.error=Ch),r.complete===void 0&&(r.complete=Ch);const s=QO(),o=this.unsubscribeOne.bind(this,s);if(this.observers.push({subscriptionID:s,observer:r}),this.finalized)try{this.finalError?r.error(this.finalError):r.complete()}catch(a){U.warn(a)}return o}unsubscribeOne(e){var t;this.observers=(t=this.observers)==null?void 0:t.filter(i=>i.subscriptionID!==e)}forEachObserver(e){if(!this.finalized)for(let t=0;te}}class Jr{constructor(e,t,i,r){d(this,"id");d(this,"delimiter");d(this,"message");d(this,"root");d(this,"operations");d(this,"presenceChange");d(this,"previousPresence");d(this,"reversePresenceKeys");this.id=e,this.delimiter=Hm,this.root=t,this.operations=[],this.previousPresence=Wt(i),this.presenceChange=void 0,this.reversePresenceKeys=new Set,this.message=r}static create(e,t,i,r){return new Jr(e,t,i,r)}push(e){this.operations.push(e)}registerElement(e,t){this.root.registerElement(e,t)}registerRemovedElement(e){this.root.registerRemovedElement(e)}registerGCPair(e){this.root.registerGCPair(e)}getChange(){return ds.create({id:this.id,operations:this.operations,presenceChange:this.presenceChange,message:this.message})}hasChange(){return this.operations.length>0||this.presenceChange!==void 0}setPresenceChange(e){this.presenceChange=e}setReversePresence(e,t){for(const i of Object.keys(e))t!=null&&t.addToHistory?this.reversePresenceKeys.add(i):this.reversePresenceKeys.delete(i)}getReversePresence(){if(this.reversePresenceKeys.size===0)return;const e={};for(const t of this.reversePresenceKeys)e[t]=this.previousPresence[t];return e}issueTimeTicket(){return this.delimiter+=1,this.id.createTimeTicket(this.delimiter)}getLastTimeTicket(){return this.id.createTimeTicket(this.delimiter)}}class mo{constructor(e){d(this,"rootObject");d(this,"elementPairMapByCreatedAt");d(this,"gcElementSetByCreatedAt");d(this,"gcPairMap");this.rootObject=e,this.elementPairMapByCreatedAt=new Map,this.gcElementSetByCreatedAt=new Set,this.gcPairMap=new Map,this.registerElement(e,void 0),e.getDescendants(t=>{if(t.getRemovedAt()&&this.registerRemovedElement(t),t instanceof qt||t instanceof Mt)for(const i of t.getGCPairs())this.registerGCPair(i);return!1})}static create(){return new mo(nt.create(Gt))}findByCreatedAt(e){const t=this.elementPairMapByCreatedAt.get(e.toIDString());if(t)return t.element}findElementPairByCreatedAt(e){return this.elementPairMapByCreatedAt.get(e.toIDString())}createSubPaths(e){let t=this.elementPairMapByCreatedAt.get(e.toIDString());if(!t)return[];const i=[];for(;t.parent;){const r=t.element.getCreatedAt(),s=t.parent.subPathOf(r);if(s===void 0)throw new v(w.ErrInvalidArgument,`cant find the given element: ${r.toIDString()}`);i.unshift(s),t=this.elementPairMapByCreatedAt.get(t.parent.getCreatedAt().toIDString())}return i.unshift("$"),i}createPath(e){return this.createSubPaths(e).join(".")}registerElement(e,t){this.elementPairMapByCreatedAt.set(e.getCreatedAt().toIDString(),{parent:t,element:e}),e instanceof rr&&e.getDescendants((i,r)=>(this.registerElement(i,r),!1))}deregisterElement(e){let t=0;const i=r=>{const s=r.getCreatedAt().toIDString();this.elementPairMapByCreatedAt.delete(s),this.gcElementSetByCreatedAt.delete(s),t++};return i(e),e instanceof rr&&e.getDescendants(r=>(i(r),!1)),t}registerRemovedElement(e){this.gcElementSetByCreatedAt.add(e.getCreatedAt().toIDString())}registerGCPair(e){if(this.gcPairMap.get(e.child.toIDString())){this.gcPairMap.delete(e.child.toIDString());return}this.gcPairMap.set(e.child.toIDString(),e)}getElementMapSize(){return this.elementPairMapByCreatedAt.size}getGarbageElementSetSize(){const e=new Set;for(const t of this.gcElementSetByCreatedAt){e.add(t);const i=this.elementPairMapByCreatedAt.get(t);i.element instanceof rr&&i.element.getDescendants(r=>(e.add(r.getCreatedAt().toIDString()),!1))}return e.size}getObject(){return this.rootObject}getGarbageLen(){return this.getGarbageElementSetSize()+this.gcPairMap.size}deepcopy(){return new mo(this.rootObject.deepcopy())}garbageCollect(e){let t=0;for(const i of this.gcElementSetByCreatedAt){const r=this.elementPairMapByCreatedAt.get(i),s=r.element.getRemovedAt();s&&(e!=null&&e.afterOrEqual(s))&&(r.parent.purge(r.element),t+=this.deregisterElement(r.element))}for(const[,i]of this.gcPairMap){const r=i.child.getRemovedAt();r&&(e!=null&&e.afterOrEqual(r))&&(i.parent.purge(i.child),this.gcPairMap.delete(i.child.toIDString()),t+=1)}return t}toJSON(){return this.rootObject.toJSON()}toSortedJSON(){return this.rootObject.toSortedJSON()}getStats(){return{elements:this.getElementMapSize(),gcPairs:this.gcPairMap.size,gcElements:this.getGarbageElementSetSize()}}}function PO(n,e){const t=new Oo(n);return new Proxy(e,t.getHandlers())}class Oo{constructor(e){d(this,"context");d(this,"handlers");this.context=e,this.handlers={set:(t,i,r)=>(U.isEnabled(Ge.Trivial)&&U.trivial(`obj[${i}]=${JSON.stringify(r)}`),Oo.setInternal(e,t,i,r),!0),get:(t,i)=>(U.isEnabled(Ge.Trivial)&&U.trivial(`obj[${i}]`),i==="getID"?()=>t.getCreatedAt():i==="toJSON"||i==="toString"?()=>t.toJSON():i==="toJS"?()=>t.toJS():i==="toJSForTest"?()=>t.toJSForTest():kr(e,t.get(i))),ownKeys:t=>t.getKeys(),getOwnPropertyDescriptor:()=>({enumerable:!0,configurable:!0}),deleteProperty:(t,i)=>(U.isEnabled(Ge.Trivial)&&U.trivial(`obj[${i}]`),Oo.deleteInternal(e,t,i),!0)}}static setInternal(e,t,i,r){if(i.includes("."))throw new v(w.ErrInvalidObjectKey,"key must not contain the '.'.");const s=e.issueTimeTicket(),o=wl(e,r,s),a=t.set(i,o,s);e.registerElement(o,t),a&&e.registerRemovedElement(a),e.push(Nr.create(i,o.deepcopy(),t.getCreatedAt(),s))}static buildObjectMembers(e,t){const i={};for(const[r,s]of Object.entries(t)){if(r.includes("."))throw new v(w.ErrInvalidObjectKey,"key must not contain the '.'.");const o=e.issueTimeTicket(),a=wl(e,s,o);i[r]=a}return i}static deleteInternal(e,t,i){const r=e.issueTimeTicket(),s=t.deleteByKey(i,r);s&&(e.push(ur.create(t.getCreatedAt(),s.getCreatedAt(),r)),e.registerRemovedElement(s))}getHandlers(){return this.handlers}}function Yw(n,e){const t=new me(n,e);return new Proxy(e,t.getHandlers())}function Hw(n){return typeof n=="string"||n instanceof String?!isNaN(n):!1}function Kw(n){return["concat","entries","every","filter","find","findIndex","forEach","join","keys","map","reduce","reduceRight","slice","some","toLocaleString","toString","values"].includes(n)}class me{constructor(e,t){d(this,"context");d(this,"handlers");d(this,"array");this.context=e,this.array=t,this.handlers={get:(i,r,s)=>r==="getID"?()=>i.getCreatedAt():r==="getElementByID"?o=>{const a=i.getByID(o);if(!(!a||a.isRemoved()))return _n(e,a)}:r==="getElementByIndex"?o=>{const a=i.get(o);return _n(e,a)}:r==="getLast"?()=>_n(e,i.getLast()):r==="deleteByID"?o=>{const a=me.deleteInternalByID(e,i,o);return _n(e,a)}:r==="insertAfter"?(o,a)=>{const l=me.insertAfterInternal(e,i,o,a);return _n(e,l)}:r==="insertBefore"?(o,a)=>{const l=me.insertBeforeInternal(e,i,o,a);return _n(e,l)}:r==="moveBefore"?(o,a)=>{me.moveBeforeInternal(e,i,o,a)}:r==="moveAfter"?(o,a)=>{me.moveAfterInternal(e,i,o,a)}:r==="moveFront"?o=>{me.moveFrontInternal(e,i,o)}:r==="moveLast"?o=>{me.moveLastInternal(e,i,o)}:Hw(r)?kr(e,i.get(Number(r))):r==="push"?o=>me.pushInternal(e,i,o):r==="splice"?(o,a,...l)=>me.splice(e,i,o,a,...l):r==="length"?i.length:typeof r=="symbol"&&r===Symbol.iterator?me.iteratorInternal.bind(this,e,i):r==="includes"?(o,a)=>me.includes(e,i,o,a):r==="indexOf"?(o,a)=>me.indexOf(e,i,o,a):r==="lastIndexOf"?(o,a)=>me.lastIndexOf(e,i,o,a):r==="toJSForTest"?()=>i.toJSForTest():r==="toTestString"?()=>me.toTestString(i):typeof r=="string"&&Kw(r)?(...o)=>{const a=Array.from(i).map(l=>kr(e,l));return Array.prototype[r].apply(a,o)}:Reflect.get(i,r,s),deleteProperty:(i,r)=>(U.isEnabled(Ge.Trivial)&&U.trivial(`array[${r}]`),me.deleteInternalByIndex(e,i,Number.parseInt(r)),!0)}}static*iteratorInternal(e,t){for(const i of t)yield _n(e,i)}static buildArrayElements(e,t){const i=[];for(const r of t){const s=e.issueTimeTicket(),o=wl(e,r,s);i.push(o)}return i}static pushInternal(e,t,i){return me.insertAfterInternal(e,t,t.getLastCreatedAt(),i),t.length}static moveBeforeInternal(e,t,i,r){const s=e.issueTimeTicket(),o=t.getPrevCreatedAt(i);t.moveAfter(o,r,s),e.push(Kn.create(t.getCreatedAt(),o,r,s))}static moveAfterInternal(e,t,i,r){const s=e.issueTimeTicket();t.moveAfter(i,r,s),e.push(Kn.create(t.getCreatedAt(),i,r,s))}static moveFrontInternal(e,t,i){const r=e.issueTimeTicket(),s=t.getHead();t.moveAfter(s.getCreatedAt(),i,r),e.push(Kn.create(t.getCreatedAt(),s.getCreatedAt(),i,r))}static moveLastInternal(e,t,i){const r=e.issueTimeTicket(),s=t.getLastCreatedAt();t.moveAfter(s,i,r),e.push(Kn.create(t.getCreatedAt(),s,i,r))}static insertAfterInternal(e,t,i,r){const s=e.issueTimeTicket(),o=wl(e,r,s);return t.insertAfter(i,o),e.registerElement(o,t),e.push(Mo.create(t.getCreatedAt(),i,o.deepcopy(),s)),o}static insertBeforeInternal(e,t,i,r){return me.insertAfterInternal(e,t,t.getPrevCreatedAt(i),r)}static deleteInternalByIndex(e,t,i){const r=e.issueTimeTicket(),s=t.deleteByIndex(i,r);if(s)return e.push(ur.create(t.getCreatedAt(),s.getCreatedAt(),r)),e.registerRemovedElement(s),s}static deleteInternalByID(e,t,i){const r=e.issueTimeTicket(),s=t.delete(i,r);return e.push(ur.create(t.getCreatedAt(),s.getCreatedAt(),r)),e.registerRemovedElement(s),s}static splice(e,t,i,r,...s){const o=t.length,a=i>=0?Math.min(i,o):Math.max(o+i,0),l=r===void 0?o:r<0?a:Math.min(a+r,o),h=[];for(let c=a;c=s)return!1;if(pe.isSupport(i))return Array.from(t).map(h=>kr(e,h)).includes(i,o);for(let l=o;l=s)return-1;if(pe.isSupport(i))return Array.from(t).map(h=>kr(e,h)).indexOf(i,o);for(let l=o;l=s?s-1:r<0?r+s:r;if(o<0)return-1;if(pe.isSupport(i))return Array.from(t).map(h=>kr(e,h)).lastIndexOf(i,o);for(let l=o;l>0;l--)if(((a=t.get(l))==null?void 0:a.getID())===i.getID())return l;return-1}static toTestString(e){return e.toTestString()}getHandlers(){return this.handlers}}let nh=class{constructor(e,t){d(this,"context");d(this,"text");this.context=e,this.text=t}initialize(e,t){this.context=e,this.text=t}getID(){return this.text.getID()}edit(e,t,i,r){if(!this.context||!this.text)throw new v(w.ErrNotInitialized,"Text is not initialized yet");if(e>t)throw new v(w.ErrInvalidArgument,"from should be less than or equal to to");const s=this.text.indexRangeToPosRange(e,t);U.isEnabled(Ge.Debug)&&U.debug(`EDIT: f:${e}->${s[0].toTestString()}, t:${t}->${s[1].toTestString()} c:${i}`);const o=r?us(r):void 0,a=this.context.issueTimeTicket(),[l,,h,c]=this.text.edit(s,i,a,o);for(const u of h)this.context.registerGCPair(u);return this.context.push(new Vo(this.text.getCreatedAt(),s[0],s[1],l,i,o?new Map(Object.entries(o)):new Map,a)),this.text.findIndexesFromRange(c)}delete(e,t){return this.edit(e,t,"")}empty(){return this.edit(0,this.length,"")}setStyle(e,t,i){if(!this.context||!this.text)throw new v(w.ErrNotInitialized,"Text is not initialized yet");if(e>t)throw new v(w.ErrInvalidArgument,"from should be less than or equal to to");const r=this.text.indexRangeToPosRange(e,t);U.isEnabled(Ge.Debug)&&U.debug(`STYL: f:${e}->${r[0].toTestString()}, t:${t}->${r[1].toTestString()} a:${JSON.stringify(i)}`);const s=us(i),o=this.context.issueTimeTicket(),[a,l]=this.text.setStyle(r,s,o);for(const h of l)this.context.registerGCPair(h);return this.context.push(new Xo(this.text.getCreatedAt(),r[0],r[1],a,new Map(Object.entries(s)),o)),!0}indexRangeToPosRange(e){if(!this.context||!this.text)throw new v(w.ErrNotInitialized,"Text is not initialized yet");const t=this.text.indexRangeToPosRange(e[0],e[1]);return[t[0].toStruct(),t[1].toStruct()]}posRangeToIndexRange(e){if(!this.context||!this.text)throw new v(w.ErrNotInitialized,"Text is not initialized yet");const t=this.text.findIndexesFromRange([Jt.fromStruct(e[0]),Jt.fromStruct(e[1])]);return[t[0],t[1]]}toTestString(){if(!this.context||!this.text)throw new v(w.ErrNotInitialized,"Text is not initialized yet");return this.text.toTestString()}values(){if(!this.context||!this.text)throw new v(w.ErrNotInitialized,"Text is not initialized yet");return this.text.values()}get length(){return this.text.length}getTreeByIndex(){return this.text.getTreeByIndex()}getTreeByID(){return this.text.getTreeByID()}toString(){if(!this.context||!this.text)throw new v(w.ErrNotInitialized,"Text is not initialized yet");return this.text.toString()}toJSON(){if(!this.context||!this.text)throw new v(w.ErrNotInitialized,"Text is not initialized yet");return this.text.toJSON()}toJSForTest(){if(!this.context||!this.text)throw new v(w.ErrNotInitialized,"Text is not initialized yet");return this.text.toJSForTest()}createRangeForTest(e,t){if(!this.context||!this.text)throw new v(w.ErrNotInitialized,"Text is not initialized yet");return this.text.indexRangeToPosRange(e,t)}};class rh{constructor(e,t){d(this,"valueType");d(this,"value");d(this,"context");d(this,"counter");this.valueType=e,this.value=t}initialize(e,t){this.valueType=t.getValueType(),this.context=e,this.counter=t,this.value=t.getValue()}getID(){return this.counter.getID()}getValue(){return this.value}getValueType(){return this.valueType}increase(e){if(!this.context||!this.counter)throw new v(w.ErrNotInitialized,"Counter is not initialized yet");const t=this.context.issueTimeTicket(),i=pe.of(e,t);if(!i.isNumericType())throw new TypeError(`Unsupported type of value: ${typeof i.getValue()}`);return this.counter.increase(i),this.context.push(gs.create(this.counter.getCreatedAt(),i,t)),this}toJSForTest(){if(!this.context||!this.counter)throw new v(w.ErrNotInitialized,"Counter is not initialized yet");return this.counter.toJSForTest()}}function hf(n,e,t){const{type:i}=n,r=t.issueTimeTicket();if(i===Dn){AO(n);const{value:s}=n,o=ut.create(Me.of(r,0),i,s);e.append(o)}else{const{children:s=[]}=n,{attributes:o}=n;let a;if(typeof o=="object"&&!Ym(o)){const h=us(o);a=new Vn;for(const[c,u]of Object.entries(h))a.set(c,u,r)}const l=ut.create(Me.of(r,0),i,void 0,a);e.append(l);for(const h of s)hf(h,l,t)}}function ev(n,e){const{type:t}=e,i=n.issueTimeTicket();let r;if(e.type===Dn){const{value:s}=e;r=ut.create(Me.of(i,0),t,s)}else if(e){const{children:s=[]}=e,{attributes:o}=e;let a;if(typeof o=="object"&&!Ym(o)){const l=us(o);a=new Vn;for(const[h,c]of Object.entries(l))a.set(h,c,i)}r=ut.create(Me.of(n.issueTimeTicket(),0),t,void 0,a);for(const l of s)hf(l,r,n)}return r}function AO(n){if(!n.value.length)throw new v(w.ErrInvalidArgument,"text node cannot have empty value");return!0}function Md(n){if(!n.length)return!0;if(n[0].type===Dn)for(const t of n){const{type:i}=t;if(i!==Dn)throw new v(w.ErrInvalidArgument,"element node and text node cannot be passed together");AO(t)}else for(const t of n){const{type:i}=t;if(i===Dn)throw new v(w.ErrInvalidArgument,"element node and text node cannot be passed together")}return!0}let sh=class{constructor(e){d(this,"initialRoot");d(this,"context");d(this,"tree");this.initialRoot=e}initialize(e,t){this.context=e,this.tree=t}getID(){return this.tree.getID()}buildRoot(e){if(!this.initialRoot)return ut.create(Me.of(e.issueTimeTicket(),0),H1);const t=ut.create(Me.of(e.issueTimeTicket(),0),this.initialRoot.type);for(const i of this.initialRoot.children)hf(i,t,e);return t}getSize(){if(!this.context||!this.tree)throw new v(w.ErrNotInitialized,"Tree is not initialized yet");return this.tree.getSize()}getNodeSize(){if(!this.context||!this.tree)throw new v(w.ErrNotInitialized,"Tree is not initialized yet");return this.tree.getNodeSize()}getIndexTree(){if(!this.context||!this.tree)throw new v(w.ErrNotInitialized,"Tree is not initialized yet");return this.tree.getIndexTree()}styleByPath(e,t){if(!this.context||!this.tree)throw new v(w.ErrNotInitialized,"Tree is not initialized yet");if(!e.length)throw new v(w.ErrInvalidArgument,"path should not be empty");const[i,r]=this.tree.pathToPosRange(e),s=this.context.issueTimeTicket(),o=t?us(t):void 0,[a]=this.tree.style([i,r],o,s);this.context.push(Nn.create(this.tree.getCreatedAt(),i,r,a,o?new Map(Object.entries(o)):new Map,s))}style(e,t,i){if(!this.context||!this.tree)throw new v(w.ErrNotInitialized,"Tree is not initialized yet");if(e>t)throw new v(w.ErrInvalidArgument,"from should be less than or equal to to");const r=this.tree.findPos(e),s=this.tree.findPos(t),o=this.context.issueTimeTicket(),a=i?us(i):void 0,[l,h]=this.tree.style([r,s],a,o);for(const c of h)this.context.registerGCPair(c);this.context.push(Nn.create(this.tree.getCreatedAt(),r,s,l,a?new Map(Object.entries(a)):new Map,o))}removeStyle(e,t,i){if(!this.context||!this.tree)throw new v(w.ErrNotInitialized,"Tree is not initialized yet");if(e>t)throw new v(w.ErrInvalidArgument,"from should be less than or equal to to");const r=this.tree.findPos(e),s=this.tree.findPos(t),o=this.context.issueTimeTicket(),[a,l]=this.tree.removeStyle([r,s],i,o);for(const h of l)this.context.registerGCPair(h);this.context.push(Nn.createTreeRemoveStyleOperation(this.tree.getCreatedAt(),r,s,a,i,o))}editInternal(e,t,i,r=0){var h;if(i.length!==0&&i[0]&&(Md(i),i[0].type!==Dn))for(const c of i){const{children:u=[]}=c;Md(u)}const s=this.context.getLastTimeTicket();let o=new Array;if(((h=i[0])==null?void 0:h.type)===Dn){let c="";for(const u of i){const{value:f}=u;c+=f}o.push(ut.create(Me.of(this.context.issueTimeTicket(),0),Dn,c))}else o=i.map(c=>c&&ev(this.context,c)).filter(c=>c);const[,a,l]=this.tree.edit([e,t],o.length?o.map(c=>c==null?void 0:c.deepcopy()):void 0,r,s,()=>this.context.issueTimeTicket());for(const c of a)this.context.registerGCPair(c);return this.context.push(Lo.create(this.tree.getCreatedAt(),e,t,o.length?o:void 0,r,l,s)),!0}editByPath(e,t,i,r=0){if(!this.context||!this.tree)throw new v(w.ErrNotInitialized,"Tree is not initialized yet");if(e.length!==t.length)throw new v(w.ErrInvalidArgument,"path length should be equal");if(!e.length||!t.length)throw new v(w.ErrInvalidArgument,"path should not be empty");const s=this.tree.pathToPos(e),o=this.tree.pathToPos(t);return this.editInternal(s,o,i?[i]:[],r)}editBulkByPath(e,t,i,r=0){if(!this.context||!this.tree)throw new v(w.ErrNotInitialized,"Tree is not initialized yet");if(e.length!==t.length)throw new v(w.ErrInvalidArgument,"path length should be equal");if(!e.length||!t.length)throw new v(w.ErrInvalidArgument,"path should not be empty");const s=this.tree.pathToPos(e),o=this.tree.pathToPos(t);return this.editInternal(s,o,i,r)}edit(e,t,i,r=0){if(!this.context||!this.tree)throw new v(w.ErrNotInitialized,"Tree is not initialized yet");if(e>t)throw new v(w.ErrInvalidArgument,"from should be less than or equal to to");const s=this.tree.findPos(e),o=this.tree.findPos(t);return this.editInternal(s,o,i?[i]:[],r)}editBulk(e,t,i,r=0){if(!this.context||!this.tree)throw new v(w.ErrNotInitialized,"Tree is not initialized yet");if(e>t)throw new v(w.ErrInvalidArgument,"from should be less than or equal to to");const s=this.tree.findPos(e),o=this.tree.findPos(t);return this.editInternal(s,o,i,r)}toXML(){if(!this.context||!this.tree)throw new v(w.ErrNotInitialized,"Tree is not initialized yet");return this.tree.toXML()}toJSON(){if(!this.context||!this.tree)throw new v(w.ErrNotInitialized,"Tree is not initialized yet");return this.tree.toJSON()}toJSForTest(){if(!this.context||!this.tree)throw new v(w.ErrNotInitialized,"Tree is not initialized yet");return this.tree.toJSForTest()}toJSInfoForTest(){if(!this.context||!this.tree)throw new v(w.ErrNotInitialized,"Tree is not initialized yet");return this.tree.toJSInfoForTest()}getRootTreeNode(){if(!this.context||!this.tree)throw new v(w.ErrNotInitialized,"Tree is not initialized yet");return this.tree.getRootTreeNode()}indexToPath(e){if(!this.context||!this.tree)throw new v(w.ErrNotInitialized,"Tree is not initialized yet");return this.tree.indexToPath(e)}pathToIndex(e){if(!this.context||!this.tree)throw new v(w.ErrNotInitialized,"Tree is not initialized yet");return this.tree.pathToIndex(e)}pathRangeToPosRange(e){if(!this.context||!this.tree)throw new v(w.ErrNotInitialized,"Tree is not initialized yet");const t=[this.tree.pathToIndex(e[0]),this.tree.pathToIndex(e[1])],i=this.tree.indexRangeToPosRange(t);return[i[0].toStruct(),i[1].toStruct()]}indexRangeToPosRange(e){if(!this.context||!this.tree)throw new v(w.ErrNotInitialized,"Tree is not initialized yet");return this.tree.indexRangeToPosStructRange(e)}posRangeToIndexRange(e){if(!this.context||!this.tree)throw new v(w.ErrNotInitialized,"Tree is not initialized yet");const t=[_t.fromStruct(e[0]),_t.fromStruct(e[1])];return this.tree.posRangeToIndexRange(t)}posRangeToPathRange(e){if(!this.context||!this.tree)throw new v(w.ErrNotInitialized,"Tree is not initialized yet");const t=[_t.fromStruct(e[0]),_t.fromStruct(e[1])];return this.tree.posRangeToPathRange(t)}};function Vd(n,e){return PO(n,e)}function _n(n,e){if(e){if(e instanceof pe)return e;if(e instanceof nt)return PO(n,e);if(e instanceof pt)return Yw(n,e);if(e instanceof qt)return new nh(n,e);if(e instanceof gt){const t=new rh(Pi.IntegerCnt,0);return t.initialize(n,e),t}else if(e instanceof Mt){const t=new sh;return t.initialize(n,e),t}}else return;throw new TypeError(`Unsupported type of element: ${typeof e}`)}function kr(n,e){const t=_n(n,e);return t instanceof pe?t.getValue():t}function wl(n,e,t){let i;if(pe.isSupport(e))i=pe.of(e,t);else if(Array.isArray(e))i=pt.create(t,me.buildArrayElements(n,e));else if(typeof e=="object")e instanceof nh?(i=qt.create(ps.create(),t),e.initialize(n,i)):e instanceof rh?(i=gt.create(e.getValueType(),e.getValue(),t),e.initialize(n,i)):e instanceof sh?(i=Mt.create(e.buildRoot(n),t),e.initialize(n,i)):i=nt.create(t,Oo.buildObjectMembers(n,e));else throw new TypeError(`Unsupported type of value: ${typeof e}`);return i}const Xd=50;class tv{constructor(){d(this,"undoStack",[]);d(this,"redoStack",[])}hasUndo(){return this.undoStack.length>0}hasRedo(){return this.redoStack.length>0}pushUndo(e){this.undoStack.length>=Xd&&this.undoStack.shift(),this.undoStack.push(e)}popUndo(){return this.undoStack.pop()}pushRedo(e){this.redoStack.length>=Xd&&this.redoStack.shift(),this.redoStack.push(e)}popRedo(){return this.redoStack.pop()}clearRedo(){this.redoStack=[]}getUndoStackForTest(){return this.undoStack}getRedoStackForTest(){return this.redoStack}}const iv="yorkie-devtools-panel",nv="yorkie-devtools-sdk";let Fr="disconnected";const Ld=new Map,qa=new Map;typeof window<"u"&&(window.transactionEventsByDocKey=qa);function na(n,e){(e!=null&&e.force||Fr!=="disconnected")&&window.postMessage({source:nv,...n},"*")}function rv(n){if(!n.isEnableDevtools()||typeof window>"u"||Ld.has(n.getKey()))return;qa.set(n.getKey(),[]);const e=n.subscribe("all",t=>{t.some(i=>i.type!==_e.StatusChanged&&i.type!==_e.Snapshot&&i.type!==_e.LocalChange&&i.type!==_e.RemoteChange&&i.type!==_e.Initialized&&i.type!==_e.Watched&&i.type!==_e.Unwatched&&i.type!==_e.PresenceChanged)||(qa.get(n.getKey()).push(t),Fr==="synced"&&na({msg:"doc::sync::partial",docKey:n.getKey(),event:t}))});Ld.set(n.getKey(),[e]),na({msg:"refresh-devtools"},{force:!0}),window.addEventListener("message",t=>{var r;if(((r=t.data)==null?void 0:r.source)!==iv)return;switch(t.data.msg){case"devtools::connect":if(Fr!=="disconnected")break;Fr="connected",na({msg:"doc::available",docKey:n.getKey()}),U.info(`[YD] Devtools connected. Doc: ${n.getKey()}`);break;case"devtools::disconnect":Fr="disconnected",U.info(`[YD] Devtools disconnected. Doc: ${n.getKey()}`);break;case"devtools::subscribe":Fr="synced",na({msg:"doc::sync::full",docKey:n.getKey(),events:qa.get(n.getKey())}),U.info(`[YD] Devtools subscribed. Doc: ${n.getKey()}`);break}})}var Gn=(n=>(n.Detached="detached",n.Attached="attached",n.Removed="removed",n))(Gn||{}),_e=(n=>(n.StatusChanged="status-changed",n.ConnectionChanged="connection-changed",n.SyncStatusChanged="sync-status-changed",n.Snapshot="snapshot",n.LocalChange="local-change",n.RemoteChange="remote-change",n.Initialized="initialized",n.Watched="watched",n.Unwatched="unwatched",n.PresenceChanged="presence-changed",n.Broadcast="broadcast",n.LocalBroadcast="local-broadcast",n))(_e||{}),yo=(n=>(n.Connected="connected",n.Disconnected="disconnected",n))(yo||{}),Lc=(n=>(n.Synced="synced",n.SyncFailed="sync-failed",n))(Lc||{});class $O{constructor(e,t){d(this,"key");d(this,"status");d(this,"opts");d(this,"changeID");d(this,"checkpoint");d(this,"localChanges");d(this,"root");d(this,"clone");d(this,"eventStream");d(this,"eventStreamObserver");d(this,"onlineClients");d(this,"presences");d(this,"history");d(this,"internalHistory");d(this,"isUpdating");this.opts=t||{},this.key=e,this.status="detached",this.root=mo.create(),this.changeID=aw,this.checkpoint=lw,this.localChanges=[],this.eventStream=Jw(i=>{this.eventStreamObserver=i}),this.onlineClients=new Set,this.presences=new Map,this.isUpdating=!1,this.internalHistory=new tv,this.history={canUndo:this.canUndo.bind(this),canRedo:this.canRedo.bind(this),undo:this.undo.bind(this),redo:this.redo.bind(this)},rv(this)}update(e,t){if(this.getStatus()==="removed")throw new v(w.ErrDocumentRemoved,`${this.key} is removed`);this.ensureClone();const i=this.changeID.getActorID(),r=Jr.create(this.changeID.next(),this.clone.root,this.clone.presences.get(i)||{},t);try{const s=Vd(r,this.clone.root.getObject());this.presences.has(i)||this.clone.presences.set(i,{}),this.isUpdating=!0,e(s,new Ph(r,this.clone.presences.get(i)))}catch(s){throw this.clone=void 0,s}finally{this.isUpdating=!1}if(r.hasChange()){U.isEnabled(Ge.Trivial)&&U.trivial(`trying to update a local change: ${this.toJSON()}`);const s=r.getChange(),{opInfos:o,reverseOps:a}=s.execute(this.root,this.presences,se.Local),l=r.getReversePresence();l&&a.push({type:"presence",value:l}),this.localChanges.push(s),a.length>0&&this.internalHistory.pushUndo(a),o.length>0&&this.internalHistory.clearRedo(),this.changeID=s.getID();const h=[];o.length>0&&h.push({type:"local-change",source:se.Local,value:{message:s.getMessage()||"",operations:o,actor:i,clientSeq:s.getID().getClientSeq(),serverSeq:s.getID().getServerSeq()},rawChange:this.isEnableDevtools()?s.toStruct():void 0}),s.hasPresenceChange()&&h.push({type:"presence-changed",source:se.Local,value:{clientID:i,presence:this.getPresence(i)}}),this.publish(h),U.isEnabled(Ge.Trivial)&&U.trivial(`after update a local change: ${this.toJSON()}`)}}subscribe(e,t,i,r){if(typeof e=="string"){if(typeof t!="function")throw new v(w.ErrInvalidArgument,"Second argument must be a callback function");if(e==="presence"){const a=t;return this.eventStream.subscribe(l=>{for(const h of l)h.type!=="initialized"&&h.type!=="watched"&&h.type!=="unwatched"&&h.type!=="presence-changed"||a(h)},i,r)}if(e==="my-presence"){const a=t;return this.eventStream.subscribe(l=>{for(const h of l)h.type!=="initialized"&&h.type!=="presence-changed"||h.type==="presence-changed"&&h.value.clientID!==this.changeID.getActorID()||a(h)},i,r)}if(e==="others"){const a=t;return this.eventStream.subscribe(l=>{for(const h of l)h.type!=="watched"&&h.type!=="unwatched"&&h.type!=="presence-changed"||h.value.clientID!==this.changeID.getActorID()&&a(h)},i,r)}if(e==="connection"){const a=t;return this.eventStream.subscribe(l=>{for(const h of l)h.type==="connection-changed"&&a(h)},i,r)}if(e==="status"){const a=t;return this.eventStream.subscribe(l=>{for(const h of l)h.type==="status-changed"&&a(h)},i,r)}if(e==="sync"){const a=t;return this.eventStream.subscribe(l=>{for(const h of l)h.type==="sync-status-changed"&&a(h)},i,r)}if(e==="local-broadcast"){const a=t;return this.eventStream.subscribe(l=>{for(const h of l)h.type==="local-broadcast"&&a(h)},i)}if(e==="broadcast"){const a=t;return this.eventStream.subscribe(l=>{for(const h of l)h.type==="broadcast"&&a(h)},i)}if(e==="all"){const a=t;return this.eventStream.subscribe(a,i,r)}const s=e,o=t;return this.eventStream.subscribe(a=>{for(const l of a){if(l.type!=="local-change"&&l.type!=="remote-change")continue;const h=[];for(const c of l.value.operations)this.isSameElementOrChildOf(c.path,s)&&h.push(c);h.length&&o({...l,value:{...l.value,operations:h}})}},i,r)}if(typeof e=="function"){const s=e,o=t,a=i;return this.eventStream.subscribe(l=>{for(const h of l)h.type!=="snapshot"&&h.type!=="local-change"&&h.type!=="remote-change"||s(h)},o,a)}throw new v(w.ErrInvalidArgument,`"${e}" is not a valid`)}publish(e){this.eventStreamObserver&&this.eventStreamObserver.next(e)}isSameElementOrChildOf(e,t){if(t===e)return!0;const i=e.split(".");return t.split(".").every((s,o)=>s===i[o])}removePushedLocalChanges(e){for(;this.localChanges.length&&!(this.localChanges[0].getID().getClientSeq()>e);)this.localChanges.shift()}applyChangePack(e){const t=e.hasSnapshot();t?this.applySnapshot(e.getCheckpoint().getServerSeq(),e.getVersionVector(),e.getSnapshot(),e.getCheckpoint().getClientSeq()):(this.applyChanges(e.getChanges(),se.Remote),this.removePushedLocalChanges(e.getCheckpoint().getClientSeq())),this.checkpoint=this.checkpoint.forward(e.getCheckpoint()),t||this.garbageCollect(e.getVersionVector()),t||this.filterVersionVector(e.getVersionVector()),e.getIsRemoved()&&this.applyStatus("removed"),U.isEnabled(Ge.Trivial)&&U.trivial(`${this.root.toJSON()}`)}getCheckpoint(){return this.checkpoint}getChangeID(){return this.changeID}hasLocalChanges(){return this.localChanges.length>0}ensureClone(){this.clone||(this.clone={root:this.root.deepcopy(),presences:Wt(this.presences)})}createChangePack(){const e=Array.from(this.localChanges),t=this.checkpoint.increaseClientSeq(e.length);return ih.create(this.key,t,!1,e,this.getVersionVector())}setActor(e){for(const t of this.localChanges)t.setActor(e);this.changeID=this.changeID.setActor(e)}isEnableDevtools(){return!!this.opts.enableDevtools}getKey(){return this.key}getStatus(){return this.status}getCloneRoot(){if(this.clone)return this.clone.root.getObject()}getRoot(){this.ensureClone();const e=Jr.create(this.changeID.next(),this.clone.root,this.clone.presences.get(this.changeID.getActorID())||{});return Vd(e,this.clone.root.getObject())}garbageCollect(e){return this.opts.disableGC?0:(this.clone&&this.clone.root.garbageCollect(e),this.root.garbageCollect(e))}getRootObject(){return this.root.getObject()}getGarbageLen(){return this.root.getGarbageLen()}getGarbageLenFromClone(){return this.clone.root.getGarbageLen()}toJSON(){return this.root.toJSON()}toSortedJSON(){return this.root.toSortedJSON()}getStats(){return this.root.getStats()}toJSForTest(){return{...this.getRoot().toJSForTest(),key:"root"}}applySnapshot(e,t,i,r=-1){const{root:s,presences:o}=we.bytesToSnapshot(i);this.root=new mo(s),this.presences=o,this.changeID=this.changeID.setClocks(e,t),this.clone=void 0,this.removePushedLocalChanges(r),this.applyChanges(this.localChanges,se.Local),this.publish([{type:"snapshot",source:se.Remote,value:{serverSeq:e.toString(),snapshot:this.isEnableDevtools()?we.bytesToHex(i):void 0,snapshotVector:we.versionVectorToHex(t)}}])}applyChanges(e,t){U.isEnabled(Ge.Debug)&&U.debug(`trying to apply ${e.length} remote changes.elements:${this.root.getElementMapSize()}, removeds:${this.root.getGarbageElementSetSize()}`),U.isEnabled(Ge.Trivial)&&U.trivial(e.map(i=>`${i.getID().toTestString()} ${i.toTestString()}`).join(` `));for(const i of e)this.applyChange(i,t);U.isEnabled(Ge.Debug)&&U.debug(`after appling ${e.length} remote changes.elements:${this.root.getElementMapSize()}, removeds:${this.root.getGarbageElementSetSize()}`)}applyChange(e,t){this.ensureClone(),e.execute(this.clone.root,this.clone.presences,t);const i=[],r=e.getID().getActorID();if(e.hasPresenceChange()&&this.onlineClients.has(r)){const o=e.getPresenceChange();switch(o.type){case cr.Put:i.push(this.presences.has(r)?{type:"presence-changed",source:t,value:{clientID:r,presence:o.presence}}:{type:"watched",source:se.Remote,value:{clientID:r,presence:o.presence}});break;case cr.Clear:i.push({type:"unwatched",source:se.Remote,value:{clientID:r,presence:this.getPresence(r)}}),this.removeOnlineClient(r);break}}const{opInfos:s}=e.execute(this.root,this.presences,t);if(this.changeID=this.changeID.syncClocks(e.getID()),s.length>0){const o=this.isEnableDevtools()?e.toStruct():void 0;i.push(t===se.Remote?{type:"remote-change",source:t,value:{actor:r,clientSeq:e.getID().getClientSeq(),serverSeq:e.getID().getServerSeq(),message:e.getMessage()||"",operations:s},rawChange:o}:{type:"local-change",source:t,value:{actor:r,clientSeq:e.getID().getClientSeq(),serverSeq:e.getID().getServerSeq(),message:e.getMessage()||"",operations:s},rawChange:o})}i.length>0&&this.publish(i)}applyWatchStream(e){if(e.body.case==="initialization"){const t=e.body.value.clientIds,i=new Set;for(const r of t)r!==this.changeID.getActorID()&&i.add(r);this.setOnlineClients(i),this.publish([{type:"initialized",source:se.Local,value:this.getPresences()}]);return}if(e.body.case==="event"){const{type:t,publisher:i}=e.body.value,r=[];if(t===Rr.DOCUMENT_WATCHED){if(this.onlineClients.has(i)&&this.hasPresence(i))return;this.addOnlineClient(i),this.hasPresence(i)&&r.push({type:"watched",source:se.Remote,value:{clientID:i,presence:this.getPresence(i)}})}else if(t===Rr.DOCUMENT_UNWATCHED){const s=this.getPresence(i);this.removeOnlineClient(i),s&&r.push({type:"unwatched",source:se.Remote,value:{clientID:i,presence:s}})}else if(t===Rr.DOCUMENT_BROADCAST&&e.body.value.body){const{topic:s,payload:o}=e.body.value.body,a=new TextDecoder;r.push({type:"broadcast",value:{clientID:i,topic:s,payload:JSON.parse(a.decode(o))}})}r.length>0&&this.publish(r)}}applyStatus(e){this.status=e,e==="detached"&&this.setActor(zu),this.publish([{source:e==="removed"?se.Remote:se.Local,type:"status-changed",value:e==="attached"?{status:e,actorID:this.changeID.getActorID()}:{status:e}}])}applyDocEvent(e){if(e.type==="status-changed"){this.applyStatus(e.value.status),e.value.status==="attached"&&this.setActor(e.value.actorID);return}if(e.type==="snapshot"){const{snapshot:t,serverSeq:i,snapshotVector:r}=e.value;if(!t)return;this.applySnapshot(BigInt(i),we.hexToVersionVector(r),we.hexToBytes(t));return}if(e.type==="local-change"||e.type==="remote-change"){if(!e.rawChange)return;const t=ds.fromStruct(e.rawChange);this.applyChange(t,e.source)}if(e.type==="initialized"){const t=new Set;for(const{clientID:i,presence:r}of e.value)t.add(i),this.presences.set(i,r);this.setOnlineClients(t);return}if(e.type==="watched"){const{clientID:t,presence:i}=e.value;this.addOnlineClient(t),this.presences.set(t,i);return}if(e.type==="unwatched"){const{clientID:t}=e.value;this.removeOnlineClient(t),this.presences.delete(t)}if(e.type==="presence-changed"){const{clientID:t,presence:i}=e.value;this.presences.set(t,i)}}applyTransactionEvent(e){for(const t of e)this.applyDocEvent(t)}getValueByPath(e){if(!e.startsWith("$"))throw new v(w.ErrInvalidArgument,'path must start with "$"');const t=e.split(".");t.shift();let i=this.getRoot();for(const r of t)if(i=i[r],i===void 0)return;return i}setOnlineClients(e){this.onlineClients=e}resetOnlineClients(){this.onlineClients=new Set}addOnlineClient(e){this.onlineClients.add(e)}removeOnlineClient(e){this.onlineClients.delete(e)}hasPresence(e){return this.presences.has(e)}getMyPresence(){if(this.status!=="attached")return{};const e=this.presences.get(this.changeID.getActorID());return e?Wt(e):{}}getPresence(e){if(e===this.changeID.getActorID())return this.getMyPresence();if(!this.onlineClients.has(e))return;const t=this.presences.get(e);return t?Wt(t):void 0}getPresenceForTest(e){const t=this.presences.get(e);return t?Wt(t):void 0}getPresences(){const e=[];e.push({clientID:this.changeID.getActorID(),presence:Wt(this.getMyPresence())});for(const t of this.onlineClients)this.presences.has(t)&&e.push({clientID:t,presence:Wt(this.presences.get(t))});return e}getSelfForTest(){return{clientID:this.getChangeID().getActorID(),presence:this.getMyPresence()}}getOthersForTest(){const e=this.getChangeID().getActorID();return this.getPresences().filter(t=>t.clientID!==e).sort((t,i)=>t.clientID>i.clientID?1:-1)}canUndo(){return this.internalHistory.hasUndo()&&!this.isUpdating}filterVersionVector(e){const i=this.changeID.getVersionVector().filter(e);this.changeID=this.changeID.setVersionVector(i)}canRedo(){return this.internalHistory.hasRedo()&&!this.isUpdating}undo(){if(this.isUpdating)throw new v(w.ErrRefused,"Undo is not allowed during an update");const e=this.internalHistory.popUndo();if(e===void 0)throw new v(w.ErrRefused,"There is no operation to be undone");this.ensureClone();const t=Jr.create(this.changeID.next(),this.clone.root,this.clone.presences.get(this.changeID.getActorID())||{});for(const h of e){if(!(h instanceof Yt)){new Ph(t,Wt(this.clone.presences.get(this.changeID.getActorID()))).set(h.value,{addToHistory:!0});continue}const c=t.issueTimeTicket();h.setExecutedAt(c),t.push(h)}const i=t.getChange();i.execute(this.clone.root,this.clone.presences,se.UndoRedo);const{opInfos:r,reverseOps:s}=i.execute(this.root,this.presences,se.UndoRedo),o=t.getReversePresence();if(o&&s.push({type:"presence",value:o}),s.length>0&&this.internalHistory.pushRedo(s),!i.hasPresenceChange()&&r.length===0)return;this.localChanges.push(i),this.changeID=i.getID();const a=this.changeID.getActorID(),l=[];r.length>0&&l.push({type:"local-change",source:se.UndoRedo,value:{message:i.getMessage()||"",operations:r,actor:a,clientSeq:i.getID().getClientSeq(),serverSeq:i.getID().getServerSeq()},rawChange:this.isEnableDevtools()?i.toStruct():void 0}),i.hasPresenceChange()&&l.push({type:"presence-changed",source:se.UndoRedo,value:{clientID:a,presence:this.getPresence(a)}}),this.publish(l)}redo(){if(this.isUpdating)throw new v(w.ErrRefused,"Redo is not allowed during an update");const e=this.internalHistory.popRedo();if(e===void 0)throw new v(w.ErrRefused,"There is no operation to be redone");this.ensureClone();const t=Jr.create(this.changeID.next(),this.clone.root,this.clone.presences.get(this.changeID.getActorID())||{});for(const h of e){if(!(h instanceof Yt)){new Ph(t,Wt(this.clone.presences.get(this.changeID.getActorID()))).set(h.value,{addToHistory:!0});continue}const c=t.issueTimeTicket();h.setExecutedAt(c),t.push(h)}const i=t.getChange();i.execute(this.clone.root,this.clone.presences,se.UndoRedo);const{opInfos:r,reverseOps:s}=i.execute(this.root,this.presences,se.UndoRedo),o=t.getReversePresence();if(o&&s.push({type:"presence",value:o}),s.length>0&&this.internalHistory.pushUndo(s),!i.hasPresenceChange()&&r.length===0)return;this.localChanges.push(i),this.changeID=i.getID();const a=this.changeID.getActorID(),l=[];r.length>0&&l.push({type:"local-change",source:se.UndoRedo,value:{message:i.getMessage()||"",operations:r,actor:a,clientSeq:i.getID().getClientSeq(),serverSeq:i.getID().getServerSeq()},rawChange:this.isEnableDevtools()?i.toStruct():void 0}),i.hasPresenceChange()&&l.push({type:"presence-changed",source:se.UndoRedo,value:{clientID:a,presence:this.getPresence(a)}}),this.publish(l)}getUndoStackForTest(){return this.internalHistory.getUndoStackForTest()}getRedoStackForTest(){return this.internalHistory.getRedoStackForTest()}broadcast(e,t,i){const r={type:"local-broadcast",value:{topic:e,payload:t},options:i};this.publish([r])}getVersionVector(){return this.changeID.getVersionVector()}}function sv(n,e){return t=>async i=>(n&&i.header.set("x-api-key",n),e&&i.header.set("authorization",e),await t(i))}const ov="yorkie-js-sdk",av="0.5.4",lv="Yorkie JS SDK",hv="./src/yorkie.ts",cv={access:"public",main:"./dist/yorkie-js-sdk.js",typings:"./dist/yorkie-js-sdk.d.ts"},uv=["dist"],fv={build:"tsc && vite build","build:proto":"npx buf generate","build:docs":"typedoc","build:ghpages":"mkdir -p ghpages/examples && cp -r docs ghpages/api-reference && find ../../examples -name 'dist' -type d -exec sh -c 'cp -r {} ghpages/examples/$(basename $(dirname {}))' \\;",dev:"vite build -c vite.preview.ts && vite preview",test:"vitest run","test:watch":"vitest","test:bench":"vitest bench","test:ci":"vitest run --coverage","test:yorkie.dev":"TEST_RPC_ADDR=https://api.yorkie.dev vitest run --coverage",prepare:"pnpm build"},dv={node:">=18.0.0",npm:">=7.1.0"},pv={type:"git",url:"git+https://github.com/yorkie-team/yorkie-js-sdk.git"},gv={name:"hackerwins",email:"susukang98@gmail.com"},mv="Apache-2.0",Ov={url:"https://github.com/yorkie-team/yorkie-js-sdk/issues"},yv="https://github.com/yorkie-team/yorkie-js-sdk#readme",bv={"@buf/googleapis_googleapis.bufbuild_es":"^1.4.0-20240524201209-f0e53af8f2fc.3","@bufbuild/buf":"^1.28.1","@bufbuild/protoc-gen-es":"^1.6.0","@connectrpc/protoc-gen-connect-es":"^1.4.0","@types/google-protobuf":"^3.15.5","@types/long":"^4.0.1","@typescript-eslint/eslint-plugin":"^6.21.0","@typescript-eslint/parser":"^6.21.0","@vitest/coverage-istanbul":"^0.34.5","@vitest/coverage-v8":"^0.34.5","eslint-plugin-tsdoc":"^0.2.16",prettier:"^2.7.1","ts-node":"^10.9.1",typedoc:"^0.25.13",typescript:"^5.3.3","typescript-transform-paths":"^3.3.1",vite:"^5.0.12","vite-plugin-commonjs":"^0.10.1","vite-plugin-dts":"^3.9.1","vite-tsconfig-paths":"^4.2.1",vitest:"^0.34.5"},Sv={"@bufbuild/protobuf":"^1.6.0","@connectrpc/connect":"^1.4.0","@connectrpc/connect-web":"^1.4.0",long:"^5.2.0"},Ud={name:ov,version:av,description:lv,main:hv,publishConfig:cv,files:uv,scripts:fv,engines:dv,repository:pv,author:gv,license:mv,bugs:Ov,homepage:yv,devDependencies:bv,dependencies:Sv};function wv(){return n=>async e=>(e.header.set("x-yorkie-user-agent",Ud.name+"/"+Ud.version),await n(e))}const vv=n=>{try{if(JSON.stringify(n)===void 0)return!1}catch{return!1}return!0};var Ma=(n=>(n.Manual="manual",n.Realtime="realtime",n.RealtimePushOnly="realtime-pushonly",n.RealtimeSyncOff="realtime-syncoff",n))(Ma||{});const ra={syncLoopDuration:50,retrySyncLoopDelay:1e3,reconnectStreamDelay:1e3},Ih={maxRetries:1/0,initialRetryInterval:1e3,maxBackoff:2e4};class CO{constructor(e,t){d(this,"id");d(this,"key");d(this,"status");d(this,"attachmentMap");d(this,"apiKey");d(this,"conditions");d(this,"syncLoopDuration");d(this,"reconnectStreamDelay");d(this,"retrySyncLoopDelay");d(this,"rpcClient");d(this,"taskQueue");d(this,"processing",!1);t=t||ra,this.key=t.key?t.key:QO(),this.status="deactivated",this.attachmentMap=new Map,this.apiKey=t.apiKey||"",this.conditions={SyncLoop:!1,WatchLoop:!1},this.syncLoopDuration=t.syncLoopDuration||ra.syncLoopDuration,this.reconnectStreamDelay=t.reconnectStreamDelay||ra.reconnectStreamDelay,this.retrySyncLoopDelay=t.retrySyncLoopDelay||ra.retrySyncLoopDelay,this.rpcClient=y1(L1,X1({baseUrl:e,interceptors:[sv(t.apiKey,t.token),wv()]})),this.taskQueue=[]}activate(){return this.isActive()?Promise.resolve():this.enqueueTask(async()=>this.rpcClient.activateClient({clientKey:this.key},{headers:{"x-shard-key":this.apiKey}}).then(e=>{this.id=e.clientId,this.status="activated",this.runSyncLoop(),U.info(`[AC] c:"${this.getKey()}" activated, id:"${this.id}"`)}).catch(e=>{throw U.error(`[AC] c:"${this.getKey()}" err :`,e),this.handleConnectError(e),e}))}deactivate(){return this.status==="deactivated"?Promise.resolve():this.enqueueTask(async()=>this.rpcClient.deactivateClient({clientId:this.id},{headers:{"x-shard-key":this.apiKey}}).then(()=>{this.deactivateInternal(),U.info(`[DC] c"${this.getKey()}" deactivated`)}).catch(e=>{throw U.error(`[DC] c:"${this.getKey()}" err :`,e),this.handleConnectError(e),e}))}attach(e,t={}){if(!this.isActive())throw new v(w.ErrClientNotActivated,`${this.key} is not active`);if(e.getStatus()!==Gn.Detached)throw new v(w.ErrDocumentNotDetached,`${e.getKey()} is not detached`);e.setActor(this.id),e.update((s,o)=>o.set(t.initialPresence||{}));const i=e.subscribe("local-broadcast",async s=>{var c;const{topic:o,payload:a}=s.value,l=(c=s.options)==null?void 0:c.error,h=s.options;try{await this.broadcast(e.getKey(),o,a,h)}catch(u){u instanceof Error&&(l==null||l(u))}}),r=t.syncMode??"realtime";return this.enqueueTask(async()=>this.rpcClient.attachDocument({clientId:this.id,changePack:we.toChangePack(e.createChangePack())},{headers:{"x-shard-key":`${this.apiKey}/${e.getKey()}`}}).then(async s=>{const o=we.fromChangePack(s.changePack);if(e.applyChangePack(o),e.getStatus()===Gn.Removed)return e;e.applyStatus(Gn.Attached),this.attachmentMap.set(e.getKey(),new _w(this.reconnectStreamDelay,e,s.documentId,r,i)),r!=="manual"&&await this.runWatchLoop(e.getKey()),U.info(`[AD] c:"${this.getKey()}" attaches d:"${e.getKey()}"`);const a=e.getRootObject();if(t.initialRoot){const l=t.initialRoot;e.update(h=>{for(const[c,u]of Object.entries(l))if(!a.has(c)){const f=c;h[f]=u}})}return e}).catch(s=>{throw U.error(`[AD] c:"${this.getKey()}" err :`,s),this.handleConnectError(s),s}))}detach(e,t={}){if(!this.isActive())throw new v(w.ErrClientNotActivated,`${this.key} is not active`);const i=this.attachmentMap.get(e.getKey());if(!i)throw new v(w.ErrDocumentNotAttached,`${e.getKey()} is not attached`);return e.update((r,s)=>s.clear()),this.enqueueTask(async()=>this.rpcClient.detachDocument({clientId:this.id,documentId:i.docID,changePack:we.toChangePack(e.createChangePack()),removeIfNotAttached:t.removeIfNotAttached??!1},{headers:{"x-shard-key":`${this.apiKey}/${e.getKey()}`}}).then(r=>{const s=we.fromChangePack(r.changePack);return e.applyChangePack(s),e.getStatus()!==Gn.Removed&&e.applyStatus(Gn.Detached),this.detachInternal(e.getKey()),U.info(`[DD] c:"${this.getKey()}" detaches d:"${e.getKey()}"`),e}).catch(r=>{throw U.error(`[DD] c:"${this.getKey()}" err :`,r),this.handleConnectError(r),r}))}async changeSyncMode(e,t){if(!this.isActive())throw new v(w.ErrClientNotActivated,`${this.key} is not active`);const i=this.attachmentMap.get(e.getKey());if(!i)throw new v(w.ErrDocumentNotAttached,`${e.getKey()} is not attached`);const r=i.syncMode;return r===t?e:(i.changeSyncMode(t),t==="manual"?(i.cancelWatchStream(),e):(t==="realtime"&&(i.remoteChangeEventReceived=!0),r==="manual"&&await this.runWatchLoop(e.getKey()),e))}sync(e){if(!this.isActive())throw new v(w.ErrClientNotActivated,`${this.key} is not active`);if(e){const t=this.attachmentMap.get(e.getKey());if(!t)throw new v(w.ErrDocumentNotAttached,`${e.getKey()} is not attached`);return this.enqueueTask(async()=>this.syncInternal(t,"realtime").catch(i=>{throw U.error(`[SY] c:"${this.getKey()}" err :`,i),this.handleConnectError(i),i}))}return this.enqueueTask(async()=>{const t=[];for(const[,i]of this.attachmentMap)t.push(this.syncInternal(i,i.syncMode));return Promise.all(t).catch(i=>{throw U.error(`[SY] c:"${this.getKey()}" err :`,i),this.handleConnectError(i),i})})}remove(e){if(!this.isActive())throw new v(w.ErrClientNotActivated,`${this.key} is not active`);const t=this.attachmentMap.get(e.getKey());if(!t)throw new v(w.ErrDocumentNotAttached,`${e.getKey()} is not attached`);e.setActor(this.id);const i=we.toChangePack(e.createChangePack());return i.isRemoved=!0,this.enqueueTask(async()=>this.rpcClient.removeDocument({clientId:this.id,documentId:t.docID,changePack:i},{headers:{"x-shard-key":`${this.apiKey}/${e.getKey()}`}}).then(r=>{const s=we.fromChangePack(r.changePack);e.applyChangePack(s),this.detachInternal(e.getKey()),U.info(`[RD] c:"${this.getKey()}" removes d:"${e.getKey()}"`)}).catch(r=>{throw U.error(`[RD] c:"${this.getKey()}" err :`,r),this.handleConnectError(r),r}))}getID(){return this.id}getKey(){return this.key}isActive(){return this.status==="activated"}getStatus(){return this.status}getCondition(e){return this.conditions[e]}broadcast(e,t,i,r){if(!this.isActive())throw new v(w.ErrClientNotActivated,`${this.key} is not active`);const s=this.attachmentMap.get(e);if(!s)throw new v(w.ErrDocumentNotAttached,`${e} is not attached`);if(!vv(i))throw new v(w.ErrInvalidArgument,"payload is not serializable");const o=(r==null?void 0:r.maxRetries)??Ih.maxRetries,a=Ih.maxBackoff;let l=0;const h=u=>Math.min(Ih.initialRetryInterval*2**u,a),c=async()=>this.enqueueTask(async()=>this.rpcClient.broadcast({clientId:this.id,documentId:s.docID,topic:t,payload:new TextEncoder().encode(JSON.stringify(i))},{headers:{"x-shard-key":`${this.apiKey}/${e}`}}).then(()=>{U.info(`[BC] c:"${this.getKey()}" broadcasts d:"${e}" t:"${t}"`)}).catch(u=>{if(U.error(`[BC] c:"${this.getKey()}" err:`,u),this.handleConnectError(u))if(lc(),h(l-1)),U.info(`[BC] c:"${this.getKey()}" retry attempt ${l}/${o}`);else throw U.error(`[BC] c:"${this.getKey()}" exceeded maximum retry attempts`),u;else throw u}));return c()}runSyncLoop(){const e=()=>{if(!this.isActive()){U.debug(`[SL] c:"${this.getKey()}" exit sync loop`),this.conditions.SyncLoop=!1;return}const t=[];for(const[,i]of this.attachmentMap)i.needRealtimeSync()&&(i.remoteChangeEventReceived=!1,t.push(this.syncInternal(i,i.syncMode)));Promise.all(t).then(()=>setTimeout(e,this.syncLoopDuration)).catch(i=>{U.error(`[SL] c:"${this.getKey()}" sync failed:`,i),this.handleConnectError(i)?setTimeout(e,this.retrySyncLoopDelay):this.conditions.SyncLoop=!1})};U.debug(`[SL] c:"${this.getKey()}" run sync loop`),this.conditions.SyncLoop=!0,e()}async runWatchLoop(e){const t=this.attachmentMap.get(e);if(!t)throw new v(w.ErrDocumentNotAttached,`${e} is not attached`);return this.conditions.WatchLoop=!0,t.runWatchLoop(i=>{if(!this.isActive())return this.conditions.WatchLoop=!1,Promise.reject(new v(w.ErrClientNotActivated,`${this.key} is not active`));const r=new AbortController,s=this.rpcClient.watchDocument({clientId:this.id,documentId:t.docID},{headers:{"x-shard-key":`${this.apiKey}/${e}`},signal:r.signal});return t.doc.publish([{type:_e.ConnectionChanged,value:yo.Connected}]),U.info(`[WD] c:"${this.getKey()}" watches d:"${e}"`),new Promise((o,a)=>{(async()=>{try{for await(const h of s)this.handleWatchDocumentsResponse(t,h),h.body.case==="initialization"&&o([s,r])}catch(h){t.doc.resetOnlineClients(),t.doc.publish([{type:_e.Initialized,source:se.Local,value:t.doc.getPresences()}]),t.doc.publish([{type:_e.ConnectionChanged,value:yo.Disconnected}]),U.debug(`[WD] c:"${this.getKey()}" unwatches`),this.handleConnectError(h)?i():this.conditions.WatchLoop=!1,a(h)}})()})})}handleWatchDocumentsResponse(e,t){if(t.body.case==="event"&&t.body.value.type===Rr.DOCUMENT_CHANGED){e.remoteChangeEventReceived=!0;return}e.doc.applyWatchStream(t)}deactivateInternal(){this.status="deactivated";for(const[e,t]of this.attachmentMap)this.detachInternal(e),t.doc.applyStatus(Gn.Detached)}detachInternal(e){const t=this.attachmentMap.get(e);t&&(t.cancelWatchStream(),t.unsubscribeBroadcastEvent(),this.attachmentMap.delete(e))}syncInternal(e,t){const{doc:i,docID:r}=e,s=i.createChangePack();return this.rpcClient.pushPullChanges({clientId:this.id,documentId:r,changePack:we.toChangePack(s),pushOnly:t==="realtime-pushonly"},{headers:{"x-shard-key":`${this.apiKey}/${i.getKey()}`}}).then(o=>{const a=we.fromChangePack(o.changePack);if(a.hasChanges()&&(e.syncMode==="realtime-pushonly"||e.syncMode==="realtime-syncoff"))return i;i.applyChangePack(a),e.doc.publish([{type:_e.SyncStatusChanged,value:Lc.Synced}]),i.getStatus()===Gn.Removed&&this.detachInternal(i.getKey());const l=i.getKey(),h=a.getChangeSize();return U.info(`[PP] c:"${this.getKey()}" sync d:"${l}", push:${s.getChangeSize()} pull:${h} cp:${a.getCheckpoint().toTestString()}`),i}).catch(o=>{throw i.publish([{type:_e.SyncStatusChanged,value:Lc.SyncFailed}]),U.error(`[PP] c:"${this.getKey()}" err :`,o),o})}handleConnectError(e){return e instanceof Te?e.code===ie.Canceled||e.code===ie.Unknown||e.code===ie.ResourceExhausted||e.code===ie.Unavailable?!0:((qd(e)===w.ErrClientNotActivated||qd(e)===w.ErrClientNotFound)&&this.deactivateInternal(),!1):!1}enqueueTask(e){return new Promise((t,i)=>{this.taskQueue.push(()=>e().then(t).catch(i)),this.processing||this.processNext()})}async processNext(){if(this.taskQueue.length===0){this.processing=!1;return}try{this.processing=!0,await this.taskQueue.shift()()}catch{U.error(`[TQ] c:"${this.getKey()}" process failed, id:"${this.id}"`)}this.processNext()}}const Rh={Client:CO,Document:$O,Primitive:pe,Text:nh,Counter:rh,Tree:sh,LogLevel:Ge,setLogLevel:TO,IntType:Pi.IntegerCnt,LongType:Pi.LongCnt};typeof globalThis<"u"&&(globalThis.yorkie={Client:CO,Document:$O,Primitive:pe,Text:nh,Counter:rh,Tree:sh,LogLevel:Ge,setLogLevel:TO,IntType:Pi.IntegerCnt,LongType:Pi.LongCnt});class K{lineAt(e){if(e<0||e>this.length)throw new RangeError(`Invalid position ${e} in document of length ${this.length}`);return this.lineInner(e,!1,1,0)}line(e){if(e<1||e>this.lines)throw new RangeError(`Invalid line number ${e} in ${this.lines}-line document`);return this.lineInner(e,!0,1,0)}replace(e,t,i){[e,t]=ms(this,e,t);let r=[];return this.decompose(0,e,r,2),i.length&&i.decompose(0,i.length,r,3),this.decompose(t,this.length,r,1),ui.from(r,this.length-(t-e)+i.length)}append(e){return this.replace(this.length,this.length,e)}slice(e,t=this.length){[e,t]=ms(this,e,t);let i=[];return this.decompose(e,t,i,0),ui.from(i,t-e)}eq(e){if(e==this)return!0;if(e.length!=this.length||e.lines!=this.lines)return!1;let t=this.scanIdentical(e,1),i=this.length-this.scanIdentical(e,-1),r=new eo(this),s=new eo(e);for(let o=t,a=t;;){if(r.next(o),s.next(o),o=0,r.lineBreak!=s.lineBreak||r.done!=s.done||r.value!=s.value)return!1;if(a+=r.value.length,r.done||a>=i)return!0}}iter(e=1){return new eo(this,e)}iterRange(e,t=this.length){return new IO(this,e,t)}iterLines(e,t){let i;if(e==null)i=this.iter();else{t==null&&(t=this.lines+1);let r=this.line(e).from;i=this.iterRange(r,Math.max(r,t==this.lines+1?this.length:t<=1?0:this.line(t-1).to))}return new RO(i)}toString(){return this.sliceString(0)}toJSON(){let e=[];return this.flatten(e),e}constructor(){}static of(e){if(e.length==0)throw new RangeError("A document must have at least one line");return e.length==1&&!e[0]?K.empty:e.length<=32?new Se(e):ui.from(Se.split(e,[]))}}class Se extends K{constructor(e,t=kv(e)){super(),this.text=e,this.length=t}get lines(){return this.text.length}get children(){return null}lineInner(e,t,i,r){for(let s=0;;s++){let o=this.text[s],a=r+o.length;if((t?i:a)>=e)return new xv(r,a,i,o);r=a+1,i++}}decompose(e,t,i,r){let s=e<=0&&t>=this.length?this:new Se(Zd(this.text,e,t),Math.min(t,this.length)-Math.max(0,e));if(r&1){let o=i.pop(),a=Va(s.text,o.text.slice(),0,s.length);if(a.length<=32)i.push(new Se(a,o.length+s.length));else{let l=a.length>>1;i.push(new Se(a.slice(0,l)),new Se(a.slice(l)))}}else i.push(s)}replace(e,t,i){if(!(i instanceof Se))return super.replace(e,t,i);[e,t]=ms(this,e,t);let r=Va(this.text,Va(i.text,Zd(this.text,0,e)),t),s=this.length+i.length-(t-e);return r.length<=32?new Se(r,s):ui.from(Se.split(r,[]),s)}sliceString(e,t=this.length,i=` `){[e,t]=ms(this,e,t);let r="";for(let s=0,o=0;s<=t&&oe&&o&&(r+=i),es&&(r+=a.slice(Math.max(0,e-s),t-s)),s=l+1}return r}flatten(e){for(let t of this.text)e.push(t)}scanIdentical(){return 0}static split(e,t){let i=[],r=-1;for(let s of e)i.push(s),r+=s.length+1,i.length==32&&(t.push(new Se(i,r)),i=[],r=-1);return r>-1&&t.push(new Se(i,r)),t}}class ui extends K{constructor(e,t){super(),this.children=e,this.length=t,this.lines=0;for(let i of e)this.lines+=i.lines}lineInner(e,t,i,r){for(let s=0;;s++){let o=this.children[s],a=r+o.length,l=i+o.lines-1;if((t?l:a)>=e)return o.lineInner(e,t,i,r);r=a+1,i=l+1}}decompose(e,t,i,r){for(let s=0,o=0;o<=t&&s=o){let h=r&((o<=e?1:0)|(l>=t?2:0));o>=e&&l<=t&&!h?i.push(a):a.decompose(e-o,t-o,i,h)}o=l+1}}replace(e,t,i){if([e,t]=ms(this,e,t),i.lines=s&&t<=a){let l=o.replace(e-s,t-s,i),h=this.lines-o.lines+l.lines;if(l.lines>4&&l.lines>h>>6){let c=this.children.slice();return c[r]=l,new ui(c,this.length-(t-e)+i.length)}return super.replace(s,a,l)}s=a+1}return super.replace(e,t,i)}sliceString(e,t=this.length,i=` -`){[e,t]=ms(this,e,t);let r="";for(let s=0,o=0;se&&s&&(r+=i),eo&&(r+=a.sliceString(e-o,t-o,i)),o=l+1}return r}flatten(e){for(let t of this.children)t.flatten(e)}scanIdentical(e,t){if(!(e instanceof ui))return 0;let i=0,[r,s,o,a]=t>0?[0,0,this.children.length,e.children.length]:[this.children.length-1,e.children.length-1,-1,-1];for(;;r+=t,s+=t){if(r==o||s==a)return i;let l=this.children[r],h=e.children[s];if(l!=h)return i+l.scanIdentical(h,t);i+=l.length+1}}static from(e,t=e.reduce((i,r)=>i+r.length+1,-1)){let i=0;for(let p of e)i+=p.lines;if(i<32){let p=[];for(let g of e)g.flatten(p);return new Se(p,t)}let r=Math.max(32,i>>5),s=r<<1,o=r>>1,a=[],l=0,h=-1,c=[];function u(p){let g;if(p.lines>s&&p instanceof ui)for(let y of p.children)u(y);else p.lines>o&&(l>o||!l)?(f(),a.push(p)):p instanceof Se&&l&&(g=c[c.length-1])instanceof Se&&p.lines+g.lines<=32?(l+=p.lines,h+=p.length+1,c[c.length-1]=new Se(g.text.concat(p.text),g.length+1+p.length)):(l+p.lines>r&&f(),l+=p.lines,h+=p.length+1,c.push(p))}function f(){l!=0&&(a.push(c.length==1?c[0]:ui.from(c,h)),h=-1,l=c.length=0)}for(let p of e)u(p);return f(),a.length==1?a[0]:new ui(a,t)}}K.empty=new Se([""],0);function kv(n){let e=-1;for(let t of n)e+=t.length+1;return e}function Va(n,e,t=0,i=1e9){for(let r=0,s=0,o=!0;s=t&&(l>i&&(a=a.slice(0,i-r)),r0?1:(e instanceof Se?e.text.length:e.children.length)<<1]}nextInner(e,t){for(this.done=this.lineBreak=!1;;){let i=this.nodes.length-1,r=this.nodes[i],s=this.offsets[i],o=s>>1,a=r instanceof Se?r.text.length:r.children.length;if(o==(t>0?a:0)){if(i==0)return this.done=!0,this.value="",this;t>0&&this.offsets[i-1]++,this.nodes.pop(),this.offsets.pop()}else if((s&1)==(t>0?0:1)){if(this.offsets[i]+=t,e==0)return this.lineBreak=!0,this.value=` -`,this;e--}else if(r instanceof Se){let l=r.text[o+(t<0?-1:0)];if(this.offsets[i]+=t,l.length>Math.max(0,e))return this.value=e==0?l:t>0?l.slice(e):l.slice(0,l.length-e),this;e-=l.length}else{let l=r.children[o+(t<0?-1:0)];e>l.length?(e-=l.length,this.offsets[i]+=t):(t<0&&this.offsets[i]--,this.nodes.push(l),this.offsets.push(t>0?1:(l instanceof Se?l.text.length:l.children.length)<<1))}}}next(e=0){return e<0&&(this.nextInner(-e,-this.dir),e=this.value.length),this.nextInner(e,this.dir)}}class IO{constructor(e,t,i){this.value="",this.done=!1,this.cursor=new eo(e,t>i?-1:1),this.pos=t>i?e.length:0,this.from=Math.min(t,i),this.to=Math.max(t,i)}nextInner(e,t){if(t<0?this.pos<=this.from:this.pos>=this.to)return this.value="",this.done=!0,this;e+=Math.max(0,t<0?this.pos-this.to:this.from-this.pos);let i=t<0?this.pos-this.from:this.to-this.pos;e>i&&(e=i),i-=e;let{value:r}=this.cursor.next(e);return this.pos+=(r.length+e)*t,this.value=r.length<=i?r:t<0?r.slice(r.length-i):r.slice(0,i),this.done=!this.value,this}next(e=0){return e<0?e=Math.max(e,this.from-this.pos):e>0&&(e=Math.min(e,this.to-this.pos)),this.nextInner(e,this.cursor.dir)}get lineBreak(){return this.cursor.lineBreak&&this.value!=""}}class RO{constructor(e){this.inner=e,this.afterBreak=!0,this.value="",this.done=!1}next(e=0){let{done:t,lineBreak:i,value:r}=this.inner.next(e);return t&&this.afterBreak?(this.value="",this.afterBreak=!1):t?(this.done=!0,this.value=""):i?this.afterBreak?this.value="":(this.afterBreak=!0,this.next()):(this.value=r,this.afterBreak=!1),this}get lineBreak(){return!1}}typeof Symbol<"u"&&(K.prototype[Symbol.iterator]=function(){return this.iter()},eo.prototype[Symbol.iterator]=IO.prototype[Symbol.iterator]=RO.prototype[Symbol.iterator]=function(){return this});let xv=class{constructor(e,t,i,r){this.from=e,this.to=t,this.number=i,this.text=r}get length(){return this.to-this.from}};function ms(n,e,t){return e=Math.max(0,Math.min(n.length,e)),[e,Math.max(e,Math.min(n.length,t))]}let ns="lc,34,7n,7,7b,19,,,,2,,2,,,20,b,1c,l,g,,2t,7,2,6,2,2,,4,z,,u,r,2j,b,1m,9,9,,o,4,,9,,3,,5,17,3,3b,f,,w,1j,,,,4,8,4,,3,7,a,2,t,,1m,,,,2,4,8,,9,,a,2,q,,2,2,1l,,4,2,4,2,2,3,3,,u,2,3,,b,2,1l,,4,5,,2,4,,k,2,m,6,,,1m,,,2,,4,8,,7,3,a,2,u,,1n,,,,c,,9,,14,,3,,1l,3,5,3,,4,7,2,b,2,t,,1m,,2,,2,,3,,5,2,7,2,b,2,s,2,1l,2,,,2,4,8,,9,,a,2,t,,20,,4,,2,3,,,8,,29,,2,7,c,8,2q,,2,9,b,6,22,2,r,,,,,,1j,e,,5,,2,5,b,,10,9,,2u,4,,6,,2,2,2,p,2,4,3,g,4,d,,2,2,6,,f,,jj,3,qa,3,t,3,t,2,u,2,1s,2,,7,8,,2,b,9,,19,3,3b,2,y,,3a,3,4,2,9,,6,3,63,2,2,,1m,,,7,,,,,2,8,6,a,2,,1c,h,1r,4,1c,7,,,5,,14,9,c,2,w,4,2,2,,3,1k,,,2,3,,,3,1m,8,2,2,48,3,,d,,7,4,,6,,3,2,5i,1m,,5,ek,,5f,x,2da,3,3x,,2o,w,fe,6,2x,2,n9w,4,,a,w,2,28,2,7k,,3,,4,,p,2,5,,47,2,q,i,d,,12,8,p,b,1a,3,1c,,2,4,2,2,13,,1v,6,2,2,2,2,c,,8,,1b,,1f,,,3,2,2,5,2,,,16,2,8,,6m,,2,,4,,fn4,,kh,g,g,g,a6,2,gt,,6a,,45,5,1ae,3,,2,5,4,14,3,4,,4l,2,fx,4,ar,2,49,b,4w,,1i,f,1k,3,1d,4,2,2,1x,3,10,5,,8,1q,,c,2,1g,9,a,4,2,,2n,3,2,,,2,6,,4g,,3,8,l,2,1l,2,,,,,m,,e,7,3,5,5f,8,2,3,,,n,,29,,2,6,,,2,,,2,,2,6j,,2,4,6,2,,2,r,2,2d,8,2,,,2,2y,,,,2,6,,,2t,3,2,4,,5,77,9,,2,6t,,a,2,,,4,,40,4,2,2,4,,w,a,14,6,2,4,8,,9,6,2,3,1a,d,,2,ba,7,,6,,,2a,m,2,7,,2,,2,3e,6,3,,,2,,7,,,20,2,3,,,,9n,2,f0b,5,1n,7,t4,,1r,4,29,,f5k,2,43q,,,3,4,5,8,8,2,7,u,4,44,3,1iz,1j,4,1e,8,,e,,m,5,,f,11s,7,,h,2,7,,2,,5,79,7,c5,4,15s,7,31,7,240,5,gx7k,2o,3k,6o".split(",").map(n=>n?parseInt(n,36):1);for(let n=1;nn)return ns[e-1]<=n;return!1}function Wd(n){return n>=127462&&n<=127487}const jd=8205;function We(n,e,t=!0,i=!0){return(t?EO:Qv)(n,e,i)}function EO(n,e,t){if(e==n.length)return e;e&&DO(n.charCodeAt(e))&&NO(n.charCodeAt(e-1))&&e--;let i=Ne(n,e);for(e+=lt(i);e=0&&Wd(Ne(n,o));)s++,o-=2;if(s%2==0)break;e+=2}else break}return e}function Qv(n,e,t){for(;e>0;){let i=EO(n,e-2,t);if(i=56320&&n<57344}function NO(n){return n>=55296&&n<56320}function Ne(n,e){let t=n.charCodeAt(e);if(!NO(t)||e+1==n.length)return t;let i=n.charCodeAt(e+1);return DO(i)?(t-55296<<10)+(i-56320)+65536:t}function cf(n){return n<=65535?String.fromCharCode(n):(n-=65536,String.fromCharCode((n>>10)+55296,(n&1023)+56320))}function lt(n){return n<65536?1:2}const Uc=/\r\n?|\n/;var qe=function(n){return n[n.Simple=0]="Simple",n[n.TrackDel=1]="TrackDel",n[n.TrackBefore=2]="TrackBefore",n[n.TrackAfter=3]="TrackAfter",n}(qe||(qe={}));class Qi{constructor(e){this.sections=e}get length(){let e=0;for(let t=0;te)return s+(e-r);s+=a}else{if(i!=qe.Simple&&h>=e&&(i==qe.TrackDel&&re||i==qe.TrackBefore&&re))return null;if(h>e||h==e&&t<0&&!a)return e==r||t<0?s:s+l;s+=l}r=h}if(e>r)throw new RangeError(`Position ${e} is out of range for changeset of length ${r}`);return s}touchesRange(e,t=e){for(let i=0,r=0;i=0&&r<=t&&a>=e)return rt?"cover":!0;r=a}return!1}toString(){let e="";for(let t=0;t=0?":"+r:"")}return e}toJSON(){return this.sections}static fromJSON(e){if(!Array.isArray(e)||e.length%2||e.some(t=>typeof t!="number"))throw new RangeError("Invalid JSON representation of ChangeDesc");return new Qi(e)}static create(e){return new Qi(e)}}class Ce extends Qi{constructor(e,t){super(e),this.inserted=t}apply(e){if(this.length!=e.length)throw new RangeError("Applying change set to a document with the wrong length");return Zc(this,(t,i,r,s,o)=>e=e.replace(r,r+(i-t),o),!1),e}mapDesc(e,t=!1){return Wc(this,e,t,!0)}invert(e){let t=this.sections.slice(),i=[];for(let r=0,s=0;r=0){t[r]=a,t[r+1]=o;let l=r>>1;for(;i.length0&&er(i,t,s.text),s.forward(c),a+=c}let h=e[o++];for(;a>1].toJSON()))}return e}static of(e,t,i){let r=[],s=[],o=0,a=null;function l(c=!1){if(!c&&!r.length)return;of||u<0||f>t)throw new RangeError(`Invalid change range ${u} to ${f} (in doc of length ${t})`);let g=p?typeof p=="string"?K.of(p.split(i||Uc)):p:K.empty,y=g.length;if(u==f&&y==0)return;uo&&Le(r,u-o,-1),Le(r,f-u,y),er(s,r,g),o=f}}return h(e),l(!a),a}static empty(e){return new Ce(e?[e,-1]:[],[])}static fromJSON(e){if(!Array.isArray(e))throw new RangeError("Invalid JSON representation of ChangeSet");let t=[],i=[];for(let r=0;ra&&typeof o!="string"))throw new RangeError("Invalid JSON representation of ChangeSet");if(s.length==1)t.push(s[0],0);else{for(;i.length=0&&t<=0&&t==n[r+1]?n[r]+=e:e==0&&n[r]==0?n[r+1]+=t:i?(n[r]+=e,n[r+1]+=t):n.push(e,t)}function er(n,e,t){if(t.length==0)return;let i=e.length-2>>1;if(i>1])),!(t||o==n.sections.length||n.sections[o+1]<0);)a=n.sections[o++],l=n.sections[o++];e(r,h,s,c,u),r=h,s=c}}}function Wc(n,e,t,i=!1){let r=[],s=i?[]:null,o=new bo(n),a=new bo(e);for(let l=-1;;)if(o.ins==-1&&a.ins==-1){let h=Math.min(o.len,a.len);Le(r,h,-1),o.forward(h),a.forward(h)}else if(a.ins>=0&&(o.ins<0||l==o.i||o.off==0&&(a.len=0&&l=0){let h=0,c=o.len;for(;c;)if(a.ins==-1){let u=Math.min(c,a.len);h+=u,c-=u,a.forward(u)}else if(a.ins==0&&a.lenl||o.ins>=0&&o.len>l)&&(a||i.length>h),s.forward2(l),o.forward(l)}}}}class bo{constructor(e){this.set=e,this.i=0,this.next()}next(){let{sections:e}=this.set;this.i>1;return t>=e.length?K.empty:e[t]}textBit(e){let{inserted:t}=this.set,i=this.i-2>>1;return i>=t.length&&!e?K.empty:t[i].slice(this.off,e==null?void 0:this.off+e)}forward(e){e==this.len?this.next():(this.len-=e,this.off+=e)}forward2(e){this.ins==-1?this.forward(e):e==this.ins?this.next():(this.ins-=e,this.off+=e)}}class $r{constructor(e,t,i){this.from=e,this.to=t,this.flags=i}get anchor(){return this.flags&32?this.to:this.from}get head(){return this.flags&32?this.from:this.to}get empty(){return this.from==this.to}get assoc(){return this.flags&8?-1:this.flags&16?1:0}get bidiLevel(){let e=this.flags&7;return e==7?null:e}get goalColumn(){let e=this.flags>>6;return e==16777215?void 0:e}map(e,t=-1){let i,r;return this.empty?i=r=e.mapPos(this.from,t):(i=e.mapPos(this.from,1),r=e.mapPos(this.to,-1)),i==this.from&&r==this.to?this:new $r(i,r,this.flags)}extend(e,t=e){if(e<=this.anchor&&t>=this.anchor)return P.range(e,t);let i=Math.abs(e-this.anchor)>Math.abs(t-this.anchor)?e:t;return P.range(this.anchor,i)}eq(e,t=!1){return this.anchor==e.anchor&&this.head==e.head&&(!t||!this.empty||this.assoc==e.assoc)}toJSON(){return{anchor:this.anchor,head:this.head}}static fromJSON(e){if(!e||typeof e.anchor!="number"||typeof e.head!="number")throw new RangeError("Invalid JSON representation for SelectionRange");return P.range(e.anchor,e.head)}static create(e,t,i){return new $r(e,t,i)}}class P{constructor(e,t){this.ranges=e,this.mainIndex=t}map(e,t=-1){return e.empty?this:P.create(this.ranges.map(i=>i.map(e,t)),this.mainIndex)}eq(e,t=!1){if(this.ranges.length!=e.ranges.length||this.mainIndex!=e.mainIndex)return!1;for(let i=0;ie.toJSON()),main:this.mainIndex}}static fromJSON(e){if(!e||!Array.isArray(e.ranges)||typeof e.main!="number"||e.main>=e.ranges.length)throw new RangeError("Invalid JSON representation for EditorSelection");return new P(e.ranges.map(t=>$r.fromJSON(t)),e.main)}static single(e,t=e){return new P([P.range(e,t)],0)}static create(e,t=0){if(e.length==0)throw new RangeError("A selection needs at least one range");for(let i=0,r=0;re?8:0)|s)}static normalized(e,t=0){let i=e[t];e.sort((r,s)=>r.from-s.from),t=e.indexOf(i);for(let r=1;rs.head?P.range(l,a):P.range(a,l))}}return new P(e,t)}}function qO(n,e){for(let t of n.ranges)if(t.to>e)throw new RangeError("Selection points outside of document")}let uf=0;class B{constructor(e,t,i,r,s){this.combine=e,this.compareInput=t,this.compare=i,this.isStatic=r,this.id=uf++,this.default=e([]),this.extensions=typeof s=="function"?s(this):s}get reader(){return this}static define(e={}){return new B(e.combine||(t=>t),e.compareInput||((t,i)=>t===i),e.compare||(e.combine?(t,i)=>t===i:ff),!!e.static,e.enables)}of(e){return new Xa([],this,0,e)}compute(e,t){if(this.isStatic)throw new Error("Can't compute a static facet");return new Xa(e,this,1,t)}computeN(e,t){if(this.isStatic)throw new Error("Can't compute a static facet");return new Xa(e,this,2,t)}from(e,t){return t||(t=i=>i),this.compute([e],i=>t(i.field(e)))}}function ff(n,e){return n==e||n.length==e.length&&n.every((t,i)=>t===e[i])}class Xa{constructor(e,t,i,r){this.dependencies=e,this.facet=t,this.type=i,this.value=r,this.id=uf++}dynamicSlot(e){var t;let i=this.value,r=this.facet.compareInput,s=this.id,o=e[s]>>1,a=this.type==2,l=!1,h=!1,c=[];for(let u of this.dependencies)u=="doc"?l=!0:u=="selection"?h=!0:((t=e[u.id])!==null&&t!==void 0?t:1)&1||c.push(e[u.id]);return{create(u){return u.values[o]=i(u),1},update(u,f){if(l&&f.docChanged||h&&(f.docChanged||f.selection)||jc(u,c)){let p=i(u);if(a?!Fd(p,u.values[o],r):!r(p,u.values[o]))return u.values[o]=p,1}return 0},reconfigure:(u,f)=>{let p,g=f.config.address[s];if(g!=null){let y=kl(f,g);if(this.dependencies.every(O=>O instanceof B?f.facet(O)===u.facet(O):O instanceof Re?f.field(O,!1)==u.field(O,!1):!0)||(a?Fd(p=i(u),y,r):r(p=i(u),y)))return u.values[o]=y,0}else p=i(u);return u.values[o]=p,1}}}}function Fd(n,e,t){if(n.length!=e.length)return!1;for(let i=0;in[l.id]),r=t.map(l=>l.type),s=i.filter(l=>!(l&1)),o=n[e.id]>>1;function a(l){let h=[];for(let c=0;ci===r),e);return e.provide&&(t.provides=e.provide(t)),t}create(e){let t=e.facet(zd).find(i=>i.field==this);return((t==null?void 0:t.create)||this.createF)(e)}slot(e){let t=e[this.id]>>1;return{create:i=>(i.values[t]=this.create(i),1),update:(i,r)=>{let s=i.values[t],o=this.updateF(s,r);return this.compareF(s,o)?0:(i.values[t]=o,1)},reconfigure:(i,r)=>r.config.address[this.id]!=null?(i.values[t]=r.field(this),0):(i.values[t]=this.create(i),1)}}init(e){return[this,zd.of({field:this,create:e})]}get extension(){return this}}const Tr={lowest:4,low:3,default:2,high:1,highest:0};function Ds(n){return e=>new MO(e,n)}const mr={highest:Ds(Tr.highest),high:Ds(Tr.high),default:Ds(Tr.default),low:Ds(Tr.low),lowest:Ds(Tr.lowest)};class MO{constructor(e,t){this.inner=e,this.prec=t}}class oh{of(e){return new Fc(this,e)}reconfigure(e){return oh.reconfigure.of({compartment:this,extension:e})}get(e){return e.config.compartments.get(this)}}class Fc{constructor(e,t){this.compartment=e,this.inner=t}}class vl{constructor(e,t,i,r,s,o){for(this.base=e,this.compartments=t,this.dynamicSlots=i,this.address=r,this.staticValues=s,this.facets=o,this.statusTemplate=[];this.statusTemplate.length>1]}static resolve(e,t,i){let r=[],s=Object.create(null),o=new Map;for(let f of Av(e,t,o))f instanceof Re?r.push(f):(s[f.facet.id]||(s[f.facet.id]=[])).push(f);let a=Object.create(null),l=[],h=[];for(let f of r)a[f.id]=h.length<<1,h.push(p=>f.slot(p));let c=i==null?void 0:i.config.facets;for(let f in s){let p=s[f],g=p[0].facet,y=c&&c[f]||[];if(p.every(O=>O.type==0))if(a[g.id]=l.length<<1|1,ff(y,p))l.push(i.facet(g));else{let O=g.combine(p.map(S=>S.value));l.push(i&&g.compare(O,i.facet(g))?i.facet(g):O)}else{for(let O of p)O.type==0?(a[O.id]=l.length<<1|1,l.push(O.value)):(a[O.id]=h.length<<1,h.push(S=>O.dynamicSlot(S)));a[g.id]=h.length<<1,h.push(O=>Pv(O,g,p))}}let u=h.map(f=>f(a));return new vl(e,o,u,a,l,s)}}function Av(n,e,t){let i=[[],[],[],[],[]],r=new Map;function s(o,a){let l=r.get(o);if(l!=null){if(l<=a)return;let h=i[l].indexOf(o);h>-1&&i[l].splice(h,1),o instanceof Fc&&t.delete(o.compartment)}if(r.set(o,a),Array.isArray(o))for(let h of o)s(h,a);else if(o instanceof Fc){if(t.has(o.compartment))throw new RangeError("Duplicate use of compartment in extensions");let h=e.get(o.compartment)||o.inner;t.set(o.compartment,h),s(h,a)}else if(o instanceof MO)s(o.inner,o.prec);else if(o instanceof Re)i[a].push(o),o.provides&&s(o.provides,a);else if(o instanceof Xa)i[a].push(o),o.facet.extensions&&s(o.facet.extensions,Tr.default);else{let h=o.extension;if(!h)throw new Error(`Unrecognized extension value in extension set (${o}). This sometimes happens because multiple instances of @codemirror/state are loaded, breaking instanceof checks.`);s(h,a)}}return s(n,Tr.default),i.reduce((o,a)=>o.concat(a))}function to(n,e){if(e&1)return 2;let t=e>>1,i=n.status[t];if(i==4)throw new Error("Cyclic dependency between fields and/or facets");if(i&2)return i;n.status[t]=4;let r=n.computeSlot(n,n.config.dynamicSlots[t]);return n.status[t]=2|r}function kl(n,e){return e&1?n.config.staticValues[e>>1]:n.values[e>>1]}const VO=B.define(),zc=B.define({combine:n=>n.some(e=>e),static:!0}),XO=B.define({combine:n=>n.length?n[0]:void 0,static:!0}),LO=B.define(),UO=B.define(),ZO=B.define(),WO=B.define({combine:n=>n.length?n[0]:!1});class jn{constructor(e,t){this.type=e,this.value=t}static define(){return new $v}}class $v{of(e){return new jn(this,e)}}class Cv{constructor(e){this.map=e}of(e){return new z(this,e)}}class z{constructor(e,t){this.type=e,this.value=t}map(e){let t=this.type.map(this.value,e);return t===void 0?void 0:t==this.value?this:new z(this.type,t)}is(e){return this.type==e}static define(e={}){return new Cv(e.map||(t=>t))}static mapEffects(e,t){if(!e.length)return e;let i=[];for(let r of e){let s=r.map(t);s&&i.push(s)}return i}}z.reconfigure=z.define();z.appendConfig=z.define();class ye{constructor(e,t,i,r,s,o){this.startState=e,this.changes=t,this.selection=i,this.effects=r,this.annotations=s,this.scrollIntoView=o,this._doc=null,this._state=null,i&&qO(i,t.newLength),s.some(a=>a.type==ye.time)||(this.annotations=s.concat(ye.time.of(Date.now())))}static create(e,t,i,r,s,o){return new ye(e,t,i,r,s,o)}get newDoc(){return this._doc||(this._doc=this.changes.apply(this.startState.doc))}get newSelection(){return this.selection||this.startState.selection.map(this.changes)}get state(){return this._state||this.startState.applyTransaction(this),this._state}annotation(e){for(let t of this.annotations)if(t.type==e)return t.value}get docChanged(){return!this.changes.empty}get reconfigured(){return this.startState.config!=this.state.config}isUserEvent(e){let t=this.annotation(ye.userEvent);return!!(t&&(t==e||t.length>e.length&&t.slice(0,e.length)==e&&t[e.length]=="."))}}ye.time=jn.define();ye.userEvent=jn.define();ye.addToHistory=jn.define();ye.remote=jn.define();function Iv(n,e){let t=[];for(let i=0,r=0;;){let s,o;if(i=n[i]))s=n[i++],o=n[i++];else if(r=0;r--){let s=i[r](n);s instanceof ye?n=s:Array.isArray(s)&&s.length==1&&s[0]instanceof ye?n=s[0]:n=FO(e,rs(s),!1)}return n}function Ev(n){let e=n.startState,t=e.facet(ZO),i=n;for(let r=t.length-1;r>=0;r--){let s=t[r](n);s&&Object.keys(s).length&&(i=jO(i,_c(e,s,n.changes.newLength),!0))}return i==n?n:ye.create(e,n.changes,n.selection,i.effects,i.annotations,i.scrollIntoView)}const Dv=[];function rs(n){return n==null?Dv:Array.isArray(n)?n:[n]}var fe=function(n){return n[n.Word=0]="Word",n[n.Space=1]="Space",n[n.Other=2]="Other",n}(fe||(fe={}));const Nv=/[\u00df\u0587\u0590-\u05f4\u0600-\u06ff\u3040-\u309f\u30a0-\u30ff\u3400-\u4db5\u4e00-\u9fcc\uac00-\ud7af]/;let Gc;try{Gc=new RegExp("[\\p{Alphabetic}\\p{Number}_]","u")}catch{}function Bv(n){if(Gc)return Gc.test(n);for(let e=0;e"€"&&(t.toUpperCase()!=t.toLowerCase()||Nv.test(t)))return!0}return!1}function qv(n){return e=>{if(!/\S/.test(e))return fe.Space;if(Bv(e))return fe.Word;for(let t=0;t-1)return fe.Word;return fe.Other}}class H{constructor(e,t,i,r,s,o){this.config=e,this.doc=t,this.selection=i,this.values=r,this.status=e.statusTemplate.slice(),this.computeSlot=s,o&&(o._state=this);for(let a=0;ar.set(h,l)),t=null),r.set(a.value.compartment,a.value.extension)):a.is(z.reconfigure)?(t=null,i=a.value):a.is(z.appendConfig)&&(t=null,i=rs(i).concat(a.value));let s;t?s=e.startState.values.slice():(t=vl.resolve(i,r,this),s=new H(t,this.doc,this.selection,t.dynamicSlots.map(()=>null),(l,h)=>h.reconfigure(l,this),null).values);let o=e.startState.facet(zc)?e.newSelection:e.newSelection.asSingle();new H(t,e.newDoc,o,s,(a,l)=>l.update(a,e),e)}replaceSelection(e){return typeof e=="string"&&(e=this.toText(e)),this.changeByRange(t=>({changes:{from:t.from,to:t.to,insert:e},range:P.cursor(t.from+e.length)}))}changeByRange(e){let t=this.selection,i=e(t.ranges[0]),r=this.changes(i.changes),s=[i.range],o=rs(i.effects);for(let a=1;ao.spec.fromJSON(a,l)))}}return H.create({doc:e.doc,selection:P.fromJSON(e.selection),extensions:t.extensions?r.concat([t.extensions]):r})}static create(e={}){let t=vl.resolve(e.extensions||[],new Map),i=e.doc instanceof K?e.doc:K.of((e.doc||"").split(t.staticFacet(H.lineSeparator)||Uc)),r=e.selection?e.selection instanceof P?e.selection:P.single(e.selection.anchor,e.selection.head):P.single(0);return qO(r,i.length),t.staticFacet(zc)||(r=r.asSingle()),new H(t,i,r,t.dynamicSlots.map(()=>null),(s,o)=>o.create(s),null)}get tabSize(){return this.facet(H.tabSize)}get lineBreak(){return this.facet(H.lineSeparator)||` -`}get readOnly(){return this.facet(WO)}phrase(e,...t){for(let i of this.facet(H.phrases))if(Object.prototype.hasOwnProperty.call(i,e)){e=i[e];break}return t.length&&(e=e.replace(/\$(\$|\d*)/g,(i,r)=>{if(r=="$")return"$";let s=+(r||1);return!s||s>t.length?i:t[s-1]})),e}languageDataAt(e,t,i=-1){let r=[];for(let s of this.facet(VO))for(let o of s(this,t,i))Object.prototype.hasOwnProperty.call(o,e)&&r.push(o[e]);return r}charCategorizer(e){return qv(this.languageDataAt("wordChars",e).join(""))}wordAt(e){let{text:t,from:i,length:r}=this.doc.lineAt(e),s=this.charCategorizer(e),o=e-i,a=e-i;for(;o>0;){let l=We(t,o,!1);if(s(t.slice(l,o))!=fe.Word)break;o=l}for(;an.length?n[0]:4});H.lineSeparator=XO;H.readOnly=WO;H.phrases=B.define({compare(n,e){let t=Object.keys(n),i=Object.keys(e);return t.length==i.length&&t.every(r=>n[r]==e[r])}});H.languageData=VO;H.changeFilter=LO;H.transactionFilter=UO;H.transactionExtender=ZO;oh.reconfigure=z.define();function Ai(n,e,t={}){let i={};for(let r of n)for(let s of Object.keys(r)){let o=r[s],a=i[s];if(a===void 0)i[s]=o;else if(!(a===o||o===void 0))if(Object.hasOwnProperty.call(t,s))i[s]=t[s](a,o);else throw new Error("Config merge conflict for field "+s)}for(let r in e)i[r]===void 0&&(i[r]=e[r]);return i}class Br{eq(e){return this==e}range(e,t=e){return Jc.create(e,t,this)}}Br.prototype.startSide=Br.prototype.endSide=0;Br.prototype.point=!1;Br.prototype.mapMode=qe.TrackDel;let Jc=class zO{constructor(e,t,i){this.from=e,this.to=t,this.value=i}static create(e,t,i){return new zO(e,t,i)}};function Yc(n,e){return n.from-e.from||n.value.startSide-e.value.startSide}class df{constructor(e,t,i,r){this.from=e,this.to=t,this.value=i,this.maxPoint=r}get length(){return this.to[this.to.length-1]}findIndex(e,t,i,r=0){let s=i?this.to:this.from;for(let o=r,a=s.length;;){if(o==a)return o;let l=o+a>>1,h=s[l]-e||(i?this.value[l].endSide:this.value[l].startSide)-t;if(l==o)return h>=0?o:a;h>=0?a=l:o=l+1}}between(e,t,i,r){for(let s=this.findIndex(t,-1e9,!0),o=this.findIndex(i,1e9,!1,s);sp||f==p&&h.startSide>0&&h.endSide<=0)continue;(p-f||h.endSide-h.startSide)<0||(o<0&&(o=f),h.point&&(a=Math.max(a,p-f)),i.push(h),r.push(f-o),s.push(p-o))}return{mapped:i.length?new df(r,s,i,a):null,pos:o}}}class J{constructor(e,t,i,r){this.chunkPos=e,this.chunk=t,this.nextLayer=i,this.maxPoint=r}static create(e,t,i,r){return new J(e,t,i,r)}get length(){let e=this.chunk.length-1;return e<0?0:Math.max(this.chunkEnd(e),this.nextLayer.length)}get size(){if(this.isEmpty)return 0;let e=this.nextLayer.size;for(let t of this.chunk)e+=t.value.length;return e}chunkEnd(e){return this.chunkPos[e]+this.chunk[e].length}update(e){let{add:t=[],sort:i=!1,filterFrom:r=0,filterTo:s=this.length}=e,o=e.filter;if(t.length==0&&!o)return this;if(i&&(t=t.slice().sort(Yc)),this.isEmpty)return t.length?J.of(t):this;let a=new _O(this,null,-1).goto(0),l=0,h=[],c=new fr;for(;a.value||l=0){let u=t[l++];c.addInner(u.from,u.to,u.value)||h.push(u)}else a.rangeIndex==1&&a.chunkIndexthis.chunkEnd(a.chunkIndex)||sa.to||s=s&&e<=s+o.length&&o.between(s,e-s,t-s,i)===!1)return}this.nextLayer.between(e,t,i)}}iter(e=0){return So.from([this]).goto(e)}get isEmpty(){return this.nextLayer==this}static iter(e,t=0){return So.from(e).goto(t)}static compare(e,t,i,r,s=-1){let o=e.filter(u=>u.maxPoint>0||!u.isEmpty&&u.maxPoint>=s),a=t.filter(u=>u.maxPoint>0||!u.isEmpty&&u.maxPoint>=s),l=_d(o,a,i),h=new Ns(o,l,s),c=new Ns(a,l,s);i.iterGaps((u,f,p)=>Gd(h,u,c,f,p,r)),i.empty&&i.length==0&&Gd(h,0,c,0,0,r)}static eq(e,t,i=0,r){r==null&&(r=999999999);let s=e.filter(c=>!c.isEmpty&&t.indexOf(c)<0),o=t.filter(c=>!c.isEmpty&&e.indexOf(c)<0);if(s.length!=o.length)return!1;if(!s.length)return!0;let a=_d(s,o),l=new Ns(s,a,0).goto(i),h=new Ns(o,a,0).goto(i);for(;;){if(l.to!=h.to||!Hc(l.active,h.active)||l.point&&(!h.point||!l.point.eq(h.point)))return!1;if(l.to>r)return!0;l.next(),h.next()}}static spans(e,t,i,r,s=-1){let o=new Ns(e,null,s).goto(t),a=t,l=o.openStart;for(;;){let h=Math.min(o.to,i);if(o.point){let c=o.activeForPoint(o.to),u=o.pointFroma&&(r.span(a,h,o.active,l),l=o.openEnd(h));if(o.to>i)return l+(o.point&&o.to>i?1:0);a=o.to,o.next()}}static of(e,t=!1){let i=new fr;for(let r of e instanceof Jc?[e]:t?Mv(e):e)i.add(r.from,r.to,r.value);return i.finish()}static join(e){if(!e.length)return J.empty;let t=e[e.length-1];for(let i=e.length-2;i>=0;i--)for(let r=e[i];r!=J.empty;r=r.nextLayer)t=new J(r.chunkPos,r.chunk,t,Math.max(r.maxPoint,t.maxPoint));return t}}J.empty=new J([],[],null,-1);function Mv(n){if(n.length>1)for(let e=n[0],t=1;t0)return n.slice().sort(Yc);e=i}return n}J.empty.nextLayer=J.empty;class fr{finishChunk(e){this.chunks.push(new df(this.from,this.to,this.value,this.maxPoint)),this.chunkPos.push(this.chunkStart),this.chunkStart=-1,this.setMaxPoint=Math.max(this.setMaxPoint,this.maxPoint),this.maxPoint=-1,e&&(this.from=[],this.to=[],this.value=[])}constructor(){this.chunks=[],this.chunkPos=[],this.chunkStart=-1,this.last=null,this.lastFrom=-1e9,this.lastTo=-1e9,this.from=[],this.to=[],this.value=[],this.maxPoint=-1,this.setMaxPoint=-1,this.nextLayer=null}add(e,t,i){this.addInner(e,t,i)||(this.nextLayer||(this.nextLayer=new fr)).add(e,t,i)}addInner(e,t,i){let r=e-this.lastTo||i.startSide-this.last.endSide;if(r<=0&&(e-this.lastFrom||i.startSide-this.last.startSide)<0)throw new Error("Ranges must be added sorted by `from` position and `startSide`");return r<0?!1:(this.from.length==250&&this.finishChunk(!0),this.chunkStart<0&&(this.chunkStart=e),this.from.push(e-this.chunkStart),this.to.push(t-this.chunkStart),this.last=i,this.lastFrom=e,this.lastTo=t,this.value.push(i),i.point&&(this.maxPoint=Math.max(this.maxPoint,t-e)),!0)}addChunk(e,t){if((e-this.lastTo||t.value[0].startSide-this.last.endSide)<0)return!1;this.from.length&&this.finishChunk(!0),this.setMaxPoint=Math.max(this.setMaxPoint,t.maxPoint),this.chunks.push(t),this.chunkPos.push(e);let i=t.value.length-1;return this.last=t.value[i],this.lastFrom=t.from[i]+e,this.lastTo=t.to[i]+e,!0}finish(){return this.finishInner(J.empty)}finishInner(e){if(this.from.length&&this.finishChunk(!1),this.chunks.length==0)return e;let t=J.create(this.chunkPos,this.chunks,this.nextLayer?this.nextLayer.finishInner(e):e,this.setMaxPoint);return this.from=null,t}}function _d(n,e,t){let i=new Map;for(let s of n)for(let o=0;o=this.minPoint)break}}setRangeIndex(e){if(e==this.layer.chunk[this.chunkIndex].value.length){if(this.chunkIndex++,this.skip)for(;this.chunkIndex=i&&r.push(new _O(o,t,i,s));return r.length==1?r[0]:new So(r)}get startSide(){return this.value?this.value.startSide:0}goto(e,t=-1e9){for(let i of this.heap)i.goto(e,t);for(let i=this.heap.length>>1;i>=0;i--)Eh(this.heap,i);return this.next(),this}forward(e,t){for(let i of this.heap)i.forward(e,t);for(let i=this.heap.length>>1;i>=0;i--)Eh(this.heap,i);(this.to-e||this.value.endSide-t)<0&&this.next()}next(){if(this.heap.length==0)this.from=this.to=1e9,this.value=null,this.rank=-1;else{let e=this.heap[0];this.from=e.from,this.to=e.to,this.value=e.value,this.rank=e.rank,e.value&&e.next(),Eh(this.heap,0)}}}function Eh(n,e){for(let t=n[e];;){let i=(e<<1)+1;if(i>=n.length)break;let r=n[i];if(i+1=0&&(r=n[i+1],i++),t.compare(r)<0)break;n[i]=t,n[e]=r,e=i}}class Ns{constructor(e,t,i){this.minPoint=i,this.active=[],this.activeTo=[],this.activeRank=[],this.minActive=-1,this.point=null,this.pointFrom=0,this.pointRank=0,this.to=-1e9,this.endSide=0,this.openStart=-1,this.cursor=So.from(e,t,i)}goto(e,t=-1e9){return this.cursor.goto(e,t),this.active.length=this.activeTo.length=this.activeRank.length=0,this.minActive=-1,this.to=e,this.endSide=t,this.openStart=-1,this.next(),this}forward(e,t){for(;this.minActive>-1&&(this.activeTo[this.minActive]-e||this.active[this.minActive].endSide-t)<0;)this.removeActive(this.minActive);this.cursor.forward(e,t)}removeActive(e){sa(this.active,e),sa(this.activeTo,e),sa(this.activeRank,e),this.minActive=Jd(this.active,this.activeTo)}addActive(e){let t=0,{value:i,to:r,rank:s}=this.cursor;for(;t0;)t++;oa(this.active,t,i),oa(this.activeTo,t,r),oa(this.activeRank,t,s),e&&oa(e,t,this.cursor.from),this.minActive=Jd(this.active,this.activeTo)}next(){let e=this.to,t=this.point;this.point=null;let i=this.openStart<0?[]:null;for(;;){let r=this.minActive;if(r>-1&&(this.activeTo[r]-this.cursor.from||this.active[r].endSide-this.cursor.startSide)<0){if(this.activeTo[r]>e){this.to=this.activeTo[r],this.endSide=this.active[r].endSide;break}this.removeActive(r),i&&sa(i,r)}else if(this.cursor.value)if(this.cursor.from>e){this.to=this.cursor.from,this.endSide=this.cursor.startSide;break}else{let s=this.cursor.value;if(!s.point)this.addActive(i),this.cursor.next();else if(t&&this.cursor.to==this.to&&this.cursor.from=0&&i[r]=0&&!(this.activeRank[i]e||this.activeTo[i]==e&&this.active[i].endSide>=this.point.endSide)&&t.push(this.active[i]);return t.reverse()}openEnd(e){let t=0;for(let i=this.activeTo.length-1;i>=0&&this.activeTo[i]>e;i--)t++;return t}}function Gd(n,e,t,i,r,s){n.goto(e),t.goto(i);let o=i+r,a=i,l=i-e;for(;;){let h=n.to+l-t.to||n.endSide-t.endSide,c=h<0?n.to+l:t.to,u=Math.min(c,o);if(n.point||t.point?n.point&&t.point&&(n.point==t.point||n.point.eq(t.point))&&Hc(n.activeForPoint(n.to),t.activeForPoint(t.to))||s.comparePoint(a,u,n.point,t.point):u>a&&!Hc(n.active,t.active)&&s.compareRange(a,u,n.active,t.active),c>o)break;a=c,h<=0&&n.next(),h>=0&&t.next()}}function Hc(n,e){if(n.length!=e.length)return!1;for(let t=0;t=e;i--)n[i+1]=n[i];n[e]=t}function Jd(n,e){let t=-1,i=1e9;for(let r=0;r=e)return r;if(r==n.length)break;s+=n.charCodeAt(r)==9?t-s%t:1,r=We(n,r)}return i===!0?-1:n.length}const eu="ͼ",Yd=typeof Symbol>"u"?"__"+eu:Symbol.for(eu),tu=typeof Symbol>"u"?"__styleSet"+Math.floor(Math.random()*1e8):Symbol("styleSet"),Hd=typeof globalThis<"u"?globalThis:typeof window<"u"?window:{};let Os=class{constructor(e,t){this.rules=[];let{finish:i}=t||{};function r(o){return/^@/.test(o)?[o]:o.split(/,\s*/)}function s(o,a,l,h){let c=[],u=/^@(\w+)\b/.exec(o[0]),f=u&&u[1]=="keyframes";if(u&&a==null)return l.push(o[0]+";");for(let p in a){let g=a[p];if(/&/.test(p))s(p.split(/,\s*/).map(y=>o.map(O=>y.replace(/&/,O))).reduce((y,O)=>y.concat(O)),g,l);else if(g&&typeof g=="object"){if(!u)throw new RangeError("The value of a property ("+p+") should be a primitive value.");s(r(p),g,c,f)}else g!=null&&c.push(p.replace(/_.*/,"").replace(/[A-Z]/g,y=>"-"+y.toLowerCase())+": "+g+";")}(c.length||f)&&l.push((i&&!u&&!h?o.map(i):o).join(", ")+" {"+c.join(" ")+"}")}for(let o in e)s(r(o),e[o],this.rules)}getRules(){return this.rules.join(` +`){[e,t]=ms(this,e,t);let r="";for(let s=0,o=0;se&&s&&(r+=i),eo&&(r+=a.sliceString(e-o,t-o,i)),o=l+1}return r}flatten(e){for(let t of this.children)t.flatten(e)}scanIdentical(e,t){if(!(e instanceof ui))return 0;let i=0,[r,s,o,a]=t>0?[0,0,this.children.length,e.children.length]:[this.children.length-1,e.children.length-1,-1,-1];for(;;r+=t,s+=t){if(r==o||s==a)return i;let l=this.children[r],h=e.children[s];if(l!=h)return i+l.scanIdentical(h,t);i+=l.length+1}}static from(e,t=e.reduce((i,r)=>i+r.length+1,-1)){let i=0;for(let p of e)i+=p.lines;if(i<32){let p=[];for(let g of e)g.flatten(p);return new Se(p,t)}let r=Math.max(32,i>>5),s=r<<1,o=r>>1,a=[],l=0,h=-1,c=[];function u(p){let g;if(p.lines>s&&p instanceof ui)for(let O of p.children)u(O);else p.lines>o&&(l>o||!l)?(f(),a.push(p)):p instanceof Se&&l&&(g=c[c.length-1])instanceof Se&&p.lines+g.lines<=32?(l+=p.lines,h+=p.length+1,c[c.length-1]=new Se(g.text.concat(p.text),g.length+1+p.length)):(l+p.lines>r&&f(),l+=p.lines,h+=p.length+1,c.push(p))}function f(){l!=0&&(a.push(c.length==1?c[0]:ui.from(c,h)),h=-1,l=c.length=0)}for(let p of e)u(p);return f(),a.length==1?a[0]:new ui(a,t)}}K.empty=new Se([""],0);function kv(n){let e=-1;for(let t of n)e+=t.length+1;return e}function Va(n,e,t=0,i=1e9){for(let r=0,s=0,o=!0;s=t&&(l>i&&(a=a.slice(0,i-r)),r0?1:(e instanceof Se?e.text.length:e.children.length)<<1]}nextInner(e,t){for(this.done=this.lineBreak=!1;;){let i=this.nodes.length-1,r=this.nodes[i],s=this.offsets[i],o=s>>1,a=r instanceof Se?r.text.length:r.children.length;if(o==(t>0?a:0)){if(i==0)return this.done=!0,this.value="",this;t>0&&this.offsets[i-1]++,this.nodes.pop(),this.offsets.pop()}else if((s&1)==(t>0?0:1)){if(this.offsets[i]+=t,e==0)return this.lineBreak=!0,this.value=` +`,this;e--}else if(r instanceof Se){let l=r.text[o+(t<0?-1:0)];if(this.offsets[i]+=t,l.length>Math.max(0,e))return this.value=e==0?l:t>0?l.slice(e):l.slice(0,l.length-e),this;e-=l.length}else{let l=r.children[o+(t<0?-1:0)];e>l.length?(e-=l.length,this.offsets[i]+=t):(t<0&&this.offsets[i]--,this.nodes.push(l),this.offsets.push(t>0?1:(l instanceof Se?l.text.length:l.children.length)<<1))}}}next(e=0){return e<0&&(this.nextInner(-e,-this.dir),e=this.value.length),this.nextInner(e,this.dir)}}class IO{constructor(e,t,i){this.value="",this.done=!1,this.cursor=new eo(e,t>i?-1:1),this.pos=t>i?e.length:0,this.from=Math.min(t,i),this.to=Math.max(t,i)}nextInner(e,t){if(t<0?this.pos<=this.from:this.pos>=this.to)return this.value="",this.done=!0,this;e+=Math.max(0,t<0?this.pos-this.to:this.from-this.pos);let i=t<0?this.pos-this.from:this.to-this.pos;e>i&&(e=i),i-=e;let{value:r}=this.cursor.next(e);return this.pos+=(r.length+e)*t,this.value=r.length<=i?r:t<0?r.slice(r.length-i):r.slice(0,i),this.done=!this.value,this}next(e=0){return e<0?e=Math.max(e,this.from-this.pos):e>0&&(e=Math.min(e,this.to-this.pos)),this.nextInner(e,this.cursor.dir)}get lineBreak(){return this.cursor.lineBreak&&this.value!=""}}class RO{constructor(e){this.inner=e,this.afterBreak=!0,this.value="",this.done=!1}next(e=0){let{done:t,lineBreak:i,value:r}=this.inner.next(e);return t&&this.afterBreak?(this.value="",this.afterBreak=!1):t?(this.done=!0,this.value=""):i?this.afterBreak?this.value="":(this.afterBreak=!0,this.next()):(this.value=r,this.afterBreak=!1),this}get lineBreak(){return!1}}typeof Symbol<"u"&&(K.prototype[Symbol.iterator]=function(){return this.iter()},eo.prototype[Symbol.iterator]=IO.prototype[Symbol.iterator]=RO.prototype[Symbol.iterator]=function(){return this});let xv=class{constructor(e,t,i,r){this.from=e,this.to=t,this.number=i,this.text=r}get length(){return this.to-this.from}};function ms(n,e,t){return e=Math.max(0,Math.min(n.length,e)),[e,Math.max(e,Math.min(n.length,t))]}let ns="lc,34,7n,7,7b,19,,,,2,,2,,,20,b,1c,l,g,,2t,7,2,6,2,2,,4,z,,u,r,2j,b,1m,9,9,,o,4,,9,,3,,5,17,3,3b,f,,w,1j,,,,4,8,4,,3,7,a,2,t,,1m,,,,2,4,8,,9,,a,2,q,,2,2,1l,,4,2,4,2,2,3,3,,u,2,3,,b,2,1l,,4,5,,2,4,,k,2,m,6,,,1m,,,2,,4,8,,7,3,a,2,u,,1n,,,,c,,9,,14,,3,,1l,3,5,3,,4,7,2,b,2,t,,1m,,2,,2,,3,,5,2,7,2,b,2,s,2,1l,2,,,2,4,8,,9,,a,2,t,,20,,4,,2,3,,,8,,29,,2,7,c,8,2q,,2,9,b,6,22,2,r,,,,,,1j,e,,5,,2,5,b,,10,9,,2u,4,,6,,2,2,2,p,2,4,3,g,4,d,,2,2,6,,f,,jj,3,qa,3,t,3,t,2,u,2,1s,2,,7,8,,2,b,9,,19,3,3b,2,y,,3a,3,4,2,9,,6,3,63,2,2,,1m,,,7,,,,,2,8,6,a,2,,1c,h,1r,4,1c,7,,,5,,14,9,c,2,w,4,2,2,,3,1k,,,2,3,,,3,1m,8,2,2,48,3,,d,,7,4,,6,,3,2,5i,1m,,5,ek,,5f,x,2da,3,3x,,2o,w,fe,6,2x,2,n9w,4,,a,w,2,28,2,7k,,3,,4,,p,2,5,,47,2,q,i,d,,12,8,p,b,1a,3,1c,,2,4,2,2,13,,1v,6,2,2,2,2,c,,8,,1b,,1f,,,3,2,2,5,2,,,16,2,8,,6m,,2,,4,,fn4,,kh,g,g,g,a6,2,gt,,6a,,45,5,1ae,3,,2,5,4,14,3,4,,4l,2,fx,4,ar,2,49,b,4w,,1i,f,1k,3,1d,4,2,2,1x,3,10,5,,8,1q,,c,2,1g,9,a,4,2,,2n,3,2,,,2,6,,4g,,3,8,l,2,1l,2,,,,,m,,e,7,3,5,5f,8,2,3,,,n,,29,,2,6,,,2,,,2,,2,6j,,2,4,6,2,,2,r,2,2d,8,2,,,2,2y,,,,2,6,,,2t,3,2,4,,5,77,9,,2,6t,,a,2,,,4,,40,4,2,2,4,,w,a,14,6,2,4,8,,9,6,2,3,1a,d,,2,ba,7,,6,,,2a,m,2,7,,2,,2,3e,6,3,,,2,,7,,,20,2,3,,,,9n,2,f0b,5,1n,7,t4,,1r,4,29,,f5k,2,43q,,,3,4,5,8,8,2,7,u,4,44,3,1iz,1j,4,1e,8,,e,,m,5,,f,11s,7,,h,2,7,,2,,5,79,7,c5,4,15s,7,31,7,240,5,gx7k,2o,3k,6o".split(",").map(n=>n?parseInt(n,36):1);for(let n=1;nn)return ns[e-1]<=n;return!1}function Wd(n){return n>=127462&&n<=127487}const jd=8205;function We(n,e,t=!0,i=!0){return(t?EO:Qv)(n,e,i)}function EO(n,e,t){if(e==n.length)return e;e&&DO(n.charCodeAt(e))&&NO(n.charCodeAt(e-1))&&e--;let i=Ne(n,e);for(e+=lt(i);e=0&&Wd(Ne(n,o));)s++,o-=2;if(s%2==0)break;e+=2}else break}return e}function Qv(n,e,t){for(;e>0;){let i=EO(n,e-2,t);if(i=56320&&n<57344}function NO(n){return n>=55296&&n<56320}function Ne(n,e){let t=n.charCodeAt(e);if(!NO(t)||e+1==n.length)return t;let i=n.charCodeAt(e+1);return DO(i)?(t-55296<<10)+(i-56320)+65536:t}function cf(n){return n<=65535?String.fromCharCode(n):(n-=65536,String.fromCharCode((n>>10)+55296,(n&1023)+56320))}function lt(n){return n<65536?1:2}const Uc=/\r\n?|\n/;var qe=function(n){return n[n.Simple=0]="Simple",n[n.TrackDel=1]="TrackDel",n[n.TrackBefore=2]="TrackBefore",n[n.TrackAfter=3]="TrackAfter",n}(qe||(qe={}));class Qi{constructor(e){this.sections=e}get length(){let e=0;for(let t=0;te)return s+(e-r);s+=a}else{if(i!=qe.Simple&&h>=e&&(i==qe.TrackDel&&re||i==qe.TrackBefore&&re))return null;if(h>e||h==e&&t<0&&!a)return e==r||t<0?s:s+l;s+=l}r=h}if(e>r)throw new RangeError(`Position ${e} is out of range for changeset of length ${r}`);return s}touchesRange(e,t=e){for(let i=0,r=0;i=0&&r<=t&&a>=e)return rt?"cover":!0;r=a}return!1}toString(){let e="";for(let t=0;t=0?":"+r:"")}return e}toJSON(){return this.sections}static fromJSON(e){if(!Array.isArray(e)||e.length%2||e.some(t=>typeof t!="number"))throw new RangeError("Invalid JSON representation of ChangeDesc");return new Qi(e)}static create(e){return new Qi(e)}}class Ce extends Qi{constructor(e,t){super(e),this.inserted=t}apply(e){if(this.length!=e.length)throw new RangeError("Applying change set to a document with the wrong length");return Zc(this,(t,i,r,s,o)=>e=e.replace(r,r+(i-t),o),!1),e}mapDesc(e,t=!1){return Wc(this,e,t,!0)}invert(e){let t=this.sections.slice(),i=[];for(let r=0,s=0;r=0){t[r]=a,t[r+1]=o;let l=r>>1;for(;i.length0&&er(i,t,s.text),s.forward(c),a+=c}let h=e[o++];for(;a>1].toJSON()))}return e}static of(e,t,i){let r=[],s=[],o=0,a=null;function l(c=!1){if(!c&&!r.length)return;of||u<0||f>t)throw new RangeError(`Invalid change range ${u} to ${f} (in doc of length ${t})`);let g=p?typeof p=="string"?K.of(p.split(i||Uc)):p:K.empty,O=g.length;if(u==f&&O==0)return;uo&&Le(r,u-o,-1),Le(r,f-u,O),er(s,r,g),o=f}}return h(e),l(!a),a}static empty(e){return new Ce(e?[e,-1]:[],[])}static fromJSON(e){if(!Array.isArray(e))throw new RangeError("Invalid JSON representation of ChangeSet");let t=[],i=[];for(let r=0;ra&&typeof o!="string"))throw new RangeError("Invalid JSON representation of ChangeSet");if(s.length==1)t.push(s[0],0);else{for(;i.length=0&&t<=0&&t==n[r+1]?n[r]+=e:e==0&&n[r]==0?n[r+1]+=t:i?(n[r]+=e,n[r+1]+=t):n.push(e,t)}function er(n,e,t){if(t.length==0)return;let i=e.length-2>>1;if(i>1])),!(t||o==n.sections.length||n.sections[o+1]<0);)a=n.sections[o++],l=n.sections[o++];e(r,h,s,c,u),r=h,s=c}}}function Wc(n,e,t,i=!1){let r=[],s=i?[]:null,o=new bo(n),a=new bo(e);for(let l=-1;;)if(o.ins==-1&&a.ins==-1){let h=Math.min(o.len,a.len);Le(r,h,-1),o.forward(h),a.forward(h)}else if(a.ins>=0&&(o.ins<0||l==o.i||o.off==0&&(a.len=0&&l=0){let h=0,c=o.len;for(;c;)if(a.ins==-1){let u=Math.min(c,a.len);h+=u,c-=u,a.forward(u)}else if(a.ins==0&&a.lenl||o.ins>=0&&o.len>l)&&(a||i.length>h),s.forward2(l),o.forward(l)}}}}class bo{constructor(e){this.set=e,this.i=0,this.next()}next(){let{sections:e}=this.set;this.i>1;return t>=e.length?K.empty:e[t]}textBit(e){let{inserted:t}=this.set,i=this.i-2>>1;return i>=t.length&&!e?K.empty:t[i].slice(this.off,e==null?void 0:this.off+e)}forward(e){e==this.len?this.next():(this.len-=e,this.off+=e)}forward2(e){this.ins==-1?this.forward(e):e==this.ins?this.next():(this.ins-=e,this.off+=e)}}class $r{constructor(e,t,i){this.from=e,this.to=t,this.flags=i}get anchor(){return this.flags&32?this.to:this.from}get head(){return this.flags&32?this.from:this.to}get empty(){return this.from==this.to}get assoc(){return this.flags&8?-1:this.flags&16?1:0}get bidiLevel(){let e=this.flags&7;return e==7?null:e}get goalColumn(){let e=this.flags>>6;return e==16777215?void 0:e}map(e,t=-1){let i,r;return this.empty?i=r=e.mapPos(this.from,t):(i=e.mapPos(this.from,1),r=e.mapPos(this.to,-1)),i==this.from&&r==this.to?this:new $r(i,r,this.flags)}extend(e,t=e){if(e<=this.anchor&&t>=this.anchor)return P.range(e,t);let i=Math.abs(e-this.anchor)>Math.abs(t-this.anchor)?e:t;return P.range(this.anchor,i)}eq(e,t=!1){return this.anchor==e.anchor&&this.head==e.head&&(!t||!this.empty||this.assoc==e.assoc)}toJSON(){return{anchor:this.anchor,head:this.head}}static fromJSON(e){if(!e||typeof e.anchor!="number"||typeof e.head!="number")throw new RangeError("Invalid JSON representation for SelectionRange");return P.range(e.anchor,e.head)}static create(e,t,i){return new $r(e,t,i)}}class P{constructor(e,t){this.ranges=e,this.mainIndex=t}map(e,t=-1){return e.empty?this:P.create(this.ranges.map(i=>i.map(e,t)),this.mainIndex)}eq(e,t=!1){if(this.ranges.length!=e.ranges.length||this.mainIndex!=e.mainIndex)return!1;for(let i=0;ie.toJSON()),main:this.mainIndex}}static fromJSON(e){if(!e||!Array.isArray(e.ranges)||typeof e.main!="number"||e.main>=e.ranges.length)throw new RangeError("Invalid JSON representation for EditorSelection");return new P(e.ranges.map(t=>$r.fromJSON(t)),e.main)}static single(e,t=e){return new P([P.range(e,t)],0)}static create(e,t=0){if(e.length==0)throw new RangeError("A selection needs at least one range");for(let i=0,r=0;re?8:0)|s)}static normalized(e,t=0){let i=e[t];e.sort((r,s)=>r.from-s.from),t=e.indexOf(i);for(let r=1;rs.head?P.range(l,a):P.range(a,l))}}return new P(e,t)}}function qO(n,e){for(let t of n.ranges)if(t.to>e)throw new RangeError("Selection points outside of document")}let uf=0;class B{constructor(e,t,i,r,s){this.combine=e,this.compareInput=t,this.compare=i,this.isStatic=r,this.id=uf++,this.default=e([]),this.extensions=typeof s=="function"?s(this):s}get reader(){return this}static define(e={}){return new B(e.combine||(t=>t),e.compareInput||((t,i)=>t===i),e.compare||(e.combine?(t,i)=>t===i:ff),!!e.static,e.enables)}of(e){return new Xa([],this,0,e)}compute(e,t){if(this.isStatic)throw new Error("Can't compute a static facet");return new Xa(e,this,1,t)}computeN(e,t){if(this.isStatic)throw new Error("Can't compute a static facet");return new Xa(e,this,2,t)}from(e,t){return t||(t=i=>i),this.compute([e],i=>t(i.field(e)))}}function ff(n,e){return n==e||n.length==e.length&&n.every((t,i)=>t===e[i])}class Xa{constructor(e,t,i,r){this.dependencies=e,this.facet=t,this.type=i,this.value=r,this.id=uf++}dynamicSlot(e){var t;let i=this.value,r=this.facet.compareInput,s=this.id,o=e[s]>>1,a=this.type==2,l=!1,h=!1,c=[];for(let u of this.dependencies)u=="doc"?l=!0:u=="selection"?h=!0:((t=e[u.id])!==null&&t!==void 0?t:1)&1||c.push(e[u.id]);return{create(u){return u.values[o]=i(u),1},update(u,f){if(l&&f.docChanged||h&&(f.docChanged||f.selection)||jc(u,c)){let p=i(u);if(a?!Fd(p,u.values[o],r):!r(p,u.values[o]))return u.values[o]=p,1}return 0},reconfigure:(u,f)=>{let p,g=f.config.address[s];if(g!=null){let O=kl(f,g);if(this.dependencies.every(y=>y instanceof B?f.facet(y)===u.facet(y):y instanceof Re?f.field(y,!1)==u.field(y,!1):!0)||(a?Fd(p=i(u),O,r):r(p=i(u),O)))return u.values[o]=O,0}else p=i(u);return u.values[o]=p,1}}}}function Fd(n,e,t){if(n.length!=e.length)return!1;for(let i=0;in[l.id]),r=t.map(l=>l.type),s=i.filter(l=>!(l&1)),o=n[e.id]>>1;function a(l){let h=[];for(let c=0;ci===r),e);return e.provide&&(t.provides=e.provide(t)),t}create(e){let t=e.facet(zd).find(i=>i.field==this);return((t==null?void 0:t.create)||this.createF)(e)}slot(e){let t=e[this.id]>>1;return{create:i=>(i.values[t]=this.create(i),1),update:(i,r)=>{let s=i.values[t],o=this.updateF(s,r);return this.compareF(s,o)?0:(i.values[t]=o,1)},reconfigure:(i,r)=>r.config.address[this.id]!=null?(i.values[t]=r.field(this),0):(i.values[t]=this.create(i),1)}}init(e){return[this,zd.of({field:this,create:e})]}get extension(){return this}}const Tr={lowest:4,low:3,default:2,high:1,highest:0};function Ds(n){return e=>new MO(e,n)}const mr={highest:Ds(Tr.highest),high:Ds(Tr.high),default:Ds(Tr.default),low:Ds(Tr.low),lowest:Ds(Tr.lowest)};class MO{constructor(e,t){this.inner=e,this.prec=t}}class oh{of(e){return new Fc(this,e)}reconfigure(e){return oh.reconfigure.of({compartment:this,extension:e})}get(e){return e.config.compartments.get(this)}}class Fc{constructor(e,t){this.compartment=e,this.inner=t}}class vl{constructor(e,t,i,r,s,o){for(this.base=e,this.compartments=t,this.dynamicSlots=i,this.address=r,this.staticValues=s,this.facets=o,this.statusTemplate=[];this.statusTemplate.length>1]}static resolve(e,t,i){let r=[],s=Object.create(null),o=new Map;for(let f of Av(e,t,o))f instanceof Re?r.push(f):(s[f.facet.id]||(s[f.facet.id]=[])).push(f);let a=Object.create(null),l=[],h=[];for(let f of r)a[f.id]=h.length<<1,h.push(p=>f.slot(p));let c=i==null?void 0:i.config.facets;for(let f in s){let p=s[f],g=p[0].facet,O=c&&c[f]||[];if(p.every(y=>y.type==0))if(a[g.id]=l.length<<1|1,ff(O,p))l.push(i.facet(g));else{let y=g.combine(p.map(S=>S.value));l.push(i&&g.compare(y,i.facet(g))?i.facet(g):y)}else{for(let y of p)y.type==0?(a[y.id]=l.length<<1|1,l.push(y.value)):(a[y.id]=h.length<<1,h.push(S=>y.dynamicSlot(S)));a[g.id]=h.length<<1,h.push(y=>Pv(y,g,p))}}let u=h.map(f=>f(a));return new vl(e,o,u,a,l,s)}}function Av(n,e,t){let i=[[],[],[],[],[]],r=new Map;function s(o,a){let l=r.get(o);if(l!=null){if(l<=a)return;let h=i[l].indexOf(o);h>-1&&i[l].splice(h,1),o instanceof Fc&&t.delete(o.compartment)}if(r.set(o,a),Array.isArray(o))for(let h of o)s(h,a);else if(o instanceof Fc){if(t.has(o.compartment))throw new RangeError("Duplicate use of compartment in extensions");let h=e.get(o.compartment)||o.inner;t.set(o.compartment,h),s(h,a)}else if(o instanceof MO)s(o.inner,o.prec);else if(o instanceof Re)i[a].push(o),o.provides&&s(o.provides,a);else if(o instanceof Xa)i[a].push(o),o.facet.extensions&&s(o.facet.extensions,Tr.default);else{let h=o.extension;if(!h)throw new Error(`Unrecognized extension value in extension set (${o}). This sometimes happens because multiple instances of @codemirror/state are loaded, breaking instanceof checks.`);s(h,a)}}return s(n,Tr.default),i.reduce((o,a)=>o.concat(a))}function to(n,e){if(e&1)return 2;let t=e>>1,i=n.status[t];if(i==4)throw new Error("Cyclic dependency between fields and/or facets");if(i&2)return i;n.status[t]=4;let r=n.computeSlot(n,n.config.dynamicSlots[t]);return n.status[t]=2|r}function kl(n,e){return e&1?n.config.staticValues[e>>1]:n.values[e>>1]}const VO=B.define(),zc=B.define({combine:n=>n.some(e=>e),static:!0}),XO=B.define({combine:n=>n.length?n[0]:void 0,static:!0}),LO=B.define(),UO=B.define(),ZO=B.define(),WO=B.define({combine:n=>n.length?n[0]:!1});class jn{constructor(e,t){this.type=e,this.value=t}static define(){return new $v}}class $v{of(e){return new jn(this,e)}}class Cv{constructor(e){this.map=e}of(e){return new z(this,e)}}class z{constructor(e,t){this.type=e,this.value=t}map(e){let t=this.type.map(this.value,e);return t===void 0?void 0:t==this.value?this:new z(this.type,t)}is(e){return this.type==e}static define(e={}){return new Cv(e.map||(t=>t))}static mapEffects(e,t){if(!e.length)return e;let i=[];for(let r of e){let s=r.map(t);s&&i.push(s)}return i}}z.reconfigure=z.define();z.appendConfig=z.define();class ye{constructor(e,t,i,r,s,o){this.startState=e,this.changes=t,this.selection=i,this.effects=r,this.annotations=s,this.scrollIntoView=o,this._doc=null,this._state=null,i&&qO(i,t.newLength),s.some(a=>a.type==ye.time)||(this.annotations=s.concat(ye.time.of(Date.now())))}static create(e,t,i,r,s,o){return new ye(e,t,i,r,s,o)}get newDoc(){return this._doc||(this._doc=this.changes.apply(this.startState.doc))}get newSelection(){return this.selection||this.startState.selection.map(this.changes)}get state(){return this._state||this.startState.applyTransaction(this),this._state}annotation(e){for(let t of this.annotations)if(t.type==e)return t.value}get docChanged(){return!this.changes.empty}get reconfigured(){return this.startState.config!=this.state.config}isUserEvent(e){let t=this.annotation(ye.userEvent);return!!(t&&(t==e||t.length>e.length&&t.slice(0,e.length)==e&&t[e.length]=="."))}}ye.time=jn.define();ye.userEvent=jn.define();ye.addToHistory=jn.define();ye.remote=jn.define();function Iv(n,e){let t=[];for(let i=0,r=0;;){let s,o;if(i=n[i]))s=n[i++],o=n[i++];else if(r=0;r--){let s=i[r](n);s instanceof ye?n=s:Array.isArray(s)&&s.length==1&&s[0]instanceof ye?n=s[0]:n=FO(e,rs(s),!1)}return n}function Ev(n){let e=n.startState,t=e.facet(ZO),i=n;for(let r=t.length-1;r>=0;r--){let s=t[r](n);s&&Object.keys(s).length&&(i=jO(i,_c(e,s,n.changes.newLength),!0))}return i==n?n:ye.create(e,n.changes,n.selection,i.effects,i.annotations,i.scrollIntoView)}const Dv=[];function rs(n){return n==null?Dv:Array.isArray(n)?n:[n]}var fe=function(n){return n[n.Word=0]="Word",n[n.Space=1]="Space",n[n.Other=2]="Other",n}(fe||(fe={}));const Nv=/[\u00df\u0587\u0590-\u05f4\u0600-\u06ff\u3040-\u309f\u30a0-\u30ff\u3400-\u4db5\u4e00-\u9fcc\uac00-\ud7af]/;let Gc;try{Gc=new RegExp("[\\p{Alphabetic}\\p{Number}_]","u")}catch{}function Bv(n){if(Gc)return Gc.test(n);for(let e=0;e"€"&&(t.toUpperCase()!=t.toLowerCase()||Nv.test(t)))return!0}return!1}function qv(n){return e=>{if(!/\S/.test(e))return fe.Space;if(Bv(e))return fe.Word;for(let t=0;t-1)return fe.Word;return fe.Other}}class H{constructor(e,t,i,r,s,o){this.config=e,this.doc=t,this.selection=i,this.values=r,this.status=e.statusTemplate.slice(),this.computeSlot=s,o&&(o._state=this);for(let a=0;ar.set(h,l)),t=null),r.set(a.value.compartment,a.value.extension)):a.is(z.reconfigure)?(t=null,i=a.value):a.is(z.appendConfig)&&(t=null,i=rs(i).concat(a.value));let s;t?s=e.startState.values.slice():(t=vl.resolve(i,r,this),s=new H(t,this.doc,this.selection,t.dynamicSlots.map(()=>null),(l,h)=>h.reconfigure(l,this),null).values);let o=e.startState.facet(zc)?e.newSelection:e.newSelection.asSingle();new H(t,e.newDoc,o,s,(a,l)=>l.update(a,e),e)}replaceSelection(e){return typeof e=="string"&&(e=this.toText(e)),this.changeByRange(t=>({changes:{from:t.from,to:t.to,insert:e},range:P.cursor(t.from+e.length)}))}changeByRange(e){let t=this.selection,i=e(t.ranges[0]),r=this.changes(i.changes),s=[i.range],o=rs(i.effects);for(let a=1;ao.spec.fromJSON(a,l)))}}return H.create({doc:e.doc,selection:P.fromJSON(e.selection),extensions:t.extensions?r.concat([t.extensions]):r})}static create(e={}){let t=vl.resolve(e.extensions||[],new Map),i=e.doc instanceof K?e.doc:K.of((e.doc||"").split(t.staticFacet(H.lineSeparator)||Uc)),r=e.selection?e.selection instanceof P?e.selection:P.single(e.selection.anchor,e.selection.head):P.single(0);return qO(r,i.length),t.staticFacet(zc)||(r=r.asSingle()),new H(t,i,r,t.dynamicSlots.map(()=>null),(s,o)=>o.create(s),null)}get tabSize(){return this.facet(H.tabSize)}get lineBreak(){return this.facet(H.lineSeparator)||` +`}get readOnly(){return this.facet(WO)}phrase(e,...t){for(let i of this.facet(H.phrases))if(Object.prototype.hasOwnProperty.call(i,e)){e=i[e];break}return t.length&&(e=e.replace(/\$(\$|\d*)/g,(i,r)=>{if(r=="$")return"$";let s=+(r||1);return!s||s>t.length?i:t[s-1]})),e}languageDataAt(e,t,i=-1){let r=[];for(let s of this.facet(VO))for(let o of s(this,t,i))Object.prototype.hasOwnProperty.call(o,e)&&r.push(o[e]);return r}charCategorizer(e){return qv(this.languageDataAt("wordChars",e).join(""))}wordAt(e){let{text:t,from:i,length:r}=this.doc.lineAt(e),s=this.charCategorizer(e),o=e-i,a=e-i;for(;o>0;){let l=We(t,o,!1);if(s(t.slice(l,o))!=fe.Word)break;o=l}for(;an.length?n[0]:4});H.lineSeparator=XO;H.readOnly=WO;H.phrases=B.define({compare(n,e){let t=Object.keys(n),i=Object.keys(e);return t.length==i.length&&t.every(r=>n[r]==e[r])}});H.languageData=VO;H.changeFilter=LO;H.transactionFilter=UO;H.transactionExtender=ZO;oh.reconfigure=z.define();function Ai(n,e,t={}){let i={};for(let r of n)for(let s of Object.keys(r)){let o=r[s],a=i[s];if(a===void 0)i[s]=o;else if(!(a===o||o===void 0))if(Object.hasOwnProperty.call(t,s))i[s]=t[s](a,o);else throw new Error("Config merge conflict for field "+s)}for(let r in e)i[r]===void 0&&(i[r]=e[r]);return i}class Br{eq(e){return this==e}range(e,t=e){return Jc.create(e,t,this)}}Br.prototype.startSide=Br.prototype.endSide=0;Br.prototype.point=!1;Br.prototype.mapMode=qe.TrackDel;let Jc=class zO{constructor(e,t,i){this.from=e,this.to=t,this.value=i}static create(e,t,i){return new zO(e,t,i)}};function Yc(n,e){return n.from-e.from||n.value.startSide-e.value.startSide}class df{constructor(e,t,i,r){this.from=e,this.to=t,this.value=i,this.maxPoint=r}get length(){return this.to[this.to.length-1]}findIndex(e,t,i,r=0){let s=i?this.to:this.from;for(let o=r,a=s.length;;){if(o==a)return o;let l=o+a>>1,h=s[l]-e||(i?this.value[l].endSide:this.value[l].startSide)-t;if(l==o)return h>=0?o:a;h>=0?a=l:o=l+1}}between(e,t,i,r){for(let s=this.findIndex(t,-1e9,!0),o=this.findIndex(i,1e9,!1,s);sp||f==p&&h.startSide>0&&h.endSide<=0)continue;(p-f||h.endSide-h.startSide)<0||(o<0&&(o=f),h.point&&(a=Math.max(a,p-f)),i.push(h),r.push(f-o),s.push(p-o))}return{mapped:i.length?new df(r,s,i,a):null,pos:o}}}class J{constructor(e,t,i,r){this.chunkPos=e,this.chunk=t,this.nextLayer=i,this.maxPoint=r}static create(e,t,i,r){return new J(e,t,i,r)}get length(){let e=this.chunk.length-1;return e<0?0:Math.max(this.chunkEnd(e),this.nextLayer.length)}get size(){if(this.isEmpty)return 0;let e=this.nextLayer.size;for(let t of this.chunk)e+=t.value.length;return e}chunkEnd(e){return this.chunkPos[e]+this.chunk[e].length}update(e){let{add:t=[],sort:i=!1,filterFrom:r=0,filterTo:s=this.length}=e,o=e.filter;if(t.length==0&&!o)return this;if(i&&(t=t.slice().sort(Yc)),this.isEmpty)return t.length?J.of(t):this;let a=new _O(this,null,-1).goto(0),l=0,h=[],c=new fr;for(;a.value||l=0){let u=t[l++];c.addInner(u.from,u.to,u.value)||h.push(u)}else a.rangeIndex==1&&a.chunkIndexthis.chunkEnd(a.chunkIndex)||sa.to||s=s&&e<=s+o.length&&o.between(s,e-s,t-s,i)===!1)return}this.nextLayer.between(e,t,i)}}iter(e=0){return So.from([this]).goto(e)}get isEmpty(){return this.nextLayer==this}static iter(e,t=0){return So.from(e).goto(t)}static compare(e,t,i,r,s=-1){let o=e.filter(u=>u.maxPoint>0||!u.isEmpty&&u.maxPoint>=s),a=t.filter(u=>u.maxPoint>0||!u.isEmpty&&u.maxPoint>=s),l=_d(o,a,i),h=new Ns(o,l,s),c=new Ns(a,l,s);i.iterGaps((u,f,p)=>Gd(h,u,c,f,p,r)),i.empty&&i.length==0&&Gd(h,0,c,0,0,r)}static eq(e,t,i=0,r){r==null&&(r=999999999);let s=e.filter(c=>!c.isEmpty&&t.indexOf(c)<0),o=t.filter(c=>!c.isEmpty&&e.indexOf(c)<0);if(s.length!=o.length)return!1;if(!s.length)return!0;let a=_d(s,o),l=new Ns(s,a,0).goto(i),h=new Ns(o,a,0).goto(i);for(;;){if(l.to!=h.to||!Hc(l.active,h.active)||l.point&&(!h.point||!l.point.eq(h.point)))return!1;if(l.to>r)return!0;l.next(),h.next()}}static spans(e,t,i,r,s=-1){let o=new Ns(e,null,s).goto(t),a=t,l=o.openStart;for(;;){let h=Math.min(o.to,i);if(o.point){let c=o.activeForPoint(o.to),u=o.pointFroma&&(r.span(a,h,o.active,l),l=o.openEnd(h));if(o.to>i)return l+(o.point&&o.to>i?1:0);a=o.to,o.next()}}static of(e,t=!1){let i=new fr;for(let r of e instanceof Jc?[e]:t?Mv(e):e)i.add(r.from,r.to,r.value);return i.finish()}static join(e){if(!e.length)return J.empty;let t=e[e.length-1];for(let i=e.length-2;i>=0;i--)for(let r=e[i];r!=J.empty;r=r.nextLayer)t=new J(r.chunkPos,r.chunk,t,Math.max(r.maxPoint,t.maxPoint));return t}}J.empty=new J([],[],null,-1);function Mv(n){if(n.length>1)for(let e=n[0],t=1;t0)return n.slice().sort(Yc);e=i}return n}J.empty.nextLayer=J.empty;class fr{finishChunk(e){this.chunks.push(new df(this.from,this.to,this.value,this.maxPoint)),this.chunkPos.push(this.chunkStart),this.chunkStart=-1,this.setMaxPoint=Math.max(this.setMaxPoint,this.maxPoint),this.maxPoint=-1,e&&(this.from=[],this.to=[],this.value=[])}constructor(){this.chunks=[],this.chunkPos=[],this.chunkStart=-1,this.last=null,this.lastFrom=-1e9,this.lastTo=-1e9,this.from=[],this.to=[],this.value=[],this.maxPoint=-1,this.setMaxPoint=-1,this.nextLayer=null}add(e,t,i){this.addInner(e,t,i)||(this.nextLayer||(this.nextLayer=new fr)).add(e,t,i)}addInner(e,t,i){let r=e-this.lastTo||i.startSide-this.last.endSide;if(r<=0&&(e-this.lastFrom||i.startSide-this.last.startSide)<0)throw new Error("Ranges must be added sorted by `from` position and `startSide`");return r<0?!1:(this.from.length==250&&this.finishChunk(!0),this.chunkStart<0&&(this.chunkStart=e),this.from.push(e-this.chunkStart),this.to.push(t-this.chunkStart),this.last=i,this.lastFrom=e,this.lastTo=t,this.value.push(i),i.point&&(this.maxPoint=Math.max(this.maxPoint,t-e)),!0)}addChunk(e,t){if((e-this.lastTo||t.value[0].startSide-this.last.endSide)<0)return!1;this.from.length&&this.finishChunk(!0),this.setMaxPoint=Math.max(this.setMaxPoint,t.maxPoint),this.chunks.push(t),this.chunkPos.push(e);let i=t.value.length-1;return this.last=t.value[i],this.lastFrom=t.from[i]+e,this.lastTo=t.to[i]+e,!0}finish(){return this.finishInner(J.empty)}finishInner(e){if(this.from.length&&this.finishChunk(!1),this.chunks.length==0)return e;let t=J.create(this.chunkPos,this.chunks,this.nextLayer?this.nextLayer.finishInner(e):e,this.setMaxPoint);return this.from=null,t}}function _d(n,e,t){let i=new Map;for(let s of n)for(let o=0;o=this.minPoint)break}}setRangeIndex(e){if(e==this.layer.chunk[this.chunkIndex].value.length){if(this.chunkIndex++,this.skip)for(;this.chunkIndex=i&&r.push(new _O(o,t,i,s));return r.length==1?r[0]:new So(r)}get startSide(){return this.value?this.value.startSide:0}goto(e,t=-1e9){for(let i of this.heap)i.goto(e,t);for(let i=this.heap.length>>1;i>=0;i--)Eh(this.heap,i);return this.next(),this}forward(e,t){for(let i of this.heap)i.forward(e,t);for(let i=this.heap.length>>1;i>=0;i--)Eh(this.heap,i);(this.to-e||this.value.endSide-t)<0&&this.next()}next(){if(this.heap.length==0)this.from=this.to=1e9,this.value=null,this.rank=-1;else{let e=this.heap[0];this.from=e.from,this.to=e.to,this.value=e.value,this.rank=e.rank,e.value&&e.next(),Eh(this.heap,0)}}}function Eh(n,e){for(let t=n[e];;){let i=(e<<1)+1;if(i>=n.length)break;let r=n[i];if(i+1=0&&(r=n[i+1],i++),t.compare(r)<0)break;n[i]=t,n[e]=r,e=i}}class Ns{constructor(e,t,i){this.minPoint=i,this.active=[],this.activeTo=[],this.activeRank=[],this.minActive=-1,this.point=null,this.pointFrom=0,this.pointRank=0,this.to=-1e9,this.endSide=0,this.openStart=-1,this.cursor=So.from(e,t,i)}goto(e,t=-1e9){return this.cursor.goto(e,t),this.active.length=this.activeTo.length=this.activeRank.length=0,this.minActive=-1,this.to=e,this.endSide=t,this.openStart=-1,this.next(),this}forward(e,t){for(;this.minActive>-1&&(this.activeTo[this.minActive]-e||this.active[this.minActive].endSide-t)<0;)this.removeActive(this.minActive);this.cursor.forward(e,t)}removeActive(e){sa(this.active,e),sa(this.activeTo,e),sa(this.activeRank,e),this.minActive=Jd(this.active,this.activeTo)}addActive(e){let t=0,{value:i,to:r,rank:s}=this.cursor;for(;t0;)t++;oa(this.active,t,i),oa(this.activeTo,t,r),oa(this.activeRank,t,s),e&&oa(e,t,this.cursor.from),this.minActive=Jd(this.active,this.activeTo)}next(){let e=this.to,t=this.point;this.point=null;let i=this.openStart<0?[]:null;for(;;){let r=this.minActive;if(r>-1&&(this.activeTo[r]-this.cursor.from||this.active[r].endSide-this.cursor.startSide)<0){if(this.activeTo[r]>e){this.to=this.activeTo[r],this.endSide=this.active[r].endSide;break}this.removeActive(r),i&&sa(i,r)}else if(this.cursor.value)if(this.cursor.from>e){this.to=this.cursor.from,this.endSide=this.cursor.startSide;break}else{let s=this.cursor.value;if(!s.point)this.addActive(i),this.cursor.next();else if(t&&this.cursor.to==this.to&&this.cursor.from=0&&i[r]=0&&!(this.activeRank[i]e||this.activeTo[i]==e&&this.active[i].endSide>=this.point.endSide)&&t.push(this.active[i]);return t.reverse()}openEnd(e){let t=0;for(let i=this.activeTo.length-1;i>=0&&this.activeTo[i]>e;i--)t++;return t}}function Gd(n,e,t,i,r,s){n.goto(e),t.goto(i);let o=i+r,a=i,l=i-e;for(;;){let h=n.to+l-t.to||n.endSide-t.endSide,c=h<0?n.to+l:t.to,u=Math.min(c,o);if(n.point||t.point?n.point&&t.point&&(n.point==t.point||n.point.eq(t.point))&&Hc(n.activeForPoint(n.to),t.activeForPoint(t.to))||s.comparePoint(a,u,n.point,t.point):u>a&&!Hc(n.active,t.active)&&s.compareRange(a,u,n.active,t.active),c>o)break;a=c,h<=0&&n.next(),h>=0&&t.next()}}function Hc(n,e){if(n.length!=e.length)return!1;for(let t=0;t=e;i--)n[i+1]=n[i];n[e]=t}function Jd(n,e){let t=-1,i=1e9;for(let r=0;r=e)return r;if(r==n.length)break;s+=n.charCodeAt(r)==9?t-s%t:1,r=We(n,r)}return i===!0?-1:n.length}const eu="ͼ",Yd=typeof Symbol>"u"?"__"+eu:Symbol.for(eu),tu=typeof Symbol>"u"?"__styleSet"+Math.floor(Math.random()*1e8):Symbol("styleSet"),Hd=typeof globalThis<"u"?globalThis:typeof window<"u"?window:{};let Os=class{constructor(e,t){this.rules=[];let{finish:i}=t||{};function r(o){return/^@/.test(o)?[o]:o.split(/,\s*/)}function s(o,a,l,h){let c=[],u=/^@(\w+)\b/.exec(o[0]),f=u&&u[1]=="keyframes";if(u&&a==null)return l.push(o[0]+";");for(let p in a){let g=a[p];if(/&/.test(p))s(p.split(/,\s*/).map(O=>o.map(y=>O.replace(/&/,y))).reduce((O,y)=>O.concat(y)),g,l);else if(g&&typeof g=="object"){if(!u)throw new RangeError("The value of a property ("+p+") should be a primitive value.");s(r(p),g,c,f)}else g!=null&&c.push(p.replace(/_.*/,"").replace(/[A-Z]/g,O=>"-"+O.toLowerCase())+": "+g+";")}(c.length||f)&&l.push((i&&!u&&!h?o.map(i):o).join(", ")+" {"+c.join(" ")+"}")}for(let o in e)s(r(o),e[o],this.rules)}getRules(){return this.rules.join(` `)}static newName(){let e=Hd[Yd]||1;return Hd[Yd]=e+1,eu+e.toString(36)}static mount(e,t,i){let r=e[tu],s=i&&i.nonce;r?s&&r.setNonce(s):r=new Vv(e,s),r.mount(Array.isArray(t)?t:[t],e)}},Kd=new Map,Vv=class{constructor(e,t){let i=e.ownerDocument||e,r=i.defaultView;if(!e.head&&e.adoptedStyleSheets&&r.CSSStyleSheet){let s=Kd.get(i);if(s)return e[tu]=s;this.sheet=new r.CSSStyleSheet,Kd.set(i,this)}else this.styleTag=i.createElement("style"),t&&this.styleTag.setAttribute("nonce",t);this.modules=[],e[tu]=this}mount(e,t){let i=this.sheet,r=0,s=0;for(let o=0;o-1&&(this.modules.splice(l,1),s--,l=-1),l==-1){if(this.modules.splice(s++,0,a),i)for(let h=0;h",191:"?",192:"~",219:"{",220:"|",221:"}",222:'"'},ep=typeof navigator<"u"&&/Chrome\/(\d+)/.exec(navigator.userAgent),Xv=typeof navigator<"u"&&/Mac/.test(navigator.platform),Lv=typeof navigator<"u"&&/MSIE \d|Trident\/(?:[7-9]|\d{2,})\..*rv:(\d+)/.exec(navigator.userAgent),Uv=Xv||ep&&+ep[1]<57;for(var Be=0;Be<10;Be++)dr[48+Be]=dr[96+Be]=String(Be);for(var Be=1;Be<=24;Be++)dr[Be+111]="F"+Be;for(var Be=65;Be<=90;Be++)dr[Be]=String.fromCharCode(Be+32),wo[Be]=String.fromCharCode(Be);for(var Dh in dr)wo.hasOwnProperty(Dh)||(wo[Dh]=dr[Dh]);function Zv(n){var e=Uv&&(n.ctrlKey||n.altKey||n.metaKey)||Lv&&n.shiftKey&&n.key&&n.key.length==1||n.key=="Unidentified",t=!e&&n.key||(n.shiftKey?wo:dr)[n.keyCode]||n.key||"Unidentified";return t=="Esc"&&(t="Escape"),t=="Del"&&(t="Delete"),t=="Left"&&(t="ArrowLeft"),t=="Up"&&(t="ArrowUp"),t=="Right"&&(t="ArrowRight"),t=="Down"&&(t="ArrowDown"),t}function xl(n){let e;return n.nodeType==11?e=n.getSelection?n:n.ownerDocument:e=n,e.getSelection()}function iu(n,e){return e?n==e||n.contains(e.nodeType!=1?e.parentNode:e):!1}function Wv(n){let e=n.activeElement;for(;e&&e.shadowRoot;)e=e.shadowRoot.activeElement;return e}function La(n,e){if(!e.anchorNode)return!1;try{return iu(n,e.anchorNode)}catch{return!1}}function vo(n){return n.nodeType==3?qr(n,0,n.nodeValue.length).getClientRects():n.nodeType==1?n.getClientRects():[]}function io(n,e,t,i){return t?tp(n,e,t,i,-1)||tp(n,e,t,i,1):!1}function ko(n){for(var e=0;;e++)if(n=n.previousSibling,!n)return e}function tp(n,e,t,i,r){for(;;){if(n==t&&e==i)return!0;if(e==(r<0?0:Xn(n))){if(n.nodeName=="DIV")return!1;let s=n.parentNode;if(!s||s.nodeType!=1)return!1;e=ko(n)+(r<0?0:1),n=s}else if(n.nodeType==1){if(n=n.childNodes[e+(r<0?-1:0)],n.nodeType==1&&n.contentEditable=="false")return!1;e=r<0?Xn(n):0}else return!1}}function Xn(n){return n.nodeType==3?n.nodeValue.length:n.childNodes.length}function pf(n,e){let t=e?n.left:n.right;return{left:t,right:t,top:n.top,bottom:n.bottom}}function jv(n){return{left:0,right:n.innerWidth,top:0,bottom:n.innerHeight}}function GO(n,e){let t=e.width/n.offsetWidth,i=e.height/n.offsetHeight;return(t>.995&&t<1.005||!isFinite(t)||Math.abs(e.width-n.offsetWidth)<1)&&(t=1),(i>.995&&i<1.005||!isFinite(i)||Math.abs(e.height-n.offsetHeight)<1)&&(i=1),{scaleX:t,scaleY:i}}function Fv(n,e,t,i,r,s,o,a){let l=n.ownerDocument,h=l.defaultView||window;for(let c=n,u=!1;c&&!u;)if(c.nodeType==1){let f,p=c==l.body,g=1,y=1;if(p)f=jv(h);else{if(/^(fixed|sticky)$/.test(getComputedStyle(c).position)&&(u=!0),c.scrollHeight<=c.clientHeight&&c.scrollWidth<=c.clientWidth){c=c.assignedSlot||c.parentNode;continue}let k=c.getBoundingClientRect();({scaleX:g,scaleY:y}=GO(c,k)),f={left:k.left,right:k.left+c.clientWidth*g,top:k.top,bottom:k.top+c.clientHeight*y}}let O=0,S=0;if(r=="nearest")e.top0&&e.bottom>f.bottom+S&&(S=e.bottom-f.bottom+S+o)):e.bottom>f.bottom&&(S=e.bottom-f.bottom+o,t<0&&e.top-S0&&e.right>f.right+O&&(O=e.right-f.right+O+s)):e.right>f.right&&(O=e.right-f.right+s,t<0&&e.leftt.clientHeight||t.scrollWidth>t.clientWidth)return t;t=t.assignedSlot||t.parentNode}else if(t.nodeType==11)t=t.host;else break;return null}class _v{constructor(){this.anchorNode=null,this.anchorOffset=0,this.focusNode=null,this.focusOffset=0}eq(e){return this.anchorNode==e.anchorNode&&this.anchorOffset==e.anchorOffset&&this.focusNode==e.focusNode&&this.focusOffset==e.focusOffset}setRange(e){let{anchorNode:t,focusNode:i}=e;this.set(t,Math.min(e.anchorOffset,t?Xn(t):0),i,Math.min(e.focusOffset,i?Xn(i):0))}set(e,t,i,r){this.anchorNode=e,this.anchorOffset=t,this.focusNode=i,this.focusOffset=r}}let jr=null;function JO(n){if(n.setActive)return n.setActive();if(jr)return n.focus(jr);let e=[];for(let t=n;t&&(e.push(t,t.scrollTop,t.scrollLeft),t!=t.ownerDocument);t=t.parentNode);if(n.focus(jr==null?{get preventScroll(){return jr={preventScroll:!0},!0}}:void 0),!jr){jr=!1;for(let t=0;tMath.max(1,n.scrollHeight-n.clientHeight-4)}class Ze{constructor(e,t,i=!0){this.node=e,this.offset=t,this.precise=i}static before(e,t){return new Ze(e.parentNode,ko(e),t)}static after(e,t){return new Ze(e.parentNode,ko(e)+1,t)}}const gf=[];class he{constructor(){this.parent=null,this.dom=null,this.flags=2}get overrideDOMText(){return null}get posAtStart(){return this.parent?this.parent.posBefore(this):0}get posAtEnd(){return this.posAtStart+this.length}posBefore(e){let t=this.posAtStart;for(let i of this.children){if(i==e)return t;t+=i.length+i.breakAfter}throw new RangeError("Invalid child in posBefore")}posAfter(e){return this.posBefore(e)+e.length}sync(e,t){if(this.flags&2){let i=this.dom,r=null,s;for(let o of this.children){if(o.flags&7){if(!o.dom&&(s=r?r.nextSibling:i.firstChild)){let a=he.get(s);(!a||!a.parent&&a.canReuseDOM(o))&&o.reuseDOM(s)}o.sync(e,t),o.flags&=-8}if(s=r?r.nextSibling:i.firstChild,t&&!t.written&&t.node==i&&s!=o.dom&&(t.written=!0),o.dom.parentNode==i)for(;s&&s!=o.dom;)s=np(s);else i.insertBefore(o.dom,s);r=o.dom}for(s=r?r.nextSibling:i.firstChild,s&&t&&t.node==i&&(t.written=!0);s;)s=np(s)}else if(this.flags&1)for(let i of this.children)i.flags&7&&(i.sync(e,t),i.flags&=-8)}reuseDOM(e){}localPosFromDOM(e,t){let i;if(e==this.dom)i=this.dom.childNodes[t];else{let r=Xn(e)==0?0:t==0?-1:1;for(;;){let s=e.parentNode;if(s==this.dom)break;r==0&&s.firstChild!=s.lastChild&&(e==s.firstChild?r=-1:r=1),e=s}r<0?i=e:i=e.nextSibling}if(i==this.dom.firstChild)return 0;for(;i&&!he.get(i);)i=i.nextSibling;if(!i)return this.length;for(let r=0,s=0;;r++){let o=this.children[r];if(o.dom==i)return s;s+=o.length+o.breakAfter}}domBoundsAround(e,t,i=0){let r=-1,s=-1,o=-1,a=-1;for(let l=0,h=i,c=i;lt)return u.domBoundsAround(e,t,h);if(f>=e&&r==-1&&(r=l,s=h),h>t&&u.dom.parentNode==this.dom){o=l,a=c;break}c=f,h=f+u.breakAfter}return{from:s,to:a<0?i+this.length:a,startDOM:(r?this.children[r-1].dom.nextSibling:null)||this.dom.firstChild,endDOM:o=0?this.children[o].dom:null}}markDirty(e=!1){this.flags|=2,this.markParentsDirty(e)}markParentsDirty(e){for(let t=this.parent;t;t=t.parent){if(e&&(t.flags|=2),t.flags&1)return;t.flags|=1,e=!1}}setParent(e){this.parent!=e&&(this.parent=e,this.flags&7&&this.markParentsDirty(!0))}setDOM(e){this.dom!=e&&(this.dom&&(this.dom.cmView=null),this.dom=e,e.cmView=this)}get rootView(){for(let e=this;;){let t=e.parent;if(!t)return e;e=t}}replaceChildren(e,t,i=gf){this.markDirty();for(let r=e;rthis.pos||e==this.pos&&(t>0||this.i==0||this.children[this.i-1].breakAfter))return this.off=e-this.pos,this;let i=this.children[--this.i];this.pos-=i.length+i.breakAfter}}}function e0(n,e,t,i,r,s,o,a,l){let{children:h}=n,c=h.length?h[e]:null,u=s.length?s[s.length-1]:null,f=u?u.breakAfter:o;if(!(e==i&&c&&!o&&!f&&s.length<2&&c.merge(t,r,s.length?u:null,t==0,a,l))){if(i0&&(!o&&s.length&&c.merge(t,c.length,s[0],!1,a,0)?c.breakAfter=s.shift().breakAfter:(t2);var q={mac:op||/Mac/.test(ht.platform),windows:/Win/.test(ht.platform),linux:/Linux|X11/.test(ht.platform),ie:ah,ie_version:i0?nu.documentMode||6:su?+su[1]:ru?+ru[1]:0,gecko:rp,gecko_version:rp?+(/Firefox\/(\d+)/.exec(ht.userAgent)||[0,0])[1]:0,chrome:!!Nh,chrome_version:Nh?+Nh[1]:0,ios:op,android:/Android\b/.test(ht.userAgent),webkit:sp,safari:n0,webkit_version:sp?+(/\bAppleWebKit\/(\d+)/.exec(navigator.userAgent)||[0,0])[1]:0,tabSize:nu.documentElement.style.tabSize!=null?"tab-size":"-moz-tab-size"};const Yv=256;class Ln extends he{constructor(e){super(),this.text=e}get length(){return this.text.length}createDOM(e){this.setDOM(e||document.createTextNode(this.text))}sync(e,t){this.dom||this.createDOM(),this.dom.nodeValue!=this.text&&(t&&t.node==this.dom&&(t.written=!0),this.dom.nodeValue=this.text)}reuseDOM(e){e.nodeType==3&&this.createDOM(e)}merge(e,t,i){return this.flags&8||i&&(!(i instanceof Ln)||this.length-(t-e)+i.length>Yv||i.flags&8)?!1:(this.text=this.text.slice(0,e)+(i?i.text:"")+this.text.slice(t),this.markDirty(),!0)}split(e){let t=new Ln(this.text.slice(e));return this.text=this.text.slice(0,e),this.markDirty(),t.flags|=this.flags&8,t}localPosFromDOM(e,t){return e==this.dom?t:t?this.text.length:0}domAtPos(e){return new Ze(this.dom,e)}domBoundsAround(e,t,i){return{from:i,to:i+this.length,startDOM:this.dom,endDOM:this.dom.nextSibling}}coordsAt(e,t){return Hv(this.dom,e,t)}}class Un extends he{constructor(e,t=[],i=0){super(),this.mark=e,this.children=t,this.length=i;for(let r of t)r.setParent(this)}setAttrs(e){if(YO(e),this.mark.class&&(e.className=this.mark.class),this.mark.attrs)for(let t in this.mark.attrs)e.setAttribute(t,this.mark.attrs[t]);return e}canReuseDOM(e){return super.canReuseDOM(e)&&!((this.flags|e.flags)&8)}reuseDOM(e){e.nodeName==this.mark.tagName.toUpperCase()&&(this.setDOM(e),this.flags|=6)}sync(e,t){this.dom?this.flags&4&&this.setAttrs(this.dom):this.setDOM(this.setAttrs(document.createElement(this.mark.tagName))),super.sync(e,t)}merge(e,t,i,r,s,o){return i&&(!(i instanceof Un&&i.mark.eq(this.mark))||e&&s<=0||te&&t.push(i=e&&(r=s),i=l,s++}let o=this.length-e;return this.length=e,r>-1&&(this.children.length=r,this.markDirty()),new Un(this.mark,t,o)}domAtPos(e){return r0(this,e)}coordsAt(e,t){return o0(this,e,t)}}function Hv(n,e,t){let i=n.nodeValue.length;e>i&&(e=i);let r=e,s=e,o=0;e==0&&t<0||e==i&&t>=0?q.chrome||q.gecko||(e?(r--,o=1):s=0)?0:a.length-1];return q.safari&&!o&&l.width==0&&(l=Array.prototype.find.call(a,h=>h.width)||l),o?pf(l,o<0):l||null}class tr extends he{static create(e,t,i){return new tr(e,t,i)}constructor(e,t,i){super(),this.widget=e,this.length=t,this.side=i,this.prevWidget=null}split(e){let t=tr.create(this.widget,this.length-e,this.side);return this.length-=e,t}sync(e){(!this.dom||!this.widget.updateDOM(this.dom,e))&&(this.dom&&this.prevWidget&&this.prevWidget.destroy(this.dom),this.prevWidget=null,this.setDOM(this.widget.toDOM(e)),this.widget.editable||(this.dom.contentEditable="false"))}getSide(){return this.side}merge(e,t,i,r,s,o){return i&&(!(i instanceof tr)||!this.widget.compare(i.widget)||e>0&&s<=0||t0)?Ze.before(this.dom):Ze.after(this.dom,e==this.length)}domBoundsAround(){return null}coordsAt(e,t){let i=this.widget.coordsAt(this.dom,e,t);if(i)return i;let r=this.dom.getClientRects(),s=null;if(!r.length)return null;let o=this.side?this.side<0:e>0;for(let a=o?r.length-1:0;s=r[a],!(e>0?a==0:a==r.length-1||s.top0?Ze.before(this.dom):Ze.after(this.dom)}localPosFromDOM(){return 0}domBoundsAround(){return null}coordsAt(e){return this.dom.getBoundingClientRect()}get overrideDOMText(){return K.empty}get isHidden(){return!0}}Ln.prototype.children=tr.prototype.children=ys.prototype.children=gf;function r0(n,e){let t=n.dom,{children:i}=n,r=0;for(let s=0;rs&&e0;s--){let o=i[s-1];if(o.dom.parentNode==t)return o.domAtPos(o.length)}for(let s=r;s0&&e instanceof Un&&r.length&&(i=r[r.length-1])instanceof Un&&i.mark.eq(e.mark)?s0(i,e.children[0],t-1):(r.push(e),e.setParent(n)),n.length+=e.length}function o0(n,e,t){let i=null,r=-1,s=null,o=-1;function a(h,c){for(let u=0,f=0;u=c&&(p.children.length?a(p,c-f):(!s||s.isHidden&&t>0)&&(g>c||f==g&&p.getSide()>0)?(s=p,o=c-f):(f-1?1:0)!=r.length-(t&&r.indexOf(t)>-1?1:0))return!1;for(let s of i)if(s!=t&&(r.indexOf(s)==-1||n[s]!==e[s]))return!1;return!0}function au(n,e,t){let i=!1;if(e)for(let r in e)t&&r in t||(i=!0,r=="style"?n.style.cssText="":n.removeAttribute(r));if(t)for(let r in t)e&&e[r]==t[r]||(i=!0,r=="style"?n.style.cssText=t[r]:n.setAttribute(r,t[r]));return i}function ek(n){let e=Object.create(null);for(let t=0;t0&&this.children[i-1].length==0;)this.children[--i].destroy();return this.children.length=i,this.markDirty(),this.length=e,t}transferDOM(e){this.dom&&(this.markDirty(),e.setDOM(this.dom),e.prevAttrs=this.prevAttrs===void 0?this.attrs:this.prevAttrs,this.prevAttrs=void 0,this.dom=null)}setDeco(e){mf(this.attrs,e)||(this.dom&&(this.prevAttrs=this.attrs,this.markDirty()),this.attrs=e)}append(e,t){s0(this,e,t)}addLineDeco(e){let t=e.spec.attributes,i=e.spec.class;t&&(this.attrs=ou(t,this.attrs||{})),i&&(this.attrs=ou({class:i},this.attrs||{}))}domAtPos(e){return r0(this,e)}reuseDOM(e){e.nodeName=="DIV"&&(this.setDOM(e),this.flags|=6)}sync(e,t){var i;this.dom?this.flags&4&&(YO(this.dom),this.dom.className="cm-line",this.prevAttrs=this.attrs?null:void 0):(this.setDOM(document.createElement("div")),this.dom.className="cm-line",this.prevAttrs=this.attrs?null:void 0),this.prevAttrs!==void 0&&(au(this.dom,this.prevAttrs,this.attrs),this.dom.classList.add("cm-line"),this.prevAttrs=void 0),super.sync(e,t);let r=this.dom.lastChild;for(;r&&he.get(r)instanceof Un;)r=r.lastChild;if(!r||!this.length||r.nodeName!="BR"&&((i=he.get(r))===null||i===void 0?void 0:i.isEditable)==!1&&(!q.ios||!this.children.some(s=>s instanceof Ln))){let s=document.createElement("BR");s.cmIgnore=!0,this.dom.appendChild(s)}}measureTextSize(){if(this.children.length==0||this.length>20)return null;let e=0,t;for(let i of this.children){if(!(i instanceof Ln)||/[^ -~]/.test(i.text))return null;let r=vo(i.dom);if(r.length!=1)return null;e+=r[0].width,t=r[0].height}return e?{lineHeight:this.dom.getBoundingClientRect().height,charWidth:e/this.length,textHeight:t}:null}coordsAt(e,t){let i=o0(this,e,t);if(!this.children.length&&i&&this.parent){let{heightOracle:r}=this.parent.view.viewState,s=i.bottom-i.top;if(Math.abs(s-r.lineHeight)<2&&r.textHeight=t){if(s instanceof Ae)return s;if(o>t)break}r=o+s.breakAfter}return null}}class or extends he{constructor(e,t,i){super(),this.widget=e,this.length=t,this.deco=i,this.breakAfter=0,this.prevWidget=null}merge(e,t,i,r,s,o){return i&&(!(i instanceof or)||!this.widget.compare(i.widget)||e>0&&s<=0||t0}}class Or{eq(e){return!1}updateDOM(e,t){return!1}compare(e){return this==e||this.constructor==e.constructor&&this.eq(e)}get estimatedHeight(){return-1}get lineBreaks(){return 0}ignoreEvent(e){return!0}coordsAt(e,t,i){return null}get isHidden(){return!1}get editable(){return!1}destroy(e){}}var Je=function(n){return n[n.Text=0]="Text",n[n.WidgetBefore=1]="WidgetBefore",n[n.WidgetAfter=2]="WidgetAfter",n[n.WidgetRange=3]="WidgetRange",n}(Je||(Je={}));class Z extends Br{constructor(e,t,i,r){super(),this.startSide=e,this.endSide=t,this.widget=i,this.spec=r}get heightRelevant(){return!1}static mark(e){return new Zo(e)}static widget(e){let t=Math.max(-1e4,Math.min(1e4,e.side||0)),i=!!e.block;return t+=i&&!e.inlineOrder?t>0?3e8:-4e8:t>0?1e8:-1e8,new pr(e,t,t,i,e.widget||null,!1)}static replace(e){let t=!!e.block,i,r;if(e.isBlockGap)i=-5e8,r=4e8;else{let{start:s,end:o}=a0(e,t);i=(s?t?-3e8:-1:5e8)-1,r=(o?t?2e8:1:-6e8)+1}return new pr(e,i,r,t,e.widget||null,!0)}static line(e){return new Wo(e)}static set(e,t=!1){return J.of(e,t)}hasHeight(){return this.widget?this.widget.estimatedHeight>-1:!1}}Z.none=J.empty;class Zo extends Z{constructor(e){let{start:t,end:i}=a0(e);super(t?-1:5e8,i?1:-6e8,null,e),this.tagName=e.tagName||"span",this.class=e.class||"",this.attrs=e.attributes||null}eq(e){var t,i;return this==e||e instanceof Zo&&this.tagName==e.tagName&&(this.class||((t=this.attrs)===null||t===void 0?void 0:t.class))==(e.class||((i=e.attrs)===null||i===void 0?void 0:i.class))&&mf(this.attrs,e.attrs,"class")}range(e,t=e){if(e>=t)throw new RangeError("Mark decorations may not be empty");return super.range(e,t)}}Zo.prototype.point=!1;class Wo extends Z{constructor(e){super(-2e8,-2e8,null,e)}eq(e){return e instanceof Wo&&this.spec.class==e.spec.class&&mf(this.spec.attributes,e.spec.attributes)}range(e,t=e){if(t!=e)throw new RangeError("Line decoration ranges must be zero-length");return super.range(e,t)}}Wo.prototype.mapMode=qe.TrackBefore;Wo.prototype.point=!0;class pr extends Z{constructor(e,t,i,r,s,o){super(t,i,s,e),this.block=r,this.isReplace=o,this.mapMode=r?t<=0?qe.TrackBefore:qe.TrackAfter:qe.TrackDel}get type(){return this.startSide!=this.endSide?Je.WidgetRange:this.startSide<=0?Je.WidgetBefore:Je.WidgetAfter}get heightRelevant(){return this.block||!!this.widget&&(this.widget.estimatedHeight>=5||this.widget.lineBreaks>0)}eq(e){return e instanceof pr&&tk(this.widget,e.widget)&&this.block==e.block&&this.startSide==e.startSide&&this.endSide==e.endSide}range(e,t=e){if(this.isReplace&&(e>t||e==t&&this.startSide>0&&this.endSide<=0))throw new RangeError("Invalid range for replacement decoration");if(!this.isReplace&&t!=e)throw new RangeError("Widget decorations can only have zero-length ranges");return super.range(e,t)}}pr.prototype.point=!0;function a0(n,e=!1){let{inclusiveStart:t,inclusiveEnd:i}=n;return t==null&&(t=n.inclusive),i==null&&(i=n.inclusive),{start:t??e,end:i??e}}function tk(n,e){return n==e||!!(n&&e&&n.compare(e))}function lu(n,e,t,i=0){let r=t.length-1;r>=0&&t[r]+i>=n?t[r]=Math.max(t[r],e):t.push(n,e)}class no{constructor(e,t,i,r){this.doc=e,this.pos=t,this.end=i,this.disallowBlockEffectsFor=r,this.content=[],this.curLine=null,this.breakAtStart=0,this.pendingBuffer=0,this.bufferMarks=[],this.atCursorPos=!0,this.openStart=-1,this.openEnd=-1,this.text="",this.textOff=0,this.cursor=e.iter(),this.skip=t}posCovered(){if(this.content.length==0)return!this.breakAtStart&&this.doc.lineAt(this.pos).from!=this.pos;let e=this.content[this.content.length-1];return!(e.breakAfter||e instanceof or&&e.deco.endSide<0)}getLine(){return this.curLine||(this.content.push(this.curLine=new Ae),this.atCursorPos=!0),this.curLine}flushBuffer(e=this.bufferMarks){this.pendingBuffer&&(this.curLine.append(aa(new ys(-1),e),e.length),this.pendingBuffer=0)}addBlockWidget(e){this.flushBuffer(),this.curLine=null,this.content.push(e)}finish(e){this.pendingBuffer&&e<=this.bufferMarks.length?this.flushBuffer():this.pendingBuffer=0,!this.posCovered()&&!(e&&this.content.length&&this.content[this.content.length-1]instanceof or)&&this.getLine()}buildText(e,t,i){for(;e>0;){if(this.textOff==this.text.length){let{value:s,lineBreak:o,done:a}=this.cursor.next(this.skip);if(this.skip=0,a)throw new Error("Ran out of text content when drawing inline views");if(o){this.posCovered()||this.getLine(),this.content.length?this.content[this.content.length-1].breakAfter=1:this.breakAtStart=1,this.flushBuffer(),this.curLine=null,this.atCursorPos=!0,e--;continue}else this.text=s,this.textOff=0}let r=Math.min(this.text.length-this.textOff,e,512);this.flushBuffer(t.slice(t.length-i)),this.getLine().append(aa(new Ln(this.text.slice(this.textOff,this.textOff+r)),t),i),this.atCursorPos=!0,this.textOff+=r,e-=r,i=0}}span(e,t,i,r){this.buildText(t-e,i,r),this.pos=t,this.openStart<0&&(this.openStart=r)}point(e,t,i,r,s,o){if(this.disallowBlockEffectsFor[o]&&i instanceof pr){if(i.block)throw new RangeError("Block decorations may not be specified via plugins");if(t>this.doc.lineAt(this.pos).to)throw new RangeError("Decorations that replace line breaks may not be specified via plugins")}let a=t-e;if(i instanceof pr)if(i.block)i.startSide>0&&!this.posCovered()&&this.getLine(),this.addBlockWidget(new or(i.widget||new lp("div"),a,i));else{let l=tr.create(i.widget||new lp("span"),a,a?0:i.startSide),h=this.atCursorPos&&!l.isEditable&&s<=r.length&&(e0),c=!l.isEditable&&(er.length||i.startSide<=0),u=this.getLine();this.pendingBuffer==2&&!h&&!l.isEditable&&(this.pendingBuffer=0),this.flushBuffer(r),h&&(u.append(aa(new ys(1),r),s),s=r.length+Math.max(0,s-r.length)),u.append(aa(l,r),s),this.atCursorPos=c,this.pendingBuffer=c?er.length?1:2:0,this.pendingBuffer&&(this.bufferMarks=r.slice())}else this.doc.lineAt(this.pos).from==this.pos&&this.getLine().addLineDeco(i);a&&(this.textOff+a<=this.text.length?this.textOff+=a:(this.skip+=a-(this.text.length-this.textOff),this.text="",this.textOff=0),this.pos=t),this.openStart<0&&(this.openStart=s)}static build(e,t,i,r,s){let o=new no(e,t,i,s);return o.openEnd=J.spans(r,t,i,o),o.openStart<0&&(o.openStart=o.openEnd),o.finish(o.openEnd),o}}function aa(n,e){for(let t of e)n=new Un(t,[n],n.length);return n}class lp extends Or{constructor(e){super(),this.tag=e}eq(e){return e.tag==this.tag}toDOM(){return document.createElement(this.tag)}updateDOM(e){return e.nodeName.toLowerCase()==this.tag}get isHidden(){return!0}}var ge=function(n){return n[n.LTR=0]="LTR",n[n.RTL=1]="RTL",n}(ge||(ge={}));const Mr=ge.LTR,Of=ge.RTL;function l0(n){let e=[];for(let t=0;t=t){if(a.level==i)return o;(s<0||(r!=0?r<0?a.fromt:e[s].level>a.level))&&(s=o)}}if(s<0)throw new RangeError("Index out of range");return s}}function c0(n,e){if(n.length!=e.length)return!1;for(let t=0;t=0;y-=3)if(ri[y+1]==-p){let O=ri[y+2],S=O&2?r:O&4?O&1?s:r:0;S&&(oe[u]=oe[ri[y]]=S),a=y;break}}else{if(ri.length==189)break;ri[a++]=u,ri[a++]=f,ri[a++]=l}else if((g=oe[u])==2||g==1){let y=g==r;l=y?0:1;for(let O=a-3;O>=0;O-=3){let S=ri[O+2];if(S&2)break;if(y)ri[O+2]|=2;else{if(S&4)break;ri[O+2]|=4}}}}}function ak(n,e,t,i){for(let r=0,s=i;r<=t.length;r++){let o=r?t[r-1].to:n,a=rl;)g==O&&(g=t[--y].from,O=y?t[y-1].to:n),oe[--g]=p;l=c}else s=h,l++}}}function cu(n,e,t,i,r,s,o){let a=i%2?2:1;if(i%2==r%2)for(let l=e,h=0;ll&&o.push(new ir(l,y.from,p));let O=y.direction==Mr!=!(p%2);uu(n,O?i+1:i,r,y.inner,y.from,y.to,o),l=y.to}g=y.to}else{if(g==t||(c?oe[g]!=a:oe[g]==a))break;g++}f?cu(n,l,g,i+1,r,f,o):le;){let c=!0,u=!1;if(!h||l>s[h-1].to){let y=oe[l-1];y!=a&&(c=!1,u=y==16)}let f=!c&&a==1?[]:null,p=c?i:i+1,g=l;e:for(;;)if(h&&g==s[h-1].to){if(u)break e;let y=s[--h];if(!c)for(let O=y.from,S=h;;){if(O==e)break e;if(S&&s[S-1].to==O)O=s[--S].from;else{if(oe[O-1]==a)break e;break}}if(f)f.push(y);else{y.tooe.length;)oe[oe.length]=256;let i=[],r=e==Mr?0:1;return uu(n,r,r,t,0,n.length,i),i}function u0(n){return[new ir(0,n,0)]}let f0="";function hk(n,e,t,i,r){var s;let o=i.head-n.from,a=ir.find(e,o,(s=i.bidiLevel)!==null&&s!==void 0?s:-1,i.assoc),l=e[a],h=l.side(r,t);if(o==h){let f=a+=r?1:-1;if(f<0||f>=e.length)return null;l=e[a=f],o=l.side(!r,t),h=l.side(r,t)}let c=We(n.text,o,l.forward(r,t));(cl.to)&&(c=h),f0=n.text.slice(Math.min(o,c),Math.max(o,c));let u=a==(r?e.length-1:0)?null:e[a+(r?1:-1)];return u&&c==h&&u.level+(r?0:1)n.some(e=>e)}),S0=B.define({combine:n=>n.some(e=>e)});class os{constructor(e,t="nearest",i="nearest",r=5,s=5,o=!1){this.range=e,this.y=t,this.x=i,this.yMargin=r,this.xMargin=s,this.isSnapshot=o}map(e){return e.empty?this:new os(this.range.map(e),this.y,this.x,this.yMargin,this.xMargin,this.isSnapshot)}clip(e){return this.range.to<=e.doc.length?this:new os(P.cursor(e.doc.length),this.y,this.x,this.yMargin,this.xMargin,this.isSnapshot)}}const la=z.define({map:(n,e)=>n.map(e)});function mt(n,e,t){let i=n.facet(m0);i.length?i[0](e):window.onerror?window.onerror(String(e),t,void 0,void 0,e):t?console.error(t+":",e):console.error(e)}const lh=B.define({combine:n=>n.length?n[0]:!0});let uk=0;const Ws=B.define();class ke{constructor(e,t,i,r,s){this.id=e,this.create=t,this.domEventHandlers=i,this.domEventObservers=r,this.extension=s(this)}static define(e,t){const{eventHandlers:i,eventObservers:r,provide:s,decorations:o}=t||{};return new ke(uk++,e,i,r,a=>{let l=[Ws.of(a)];return o&&l.push(xo.of(h=>{let c=h.plugin(a);return c?o(c):Z.none})),s&&l.push(s(a)),l})}static fromClass(e,t){return ke.define(i=>new e(i),t)}}class Bh{constructor(e){this.spec=e,this.mustUpdate=null,this.value=null}update(e){if(this.value){if(this.mustUpdate){let t=this.mustUpdate;if(this.mustUpdate=null,this.value.update)try{this.value.update(t)}catch(i){if(mt(t.state,i,"CodeMirror plugin crashed"),this.value.destroy)try{this.value.destroy()}catch{}this.deactivate()}}}else if(this.spec)try{this.value=this.spec.create(e)}catch(t){mt(e.state,t,"CodeMirror plugin crashed"),this.deactivate()}return this}destroy(e){var t;if(!((t=this.value)===null||t===void 0)&&t.destroy)try{this.value.destroy()}catch(i){mt(e.state,i,"CodeMirror plugin crashed")}}deactivate(){this.spec=this.value=null}}const w0=B.define(),yf=B.define(),xo=B.define(),v0=B.define(),bf=B.define(),k0=B.define();function hp(n,e){let t=n.state.facet(k0);if(!t.length)return t;let i=t.map(s=>s instanceof Function?s(n):s),r=[];return J.spans(i,e.from,e.to,{point(){},span(s,o,a,l){let h=s-e.from,c=o-e.from,u=r;for(let f=a.length-1;f>=0;f--,l--){let p=a[f].spec.bidiIsolate,g;if(p==null&&(p=ck(e.text,h,c)),l>0&&u.length&&(g=u[u.length-1]).to==h&&g.direction==p)g.to=c,u=g.inner;else{let y={from:h,to:c,direction:p,inner:[]};u.push(y),u=y.inner}}}}),r}const x0=B.define();function T0(n){let e=0,t=0,i=0,r=0;for(let s of n.state.facet(x0)){let o=s(n);o&&(o.left!=null&&(e=Math.max(e,o.left)),o.right!=null&&(t=Math.max(t,o.right)),o.top!=null&&(i=Math.max(i,o.top)),o.bottom!=null&&(r=Math.max(r,o.bottom)))}return{left:e,right:t,top:i,bottom:r}}const js=B.define();class Nt{constructor(e,t,i,r){this.fromA=e,this.toA=t,this.fromB=i,this.toB=r}join(e){return new Nt(Math.min(this.fromA,e.fromA),Math.max(this.toA,e.toA),Math.min(this.fromB,e.fromB),Math.max(this.toB,e.toB))}addToSet(e){let t=e.length,i=this;for(;t>0;t--){let r=e[t-1];if(!(r.fromA>i.toA)){if(r.toAc)break;s+=2}if(!l)return i;new Nt(l.fromA,l.toA,l.fromB,l.toB).addToSet(i),o=l.toA,a=l.toB}}}class Tl{constructor(e,t,i){this.view=e,this.state=t,this.transactions=i,this.flags=0,this.startState=e.state,this.changes=Ce.empty(this.startState.doc.length);for(let s of i)this.changes=this.changes.compose(s.changes);let r=[];this.changes.iterChangedRanges((s,o,a,l)=>r.push(new Nt(s,o,a,l))),this.changedRanges=r}static create(e,t,i){return new Tl(e,t,i)}get viewportChanged(){return(this.flags&4)>0}get heightChanged(){return(this.flags&2)>0}get geometryChanged(){return this.docChanged||(this.flags&10)>0}get focusChanged(){return(this.flags&1)>0}get docChanged(){return!this.changes.empty}get selectionSet(){return this.transactions.some(e=>e.selection)}get empty(){return this.flags==0&&this.transactions.length==0}}class cp extends he{get length(){return this.view.state.doc.length}constructor(e){super(),this.view=e,this.decorations=[],this.dynamicDecorationMap=[],this.domChanged=null,this.hasComposition=null,this.markedForComposition=new Set,this.minWidth=0,this.minWidthFrom=0,this.minWidthTo=0,this.impreciseAnchor=null,this.impreciseHead=null,this.forceSelection=!1,this.lastUpdate=Date.now(),this.setDOM(e.contentDOM),this.children=[new Ae],this.children[0].setParent(this),this.updateDeco(),this.updateInner([new Nt(0,0,0,e.state.doc.length)],0,null)}update(e){var t;let i=e.changedRanges;this.minWidth>0&&i.length&&(i.every(({fromA:h,toA:c})=>cthis.minWidthTo)?(this.minWidthFrom=e.changes.mapPos(this.minWidthFrom,1),this.minWidthTo=e.changes.mapPos(this.minWidthTo,1)):this.minWidth=this.minWidthFrom=this.minWidthTo=0);let r=-1;this.view.inputState.composing>=0&&(!((t=this.domChanged)===null||t===void 0)&&t.newSel?r=this.domChanged.newSel.head:!yk(e.changes,this.hasComposition)&&!e.selectionSet&&(r=e.state.selection.main.head));let s=r>-1?dk(this.view,e.changes,r):null;if(this.domChanged=null,this.hasComposition){this.markedForComposition.clear();let{from:h,to:c}=this.hasComposition;i=new Nt(h,c,e.changes.mapPos(h,-1),e.changes.mapPos(c,1)).addToSet(i.slice())}this.hasComposition=s?{from:s.range.fromB,to:s.range.toB}:null,(q.ie||q.chrome)&&!s&&e&&e.state.doc.lines!=e.startState.doc.lines&&(this.forceSelection=!0);let o=this.decorations,a=this.updateDeco(),l=mk(o,a,e.changes);return i=Nt.extendWithRanges(i,l),!(this.flags&7)&&i.length==0?!1:(this.updateInner(i,e.startState.doc.length,s),e.transactions.length&&(this.lastUpdate=Date.now()),!0)}updateInner(e,t,i){this.view.viewState.mustMeasureContent=!0,this.updateChildren(e,t,i);let{observer:r}=this.view;r.ignore(()=>{this.dom.style.height=this.view.viewState.contentHeight/this.view.scaleY+"px",this.dom.style.flexBasis=this.minWidth?this.minWidth+"px":"";let o=q.chrome||q.ios?{node:r.selectionRange.focusNode,written:!1}:void 0;this.sync(this.view,o),this.flags&=-8,o&&(o.written||r.selectionRange.focusNode!=o.node)&&(this.forceSelection=!0),this.dom.style.height=""}),this.markedForComposition.forEach(o=>o.flags&=-9);let s=[];if(this.view.viewport.from||this.view.viewport.to=0?r[o]:null;if(!a)break;let{fromA:l,toA:h,fromB:c,toB:u}=a,f,p,g,y;if(i&&i.range.fromBc){let x=no.build(this.view.state.doc,c,i.range.fromB,this.decorations,this.dynamicDecorationMap),Q=no.build(this.view.state.doc,i.range.toB,u,this.decorations,this.dynamicDecorationMap);p=x.breakAtStart,g=x.openStart,y=Q.openEnd;let A=this.compositionView(i);Q.breakAtStart?A.breakAfter=1:Q.content.length&&A.merge(A.length,A.length,Q.content[0],!1,Q.openStart,0)&&(A.breakAfter=Q.content[0].breakAfter,Q.content.shift()),x.content.length&&A.merge(0,0,x.content[x.content.length-1],!0,0,x.openEnd)&&x.content.pop(),f=x.content.concat(A).concat(Q.content)}else({content:f,breakAtStart:p,openStart:g,openEnd:y}=no.build(this.view.state.doc,c,u,this.decorations,this.dynamicDecorationMap));let{i:O,off:S}=s.findPos(h,1),{i:k,off:$}=s.findPos(l,-1);e0(this,k,$,O,S,f,p,g,y)}i&&this.fixCompositionDOM(i)}compositionView(e){let t=new Ln(e.text.nodeValue);t.flags|=8;for(let{deco:r}of e.marks)t=new Un(r,[t],t.length);let i=new Ae;return i.append(t,0),i}fixCompositionDOM(e){let t=(s,o)=>{o.flags|=8|(o.children.some(l=>l.flags&7)?1:0),this.markedForComposition.add(o);let a=he.get(s);a&&a!=o&&(a.dom=null),o.setDOM(s)},i=this.childPos(e.range.fromB,1),r=this.children[i.i];t(e.line,r);for(let s=e.marks.length-1;s>=-1;s--)i=r.childPos(i.off,1),r=r.children[i.i],t(s>=0?e.marks[s].node:e.text,r)}updateSelection(e=!1,t=!1){(e||!this.view.observer.selectionRange.focusNode)&&this.view.observer.readSelectionRange();let i=this.view.root.activeElement,r=i==this.dom,s=!r&&La(this.dom,this.view.observer.selectionRange)&&!(i&&this.dom.contains(i));if(!(r||t||s))return;let o=this.forceSelection;this.forceSelection=!1;let a=this.view.state.selection.main,l=this.moveToLine(this.domAtPos(a.anchor)),h=a.empty?l:this.moveToLine(this.domAtPos(a.head));if(q.gecko&&a.empty&&!this.hasComposition&&fk(l)){let u=document.createTextNode("");this.view.observer.ignore(()=>l.node.insertBefore(u,l.node.childNodes[l.offset]||null)),l=h=new Ze(u,0),o=!0}let c=this.view.observer.selectionRange;(o||!c.focusNode||(!io(l.node,l.offset,c.anchorNode,c.anchorOffset)||!io(h.node,h.offset,c.focusNode,c.focusOffset))&&!this.suppressWidgetCursorChange(c,a))&&(this.view.observer.ignore(()=>{q.android&&q.chrome&&this.dom.contains(c.focusNode)&&Ok(c.focusNode,this.dom)&&(this.dom.blur(),this.dom.focus({preventScroll:!0}));let u=xl(this.view.root);if(u)if(a.empty){if(q.gecko){let f=pk(l.node,l.offset);if(f&&f!=3){let p=P0(l.node,l.offset,f==1?1:-1);p&&(l=new Ze(p.node,p.offset))}}u.collapse(l.node,l.offset),a.bidiLevel!=null&&u.caretBidiLevel!==void 0&&(u.caretBidiLevel=a.bidiLevel)}else if(u.extend){u.collapse(l.node,l.offset);try{u.extend(h.node,h.offset)}catch{}}else{let f=document.createRange();a.anchor>a.head&&([l,h]=[h,l]),f.setEnd(h.node,h.offset),f.setStart(l.node,l.offset),u.removeAllRanges(),u.addRange(f)}s&&this.view.root.activeElement==this.dom&&(this.dom.blur(),i&&i.focus())}),this.view.observer.setSelectionRange(l,h)),this.impreciseAnchor=l.precise?null:new Ze(c.anchorNode,c.anchorOffset),this.impreciseHead=h.precise?null:new Ze(c.focusNode,c.focusOffset)}suppressWidgetCursorChange(e,t){return this.hasComposition&&t.empty&&io(e.focusNode,e.focusOffset,e.anchorNode,e.anchorOffset)&&this.posFromDOM(e.focusNode,e.focusOffset)==t.head}enforceCursorAssoc(){if(this.hasComposition)return;let{view:e}=this,t=e.state.selection.main,i=xl(e.root),{anchorNode:r,anchorOffset:s}=e.observer.selectionRange;if(!i||!t.empty||!t.assoc||!i.modify)return;let o=Ae.find(this,t.head);if(!o)return;let a=o.posAtStart;if(t.head==a||t.head==a+o.length)return;let l=this.coordsAt(t.head,-1),h=this.coordsAt(t.head,1);if(!l||!h||l.bottom>h.top)return;let c=this.domAtPos(t.head+t.assoc);i.collapse(c.node,c.offset),i.modify("move",t.assoc<0?"forward":"backward","lineboundary"),e.observer.readSelectionRange();let u=e.observer.selectionRange;e.docView.posFromDOM(u.anchorNode,u.anchorOffset)!=t.from&&i.collapse(r,s)}moveToLine(e){let t=this.dom,i;if(e.node!=t)return e;for(let r=e.offset;!i&&r=0;r--){let s=he.get(t.childNodes[r]);s instanceof Ae&&(i=s.domAtPos(s.length))}return i?new Ze(i.node,i.offset,!0):e}nearest(e){for(let t=e;t;){let i=he.get(t);if(i&&i.rootView==this)return i;t=t.parentNode}return null}posFromDOM(e,t){let i=this.nearest(e);if(!i)throw new RangeError("Trying to find position for a DOM position outside of the document");return i.localPosFromDOM(e,t)+i.posAtStart}domAtPos(e){let{i:t,off:i}=this.childCursor().findPos(e,-1);for(;t=0;o--){let a=this.children[o],l=s-a.breakAfter,h=l-a.length;if(le||a.covers(1))&&(!i||a instanceof Ae&&!(i instanceof Ae&&t>=0))&&(i=a,r=h),s=h}return i?i.coordsAt(e-r,t):null}coordsForChar(e){let{i:t,off:i}=this.childPos(e,1),r=this.children[t];if(!(r instanceof Ae))return null;for(;r.children.length;){let{i:a,off:l}=r.childPos(i,1);for(;;a++){if(a==r.children.length)return null;if((r=r.children[a]).length)break}i=l}if(!(r instanceof Ln))return null;let s=We(r.text,i);if(s==i)return null;let o=qr(r.dom,i,s).getClientRects();for(let a=0;aMath.max(this.view.scrollDOM.clientWidth,this.minWidth)+1,a=-1,l=this.view.textDirection==ge.LTR;for(let h=0,c=0;cr)break;if(h>=i){let p=u.dom.getBoundingClientRect();if(t.push(p.height),o){let g=u.dom.lastChild,y=g?vo(g):[];if(y.length){let O=y[y.length-1],S=l?O.right-p.left:p.right-O.left;S>a&&(a=S,this.minWidth=s,this.minWidthFrom=h,this.minWidthTo=f)}}}h=f+u.breakAfter}return t}textDirectionAt(e){let{i:t}=this.childPos(e,1);return getComputedStyle(this.children[t].dom).direction=="rtl"?ge.RTL:ge.LTR}measureTextSize(){for(let s of this.children)if(s instanceof Ae){let o=s.measureTextSize();if(o)return o}let e=document.createElement("div"),t,i,r;return e.className="cm-line",e.style.width="99999px",e.style.position="absolute",e.textContent="abc def ghi jkl mno pqr stu",this.view.observer.ignore(()=>{this.dom.appendChild(e);let s=vo(e.firstChild)[0];t=e.getBoundingClientRect().height,i=s?s.width/27:7,r=s?s.height:t,e.remove()}),{lineHeight:t,charWidth:i,textHeight:r}}childCursor(e=this.length){let t=this.children.length;return t&&(e-=this.children[--t].length),new KO(this.children,e,t)}computeBlockGapDeco(){let e=[],t=this.view.viewState;for(let i=0,r=0;;r++){let s=r==t.viewports.length?null:t.viewports[r],o=s?s.from-1:this.length;if(o>i){let a=(t.lineBlockAt(o).bottom-t.lineBlockAt(i).top)/this.view.scaleY;e.push(Z.replace({widget:new up(a),block:!0,inclusive:!0,isBlockGap:!0}).range(i,o))}if(!s)break;i=s.to+1}return Z.set(e)}updateDeco(){let e=this.view.state.facet(xo).map((r,s)=>(this.dynamicDecorationMap[s]=typeof r=="function")?r(this.view):r),t=!1,i=this.view.state.facet(v0).map((r,s)=>{let o=typeof r=="function";return o&&(t=!0),o?r(this.view):r});i.length&&(this.dynamicDecorationMap[e.length]=t,e.push(J.join(i)));for(let r=e.length;rt.anchor?-1:1),r;if(!i)return;!t.empty&&(r=this.coordsAt(t.anchor,t.anchor>t.head?-1:1))&&(i={left:Math.min(i.left,r.left),top:Math.min(i.top,r.top),right:Math.max(i.right,r.right),bottom:Math.max(i.bottom,r.bottom)});let s=T0(this.view),o={left:i.left-s.left,top:i.top-s.top,right:i.right+s.right,bottom:i.bottom+s.bottom},{offsetWidth:a,offsetHeight:l}=this.view.scrollDOM;Fv(this.view.scrollDOM,o,t.head0)i=i.childNodes[r-1],r=Xn(i);else break}if(t>=0)for(let i=n,r=e;;){if(i.nodeType==3)return{node:i,offset:r};if(i.nodeType==1&&r=0)i=i.childNodes[r],r=0;else break}return null}function pk(n,e){return n.nodeType!=1?0:(e&&n.childNodes[e-1].contentEditable=="false"?1:0)|(e{ie.from&&(t=!0)}),t}function bk(n,e,t=1){let i=n.charCategorizer(e),r=n.doc.lineAt(e),s=e-r.from;if(r.length==0)return P.cursor(e);s==0?t=1:s==r.length&&(t=-1);let o=s,a=s;t<0?o=We(r.text,s,!1):a=We(r.text,s);let l=i(r.text.slice(o,a));for(;o>0;){let h=We(r.text,o,!1);if(i(r.text.slice(h,o))!=l)break;o=h}for(;an?e.left-n:Math.max(0,n-e.right)}function wk(n,e){return e.top>n?e.top-n:Math.max(0,n-e.bottom)}function qh(n,e){return n.tope.top+1}function fp(n,e){return en.bottom?{top:n.top,left:n.left,right:n.right,bottom:e}:n}function du(n,e,t){let i,r,s,o,a=!1,l,h,c,u;for(let g=n.firstChild;g;g=g.nextSibling){let y=vo(g);for(let O=0;O$||o==$&&s>k){i=g,r=S,s=k,o=$;let x=$?t0?O0)}k==0?t>S.bottom&&(!c||c.bottomS.top)&&(h=g,u=S):c&&qh(c,S)?c=dp(c,S.bottom):u&&qh(u,S)&&(u=fp(u,S.top))}}if(c&&c.bottom>=t?(i=l,r=c):u&&u.top<=t&&(i=h,r=u),!i)return{node:n,offset:0};let f=Math.max(r.left,Math.min(r.right,e));if(i.nodeType==3)return pp(i,f,t);if(a&&i.contentEditable!="false")return du(i,f,t);let p=Array.prototype.indexOf.call(n.childNodes,i)+(e>=(r.left+r.right)/2?1:0);return{node:n,offset:p}}function pp(n,e,t){let i=n.nodeValue.length,r=-1,s=1e9,o=0;for(let a=0;at?c.top-t:t-c.bottom)-1;if(c.left-1<=e&&c.right+1>=e&&u=(c.left+c.right)/2,p=f;if((q.chrome||q.gecko)&&qr(n,a).getBoundingClientRect().left==c.right&&(p=!f),u<=0)return{node:n,offset:a+(p?1:0)};r=a+(p?1:0),s=u}}}return{node:n,offset:r>-1?r:o>0?n.nodeValue.length:0}}function A0(n,e,t,i=-1){var r,s;let o=n.contentDOM.getBoundingClientRect(),a=o.top+n.viewState.paddingTop,l,{docHeight:h}=n.viewState,{x:c,y:u}=e,f=u-a;if(f<0)return 0;if(f>h)return n.state.doc.length;for(let x=n.viewState.heightOracle.textHeight/2,Q=!1;l=n.elementAtHeight(f),l.type!=Je.Text;)for(;f=i>0?l.bottom+x:l.top-x,!(f>=0&&f<=h);){if(Q)return t?null:0;Q=!0,i=-i}u=a+f;let p=l.from;if(pn.viewport.to)return n.viewport.to==n.state.doc.length?n.state.doc.length:t?null:gp(n,o,l,c,u);let g=n.dom.ownerDocument,y=n.root.elementFromPoint?n.root:g,O=y.elementFromPoint(c,u);O&&!n.contentDOM.contains(O)&&(O=null),O||(c=Math.max(o.left+1,Math.min(o.right-1,c)),O=y.elementFromPoint(c,u),O&&!n.contentDOM.contains(O)&&(O=null));let S,k=-1;if(O&&((r=n.docView.nearest(O))===null||r===void 0?void 0:r.isEditable)!=!1){if(g.caretPositionFromPoint){let x=g.caretPositionFromPoint(c,u);x&&({offsetNode:S,offset:k}=x)}else if(g.caretRangeFromPoint){let x=g.caretRangeFromPoint(c,u);x&&({startContainer:S,startOffset:k}=x,(!n.contentDOM.contains(S)||q.safari&&vk(S,k,c)||q.chrome&&kk(S,k,c))&&(S=void 0))}}if(!S||!n.docView.dom.contains(S)){let x=Ae.find(n.docView,p);if(!x)return f>l.top+l.height/2?l.to:l.from;({node:S,offset:k}=du(x.dom,c,u))}let $=n.docView.nearest(S);if(!$)return null;if($.isWidget&&((s=$.dom)===null||s===void 0?void 0:s.nodeType)==1){let x=$.dom.getBoundingClientRect();return e.yn.defaultLineHeight*1.5){let a=n.viewState.heightOracle.textHeight,l=Math.floor((r-t.top-(n.defaultLineHeight-a)*.5)/a);s+=l*n.viewState.heightOracle.lineLength}let o=n.state.sliceDoc(t.from,t.to);return t.from+Kc(o,s,n.state.tabSize)}function vk(n,e,t){let i;if(n.nodeType!=3||e!=(i=n.nodeValue.length))return!1;for(let r=n.nextSibling;r;r=r.nextSibling)if(r.nodeType!=1||r.nodeName!="BR")return!1;return qr(n,i-1,i).getBoundingClientRect().left>t}function kk(n,e,t){if(e!=0)return!1;for(let r=n;;){let s=r.parentNode;if(!s||s.nodeType!=1||s.firstChild!=r)return!1;if(s.classList.contains("cm-line"))break;r=s}let i=n.nodeType==1?n.getBoundingClientRect():qr(n,0,Math.max(n.nodeValue.length,1)).getBoundingClientRect();return t-i.left>5}function pu(n,e){let t=n.lineBlockAt(e);if(Array.isArray(t.type)){for(let i of t.type)if(i.to>e||i.to==e&&(i.to==t.to||i.type==Je.Text))return i}return t}function xk(n,e,t,i){let r=pu(n,e.head),s=!i||r.type!=Je.Text||!(n.lineWrapping||r.widgetLineBreaks)?null:n.coordsAtPos(e.assoc<0&&e.head>r.from?e.head-1:e.head);if(s){let o=n.dom.getBoundingClientRect(),a=n.textDirectionAt(r.from),l=n.posAtCoords({x:t==(a==ge.LTR)?o.right-1:o.left+1,y:(s.top+s.bottom)/2});if(l!=null)return P.cursor(l,t?-1:1)}return P.cursor(t?r.to:r.from,t?-1:1)}function mp(n,e,t,i){let r=n.state.doc.lineAt(e.head),s=n.bidiSpans(r),o=n.textDirectionAt(r.from);for(let a=e,l=null;;){let h=hk(r,s,o,a,t),c=f0;if(!h){if(r.number==(t?n.state.doc.lines:1))return a;c=` -`,r=n.state.doc.line(r.number+(t?1:-1)),s=n.bidiSpans(r),h=n.visualLineSide(r,!t)}if(l){if(!l(c))return a}else{if(!i)return h;l=i(c)}a=h}}function Tk(n,e,t){let i=n.state.charCategorizer(e),r=i(t);return s=>{let o=i(s);return r==fe.Space&&(r=o),r==o}}function Qk(n,e,t,i){let r=e.head,s=t?1:-1;if(r==(t?n.state.doc.length:0))return P.cursor(r,e.assoc);let o=e.goalColumn,a,l=n.contentDOM.getBoundingClientRect(),h=n.coordsAtPos(r,e.assoc||-1),c=n.documentTop;if(h)o==null&&(o=h.left-l.left),a=s<0?h.top:h.bottom;else{let p=n.viewState.lineBlockAt(r);o==null&&(o=Math.min(l.right-l.left,n.defaultCharacterWidth*(r-p.from))),a=(s<0?p.top:p.bottom)+c}let u=l.left+o,f=i??n.viewState.heightOracle.textHeight>>1;for(let p=0;;p+=10){let g=a+(f+p)*s,y=A0(n,{x:u,y:g},!1,s);if(gl.bottom||(s<0?yr)){let O=n.docView.coordsForChar(y),S=!O||g{if(e>s&&er(n)),t.from,e.head>t.from?-1:1);return i==t.from?t:P.cursor(i,inull),q.gecko&&Zk(e.contentDOM.ownerDocument)}handleEvent(e){!Nk(this.view,e)||this.ignoreDuringComposition(e)||e.type=="keydown"&&this.keydown(e)||this.runHandlers(e.type,e)}runHandlers(e,t){let i=this.handlers[e];if(i){for(let r of i.observers)r(this.view,t);for(let r of i.handlers){if(t.defaultPrevented)break;if(r(this.view,t)){t.preventDefault();break}}}}ensureHandlers(e){let t=Ak(e),i=this.handlers,r=this.view.contentDOM;for(let s in t)if(s!="scroll"){let o=!t[s].handlers.length,a=i[s];a&&o!=!a.handlers.length&&(r.removeEventListener(s,this.handleEvent),a=null),a||r.addEventListener(s,this.handleEvent,{passive:o})}for(let s in i)s!="scroll"&&!t[s]&&r.removeEventListener(s,this.handleEvent);this.handlers=t}keydown(e){if(this.lastKeyCode=e.keyCode,this.lastKeyTime=Date.now(),e.keyCode==9&&Date.now()i.keyCode==e.keyCode))&&!e.ctrlKey||$k.indexOf(e.key)>-1&&e.ctrlKey&&!e.shiftKey)?(this.pendingIOSKey=t||e,setTimeout(()=>this.flushIOSKey(),250),!0):(e.keyCode!=229&&this.view.observer.forceFlush(),!1)}flushIOSKey(){let e=this.pendingIOSKey;return e?(this.pendingIOSKey=void 0,ss(this.view.contentDOM,e.key,e.keyCode)):!1}ignoreDuringComposition(e){return/^key/.test(e.type)?this.composing>0?!0:q.safari&&!q.ios&&this.compositionPendingKey&&Date.now()-this.compositionEndedAt<100?(this.compositionPendingKey=!1,!0):!1:!1}startMouseSelection(e){this.mouseSelection&&this.mouseSelection.destroy(),this.mouseSelection=e}update(e){this.mouseSelection&&this.mouseSelection.update(e),this.draggedContent&&e.docChanged&&(this.draggedContent=this.draggedContent.map(e.changes)),e.transactions.length&&(this.lastKeyCode=this.lastSelectionTime=0)}destroy(){this.mouseSelection&&this.mouseSelection.destroy()}}function Op(n,e){return(t,i)=>{try{return e.call(n,i,t)}catch(r){mt(t.state,r)}}}function Ak(n){let e=Object.create(null);function t(i){return e[i]||(e[i]={observers:[],handlers:[]})}for(let i of n){let r=i.spec;if(r&&r.domEventHandlers)for(let s in r.domEventHandlers){let o=r.domEventHandlers[s];o&&t(s).handlers.push(Op(i.value,o))}if(r&&r.domEventObservers)for(let s in r.domEventObservers){let o=r.domEventObservers[s];o&&t(s).observers.push(Op(i.value,o))}}for(let i in Ht)t(i).handlers.push(Ht[i]);for(let i in Kt)t(i).observers.push(Kt[i]);return e}const $0=[{key:"Backspace",keyCode:8,inputType:"deleteContentBackward"},{key:"Enter",keyCode:13,inputType:"insertParagraph"},{key:"Enter",keyCode:13,inputType:"insertLineBreak"},{key:"Delete",keyCode:46,inputType:"deleteContentForward"}],$k="dthko",C0=[16,17,18,20,91,92,224,225],ha=6;function ca(n){return Math.max(0,n)*.7+8}function Ck(n,e){return Math.max(Math.abs(n.clientX-e.clientX),Math.abs(n.clientY-e.clientY))}class Ik{constructor(e,t,i,r){this.view=e,this.startEvent=t,this.style=i,this.mustSelect=r,this.scrollSpeed={x:0,y:0},this.scrolling=-1,this.lastEvent=t,this.scrollParent=zv(e.contentDOM),this.atoms=e.state.facet(bf).map(o=>o(e));let s=e.contentDOM.ownerDocument;s.addEventListener("mousemove",this.move=this.move.bind(this)),s.addEventListener("mouseup",this.up=this.up.bind(this)),this.extend=t.shiftKey,this.multiple=e.state.facet(H.allowMultipleSelections)&&Rk(e,t),this.dragging=Dk(e,t)&&D0(t)==1?null:!1}start(e){this.dragging===!1&&this.select(e)}move(e){var t;if(e.buttons==0)return this.destroy();if(this.dragging||this.dragging==null&&Ck(this.startEvent,e)<10)return;this.select(this.lastEvent=e);let i=0,r=0,s=((t=this.scrollParent)===null||t===void 0?void 0:t.getBoundingClientRect())||{left:0,top:0,right:this.view.win.innerWidth,bottom:this.view.win.innerHeight},o=T0(this.view);e.clientX-o.left<=s.left+ha?i=-ca(s.left-e.clientX):e.clientX+o.right>=s.right-ha&&(i=ca(e.clientX-s.right)),e.clientY-o.top<=s.top+ha?r=-ca(s.top-e.clientY):e.clientY+o.bottom>=s.bottom-ha&&(r=ca(e.clientY-s.bottom)),this.setScrollSpeed(i,r)}up(e){this.dragging==null&&this.select(this.lastEvent),this.dragging||e.preventDefault(),this.destroy()}destroy(){this.setScrollSpeed(0,0);let e=this.view.contentDOM.ownerDocument;e.removeEventListener("mousemove",this.move),e.removeEventListener("mouseup",this.up),this.view.inputState.mouseSelection=this.view.inputState.draggedContent=null}setScrollSpeed(e,t){this.scrollSpeed={x:e,y:t},e||t?this.scrolling<0&&(this.scrolling=setInterval(()=>this.scroll(),50)):this.scrolling>-1&&(clearInterval(this.scrolling),this.scrolling=-1)}scroll(){this.scrollParent?(this.scrollParent.scrollLeft+=this.scrollSpeed.x,this.scrollParent.scrollTop+=this.scrollSpeed.y):this.view.win.scrollBy(this.scrollSpeed.x,this.scrollSpeed.y),this.dragging===!1&&this.select(this.lastEvent)}skipAtoms(e){let t=null;for(let i=0;ithis.select(this.lastEvent),20)}}function Rk(n,e){let t=n.state.facet(d0);return t.length?t[0](e):q.mac?e.metaKey:e.ctrlKey}function Ek(n,e){let t=n.state.facet(p0);return t.length?t[0](e):q.mac?!e.altKey:!e.ctrlKey}function Dk(n,e){let{main:t}=n.state.selection;if(t.empty)return!1;let i=xl(n.root);if(!i||i.rangeCount==0)return!0;let r=i.getRangeAt(0).getClientRects();for(let s=0;s=e.clientX&&o.top<=e.clientY&&o.bottom>=e.clientY)return!0}return!1}function Nk(n,e){if(!e.bubbles)return!0;if(e.defaultPrevented)return!1;for(let t=e.target,i;t!=n.contentDOM;t=t.parentNode)if(!t||t.nodeType==11||(i=he.get(t))&&i.ignoreEvent(e))return!1;return!0}const Ht=Object.create(null),Kt=Object.create(null),I0=q.ie&&q.ie_version<15||q.ios&&q.webkit_version<604;function Bk(n){let e=n.dom.parentNode;if(!e)return;let t=e.appendChild(document.createElement("textarea"));t.style.cssText="position: fixed; left: -10000px; top: 10px",t.focus(),setTimeout(()=>{n.focus(),t.remove(),R0(n,t.value)},50)}function R0(n,e){let{state:t}=n,i,r=1,s=t.toText(e),o=s.lines==t.selection.ranges.length;if(gu!=null&&t.selection.ranges.every(l=>l.empty)&&gu==s.toString()){let l=-1;i=t.changeByRange(h=>{let c=t.doc.lineAt(h.from);if(c.from==l)return{range:h};l=c.from;let u=t.toText((o?s.line(r++).text:e)+t.lineBreak);return{changes:{from:c.from,insert:u},range:P.cursor(h.from+u.length)}})}else o?i=t.changeByRange(l=>{let h=s.line(r++);return{changes:{from:l.from,to:l.to,insert:h.text},range:P.cursor(l.from+h.length)}}):i=t.replaceSelection(s);n.dispatch(i,{userEvent:"input.paste",scrollIntoView:!0})}Kt.scroll=n=>{n.inputState.lastScrollTop=n.scrollDOM.scrollTop,n.inputState.lastScrollLeft=n.scrollDOM.scrollLeft};Ht.keydown=(n,e)=>(n.inputState.setSelectionOrigin("select"),e.keyCode==27&&(n.inputState.lastEscPress=Date.now()),!1);Kt.touchstart=(n,e)=>{n.inputState.lastTouchTime=Date.now(),n.inputState.setSelectionOrigin("select.pointer")};Kt.touchmove=n=>{n.inputState.setSelectionOrigin("select.pointer")};Ht.mousedown=(n,e)=>{if(n.observer.flush(),n.inputState.lastTouchTime>Date.now()-2e3)return!1;let t=null;for(let i of n.state.facet(g0))if(t=i(n,e),t)break;if(!t&&e.button==0&&(t=Vk(n,e)),t){let i=!n.hasFocus;n.inputState.startMouseSelection(new Ik(n,e,t,i)),i&&n.observer.ignore(()=>JO(n.contentDOM));let r=n.inputState.mouseSelection;if(r)return r.start(e),r.dragging===!1}return!1};function yp(n,e,t,i){if(i==1)return P.cursor(e,t);if(i==2)return bk(n.state,e,t);{let r=Ae.find(n.docView,e),s=n.state.doc.lineAt(r?r.posAtEnd:e),o=r?r.posAtStart:s.from,a=r?r.posAtEnd:s.to;return an>=e.top&&n<=e.bottom,bp=(n,e,t)=>E0(e,t)&&n>=t.left&&n<=t.right;function qk(n,e,t,i){let r=Ae.find(n.docView,e);if(!r)return 1;let s=e-r.posAtStart;if(s==0)return 1;if(s==r.length)return-1;let o=r.coordsAt(s,-1);if(o&&bp(t,i,o))return-1;let a=r.coordsAt(s,1);return a&&bp(t,i,a)?1:o&&E0(i,o)?-1:1}function Sp(n,e){let t=n.posAtCoords({x:e.clientX,y:e.clientY},!1);return{pos:t,bias:qk(n,t,e.clientX,e.clientY)}}const Mk=q.ie&&q.ie_version<=11;let wp=null,vp=0,kp=0;function D0(n){if(!Mk)return n.detail;let e=wp,t=kp;return wp=n,kp=Date.now(),vp=!e||t>Date.now()-400&&Math.abs(e.clientX-n.clientX)<2&&Math.abs(e.clientY-n.clientY)<2?(vp+1)%3:1}function Vk(n,e){let t=Sp(n,e),i=D0(e),r=n.state.selection;return{update(s){s.docChanged&&(t.pos=s.changes.mapPos(t.pos),r=r.map(s.changes))},get(s,o,a){let l=Sp(n,s),h,c=yp(n,l.pos,l.bias,i);if(t.pos!=l.pos&&!o){let u=yp(n,t.pos,t.bias,i),f=Math.min(u.from,c.from),p=Math.max(u.to,c.to);c=f1&&(h=Xk(r,l.pos))?h:a?r.addRange(c):P.create([c])}}}function Xk(n,e){for(let t=0;t=e)return P.create(n.ranges.slice(0,t).concat(n.ranges.slice(t+1)),n.mainIndex==t?0:n.mainIndex-(n.mainIndex>t?1:0))}return null}Ht.dragstart=(n,e)=>{let{selection:{main:t}}=n.state;if(e.target.draggable){let r=n.docView.nearest(e.target);if(r&&r.isWidget){let s=r.posAtStart,o=s+r.length;(s>=t.to||o<=t.from)&&(t=P.range(s,o))}}let{inputState:i}=n;return i.mouseSelection&&(i.mouseSelection.dragging=!0),i.draggedContent=t,e.dataTransfer&&(e.dataTransfer.setData("Text",n.state.sliceDoc(t.from,t.to)),e.dataTransfer.effectAllowed="copyMove"),!1};Ht.dragend=n=>(n.inputState.draggedContent=null,!1);function xp(n,e,t,i){if(!t)return;let r=n.posAtCoords({x:e.clientX,y:e.clientY},!1),{draggedContent:s}=n.inputState,o=i&&s&&Ek(n,e)?{from:s.from,to:s.to}:null,a={from:r,insert:t},l=n.state.changes(o?[o,a]:a);n.focus(),n.dispatch({changes:l,selection:{anchor:l.mapPos(r,-1),head:l.mapPos(r,1)},userEvent:o?"move.drop":"input.drop"}),n.inputState.draggedContent=null}Ht.drop=(n,e)=>{if(!e.dataTransfer)return!1;if(n.state.readOnly)return!0;let t=e.dataTransfer.files;if(t&&t.length){let i=Array(t.length),r=0,s=()=>{++r==t.length&&xp(n,e,i.filter(o=>o!=null).join(n.state.lineBreak),!1)};for(let o=0;o{/[\x00-\x08\x0e-\x1f]{2}/.test(a.result)||(i[o]=a.result),s()},a.readAsText(t[o])}return!0}else{let i=e.dataTransfer.getData("Text");if(i)return xp(n,e,i,!0),!0}return!1};Ht.paste=(n,e)=>{if(n.state.readOnly)return!0;n.observer.flush();let t=I0?null:e.clipboardData;return t?(R0(n,t.getData("text/plain")||t.getData("text/uri-text")),!0):(Bk(n),!1)};function Lk(n,e){let t=n.dom.parentNode;if(!t)return;let i=t.appendChild(document.createElement("textarea"));i.style.cssText="position: fixed; left: -10000px; top: 10px",i.value=e,i.focus(),i.selectionEnd=e.length,i.selectionStart=0,setTimeout(()=>{i.remove(),n.focus()},50)}function Uk(n){let e=[],t=[],i=!1;for(let r of n.selection.ranges)r.empty||(e.push(n.sliceDoc(r.from,r.to)),t.push(r));if(!e.length){let r=-1;for(let{from:s}of n.selection.ranges){let o=n.doc.lineAt(s);o.number>r&&(e.push(o.text),t.push({from:o.from,to:Math.min(n.doc.length,o.to+1)})),r=o.number}i=!0}return{text:e.join(n.lineBreak),ranges:t,linewise:i}}let gu=null;Ht.copy=Ht.cut=(n,e)=>{let{text:t,ranges:i,linewise:r}=Uk(n.state);if(!t&&!r)return!1;gu=r?t:null,e.type=="cut"&&!n.state.readOnly&&n.dispatch({changes:i,scrollIntoView:!0,userEvent:"delete.cut"});let s=I0?null:e.clipboardData;return s?(s.clearData(),s.setData("text/plain",t),!0):(Lk(n,t),!1)};const N0=jn.define();function B0(n,e){let t=[];for(let i of n.facet(y0)){let r=i(n,e);r&&t.push(r)}return t?n.update({effects:t,annotations:N0.of(!0)}):null}function q0(n){setTimeout(()=>{let e=n.hasFocus;if(e!=n.inputState.notifiedFocused){let t=B0(n.state,e);t?n.dispatch(t):n.update([])}},10)}Kt.focus=n=>{n.inputState.lastFocusTime=Date.now(),!n.scrollDOM.scrollTop&&(n.inputState.lastScrollTop||n.inputState.lastScrollLeft)&&(n.scrollDOM.scrollTop=n.inputState.lastScrollTop,n.scrollDOM.scrollLeft=n.inputState.lastScrollLeft),q0(n)};Kt.blur=n=>{n.observer.clearSelectionRange(),q0(n)};Kt.compositionstart=Kt.compositionupdate=n=>{n.inputState.compositionFirstChange==null&&(n.inputState.compositionFirstChange=!0),n.inputState.composing<0&&(n.inputState.composing=0)};Kt.compositionend=n=>{n.inputState.composing=-1,n.inputState.compositionEndedAt=Date.now(),n.inputState.compositionPendingKey=!0,n.inputState.compositionPendingChange=n.observer.pendingRecords().length>0,n.inputState.compositionFirstChange=null,q.chrome&&q.android?n.observer.flushSoon():n.inputState.compositionPendingChange?Promise.resolve().then(()=>n.observer.flush()):setTimeout(()=>{n.inputState.composing<0&&n.docView.hasComposition&&n.update([])},50)};Kt.contextmenu=n=>{n.inputState.lastContextMenu=Date.now()};Ht.beforeinput=(n,e)=>{var t;let i;if(q.chrome&&q.android&&(i=$0.find(r=>r.inputType==e.inputType))&&(n.observer.delayAndroidKey(i.key,i.keyCode),i.key=="Backspace"||i.key=="Delete")){let r=((t=window.visualViewport)===null||t===void 0?void 0:t.height)||0;setTimeout(()=>{var s;(((s=window.visualViewport)===null||s===void 0?void 0:s.height)||0)>r+10&&n.hasFocus&&(n.contentDOM.blur(),n.focus())},100)}return!1};const Tp=new Set;function Zk(n){Tp.has(n)||(Tp.add(n),n.addEventListener("copy",()=>{}),n.addEventListener("cut",()=>{}))}const Qp=["pre-wrap","normal","pre-line","break-spaces"];class Wk{constructor(e){this.lineWrapping=e,this.doc=K.empty,this.heightSamples={},this.lineHeight=14,this.charWidth=7,this.textHeight=14,this.lineLength=30,this.heightChanged=!1}heightForGap(e,t){let i=this.doc.lineAt(t).number-this.doc.lineAt(e).number+1;return this.lineWrapping&&(i+=Math.max(0,Math.ceil((t-e-i*this.lineLength*.5)/this.lineLength))),this.lineHeight*i}heightForLine(e){return this.lineWrapping?(1+Math.max(0,Math.ceil((e-this.lineLength)/(this.lineLength-5))))*this.lineHeight:this.lineHeight}setDoc(e){return this.doc=e,this}mustRefreshForWrapping(e){return Qp.indexOf(e)>-1!=this.lineWrapping}mustRefreshForHeights(e){let t=!1;for(let i=0;i-1,l=Math.round(t)!=Math.round(this.lineHeight)||this.lineWrapping!=a;if(this.lineWrapping=a,this.lineHeight=t,this.charWidth=i,this.textHeight=r,this.lineLength=s,l){this.heightSamples={};for(let h=0;h0}set outdated(e){this.flags=(e?2:0)|this.flags&-3}setHeight(e,t){this.height!=t&&(Math.abs(this.height-t)>Za&&(e.heightChanged=!0),this.height=t)}replace(e,t,i){return Ye.of(i)}decomposeLeft(e,t){t.push(this)}decomposeRight(e,t){t.push(this)}applyChanges(e,t,i,r){let s=this,o=i.doc;for(let a=r.length-1;a>=0;a--){let{fromA:l,toA:h,fromB:c,toB:u}=r[a],f=s.lineAt(l,le.ByPosNoHeight,i.setDoc(t),0,0),p=f.to>=h?f:s.lineAt(h,le.ByPosNoHeight,i,0,0);for(u+=p.to-h,h=p.to;a>0&&f.from<=r[a-1].toA;)l=r[a-1].fromA,c=r[a-1].fromB,a--,ls*2){let a=e[t-1];a.break?e.splice(--t,1,a.left,null,a.right):e.splice(--t,1,a.left,a.right),i+=1+a.break,r-=a.size}else if(s>r*2){let a=e[i];a.break?e.splice(i,1,a.left,null,a.right):e.splice(i,1,a.left,a.right),i+=2+a.break,s-=a.size}else break;else if(r=s&&o(this.blockAt(0,i,r,s))}updateHeight(e,t=0,i=!1,r){return r&&r.from<=t&&r.more&&this.setHeight(e,r.heights[r.index++]),this.outdated=!1,this}toString(){return`block(${this.length})`}}class at extends M0{constructor(e,t){super(e,t,null),this.collapsed=0,this.widgetHeight=0,this.breaks=0}blockAt(e,t,i,r){return new fi(r,this.length,i,this.height,this.breaks)}replace(e,t,i){let r=i[0];return i.length==1&&(r instanceof at||r instanceof De&&r.flags&4)&&Math.abs(this.length-r.length)<10?(r instanceof De?r=new at(r.length,this.height):r.height=this.height,this.outdated||(r.outdated=!1),r):Ye.of(i)}updateHeight(e,t=0,i=!1,r){return r&&r.from<=t&&r.more?this.setHeight(e,r.heights[r.index++]):(i||this.outdated)&&this.setHeight(e,Math.max(this.widgetHeight,e.heightForLine(this.length-this.collapsed))+this.breaks*e.lineHeight),this.outdated=!1,this}toString(){return`line(${this.length}${this.collapsed?-this.collapsed:""}${this.widgetHeight?":"+this.widgetHeight:""})`}}class De extends Ye{constructor(e){super(e,0)}heightMetrics(e,t){let i=e.doc.lineAt(t).number,r=e.doc.lineAt(t+this.length).number,s=r-i+1,o,a=0;if(e.lineWrapping){let l=Math.min(this.height,e.lineHeight*s);o=l/s,this.length>s+1&&(a=(this.height-l)/(this.length-s-1))}else o=this.height/s;return{firstLine:i,lastLine:r,perLine:o,perChar:a}}blockAt(e,t,i,r){let{firstLine:s,lastLine:o,perLine:a,perChar:l}=this.heightMetrics(t,r);if(t.lineWrapping){let h=r+Math.round(Math.max(0,Math.min(1,(e-i)/this.height))*this.length),c=t.doc.lineAt(h),u=a+c.length*l,f=Math.max(i,e-u/2);return new fi(c.from,c.length,f,u,0)}else{let h=Math.max(0,Math.min(o-s,Math.floor((e-i)/a))),{from:c,length:u}=t.doc.line(s+h);return new fi(c,u,i+a*h,a,0)}}lineAt(e,t,i,r,s){if(t==le.ByHeight)return this.blockAt(e,i,r,s);if(t==le.ByPosNoHeight){let{from:p,to:g}=i.doc.lineAt(e);return new fi(p,g-p,0,0,0)}let{firstLine:o,perLine:a,perChar:l}=this.heightMetrics(i,s),h=i.doc.lineAt(e),c=a+h.length*l,u=h.number-o,f=r+a*u+l*(h.from-s-u);return new fi(h.from,h.length,Math.max(r,Math.min(f,r+this.height-c)),c,0)}forEachLine(e,t,i,r,s,o){e=Math.max(e,s),t=Math.min(t,s+this.length);let{firstLine:a,perLine:l,perChar:h}=this.heightMetrics(i,s);for(let c=e,u=r;c<=t;){let f=i.doc.lineAt(c);if(c==e){let g=f.number-a;u+=l*g+h*(e-s-g)}let p=l+h*f.length;o(new fi(f.from,f.length,u,p,0)),u+=p,c=f.to+1}}replace(e,t,i){let r=this.length-t;if(r>0){let s=i[i.length-1];s instanceof De?i[i.length-1]=new De(s.length+r):i.push(null,new De(r-1))}if(e>0){let s=i[0];s instanceof De?i[0]=new De(e+s.length):i.unshift(new De(e-1),null)}return Ye.of(i)}decomposeLeft(e,t){t.push(new De(e-1),null)}decomposeRight(e,t){t.push(null,new De(this.length-e-1))}updateHeight(e,t=0,i=!1,r){let s=t+this.length;if(r&&r.from<=t+this.length&&r.more){let o=[],a=Math.max(t,r.from),l=-1;for(r.from>t&&o.push(new De(r.from-t-1).updateHeight(e,t));a<=s&&r.more;){let c=e.doc.lineAt(a).length;o.length&&o.push(null);let u=r.heights[r.index++];l==-1?l=u:Math.abs(u-l)>=Za&&(l=-2);let f=new at(c,u);f.outdated=!1,o.push(f),a+=c+1}a<=s&&o.push(null,new De(s-a).updateHeight(e,a));let h=Ye.of(o);return(l<0||Math.abs(h.height-this.height)>=Za||Math.abs(l-this.heightMetrics(e,t).perLine)>=Za)&&(e.heightChanged=!0),h}else(i||this.outdated)&&(this.setHeight(e,e.heightForGap(t,t+this.length)),this.outdated=!1);return this}toString(){return`gap(${this.length})`}}class Fk extends Ye{constructor(e,t,i){super(e.length+t+i.length,e.height+i.height,t|(e.outdated||i.outdated?2:0)),this.left=e,this.right=i,this.size=e.size+i.size}get break(){return this.flags&1}blockAt(e,t,i,r){let s=i+this.left.height;return ea))return h;let c=t==le.ByPosNoHeight?le.ByPosNoHeight:le.ByPos;return l?h.join(this.right.lineAt(a,c,i,o,a)):this.left.lineAt(a,c,i,r,s).join(h)}forEachLine(e,t,i,r,s,o){let a=r+this.left.height,l=s+this.left.length+this.break;if(this.break)e=l&&this.right.forEachLine(e,t,i,a,l,o);else{let h=this.lineAt(l,le.ByPos,i,r,s);e=e&&h.from<=t&&o(h),t>h.to&&this.right.forEachLine(h.to+1,t,i,a,l,o)}}replace(e,t,i){let r=this.left.length+this.break;if(tthis.left.length)return this.balanced(this.left,this.right.replace(e-r,t-r,i));let s=[];e>0&&this.decomposeLeft(e,s);let o=s.length;for(let a of i)s.push(a);if(e>0&&Pp(s,o-1),t=i&&t.push(null)),e>i&&this.right.decomposeLeft(e-i,t)}decomposeRight(e,t){let i=this.left.length,r=i+this.break;if(e>=r)return this.right.decomposeRight(e-r,t);e2*t.size||t.size>2*e.size?Ye.of(this.break?[e,null,t]:[e,t]):(this.left=e,this.right=t,this.height=e.height+t.height,this.outdated=e.outdated||t.outdated,this.size=e.size+t.size,this.length=e.length+this.break+t.length,this)}updateHeight(e,t=0,i=!1,r){let{left:s,right:o}=this,a=t+s.length+this.break,l=null;return r&&r.from<=t+s.length&&r.more?l=s=s.updateHeight(e,t,i,r):s.updateHeight(e,t,i),r&&r.from<=a+o.length&&r.more?l=o=o.updateHeight(e,a,i,r):o.updateHeight(e,a,i),l?this.balanced(s,o):(this.height=this.left.height+this.right.height,this.outdated=!1,this)}toString(){return this.left+(this.break?" ":"-")+this.right}}function Pp(n,e){let t,i;n[e]==null&&(t=n[e-1])instanceof De&&(i=n[e+1])instanceof De&&n.splice(e-1,3,new De(t.length+1+i.length))}const zk=5;class Sf{constructor(e,t){this.pos=e,this.oracle=t,this.nodes=[],this.lineStart=-1,this.lineEnd=-1,this.covering=null,this.writtenTo=e}get isCovered(){return this.covering&&this.nodes[this.nodes.length-1]==this.covering}span(e,t){if(this.lineStart>-1){let i=Math.min(t,this.lineEnd),r=this.nodes[this.nodes.length-1];r instanceof at?r.length+=i-this.pos:(i>this.pos||!this.isCovered)&&this.nodes.push(new at(i-this.pos,-1)),this.writtenTo=i,t>i&&(this.nodes.push(null),this.writtenTo++,this.lineStart=-1)}this.pos=t}point(e,t,i){if(e=zk)&&this.addLineDeco(r,s,o)}else t>e&&this.span(e,t);this.lineEnd>-1&&this.lineEnd-1)return;let{from:e,to:t}=this.oracle.doc.lineAt(this.pos);this.lineStart=e,this.lineEnd=t,this.writtenToe&&this.nodes.push(new at(this.pos-e,-1)),this.writtenTo=this.pos}blankContent(e,t){let i=new De(t-e);return this.oracle.doc.lineAt(e).to==t&&(i.flags|=4),i}ensureLine(){this.enterLine();let e=this.nodes.length?this.nodes[this.nodes.length-1]:null;if(e instanceof at)return e;let t=new at(0,-1);return this.nodes.push(t),t}addBlock(e){this.enterLine();let t=e.deco;t&&t.startSide>0&&!this.isCovered&&this.ensureLine(),this.nodes.push(e),this.writtenTo=this.pos=this.pos+e.length,t&&t.endSide>0&&(this.covering=e)}addLineDeco(e,t,i){let r=this.ensureLine();r.length+=i,r.collapsed+=i,r.widgetHeight=Math.max(r.widgetHeight,e),r.breaks+=t,this.writtenTo=this.pos=this.pos+i}finish(e){let t=this.nodes.length==0?null:this.nodes[this.nodes.length-1];this.lineStart>-1&&!(t instanceof at)&&!this.isCovered?this.nodes.push(new at(0,-1)):(this.writtenToc.clientHeight||c.scrollWidth>c.clientWidth)&&u.overflow!="visible"){let f=c.getBoundingClientRect();s=Math.max(s,f.left),o=Math.min(o,f.right),a=Math.max(a,f.top),l=h==n.parentNode?f.bottom:Math.min(l,f.bottom)}h=u.position=="absolute"||u.position=="fixed"?c.offsetParent:c.parentNode}else if(h.nodeType==11)h=h.host;else break;return{left:s-t.left,right:Math.max(s,o)-t.left,top:a-(t.top+e),bottom:Math.max(a,l)-(t.top+e)}}function Yk(n,e){let t=n.getBoundingClientRect();return{left:0,right:t.right-t.left,top:e,bottom:t.bottom-(t.top+e)}}class Vh{constructor(e,t,i){this.from=e,this.to=t,this.size=i}static same(e,t){if(e.length!=t.length)return!1;for(let i=0;itypeof i!="function"&&i.class=="cm-lineWrapping");this.heightOracle=new Wk(t),this.stateDeco=e.facet(xo).filter(i=>typeof i!="function"),this.heightMap=Ye.empty().applyChanges(this.stateDeco,K.empty,this.heightOracle.setDoc(e.doc),[new Nt(0,0,0,e.doc.length)]),this.viewport=this.getViewport(0,null),this.updateViewportLines(),this.updateForViewport(),this.lineGaps=this.ensureLineGaps([]),this.lineGapDeco=Z.set(this.lineGaps.map(i=>i.draw(this,!1))),this.computeVisibleRanges()}updateForViewport(){let e=[this.viewport],{main:t}=this.state.selection;for(let i=0;i<=1;i++){let r=i?t.head:t.anchor;if(!e.some(({from:s,to:o})=>r>=s&&r<=o)){let{from:s,to:o}=this.lineBlockAt(r);e.push(new ua(s,o))}}this.viewports=e.sort((i,r)=>i.from-r.from),this.scaler=this.heightMap.height<=7e6?$p:new tx(this.heightOracle,this.heightMap,this.viewports)}updateViewportLines(){this.viewportLines=[],this.heightMap.forEachLine(this.viewport.from,this.viewport.to,this.heightOracle.setDoc(this.state.doc),0,0,e=>{this.viewportLines.push(this.scaler.scale==1?e:Fs(e,this.scaler))})}update(e,t=null){this.state=e.state;let i=this.stateDeco;this.stateDeco=this.state.facet(xo).filter(c=>typeof c!="function");let r=e.changedRanges,s=Nt.extendWithRanges(r,_k(i,this.stateDeco,e?e.changes:Ce.empty(this.state.doc.length))),o=this.heightMap.height,a=this.scrolledToBottom?null:this.scrollAnchorAt(this.scrollTop);this.heightMap=this.heightMap.applyChanges(this.stateDeco,e.startState.doc,this.heightOracle.setDoc(this.state.doc),s),this.heightMap.height!=o&&(e.flags|=2),a?(this.scrollAnchorPos=e.changes.mapPos(a.from,-1),this.scrollAnchorHeight=a.top):(this.scrollAnchorPos=-1,this.scrollAnchorHeight=this.heightMap.height);let l=s.length?this.mapViewport(this.viewport,e.changes):this.viewport;(t&&(t.range.headl.to)||!this.viewportIsAppropriate(l))&&(l=this.getViewport(0,t));let h=!e.changes.empty||e.flags&2||l.from!=this.viewport.from||l.to!=this.viewport.to;this.viewport=l,this.updateForViewport(),h&&this.updateViewportLines(),(this.lineGaps.length||this.viewport.to-this.viewport.from>4e3)&&this.updateLineGaps(this.ensureLineGaps(this.mapLineGaps(this.lineGaps,e.changes))),e.flags|=this.computeVisibleRanges(),t&&(this.scrollTarget=t),!this.mustEnforceCursorAssoc&&e.selectionSet&&e.view.lineWrapping&&e.state.selection.main.empty&&e.state.selection.main.assoc&&!e.state.facet(S0)&&(this.mustEnforceCursorAssoc=!0)}measure(e){let t=e.contentDOM,i=window.getComputedStyle(t),r=this.heightOracle,s=i.whiteSpace;this.defaultTextDirection=i.direction=="rtl"?ge.RTL:ge.LTR;let o=this.heightOracle.mustRefreshForWrapping(s),a=t.getBoundingClientRect(),l=o||this.mustMeasureContent||this.contentDOMHeight!=a.height;this.contentDOMHeight=a.height,this.mustMeasureContent=!1;let h=0,c=0;if(a.width&&a.height){let{scaleX:x,scaleY:Q}=GO(t,a);(this.scaleX!=x||this.scaleY!=Q)&&(this.scaleX=x,this.scaleY=Q,h|=8,o=l=!0)}let u=(parseInt(i.paddingTop)||0)*this.scaleY,f=(parseInt(i.paddingBottom)||0)*this.scaleY;(this.paddingTop!=u||this.paddingBottom!=f)&&(this.paddingTop=u,this.paddingBottom=f,h|=10),this.editorWidth!=e.scrollDOM.clientWidth&&(r.lineWrapping&&(l=!0),this.editorWidth=e.scrollDOM.clientWidth,h|=8);let p=e.scrollDOM.scrollTop*this.scaleY;this.scrollTop!=p&&(this.scrollAnchorHeight=-1,this.scrollTop=p),this.scrolledToBottom=HO(e.scrollDOM);let g=(this.printing?Yk:Jk)(t,this.paddingTop),y=g.top-this.pixelViewport.top,O=g.bottom-this.pixelViewport.bottom;this.pixelViewport=g;let S=this.pixelViewport.bottom>this.pixelViewport.top&&this.pixelViewport.right>this.pixelViewport.left;if(S!=this.inView&&(this.inView=S,S&&(l=!0)),!this.inView&&!this.scrollTarget)return 0;let k=a.width;if((this.contentDOMWidth!=k||this.editorHeight!=e.scrollDOM.clientHeight)&&(this.contentDOMWidth=a.width,this.editorHeight=e.scrollDOM.clientHeight,h|=8),l){let x=e.docView.measureVisibleLineHeights(this.viewport);if(r.mustRefreshForHeights(x)&&(o=!0),o||r.lineWrapping&&Math.abs(k-this.contentDOMWidth)>r.charWidth){let{lineHeight:Q,charWidth:A,textHeight:R}=e.docView.measureTextSize();o=Q>0&&r.refresh(s,Q,A,R,k/A,x),o&&(e.docView.minWidth=0,h|=8)}y>0&&O>0?c=Math.max(y,O):y<0&&O<0&&(c=Math.min(y,O)),r.heightChanged=!1;for(let Q of this.viewports){let A=Q.from==this.viewport.from?x:e.docView.measureVisibleLineHeights(Q);this.heightMap=(o?Ye.empty().applyChanges(this.stateDeco,K.empty,this.heightOracle,[new Nt(0,0,0,e.state.doc.length)]):this.heightMap).updateHeight(r,0,o,new jk(Q.from,A))}r.heightChanged&&(h|=2)}let $=!this.viewportIsAppropriate(this.viewport,c)||this.scrollTarget&&(this.scrollTarget.range.headthis.viewport.to);return $&&(this.viewport=this.getViewport(c,this.scrollTarget)),this.updateForViewport(),(h&2||$)&&this.updateViewportLines(),(this.lineGaps.length||this.viewport.to-this.viewport.from>4e3)&&this.updateLineGaps(this.ensureLineGaps(o?[]:this.lineGaps,e)),h|=this.computeVisibleRanges(),this.mustEnforceCursorAssoc&&(this.mustEnforceCursorAssoc=!1,e.docView.enforceCursorAssoc()),h}get visibleTop(){return this.scaler.fromDOM(this.pixelViewport.top)}get visibleBottom(){return this.scaler.fromDOM(this.pixelViewport.bottom)}getViewport(e,t){let i=.5-Math.max(-.5,Math.min(.5,e/1e3/2)),r=this.heightMap,s=this.heightOracle,{visibleTop:o,visibleBottom:a}=this,l=new ua(r.lineAt(o-i*1e3,le.ByHeight,s,0,0).from,r.lineAt(a+(1-i)*1e3,le.ByHeight,s,0,0).to);if(t){let{head:h}=t.range;if(hl.to){let c=Math.min(this.editorHeight,this.pixelViewport.bottom-this.pixelViewport.top),u=r.lineAt(h,le.ByPos,s,0,0),f;t.y=="center"?f=(u.top+u.bottom)/2-c/2:t.y=="start"||t.y=="nearest"&&h=a+Math.max(10,Math.min(i,250)))&&r>o-2*1e3&&s>1,o=r<<1;if(this.defaultTextDirection!=ge.LTR&&!i)return[];let a=[],l=(h,c,u,f)=>{if(c-hh&&OO.from>=u.from&&O.to<=u.to&&Math.abs(O.from-h)O.fromS));if(!y){if(cO.from<=c&&O.to>=c)){let O=t.moveToLineBoundary(P.cursor(c),!1,!0).head;O>h&&(c=O)}y=new Vh(h,c,this.gapSize(u,h,c,f))}a.push(y)};for(let h of this.viewportLines){if(h.lengthh.from&&l(h.from,f,h,c),pt.draw(this,this.heightOracle.lineWrapping))))}computeVisibleRanges(){let e=this.stateDeco;this.lineGaps.length&&(e=e.concat(this.lineGapDeco));let t=[];J.spans(e,this.viewport.from,this.viewport.to,{span(r,s){t.push({from:r,to:s})},point(){}},20);let i=t.length!=this.visibleRanges.length||this.visibleRanges.some((r,s)=>r.from!=t[s].from||r.to!=t[s].to);return this.visibleRanges=t,i?4:0}lineBlockAt(e){return e>=this.viewport.from&&e<=this.viewport.to&&this.viewportLines.find(t=>t.from<=e&&t.to>=e)||Fs(this.heightMap.lineAt(e,le.ByPos,this.heightOracle,0,0),this.scaler)}lineBlockAtHeight(e){return Fs(this.heightMap.lineAt(this.scaler.fromDOM(e),le.ByHeight,this.heightOracle,0,0),this.scaler)}scrollAnchorAt(e){let t=this.lineBlockAtHeight(e+8);return t.from>=this.viewport.from||this.viewportLines[0].top-e>200?t:this.viewportLines[0]}elementAtHeight(e){return Fs(this.heightMap.blockAt(this.scaler.fromDOM(e),this.heightOracle,0,0),this.scaler)}get docHeight(){return this.scaler.toDOM(this.heightMap.height)}get contentHeight(){return this.docHeight+this.paddingTop+this.paddingBottom}}class ua{constructor(e,t){this.from=e,this.to=t}}function Kk(n,e,t){let i=[],r=n,s=0;return J.spans(t,n,e,{span(){},point(o,a){o>r&&(i.push({from:r,to:o}),s+=o-r),r=a}},20),r=1)return e[e.length-1].to;let i=Math.floor(n*t);for(let r=0;;r++){let{from:s,to:o}=e[r],a=o-s;if(i<=a)return s+i;i-=a}}function da(n,e){let t=0;for(let{from:i,to:r}of n.ranges){if(e<=r){t+=e-i;break}t+=r-i}return t/n.total}function ex(n,e){for(let t of n)if(e(t))return t}const $p={toDOM(n){return n},fromDOM(n){return n},scale:1};class tx{constructor(e,t,i){let r=0,s=0,o=0;this.viewports=i.map(({from:a,to:l})=>{let h=t.lineAt(a,le.ByPos,e,0,0).top,c=t.lineAt(l,le.ByPos,e,0,0).bottom;return r+=c-h,{from:a,to:l,top:h,bottom:c,domTop:0,domBottom:0}}),this.scale=(7e6-r)/(t.height-r);for(let a of this.viewports)a.domTop=o+(a.top-s)*this.scale,o=a.domBottom=a.domTop+(a.bottom-a.top),s=a.bottom}toDOM(e){for(let t=0,i=0,r=0;;t++){let s=tFs(r,e)):n._content)}const pa=B.define({combine:n=>n.join(" ")}),mu=B.define({combine:n=>n.indexOf(!0)>-1}),Ou=Os.newName(),V0=Os.newName(),X0=Os.newName(),L0={"&light":"."+V0,"&dark":"."+X0};function yu(n,e,t){return new Os(e,{finish(i){return/&/.test(i)?i.replace(/&\w*/,r=>{if(r=="&")return n;if(!t||!t[r])throw new RangeError(`Unsupported selector: ${r}`);return t[r]}):n+" "+i}})}const ix=yu("."+Ou,{"&":{position:"relative !important",boxSizing:"border-box","&.cm-focused":{outline:"1px dotted #212121"},display:"flex !important",flexDirection:"column"},".cm-scroller":{display:"flex !important",alignItems:"flex-start !important",fontFamily:"monospace",lineHeight:1.4,height:"100%",overflowX:"auto",position:"relative",zIndex:0},".cm-content":{margin:0,flexGrow:2,flexShrink:0,display:"block",whiteSpace:"pre",wordWrap:"normal",boxSizing:"border-box",minHeight:"100%",padding:"4px 0",outline:"none","&[contenteditable=true]":{WebkitUserModify:"read-write-plaintext-only"}},".cm-lineWrapping":{whiteSpace_fallback:"pre-wrap",whiteSpace:"break-spaces",wordBreak:"break-word",overflowWrap:"anywhere",flexShrink:1},"&light .cm-content":{caretColor:"black"},"&dark .cm-content":{caretColor:"white"},".cm-line":{display:"block",padding:"0 2px 0 6px"},".cm-layer":{position:"absolute",left:0,top:0,contain:"size style","& > *":{position:"absolute"}},"&light .cm-selectionBackground":{background:"#d9d9d9"},"&dark .cm-selectionBackground":{background:"#222"},"&light.cm-focused > .cm-scroller > .cm-selectionLayer .cm-selectionBackground":{background:"#d7d4f0"},"&dark.cm-focused > .cm-scroller > .cm-selectionLayer .cm-selectionBackground":{background:"#233"},".cm-cursorLayer":{pointerEvents:"none"},"&.cm-focused > .cm-scroller > .cm-cursorLayer":{animation:"steps(1) cm-blink 1.2s infinite"},"@keyframes cm-blink":{"0%":{},"50%":{opacity:0},"100%":{}},"@keyframes cm-blink2":{"0%":{},"50%":{opacity:0},"100%":{}},".cm-cursor, .cm-dropCursor":{borderLeft:"1.2px solid black",marginLeft:"-0.6px",pointerEvents:"none"},".cm-cursor":{display:"none"},"&dark .cm-cursor":{borderLeftColor:"#444"},".cm-dropCursor":{position:"absolute"},"&.cm-focused > .cm-scroller > .cm-cursorLayer .cm-cursor":{display:"block"},".cm-iso":{unicodeBidi:"isolate"},".cm-announced":{position:"fixed",top:"-10000px"},"@media print":{".cm-announced":{display:"none"}},"&light .cm-activeLine":{backgroundColor:"#cceeff44"},"&dark .cm-activeLine":{backgroundColor:"#99eeff33"},"&light .cm-specialChar":{color:"red"},"&dark .cm-specialChar":{color:"#f78"},".cm-gutters":{flexShrink:0,display:"flex",height:"100%",boxSizing:"border-box",insetInlineStart:0,zIndex:200},"&light .cm-gutters":{backgroundColor:"#f5f5f5",color:"#6c6c6c",borderRight:"1px solid #ddd"},"&dark .cm-gutters":{backgroundColor:"#333338",color:"#ccc"},".cm-gutter":{display:"flex !important",flexDirection:"column",flexShrink:0,boxSizing:"border-box",minHeight:"100%",overflow:"hidden"},".cm-gutterElement":{boxSizing:"border-box"},".cm-lineNumbers .cm-gutterElement":{padding:"0 3px 0 5px",minWidth:"20px",textAlign:"right",whiteSpace:"nowrap"},"&light .cm-activeLineGutter":{backgroundColor:"#e2f2ff"},"&dark .cm-activeLineGutter":{backgroundColor:"#222227"},".cm-panels":{boxSizing:"border-box",position:"sticky",left:0,right:0},"&light .cm-panels":{backgroundColor:"#f5f5f5",color:"black"},"&light .cm-panels-top":{borderBottom:"1px solid #ddd"},"&light .cm-panels-bottom":{borderTop:"1px solid #ddd"},"&dark .cm-panels":{backgroundColor:"#333338",color:"white"},".cm-tab":{display:"inline-block",overflow:"hidden",verticalAlign:"bottom"},".cm-widgetBuffer":{verticalAlign:"text-top",height:"1em",width:0,display:"inline"},".cm-placeholder":{color:"#888",display:"inline-block",verticalAlign:"top"},".cm-highlightSpace:before":{content:"attr(data-display)",position:"absolute",pointerEvents:"none",color:"#888"},".cm-highlightTab":{backgroundImage:`url('data:image/svg+xml,')`,backgroundSize:"auto 100%",backgroundPosition:"right 90%",backgroundRepeat:"no-repeat"},".cm-trailingSpace":{backgroundColor:"#ff332255"},".cm-button":{verticalAlign:"middle",color:"inherit",fontSize:"70%",padding:".2em 1em",borderRadius:"1px"},"&light .cm-button":{backgroundImage:"linear-gradient(#eff1f5, #d9d9df)",border:"1px solid #888","&:active":{backgroundImage:"linear-gradient(#b4b4b4, #d0d3d6)"}},"&dark .cm-button":{backgroundImage:"linear-gradient(#393939, #111)",border:"1px solid #888","&:active":{backgroundImage:"linear-gradient(#111, #333)"}},".cm-textfield":{verticalAlign:"middle",color:"inherit",fontSize:"70%",border:"1px solid silver",padding:".2em .5em"},"&light .cm-textfield":{backgroundColor:"white"},"&dark .cm-textfield":{border:"1px solid #555",backgroundColor:"inherit"}},L0),zs="￿";class nx{constructor(e,t){this.points=e,this.text="",this.lineSeparator=t.facet(H.lineSeparator)}append(e){this.text+=e}lineBreak(){this.text+=zs}readRange(e,t){if(!e)return this;let i=e.parentNode;for(let r=e;;){this.findPointBefore(i,r);let s=this.text.length;this.readNode(r);let o=r.nextSibling;if(o==t)break;let a=he.get(r),l=he.get(o);(a&&l?a.breakAfter:(a?a.breakAfter:Cp(r))||Cp(o)&&(r.nodeName!="BR"||r.cmIgnore)&&this.text.length>s)&&this.lineBreak(),r=o}return this.findPointBefore(i,t),this}readTextNode(e){let t=e.nodeValue;for(let i of this.points)i.node==e&&(i.pos=this.text.length+Math.min(i.offset,t.length));for(let i=0,r=this.lineSeparator?null:/\r\n?|\n/g;;){let s=-1,o=1,a;if(this.lineSeparator?(s=t.indexOf(this.lineSeparator,i),o=this.lineSeparator.length):(a=r.exec(t))&&(s=a.index,o=a[0].length),this.append(t.slice(i,s<0?t.length:s)),s<0)break;if(this.lineBreak(),o>1)for(let l of this.points)l.node==e&&l.pos>this.text.length&&(l.pos-=o-1);i=s+o}}readNode(e){if(e.cmIgnore)return;let t=he.get(e),i=t&&t.overrideDOMText;if(i!=null){this.findPointInside(e,i.length);for(let r=i.iter();!r.next().done;)r.lineBreak?this.lineBreak():this.append(r.value)}else e.nodeType==3?this.readTextNode(e):e.nodeName=="BR"?e.nextSibling&&this.lineBreak():e.nodeType==1&&this.readRange(e.firstChild,null)}findPointBefore(e,t){for(let i of this.points)i.node==e&&e.childNodes[i.offset]==t&&(i.pos=this.text.length)}findPointInside(e,t){for(let i of this.points)(e.nodeType==3?i.node==e:e.contains(i.node))&&(i.pos=this.text.length+(rx(e,i.node,i.offset)?t:0))}}function rx(n,e,t){for(;;){if(!e||t-1)this.newSel=null;else if(t>-1&&(this.bounds=e.docView.domBoundsAround(t,i,0))){let a=s||o?[]:lx(e),l=new nx(a,e.state);l.readRange(this.bounds.startDOM,this.bounds.endDOM),this.text=l.text,this.newSel=hx(a,this.bounds.from)}else{let a=e.observer.selectionRange,l=s&&s.node==a.focusNode&&s.offset==a.focusOffset||!iu(e.contentDOM,a.focusNode)?e.state.selection.main.head:e.docView.posFromDOM(a.focusNode,a.focusOffset),h=o&&o.node==a.anchorNode&&o.offset==a.anchorOffset||!iu(e.contentDOM,a.anchorNode)?e.state.selection.main.anchor:e.docView.posFromDOM(a.anchorNode,a.anchorOffset),c=e.viewport;if(q.ios&&e.state.selection.main.empty&&l!=h&&(c.from>0||c.toDate.now()-100?n.inputState.lastKeyCode:-1;if(e.bounds){let{from:o,to:a}=e.bounds,l=r.from,h=null;(s===8||q.android&&e.text.length=r.from&&t.to<=r.to&&(t.from!=r.from||t.to!=r.to)&&r.to-r.from-(t.to-t.from)<=4?t={from:r.from,to:r.to,insert:n.state.doc.slice(r.from,t.from).append(t.insert).append(n.state.doc.slice(t.to,r.to))}:(q.mac||q.android)&&t&&t.from==t.to&&t.from==r.head-1&&/^\. ?$/.test(t.insert.toString())&&n.contentDOM.getAttribute("autocorrect")=="off"?(i&&t.insert.length==2&&(i=P.single(i.main.anchor-1,i.main.head-1)),t={from:r.from,to:r.to,insert:K.of([" "])}):q.chrome&&t&&t.from==t.to&&t.from==r.head&&t.insert.toString()==` - `&&n.lineWrapping&&(i&&(i=P.single(i.main.anchor-1,i.main.head-1)),t={from:r.from,to:r.to,insert:K.of([" "])}),t){if(q.ios&&n.inputState.flushIOSKey()||q.android&&(t.from==r.from&&t.to==r.to&&t.insert.length==1&&t.insert.lines==2&&ss(n.contentDOM,"Enter",13)||(t.from==r.from-1&&t.to==r.to&&t.insert.length==0||s==8&&t.insert.lengthr.head)&&ss(n.contentDOM,"Backspace",8)||t.from==r.from&&t.to==r.to+1&&t.insert.length==0&&ss(n.contentDOM,"Delete",46)))return!0;let o=t.insert.toString();n.inputState.composing>=0&&n.inputState.composing++;let a,l=()=>a||(a=ox(n,t,i));return n.state.facet(O0).some(h=>h(n,t.from,t.to,o,l))||n.dispatch(l()),!0}else if(i&&!i.main.eq(r)){let o=!1,a="select";return n.inputState.lastSelectionTime>Date.now()-50&&(n.inputState.lastSelectionOrigin=="select"&&(o=!0),a=n.inputState.lastSelectionOrigin),n.dispatch({selection:i,scrollIntoView:o,userEvent:a}),!0}else return!1}function ox(n,e,t){let i,r=n.state,s=r.selection.main;if(e.from>=s.from&&e.to<=s.to&&e.to-e.from>=(s.to-s.from)/3&&(!t||t.main.empty&&t.main.from==e.from+e.insert.length)&&n.inputState.composing<0){let a=s.frome.to?r.sliceDoc(e.to,s.to):"";i=r.replaceSelection(n.state.toText(a+e.insert.sliceString(0,void 0,n.state.lineBreak)+l))}else{let a=r.changes(e),l=t&&t.main.to<=a.newLength?t.main:void 0;if(r.selection.ranges.length>1&&n.inputState.composing>=0&&e.to<=s.to&&e.to>=s.to-10){let h=n.state.sliceDoc(e.from,e.to),c,u=t&&Q0(n,t.main.head);if(u){let g=e.insert.length-(e.to-e.from);c={from:u.from,to:u.to-g}}else c=n.state.doc.lineAt(s.head);let f=s.to-e.to,p=s.to-s.from;i=r.changeByRange(g=>{if(g.from==s.from&&g.to==s.to)return{changes:a,range:l||g.map(a)};let y=g.to-f,O=y-h.length;if(g.to-g.from!=p||n.state.sliceDoc(O,y)!=h||g.to>=c.from&&g.from<=c.to)return{range:g};let S=r.changes({from:O,to:y,insert:e.insert}),k=g.to-s.to;return{changes:S,range:l?P.range(Math.max(0,l.anchor+k),Math.max(0,l.head+k)):g.map(S)}})}else i={changes:a,selection:l&&r.selection.replaceRange(l)}}let o="input.type";return(n.composing||n.inputState.compositionPendingChange&&n.inputState.compositionEndedAt>Date.now()-50)&&(n.inputState.compositionPendingChange=!1,o+=".compose",n.inputState.compositionFirstChange&&(o+=".start",n.inputState.compositionFirstChange=!1)),r.update(i,{userEvent:o,scrollIntoView:!0})}function ax(n,e,t,i){let r=Math.min(n.length,e.length),s=0;for(;s0&&a>0&&n.charCodeAt(o-1)==e.charCodeAt(a-1);)o--,a--;if(i=="end"){let l=Math.max(0,s-Math.min(o,a));t-=o+l-s}if(o=o?s-t:0;s-=l,a=s+(a-o),o=s}else if(a=a?s-t:0;s-=l,o=s+(o-a),a=s}return{from:s,toA:o,toB:a}}function lx(n){let e=[];if(n.root.activeElement!=n.contentDOM)return e;let{anchorNode:t,anchorOffset:i,focusNode:r,focusOffset:s}=n.observer.selectionRange;return t&&(e.push(new Ip(t,i)),(r!=t||s!=i)&&e.push(new Ip(r,s))),e}function hx(n,e){if(n.length==0)return null;let t=n[0].pos,i=n.length==2?n[1].pos:t;return t>-1&&i>-1?P.single(t+e,i+e):null}const cx={childList:!0,characterData:!0,subtree:!0,attributes:!0,characterDataOldValue:!0},Xh=q.ie&&q.ie_version<=11;class ux{constructor(e){this.view=e,this.active=!1,this.selectionRange=new _v,this.selectionChanged=!1,this.delayedFlush=-1,this.resizeTimeout=-1,this.queue=[],this.delayedAndroidKey=null,this.flushingAndroidKey=-1,this.lastChange=0,this.scrollTargets=[],this.intersection=null,this.resizeScroll=null,this.intersecting=!1,this.gapIntersection=null,this.gaps=[],this.parentCheck=-1,this.dom=e.contentDOM,this.observer=new MutationObserver(t=>{for(let i of t)this.queue.push(i);(q.ie&&q.ie_version<=11||q.ios&&e.composing)&&t.some(i=>i.type=="childList"&&i.removedNodes.length||i.type=="characterData"&&i.oldValue.length>i.target.nodeValue.length)?this.flushSoon():this.flush()}),Xh&&(this.onCharData=t=>{this.queue.push({target:t.target,type:"characterData",oldValue:t.prevValue}),this.flushSoon()}),this.onSelectionChange=this.onSelectionChange.bind(this),this.onResize=this.onResize.bind(this),this.onPrint=this.onPrint.bind(this),this.onScroll=this.onScroll.bind(this),typeof ResizeObserver=="function"&&(this.resizeScroll=new ResizeObserver(()=>{var t;((t=this.view.docView)===null||t===void 0?void 0:t.lastUpdate){this.parentCheck<0&&(this.parentCheck=setTimeout(this.listenForScroll.bind(this),1e3)),t.length>0&&t[t.length-1].intersectionRatio>0!=this.intersecting&&(this.intersecting=!this.intersecting,this.intersecting!=this.view.inView&&this.onScrollChanged(document.createEvent("Event")))},{threshold:[0,.001]}),this.intersection.observe(this.dom),this.gapIntersection=new IntersectionObserver(t=>{t.length>0&&t[t.length-1].intersectionRatio>0&&this.onScrollChanged(document.createEvent("Event"))},{})),this.listenForScroll(),this.readSelectionRange()}onScrollChanged(e){this.view.inputState.runHandlers("scroll",e),this.intersecting&&this.view.measure()}onScroll(e){this.intersecting&&this.flush(!1),this.onScrollChanged(e)}onResize(){this.resizeTimeout<0&&(this.resizeTimeout=setTimeout(()=>{this.resizeTimeout=-1,this.view.requestMeasure()},50))}onPrint(){this.view.viewState.printing=!0,this.view.measure(),setTimeout(()=>{this.view.viewState.printing=!1,this.view.requestMeasure()},500)}updateGaps(e){if(this.gapIntersection&&(e.length!=this.gaps.length||this.gaps.some((t,i)=>t!=e[i]))){this.gapIntersection.disconnect();for(let t of e)this.gapIntersection.observe(t);this.gaps=e}}onSelectionChange(e){let t=this.selectionChanged;if(!this.readSelectionRange()||this.delayedAndroidKey)return;let{view:i}=this,r=this.selectionRange;if(i.state.facet(lh)?i.root.activeElement!=this.dom:!La(i.dom,r))return;let s=r.anchorNode&&i.docView.nearest(r.anchorNode);if(s&&s.ignoreEvent(e)){t||(this.selectionChanged=!1);return}(q.ie&&q.ie_version<=11||q.android&&q.chrome)&&!i.state.selection.main.empty&&r.focusNode&&io(r.focusNode,r.focusOffset,r.anchorNode,r.anchorOffset)?this.flushSoon():this.flush(!1)}readSelectionRange(){let{view:e}=this,t=q.safari&&e.root.nodeType==11&&Wv(this.dom.ownerDocument)==this.dom&&fx(this.view)||xl(e.root);if(!t||this.selectionRange.eq(t))return!1;let i=La(this.dom,t);return i&&!this.selectionChanged&&e.inputState.lastFocusTime>Date.now()-200&&e.inputState.lastTouchTime{let s=this.delayedAndroidKey;s&&(this.clearDelayedAndroidKey(),this.view.inputState.lastKeyCode=s.keyCode,this.view.inputState.lastKeyTime=Date.now(),!this.flush()&&s.force&&ss(this.dom,s.key,s.keyCode))};this.flushingAndroidKey=this.view.win.requestAnimationFrame(r)}(!this.delayedAndroidKey||e=="Enter")&&(this.delayedAndroidKey={key:e,keyCode:t,force:this.lastChange{this.delayedFlush=-1,this.flush()}))}forceFlush(){this.delayedFlush>=0&&(this.view.win.cancelAnimationFrame(this.delayedFlush),this.delayedFlush=-1),this.flush()}pendingRecords(){for(let e of this.observer.takeRecords())this.queue.push(e);return this.queue}processRecords(){let e=this.pendingRecords();e.length&&(this.queue=[]);let t=-1,i=-1,r=!1;for(let s of e){let o=this.readMutation(s);o&&(o.typeOver&&(r=!0),t==-1?{from:t,to:i}=o:(t=Math.min(o.from,t),i=Math.max(o.to,i)))}return{from:t,to:i,typeOver:r}}readChange(){let{from:e,to:t,typeOver:i}=this.processRecords(),r=this.selectionChanged&&La(this.dom,this.selectionRange);if(e<0&&!r)return null;e>-1&&(this.lastChange=Date.now()),this.view.inputState.lastFocusTime=0,this.selectionChanged=!1;let s=new sx(this.view,e,t,i);return this.view.docView.domChanged={newSel:s.newSel?s.newSel.main:null},s}flush(e=!0){if(this.delayedFlush>=0||this.delayedAndroidKey)return!1;e&&this.readSelectionRange();let t=this.readChange();if(!t)return this.view.requestMeasure(),!1;let i=this.view.state,r=U0(this.view,t);return this.view.state==i&&this.view.update([]),r}readMutation(e){let t=this.view.docView.nearest(e.target);if(!t||t.ignoreMutation(e))return null;if(t.markDirty(e.type=="attributes"),e.type=="attributes"&&(t.flags|=4),e.type=="childList"){let i=Rp(t,e.previousSibling||e.target.previousSibling,-1),r=Rp(t,e.nextSibling||e.target.nextSibling,1);return{from:i?t.posAfter(i):t.posAtStart,to:r?t.posBefore(r):t.posAtEnd,typeOver:!1}}else return e.type=="characterData"?{from:t.posAtStart,to:t.posAtEnd,typeOver:e.target.nodeValue==e.oldValue}:null}setWindow(e){e!=this.win&&(this.removeWindowListeners(this.win),this.win=e,this.addWindowListeners(this.win))}addWindowListeners(e){e.addEventListener("resize",this.onResize),e.addEventListener("beforeprint",this.onPrint),e.addEventListener("scroll",this.onScroll),e.document.addEventListener("selectionchange",this.onSelectionChange)}removeWindowListeners(e){e.removeEventListener("scroll",this.onScroll),e.removeEventListener("resize",this.onResize),e.removeEventListener("beforeprint",this.onPrint),e.document.removeEventListener("selectionchange",this.onSelectionChange)}destroy(){var e,t,i;this.stop(),(e=this.intersection)===null||e===void 0||e.disconnect(),(t=this.gapIntersection)===null||t===void 0||t.disconnect(),(i=this.resizeScroll)===null||i===void 0||i.disconnect();for(let r of this.scrollTargets)r.removeEventListener("scroll",this.onScroll);this.removeWindowListeners(this.win),clearTimeout(this.parentCheck),clearTimeout(this.resizeTimeout),this.win.cancelAnimationFrame(this.delayedFlush),this.win.cancelAnimationFrame(this.flushingAndroidKey)}}function Rp(n,e,t){for(;e;){let i=he.get(e);if(i&&i.parent==n)return i;let r=e.parentNode;e=r!=n.dom?r:t>0?e.nextSibling:e.previousSibling}return null}function fx(n){let e=null;function t(l){l.preventDefault(),l.stopImmediatePropagation(),e=l.getTargetRanges()[0]}if(n.contentDOM.addEventListener("beforeinput",t,!0),n.dom.ownerDocument.execCommand("indent"),n.contentDOM.removeEventListener("beforeinput",t,!0),!e)return null;let i=e.startContainer,r=e.startOffset,s=e.endContainer,o=e.endOffset,a=n.docView.domAtPos(n.state.selection.main.anchor);return io(a.node,a.offset,s,o)&&([i,r,s,o]=[s,o,i,r]),{anchorNode:i,anchorOffset:r,focusNode:s,focusOffset:o}}class N{get state(){return this.viewState.state}get viewport(){return this.viewState.viewport}get visibleRanges(){return this.viewState.visibleRanges}get inView(){return this.viewState.inView}get composing(){return this.inputState.composing>0}get compositionStarted(){return this.inputState.composing>=0}get root(){return this._root}get win(){return this.dom.ownerDocument.defaultView||window}constructor(e={}){this.plugins=[],this.pluginMap=new Map,this.editorAttrs={},this.contentAttrs={},this.bidiCache=[],this.destroyed=!1,this.updateState=2,this.measureScheduled=-1,this.measureRequests=[],this.contentDOM=document.createElement("div"),this.scrollDOM=document.createElement("div"),this.scrollDOM.tabIndex=-1,this.scrollDOM.className="cm-scroller",this.scrollDOM.appendChild(this.contentDOM),this.announceDOM=document.createElement("div"),this.announceDOM.className="cm-announced",this.announceDOM.setAttribute("aria-live","polite"),this.dom=document.createElement("div"),this.dom.appendChild(this.announceDOM),this.dom.appendChild(this.scrollDOM),e.parent&&e.parent.appendChild(this.dom);let{dispatch:t}=e;this.dispatchTransactions=e.dispatchTransactions||t&&(i=>i.forEach(r=>t(r,this)))||(i=>this.update(i)),this.dispatch=this.dispatch.bind(this),this._root=e.root||Gv(e.parent)||document,this.viewState=new Ap(e.state||H.create(e)),e.scrollTo&&e.scrollTo.is(la)&&(this.viewState.scrollTarget=e.scrollTo.value.clip(this.viewState.state)),this.plugins=this.state.facet(Ws).map(i=>new Bh(i));for(let i of this.plugins)i.update(this);this.observer=new ux(this),this.inputState=new Pk(this),this.inputState.ensureHandlers(this.plugins),this.docView=new cp(this),this.mountStyles(),this.updateAttrs(),this.updateState=0,this.requestMeasure()}dispatch(...e){let t=e.length==1&&e[0]instanceof ye?e:e.length==1&&Array.isArray(e[0])?e[0]:[this.state.update(...e)];this.dispatchTransactions(t,this)}update(e){if(this.updateState!=0)throw new Error("Calls to EditorView.update are not allowed while an update is in progress");let t=!1,i=!1,r,s=this.state;for(let f of e){if(f.startState!=s)throw new RangeError("Trying to update state with a transaction that doesn't start from the previous state.");s=f.state}if(this.destroyed){this.viewState.state=s;return}let o=this.hasFocus,a=0,l=null;e.some(f=>f.annotation(N0))?(this.inputState.notifiedFocused=o,a=1):o!=this.inputState.notifiedFocused&&(this.inputState.notifiedFocused=o,l=B0(s,o),l||(a=1));let h=this.observer.delayedAndroidKey,c=null;if(h?(this.observer.clearDelayedAndroidKey(),c=this.observer.readChange(),(c&&!this.state.doc.eq(s.doc)||!this.state.selection.eq(s.selection))&&(c=null)):this.observer.clear(),s.facet(H.phrases)!=this.state.facet(H.phrases))return this.setState(s);r=Tl.create(this,s,e),r.flags|=a;let u=this.viewState.scrollTarget;try{this.updateState=2;for(let f of e){if(u&&(u=u.map(f.changes)),f.scrollIntoView){let{main:p}=f.state.selection;u=new os(p.empty?p:P.cursor(p.head,p.head>p.anchor?-1:1))}for(let p of f.effects)p.is(la)&&(u=p.value.clip(this.state))}this.viewState.update(r,u),this.bidiCache=Ql.update(this.bidiCache,r.changes),r.empty||(this.updatePlugins(r),this.inputState.update(r)),t=this.docView.update(r),this.state.facet(js)!=this.styleModules&&this.mountStyles(),i=this.updateAttrs(),this.showAnnouncements(e),this.docView.updateSelection(t,e.some(f=>f.isUserEvent("select.pointer")))}finally{this.updateState=0}if(r.startState.facet(pa)!=r.state.facet(pa)&&(this.viewState.mustMeasureContent=!0),(t||i||u||this.viewState.mustEnforceCursorAssoc||this.viewState.mustMeasureContent)&&this.requestMeasure(),!r.empty)for(let f of this.state.facet(fu))try{f(r)}catch(p){mt(this.state,p,"update listener")}(l||c)&&Promise.resolve().then(()=>{l&&this.state==l.startState&&this.dispatch(l),c&&!U0(this,c)&&h.force&&ss(this.contentDOM,h.key,h.keyCode)})}setState(e){if(this.updateState!=0)throw new Error("Calls to EditorView.setState are not allowed while an update is in progress");if(this.destroyed){this.viewState.state=e;return}this.updateState=2;let t=this.hasFocus;try{for(let i of this.plugins)i.destroy(this);this.viewState=new Ap(e),this.plugins=e.facet(Ws).map(i=>new Bh(i)),this.pluginMap.clear();for(let i of this.plugins)i.update(this);this.docView.destroy(),this.docView=new cp(this),this.inputState.ensureHandlers(this.plugins),this.mountStyles(),this.updateAttrs(),this.bidiCache=[]}finally{this.updateState=0}t&&this.focus(),this.requestMeasure()}updatePlugins(e){let t=e.startState.facet(Ws),i=e.state.facet(Ws);if(t!=i){let r=[];for(let s of i){let o=t.indexOf(s);if(o<0)r.push(new Bh(s));else{let a=this.plugins[o];a.mustUpdate=e,r.push(a)}}for(let s of this.plugins)s.mustUpdate!=e&&s.destroy(this);this.plugins=r,this.pluginMap.clear()}else for(let r of this.plugins)r.mustUpdate=e;for(let r=0;r-1&&this.win.cancelAnimationFrame(this.measureScheduled),this.observer.delayedAndroidKey){this.measureScheduled=-1,this.requestMeasure();return}this.measureScheduled=0,e&&this.observer.forceFlush();let t=null,i=this.scrollDOM,r=i.scrollTop*this.scaleY,{scrollAnchorPos:s,scrollAnchorHeight:o}=this.viewState;Math.abs(r-this.viewState.scrollTop)>1&&(o=-1),this.viewState.scrollAnchorHeight=-1;try{for(let a=0;;a++){if(o<0)if(HO(i))s=-1,o=this.viewState.heightMap.height;else{let p=this.viewState.scrollAnchorAt(r);s=p.from,o=p.top}this.updateState=1;let l=this.viewState.measure(this);if(!l&&!this.measureRequests.length&&this.viewState.scrollTarget==null)break;if(a>5){console.warn(this.measureRequests.length?"Measure loop restarted more than 5 times":"Viewport failed to stabilize");break}let h=[];l&4||([this.measureRequests,h]=[h,this.measureRequests]);let c=h.map(p=>{try{return p.read(this)}catch(g){return mt(this.state,g),Ep}}),u=Tl.create(this,this.state,[]),f=!1;u.flags|=l,t?t.flags|=l:t=u,this.updateState=2,u.empty||(this.updatePlugins(u),this.inputState.update(u),this.updateAttrs(),f=this.docView.update(u));for(let p=0;p1||g<-1){r=r+g,i.scrollTop=r/this.scaleY,o=-1;continue}}break}}}finally{this.updateState=0,this.measureScheduled=-1}if(t&&!t.empty)for(let a of this.state.facet(fu))a(t)}get themeClasses(){return Ou+" "+(this.state.facet(mu)?X0:V0)+" "+this.state.facet(pa)}updateAttrs(){let e=Dp(this,w0,{class:"cm-editor"+(this.hasFocus?" cm-focused ":" ")+this.themeClasses}),t={spellcheck:"false",autocorrect:"off",autocapitalize:"off",translate:"no",contenteditable:this.state.facet(lh)?"true":"false",class:"cm-content",style:`${q.tabSize}: ${this.state.tabSize}`,role:"textbox","aria-multiline":"true"};this.state.readOnly&&(t["aria-readonly"]="true"),Dp(this,yf,t);let i=this.observer.ignore(()=>{let r=au(this.contentDOM,this.contentAttrs,t),s=au(this.dom,this.editorAttrs,e);return r||s});return this.editorAttrs=e,this.contentAttrs=t,i}showAnnouncements(e){let t=!0;for(let i of e)for(let r of i.effects)if(r.is(N.announce)){t&&(this.announceDOM.textContent=""),t=!1;let s=this.announceDOM.appendChild(document.createElement("div"));s.textContent=r.value}}mountStyles(){this.styleModules=this.state.facet(js);let e=this.state.facet(N.cspNonce);Os.mount(this.root,this.styleModules.concat(ix).reverse(),e?{nonce:e}:void 0)}readMeasured(){if(this.updateState==2)throw new Error("Reading the editor layout isn't allowed during an update");this.updateState==0&&this.measureScheduled>-1&&this.measure(!1)}requestMeasure(e){if(this.measureScheduled<0&&(this.measureScheduled=this.win.requestAnimationFrame(()=>this.measure())),e){if(this.measureRequests.indexOf(e)>-1)return;if(e.key!=null){for(let t=0;ti.spec==e)||null),t&&t.update(this).value}get documentTop(){return this.contentDOM.getBoundingClientRect().top+this.viewState.paddingTop}get documentPadding(){return{top:this.viewState.paddingTop,bottom:this.viewState.paddingBottom}}get scaleX(){return this.viewState.scaleX}get scaleY(){return this.viewState.scaleY}elementAtHeight(e){return this.readMeasured(),this.viewState.elementAtHeight(e)}lineBlockAtHeight(e){return this.readMeasured(),this.viewState.lineBlockAtHeight(e)}get viewportLineBlocks(){return this.viewState.viewportLines}lineBlockAt(e){return this.viewState.lineBlockAt(e)}get contentHeight(){return this.viewState.contentHeight}moveByChar(e,t,i){return Mh(this,e,mp(this,e,t,i))}moveByGroup(e,t){return Mh(this,e,mp(this,e,t,i=>Tk(this,e.head,i)))}visualLineSide(e,t){let i=this.bidiSpans(e),r=this.textDirectionAt(e.from),s=i[t?i.length-1:0];return P.cursor(s.side(t,r)+e.from,s.forward(!t,r)?1:-1)}moveToLineBoundary(e,t,i=!0){return xk(this,e,t,i)}moveVertically(e,t,i){return Mh(this,e,Qk(this,e,t,i))}domAtPos(e){return this.docView.domAtPos(e)}posAtDOM(e,t=0){return this.docView.posFromDOM(e,t)}posAtCoords(e,t=!0){return this.readMeasured(),A0(this,e,t)}coordsAtPos(e,t=1){this.readMeasured();let i=this.docView.coordsAt(e,t);if(!i||i.left==i.right)return i;let r=this.state.doc.lineAt(e),s=this.bidiSpans(r),o=s[ir.find(s,e-r.from,-1,t)];return pf(i,o.dir==ge.LTR==t>0)}coordsForChar(e){return this.readMeasured(),this.docView.coordsForChar(e)}get defaultCharacterWidth(){return this.viewState.heightOracle.charWidth}get defaultLineHeight(){return this.viewState.heightOracle.lineHeight}get textDirection(){return this.viewState.defaultTextDirection}textDirectionAt(e){return!this.state.facet(b0)||ethis.viewport.to?this.textDirection:(this.readMeasured(),this.docView.textDirectionAt(e))}get lineWrapping(){return this.viewState.heightOracle.lineWrapping}bidiSpans(e){if(e.length>dx)return u0(e.length);let t=this.textDirectionAt(e.from),i;for(let s of this.bidiCache)if(s.from==e.from&&s.dir==t&&(s.fresh||c0(s.isolates,i=hp(this,e))))return s.order;i||(i=hp(this,e));let r=lk(e.text,t,i);return this.bidiCache.push(new Ql(e.from,e.to,t,i,!0,r)),r}get hasFocus(){var e;return(this.dom.ownerDocument.hasFocus()||q.safari&&((e=this.inputState)===null||e===void 0?void 0:e.lastContextMenu)>Date.now()-3e4)&&this.root.activeElement==this.contentDOM}focus(){this.observer.ignore(()=>{JO(this.contentDOM),this.docView.updateSelection()})}setRoot(e){this._root!=e&&(this._root=e,this.observer.setWindow((e.nodeType==9?e:e.ownerDocument).defaultView||window),this.mountStyles())}destroy(){for(let e of this.plugins)e.destroy(this);this.plugins=[],this.inputState.destroy(),this.docView.destroy(),this.dom.remove(),this.observer.destroy(),this.measureScheduled>-1&&this.win.cancelAnimationFrame(this.measureScheduled),this.destroyed=!0}static scrollIntoView(e,t={}){return la.of(new os(typeof e=="number"?P.cursor(e):e,t.y,t.x,t.yMargin,t.xMargin))}scrollSnapshot(){let{scrollTop:e,scrollLeft:t}=this.scrollDOM,i=this.viewState.scrollAnchorAt(e);return la.of(new os(P.cursor(i.from),"start","start",i.top-e,t,!0))}static domEventHandlers(e){return ke.define(()=>({}),{eventHandlers:e})}static domEventObservers(e){return ke.define(()=>({}),{eventObservers:e})}static theme(e,t){let i=Os.newName(),r=[pa.of(i),js.of(yu(`.${i}`,e))];return t&&t.dark&&r.push(mu.of(!0)),r}static baseTheme(e){return mr.lowest(js.of(yu("."+Ou,e,L0)))}static findFromDOM(e){var t;let i=e.querySelector(".cm-content"),r=i&&he.get(i)||he.get(e);return((t=r==null?void 0:r.rootView)===null||t===void 0?void 0:t.view)||null}}N.styleModule=js;N.inputHandler=O0;N.focusChangeEffect=y0;N.perLineTextDirection=b0;N.exceptionSink=m0;N.updateListener=fu;N.editable=lh;N.mouseSelectionStyle=g0;N.dragMovesSelection=p0;N.clickAddsSelectionRange=d0;N.decorations=xo;N.outerDecorations=v0;N.atomicRanges=bf;N.bidiIsolatedRanges=k0;N.scrollMargins=x0;N.darkTheme=mu;N.cspNonce=B.define({combine:n=>n.length?n[0]:""});N.contentAttributes=yf;N.editorAttributes=w0;N.lineWrapping=N.contentAttributes.of({class:"cm-lineWrapping"});N.announce=z.define();const dx=4096,Ep={};class Ql{constructor(e,t,i,r,s,o){this.from=e,this.to=t,this.dir=i,this.isolates=r,this.fresh=s,this.order=o}static update(e,t){if(t.empty&&!e.some(s=>s.fresh))return e;let i=[],r=e.length?e[e.length-1].dir:ge.LTR;for(let s=Math.max(0,e.length-10);s=0;r--){let s=i[r],o=typeof s=="function"?s(n):s;o&&ou(o,t)}return t}const px=q.mac?"mac":q.windows?"win":q.linux?"linux":"key";function gx(n,e){const t=n.split(/-(?!$)/);let i=t[t.length-1];i=="Space"&&(i=" ");let r,s,o,a;for(let l=0;li.concat(r),[]))),t}function Ox(n,e,t){return W0(Z0(n.state),e,n,t)}let Hn=null;const yx=4e3;function bx(n,e=px){let t=Object.create(null),i=Object.create(null),r=(o,a)=>{let l=i[o];if(l==null)i[o]=a;else if(l!=a)throw new Error("Key binding "+o+" is used both as a regular binding and as a multi-stroke prefix")},s=(o,a,l,h,c)=>{var u,f;let p=t[o]||(t[o]=Object.create(null)),g=a.split(/ (?!$)/).map(S=>gx(S,e));for(let S=1;S{let x=Hn={view:$,prefix:k,scope:o};return setTimeout(()=>{Hn==x&&(Hn=null)},yx),!0}]})}let y=g.join(" ");r(y,!1);let O=p[y]||(p[y]={preventDefault:!1,stopPropagation:!1,run:((f=(u=p._any)===null||u===void 0?void 0:u.run)===null||f===void 0?void 0:f.slice())||[]});l&&O.run.push(l),h&&(O.preventDefault=!0),c&&(O.stopPropagation=!0)};for(let o of n){let a=o.scope?o.scope.split(" "):["editor"];if(o.any)for(let h of a){let c=t[h]||(t[h]=Object.create(null));c._any||(c._any={preventDefault:!1,stopPropagation:!1,run:[]});for(let u in c)c[u].run.push(o.any)}let l=o[e]||o.key;if(l)for(let h of a)s(h,l,o.run,o.preventDefault,o.stopPropagation),o.shift&&s(h,"Shift-"+l,o.shift,o.preventDefault,o.stopPropagation)}return t}function W0(n,e,t,i){let r=Zv(e),s=Ne(r,0),o=lt(s)==r.length&&r!=" ",a="",l=!1,h=!1,c=!1;Hn&&Hn.view==t&&Hn.scope==i&&(a=Hn.prefix+" ",C0.indexOf(e.keyCode)<0&&(h=!0,Hn=null));let u=new Set,f=O=>{if(O){for(let S of O.run)if(!u.has(S)&&(u.add(S),S(t,e)))return O.stopPropagation&&(c=!0),!0;O.preventDefault&&(O.stopPropagation&&(c=!0),h=!0)}return!1},p=n[i],g,y;return p&&(f(p[a+ga(r,e,!o)])?l=!0:o&&(e.altKey||e.metaKey||e.ctrlKey)&&!(q.windows&&e.ctrlKey&&e.altKey)&&(g=dr[e.keyCode])&&g!=r?(f(p[a+ga(g,e,!0)])||e.shiftKey&&(y=wo[e.keyCode])!=r&&y!=g&&f(p[a+ga(y,e,!1)]))&&(l=!0):o&&e.shiftKey&&f(p[a+ga(r,e,!0)])&&(l=!0),!l&&f(p._any)&&(l=!0)),h&&(l=!0),l&&c&&e.stopPropagation(),l}class jo{constructor(e,t,i,r,s){this.className=e,this.left=t,this.top=i,this.width=r,this.height=s}draw(){let e=document.createElement("div");return e.className=this.className,this.adjust(e),e}update(e,t){return t.className!=this.className?!1:(this.adjust(e),!0)}adjust(e){e.style.left=this.left+"px",e.style.top=this.top+"px",this.width!=null&&(e.style.width=this.width+"px"),e.style.height=this.height+"px"}eq(e){return this.left==e.left&&this.top==e.top&&this.width==e.width&&this.height==e.height&&this.className==e.className}static forRange(e,t,i){if(i.empty){let r=e.coordsAtPos(i.head,i.assoc||1);if(!r)return[];let s=j0(e);return[new jo(t,r.left-s.left,r.top-s.top,null,r.bottom-r.top)]}else return Sx(e,t,i)}}function j0(n){let e=n.scrollDOM.getBoundingClientRect();return{left:(n.textDirection==ge.LTR?e.left:e.right-n.scrollDOM.clientWidth*n.scaleX)-n.scrollDOM.scrollLeft*n.scaleX,top:e.top-n.scrollDOM.scrollTop*n.scaleY}}function Bp(n,e,t){let i=P.cursor(e);return{from:Math.max(t.from,n.moveToLineBoundary(i,!1,!0).from),to:Math.min(t.to,n.moveToLineBoundary(i,!0,!0).from),type:Je.Text}}function Sx(n,e,t){if(t.to<=n.viewport.from||t.from>=n.viewport.to)return[];let i=Math.max(t.from,n.viewport.from),r=Math.min(t.to,n.viewport.to),s=n.textDirection==ge.LTR,o=n.contentDOM,a=o.getBoundingClientRect(),l=j0(n),h=o.querySelector(".cm-line"),c=h&&window.getComputedStyle(h),u=a.left+(c?parseInt(c.paddingLeft)+Math.min(0,parseInt(c.textIndent)):0),f=a.right-(c?parseInt(c.paddingRight):0),p=pu(n,i),g=pu(n,r),y=p.type==Je.Text?p:null,O=g.type==Je.Text?g:null;if(y&&(n.lineWrapping||p.widgetLineBreaks)&&(y=Bp(n,i,y)),O&&(n.lineWrapping||g.widgetLineBreaks)&&(O=Bp(n,r,O)),y&&O&&y.from==O.from)return k($(t.from,t.to,y));{let Q=y?$(t.from,null,y):x(p,!1),A=O?$(null,t.to,O):x(g,!0),R=[];return(y||p).to<(O||g).from-(y&&O?1:0)||p.widgetLineBreaks>1&&Q.bottom+n.defaultLineHeight/2Qe&&He.from=Xe)break;Pe>Ee&&re(Math.max(be,Ee),Q==null&&be<=Qe,Math.min(Pe,Xe),A==null&&Pe>=Ve,Ke.dir)}if(Ee=ni.to+1,Ee>=Xe)break}return G.length==0&&re(Qe,Q==null,Ve,A==null,n.textDirection),{top:j,bottom:W,horizontal:G}}function x(Q,A){let R=a.top+(A?Q.top:Q.bottom);return{top:R,bottom:R,horizontal:[]}}}function wx(n,e){return n.constructor==e.constructor&&n.eq(e)}class vx{constructor(e,t){this.view=e,this.layer=t,this.drawn=[],this.scaleX=1,this.scaleY=1,this.measureReq={read:this.measure.bind(this),write:this.draw.bind(this)},this.dom=e.scrollDOM.appendChild(document.createElement("div")),this.dom.classList.add("cm-layer"),t.above&&this.dom.classList.add("cm-layer-above"),t.class&&this.dom.classList.add(t.class),this.scale(),this.dom.setAttribute("aria-hidden","true"),this.setOrder(e.state),e.requestMeasure(this.measureReq),t.mount&&t.mount(this.dom,e)}update(e){e.startState.facet(Wa)!=e.state.facet(Wa)&&this.setOrder(e.state),(this.layer.update(e,this.dom)||e.geometryChanged)&&(this.scale(),e.view.requestMeasure(this.measureReq))}setOrder(e){let t=0,i=e.facet(Wa);for(;t!wx(t,this.drawn[i]))){let t=this.dom.firstChild,i=0;for(let r of e)r.update&&t&&r.constructor&&this.drawn[i].constructor&&r.update(t,this.drawn[i])?(t=t.nextSibling,i++):this.dom.insertBefore(r.draw(),t);for(;t;){let r=t.nextSibling;t.remove(),t=r}this.drawn=e}}destroy(){this.layer.destroy&&this.layer.destroy(this.dom,this.view),this.dom.remove()}}const Wa=B.define();function F0(n){return[ke.define(e=>new vx(e,n)),Wa.of(n)]}const z0=!q.ios,To=B.define({combine(n){return Ai(n,{cursorBlinkRate:1200,drawRangeCursor:!0},{cursorBlinkRate:(e,t)=>Math.min(e,t),drawRangeCursor:(e,t)=>e||t})}});function kx(n={}){return[To.of(n),xx,Tx,Qx,S0.of(!0)]}function _0(n){return n.startState.facet(To)!=n.state.facet(To)}const xx=F0({above:!0,markers(n){let{state:e}=n,t=e.facet(To),i=[];for(let r of e.selection.ranges){let s=r==e.selection.main;if(r.empty?!s||z0:t.drawRangeCursor){let o=s?"cm-cursor cm-cursor-primary":"cm-cursor cm-cursor-secondary",a=r.empty?r:P.cursor(r.head,r.head>r.anchor?-1:1);for(let l of jo.forRange(n,o,a))i.push(l)}}return i},update(n,e){n.transactions.some(i=>i.selection)&&(e.style.animationName=e.style.animationName=="cm-blink"?"cm-blink2":"cm-blink");let t=_0(n);return t&&qp(n.state,e),n.docChanged||n.selectionSet||t},mount(n,e){qp(e.state,n)},class:"cm-cursorLayer"});function qp(n,e){e.style.animationDuration=n.facet(To).cursorBlinkRate+"ms"}const Tx=F0({above:!1,markers(n){return n.state.selection.ranges.map(e=>e.empty?[]:jo.forRange(n,"cm-selectionBackground",e)).reduce((e,t)=>e.concat(t))},update(n,e){return n.docChanged||n.selectionSet||n.viewportChanged||_0(n)},class:"cm-selectionLayer"}),bu={".cm-line":{"& ::selection":{backgroundColor:"transparent !important"},"&::selection":{backgroundColor:"transparent !important"}}};z0&&(bu[".cm-line"].caretColor="transparent !important",bu[".cm-content"]={caretColor:"transparent !important"});const Qx=mr.highest(N.theme(bu)),G0=z.define({map(n,e){return n==null?null:e.mapPos(n)}}),_s=Re.define({create(){return null},update(n,e){return n!=null&&(n=e.changes.mapPos(n)),e.effects.reduce((t,i)=>i.is(G0)?i.value:t,n)}}),Px=ke.fromClass(class{constructor(n){this.view=n,this.cursor=null,this.measureReq={read:this.readPos.bind(this),write:this.drawCursor.bind(this)}}update(n){var e;let t=n.state.field(_s);t==null?this.cursor!=null&&((e=this.cursor)===null||e===void 0||e.remove(),this.cursor=null):(this.cursor||(this.cursor=this.view.scrollDOM.appendChild(document.createElement("div")),this.cursor.className="cm-dropCursor"),(n.startState.field(_s)!=t||n.docChanged||n.geometryChanged)&&this.view.requestMeasure(this.measureReq))}readPos(){let{view:n}=this,e=n.state.field(_s),t=e!=null&&n.coordsAtPos(e);if(!t)return null;let i=n.scrollDOM.getBoundingClientRect();return{left:t.left-i.left+n.scrollDOM.scrollLeft*n.scaleX,top:t.top-i.top+n.scrollDOM.scrollTop*n.scaleY,height:t.bottom-t.top}}drawCursor(n){if(this.cursor){let{scaleX:e,scaleY:t}=this.view;n?(this.cursor.style.left=n.left/e+"px",this.cursor.style.top=n.top/t+"px",this.cursor.style.height=n.height/t+"px"):this.cursor.style.left="-100000px"}}destroy(){this.cursor&&this.cursor.remove()}setDropPos(n){this.view.state.field(_s)!=n&&this.view.dispatch({effects:G0.of(n)})}},{eventObservers:{dragover(n){this.setDropPos(this.view.posAtCoords({x:n.clientX,y:n.clientY}))},dragleave(n){(n.target==this.view.contentDOM||!this.view.contentDOM.contains(n.relatedTarget))&&this.setDropPos(null)},dragend(){this.setDropPos(null)},drop(){this.setDropPos(null)}}});function Ax(){return[_s,Px]}function Mp(n,e,t,i,r){e.lastIndex=0;for(let s=n.iterRange(t,i),o=t,a;!s.next().done;o+=s.value.length)if(!s.lineBreak)for(;a=e.exec(s.value);)r(o+a.index,a)}function $x(n,e){let t=n.visibleRanges;if(t.length==1&&t[0].from==n.viewport.from&&t[0].to==n.viewport.to)return t;let i=[];for(let{from:r,to:s}of t)r=Math.max(n.state.doc.lineAt(r).from,r-e),s=Math.min(n.state.doc.lineAt(s).to,s+e),i.length&&i[i.length-1].to>=r?i[i.length-1].to=s:i.push({from:r,to:s});return i}class Cx{constructor(e){const{regexp:t,decoration:i,decorate:r,boundary:s,maxLength:o=1e3}=e;if(!t.global)throw new RangeError("The regular expression given to MatchDecorator should have its 'g' flag set");if(this.regexp=t,r)this.addMatch=(a,l,h,c)=>r(c,h,h+a[0].length,a,l);else if(typeof i=="function")this.addMatch=(a,l,h,c)=>{let u=i(a,l,h);u&&c(h,h+a[0].length,u)};else if(i)this.addMatch=(a,l,h,c)=>c(h,h+a[0].length,i);else throw new RangeError("Either 'decorate' or 'decoration' should be provided to MatchDecorator");this.boundary=s,this.maxLength=o}createDeco(e){let t=new fr,i=t.add.bind(t);for(let{from:r,to:s}of $x(e,this.maxLength))Mp(e.state.doc,this.regexp,r,s,(o,a)=>this.addMatch(a,e,o,i));return t.finish()}updateDeco(e,t){let i=1e9,r=-1;return e.docChanged&&e.changes.iterChanges((s,o,a,l)=>{l>e.view.viewport.from&&a1e3?this.createDeco(e.view):r>-1?this.updateRange(e.view,t.map(e.changes),i,r):t}updateRange(e,t,i,r){for(let s of e.visibleRanges){let o=Math.max(s.from,i),a=Math.min(s.to,r);if(a>o){let l=e.state.doc.lineAt(o),h=l.tol.from;o--)if(this.boundary.test(l.text[o-1-l.from])){c=o;break}for(;af.push(S.range(y,O));if(l==h)for(this.regexp.lastIndex=c-l.from;(p=this.regexp.exec(l.text))&&p.indexthis.addMatch(O,e,y,g));t=t.update({filterFrom:c,filterTo:u,filter:(y,O)=>yu,add:f})}}return t}}const Su=/x/.unicode!=null?"gu":"g",Ix=new RegExp(`[\0-\b ---Ÿ­؜​‎‏\u2028\u2029‭‮⁦⁧⁩\uFEFF-]`,Su),Rx={0:"null",7:"bell",8:"backspace",10:"newline",11:"vertical tab",13:"carriage return",27:"escape",8203:"zero width space",8204:"zero width non-joiner",8205:"zero width joiner",8206:"left-to-right mark",8207:"right-to-left mark",8232:"line separator",8237:"left-to-right override",8238:"right-to-left override",8294:"left-to-right isolate",8295:"right-to-left isolate",8297:"pop directional isolate",8233:"paragraph separator",65279:"zero width no-break space",65532:"object replacement"};let Lh=null;function Ex(){var n;if(Lh==null&&typeof document<"u"&&document.body){let e=document.body.style;Lh=((n=e.tabSize)!==null&&n!==void 0?n:e.MozTabSize)!=null}return Lh||!1}const ja=B.define({combine(n){let e=Ai(n,{render:null,specialChars:Ix,addSpecialChars:null});return(e.replaceTabs=!Ex())&&(e.specialChars=new RegExp(" |"+e.specialChars.source,Su)),e.addSpecialChars&&(e.specialChars=new RegExp(e.specialChars.source+"|"+e.addSpecialChars.source,Su)),e}});function Dx(n={}){return[ja.of(n),Nx()]}let Vp=null;function Nx(){return Vp||(Vp=ke.fromClass(class{constructor(n){this.view=n,this.decorations=Z.none,this.decorationCache=Object.create(null),this.decorator=this.makeDecorator(n.state.facet(ja)),this.decorations=this.decorator.createDeco(n)}makeDecorator(n){return new Cx({regexp:n.specialChars,decoration:(e,t,i)=>{let{doc:r}=t.state,s=Ne(e[0],0);if(s==9){let o=r.lineAt(i),a=t.state.tabSize,l=Uo(o.text,a,i-o.from);return Z.replace({widget:new Vx((a-l%a)*this.view.defaultCharacterWidth/this.view.scaleX)})}return this.decorationCache[s]||(this.decorationCache[s]=Z.replace({widget:new Mx(n,s)}))},boundary:n.replaceTabs?void 0:/[^]/})}update(n){let e=n.state.facet(ja);n.startState.facet(ja)!=e?(this.decorator=this.makeDecorator(e),this.decorations=this.decorator.createDeco(n.view)):this.decorations=this.decorator.updateDeco(n,this.decorations)}},{decorations:n=>n.decorations}))}const Bx="•";function qx(n){return n>=32?Bx:n==10?"␤":String.fromCharCode(9216+n)}class Mx extends Or{constructor(e,t){super(),this.options=e,this.code=t}eq(e){return e.code==this.code}toDOM(e){let t=qx(this.code),i=e.state.phrase("Control character")+" "+(Rx[this.code]||"0x"+this.code.toString(16)),r=this.options.render&&this.options.render(this.code,i,t);if(r)return r;let s=document.createElement("span");return s.textContent=t,s.title=i,s.setAttribute("aria-label",i),s.className="cm-specialChar",s}ignoreEvent(){return!1}}class Vx extends Or{constructor(e){super(),this.width=e}eq(e){return e.width==this.width}toDOM(){let e=document.createElement("span");return e.textContent=" ",e.className="cm-tab",e.style.width=this.width+"px",e}ignoreEvent(){return!1}}function Xx(){return Ux}const Lx=Z.line({class:"cm-activeLine"}),Ux=ke.fromClass(class{constructor(n){this.decorations=this.getDeco(n)}update(n){(n.docChanged||n.selectionSet)&&(this.decorations=this.getDeco(n.view))}getDeco(n){let e=-1,t=[];for(let i of n.state.selection.ranges){let r=n.lineBlockAt(i.head);r.from>e&&(t.push(Lx.range(r.from)),e=r.from)}return Z.set(t)}},{decorations:n=>n.decorations}),wu=2e3;function Zx(n,e,t){let i=Math.min(e.line,t.line),r=Math.max(e.line,t.line),s=[];if(e.off>wu||t.off>wu||e.col<0||t.col<0){let o=Math.min(e.off,t.off),a=Math.max(e.off,t.off);for(let l=i;l<=r;l++){let h=n.doc.line(l);h.length<=a&&s.push(P.range(h.from+o,h.to+a))}}else{let o=Math.min(e.col,t.col),a=Math.max(e.col,t.col);for(let l=i;l<=r;l++){let h=n.doc.line(l),c=Kc(h.text,o,n.tabSize,!0);if(c<0)s.push(P.cursor(h.to));else{let u=Kc(h.text,a,n.tabSize);s.push(P.range(h.from+c,h.from+u))}}}return s}function Wx(n,e){let t=n.coordsAtPos(n.viewport.from);return t?Math.round(Math.abs((t.left-e)/n.defaultCharacterWidth)):-1}function Xp(n,e){let t=n.posAtCoords({x:e.clientX,y:e.clientY},!1),i=n.state.doc.lineAt(t),r=t-i.from,s=r>wu?-1:r==i.length?Wx(n,e.clientX):Uo(i.text,n.state.tabSize,t-i.from);return{line:i.number,col:s,off:r}}function jx(n,e){let t=Xp(n,e),i=n.state.selection;return t?{update(r){if(r.docChanged){let s=r.changes.mapPos(r.startState.doc.line(t.line).from),o=r.state.doc.lineAt(s);t={line:o.number,col:t.col,off:Math.min(t.off,o.length)},i=i.map(r.changes)}},get(r,s,o){let a=Xp(n,r);if(!a)return i;let l=Zx(n.state,t,a);return l.length?o?P.create(l.concat(i.ranges)):P.create(l):i}}:null}function Fx(n){let e=t=>t.altKey&&t.button==0;return N.mouseSelectionStyle.of((t,i)=>e(i)?jx(t,i):null)}const zx={Alt:[18,n=>!!n.altKey],Control:[17,n=>!!n.ctrlKey],Shift:[16,n=>!!n.shiftKey],Meta:[91,n=>!!n.metaKey]},_x={style:"cursor: crosshair"};function Gx(n={}){let[e,t]=zx[n.key||"Alt"],i=ke.fromClass(class{constructor(r){this.view=r,this.isDown=!1}set(r){this.isDown!=r&&(this.isDown=r,this.view.update([]))}},{eventObservers:{keydown(r){this.set(r.keyCode==e||t(r))},keyup(r){(r.keyCode==e||!t(r))&&this.set(!1)},mousemove(r){this.set(t(r))}}});return[i,N.contentAttributes.of(r=>{var s;return!((s=r.plugin(i))===null||s===void 0)&&s.isDown?_x:null})]}const Bs="-10000px";class J0{constructor(e,t,i,r){this.facet=t,this.createTooltipView=i,this.removeTooltipView=r,this.input=e.state.facet(t),this.tooltips=this.input.filter(s=>s),this.tooltipViews=this.tooltips.map(i)}update(e,t){var i;let r=e.state.facet(this.facet),s=r.filter(l=>l);if(r===this.input){for(let l of this.tooltipViews)l.update&&l.update(e);return!1}let o=[],a=t?[]:null;for(let l=0;lt[h]=l),t.length=a.length),this.input=r,this.tooltips=s,this.tooltipViews=o,!0}}function Jx(n){let{win:e}=n;return{top:0,left:0,bottom:e.innerHeight,right:e.innerWidth}}const Uh=B.define({combine:n=>{var e,t,i;return{position:q.ios?"absolute":((e=n.find(r=>r.position))===null||e===void 0?void 0:e.position)||"fixed",parent:((t=n.find(r=>r.parent))===null||t===void 0?void 0:t.parent)||null,tooltipSpace:((i=n.find(r=>r.tooltipSpace))===null||i===void 0?void 0:i.tooltipSpace)||Jx}}}),Lp=new WeakMap,wf=ke.fromClass(class{constructor(n){this.view=n,this.above=[],this.inView=!0,this.madeAbsolute=!1,this.lastTransaction=0,this.measureTimeout=-1;let e=n.state.facet(Uh);this.position=e.position,this.parent=e.parent,this.classes=n.themeClasses,this.createContainer(),this.measureReq={read:this.readMeasure.bind(this),write:this.writeMeasure.bind(this),key:this},this.resizeObserver=typeof ResizeObserver=="function"?new ResizeObserver(()=>this.measureSoon()):null,this.manager=new J0(n,vf,t=>this.createTooltip(t),t=>{this.resizeObserver&&this.resizeObserver.unobserve(t.dom),t.dom.remove()}),this.above=this.manager.tooltips.map(t=>!!t.above),this.intersectionObserver=typeof IntersectionObserver=="function"?new IntersectionObserver(t=>{Date.now()>this.lastTransaction-50&&t.length>0&&t[t.length-1].intersectionRatio<1&&this.measureSoon()},{threshold:[1]}):null,this.observeIntersection(),n.win.addEventListener("resize",this.measureSoon=this.measureSoon.bind(this)),this.maybeMeasure()}createContainer(){this.parent?(this.container=document.createElement("div"),this.container.style.position="relative",this.container.className=this.view.themeClasses,this.parent.appendChild(this.container)):this.container=this.view.dom}observeIntersection(){if(this.intersectionObserver){this.intersectionObserver.disconnect();for(let n of this.manager.tooltipViews)this.intersectionObserver.observe(n.dom)}}measureSoon(){this.measureTimeout<0&&(this.measureTimeout=setTimeout(()=>{this.measureTimeout=-1,this.maybeMeasure()},50))}update(n){n.transactions.length&&(this.lastTransaction=Date.now());let e=this.manager.update(n,this.above);e&&this.observeIntersection();let t=e||n.geometryChanged,i=n.state.facet(Uh);if(i.position!=this.position&&!this.madeAbsolute){this.position=i.position;for(let r of this.manager.tooltipViews)r.dom.style.position=this.position;t=!0}if(i.parent!=this.parent){this.parent&&this.container.remove(),this.parent=i.parent,this.createContainer();for(let r of this.manager.tooltipViews)this.container.appendChild(r.dom);t=!0}else this.parent&&this.view.themeClasses!=this.classes&&(this.classes=this.container.className=this.view.themeClasses);t&&this.maybeMeasure()}createTooltip(n){let e=n.create(this.view);if(e.dom.classList.add("cm-tooltip"),n.arrow&&!e.dom.querySelector(".cm-tooltip > .cm-tooltip-arrow")){let t=document.createElement("div");t.className="cm-tooltip-arrow",e.dom.appendChild(t)}return e.dom.style.position=this.position,e.dom.style.top=Bs,e.dom.style.left="0px",this.container.appendChild(e.dom),e.mount&&e.mount(this.view),this.resizeObserver&&this.resizeObserver.observe(e.dom),e}destroy(){var n,e,t;this.view.win.removeEventListener("resize",this.measureSoon);for(let i of this.manager.tooltipViews)i.dom.remove(),(n=i.destroy)===null||n===void 0||n.call(i);this.parent&&this.container.remove(),(e=this.resizeObserver)===null||e===void 0||e.disconnect(),(t=this.intersectionObserver)===null||t===void 0||t.disconnect(),clearTimeout(this.measureTimeout)}readMeasure(){let n=this.view.dom.getBoundingClientRect(),e=1,t=1,i=!1;if(this.position=="fixed"&&this.manager.tooltipViews.length){let{dom:r}=this.manager.tooltipViews[0];if(q.gecko)i=r.offsetParent!=this.container.ownerDocument.body;else if(r.style.top==Bs&&r.style.left=="0px"){let s=r.getBoundingClientRect();i=Math.abs(s.top+1e4)>1||Math.abs(s.left)>1}}if(i||this.position=="absolute")if(this.parent){let r=this.parent.getBoundingClientRect();r.width&&r.height&&(e=r.width/this.parent.offsetWidth,t=r.height/this.parent.offsetHeight)}else({scaleX:e,scaleY:t}=this.view.viewState);return{editor:n,parent:this.parent?this.container.getBoundingClientRect():n,pos:this.manager.tooltips.map((r,s)=>{let o=this.manager.tooltipViews[s];return o.getCoords?o.getCoords(r.pos):this.view.coordsAtPos(r.pos)}),size:this.manager.tooltipViews.map(({dom:r})=>r.getBoundingClientRect()),space:this.view.state.facet(Uh).tooltipSpace(this.view),scaleX:e,scaleY:t,makeAbsolute:i}}writeMeasure(n){var e;if(n.makeAbsolute){this.madeAbsolute=!0,this.position="absolute";for(let a of this.manager.tooltipViews)a.dom.style.position="absolute"}let{editor:t,space:i,scaleX:r,scaleY:s}=n,o=[];for(let a=0;a=Math.min(t.bottom,i.bottom)||u.rightMath.min(t.right,i.right)+.1){c.style.top=Bs;continue}let p=l.arrow?h.dom.querySelector(".cm-tooltip-arrow"):null,g=p?7:0,y=f.right-f.left,O=(e=Lp.get(h))!==null&&e!==void 0?e:f.bottom-f.top,S=h.offset||Hx,k=this.view.textDirection==ge.LTR,$=f.width>i.right-i.left?k?i.left:i.right-f.width:k?Math.min(u.left-(p?14:0)+S.x,i.right-y):Math.max(i.left,u.left-y+(p?14:0)-S.x),x=this.above[a];!l.strictSide&&(x?u.top-(f.bottom-f.top)-S.yi.bottom)&&x==i.bottom-u.bottom>u.top-i.top&&(x=this.above[a]=!x);let Q=(x?u.top-i.top:i.bottom-u.bottom)-g;if(Q$&&j.topA&&(A=x?j.top-O-2-g:j.bottom+g+2);if(this.position=="absolute"?(c.style.top=(A-n.parent.top)/s+"px",c.style.left=($-n.parent.left)/r+"px"):(c.style.top=A/s+"px",c.style.left=$/r+"px"),p){let j=u.left+(k?S.x:-S.x)-($+14-7);p.style.left=j/r+"px"}h.overlap!==!0&&o.push({left:$,top:A,right:R,bottom:A+O}),c.classList.toggle("cm-tooltip-above",x),c.classList.toggle("cm-tooltip-below",!x),h.positioned&&h.positioned(n.space)}}maybeMeasure(){if(this.manager.tooltips.length&&(this.view.inView&&this.view.requestMeasure(this.measureReq),this.inView!=this.view.inView&&(this.inView=this.view.inView,!this.inView)))for(let n of this.manager.tooltipViews)n.dom.style.top=Bs}},{eventObservers:{scroll(){this.maybeMeasure()}}}),Yx=N.baseTheme({".cm-tooltip":{zIndex:100,boxSizing:"border-box"},"&light .cm-tooltip":{border:"1px solid #bbb",backgroundColor:"#f5f5f5"},"&light .cm-tooltip-section:not(:first-child)":{borderTop:"1px solid #bbb"},"&dark .cm-tooltip":{backgroundColor:"#333338",color:"white"},".cm-tooltip-arrow":{height:"7px",width:`${7*2}px`,position:"absolute",zIndex:-1,overflow:"hidden","&:before, &:after":{content:"''",position:"absolute",width:0,height:0,borderLeft:"7px solid transparent",borderRight:"7px solid transparent"},".cm-tooltip-above &":{bottom:"-7px","&:before":{borderTop:"7px solid #bbb"},"&:after":{borderTop:"7px solid #f5f5f5",bottom:"1px"}},".cm-tooltip-below &":{top:"-7px","&:before":{borderBottom:"7px solid #bbb"},"&:after":{borderBottom:"7px solid #f5f5f5",top:"1px"}}},"&dark .cm-tooltip .cm-tooltip-arrow":{"&:before":{borderTopColor:"#333338",borderBottomColor:"#333338"},"&:after":{borderTopColor:"transparent",borderBottomColor:"transparent"}}}),Hx={x:0,y:0},vf=B.define({enables:[wf,Yx]}),Pl=B.define();class hh{static create(e){return new hh(e)}constructor(e){this.view=e,this.mounted=!1,this.dom=document.createElement("div"),this.dom.classList.add("cm-tooltip-hover"),this.manager=new J0(e,Pl,t=>this.createHostedView(t),t=>t.dom.remove())}createHostedView(e){let t=e.create(this.view);return t.dom.classList.add("cm-tooltip-section"),this.dom.appendChild(t.dom),this.mounted&&t.mount&&t.mount(this.view),t}mount(e){for(let t of this.manager.tooltipViews)t.mount&&t.mount(e);this.mounted=!0}positioned(e){for(let t of this.manager.tooltipViews)t.positioned&&t.positioned(e)}update(e){this.manager.update(e)}destroy(){var e;for(let t of this.manager.tooltipViews)(e=t.destroy)===null||e===void 0||e.call(t)}passProp(e){let t;for(let i of this.manager.tooltipViews){let r=i[e];if(r!==void 0){if(t===void 0)t=r;else if(t!==r)return}}return t}get offset(){return this.passProp("offset")}get getCoords(){return this.passProp("getCoords")}get overlap(){return this.passProp("overlap")}get resize(){return this.passProp("resize")}}const Kx=vf.compute([Pl],n=>{let e=n.facet(Pl).filter(t=>t);return e.length===0?null:{pos:Math.min(...e.map(t=>t.pos)),end:Math.max(...e.map(t=>{var i;return(i=t.end)!==null&&i!==void 0?i:t.pos})),create:hh.create,above:e[0].above,arrow:e.some(t=>t.arrow)}});class eT{constructor(e,t,i,r,s){this.view=e,this.source=t,this.field=i,this.setHover=r,this.hoverTime=s,this.hoverTimeout=-1,this.restartTimeout=-1,this.pending=null,this.lastMove={x:0,y:0,target:e.dom,time:0},this.checkHover=this.checkHover.bind(this),e.dom.addEventListener("mouseleave",this.mouseleave=this.mouseleave.bind(this)),e.dom.addEventListener("mousemove",this.mousemove=this.mousemove.bind(this))}update(){this.pending&&(this.pending=null,clearTimeout(this.restartTimeout),this.restartTimeout=setTimeout(()=>this.startHover(),20))}get active(){return this.view.state.field(this.field)}checkHover(){if(this.hoverTimeout=-1,this.active)return;let e=Date.now()-this.lastMove.time;ea.bottom||t.xa.right+e.defaultCharacterWidth)return;let l=e.bidiSpans(e.state.doc.lineAt(r)).find(c=>c.from<=r&&c.to>=r),h=l&&l.dir==ge.RTL?-1:1;s=t.x{this.pending==a&&(this.pending=null,l&&e.dispatch({effects:this.setHover.of(l)}))},l=>mt(e.state,l,"hover tooltip"))}else o&&e.dispatch({effects:this.setHover.of(o)})}get tooltip(){let e=this.view.plugin(wf),t=e?e.manager.tooltips.findIndex(i=>i.create==hh.create):-1;return t>-1?e.manager.tooltipViews[t]:null}mousemove(e){var t;this.lastMove={x:e.clientX,y:e.clientY,target:e.target,time:Date.now()},this.hoverTimeout<0&&(this.hoverTimeout=setTimeout(this.checkHover,this.hoverTime));let{active:i,tooltip:r}=this;if(i&&r&&!tT(r.dom,e)||this.pending){let{pos:s}=i||this.pending,o=(t=i==null?void 0:i.end)!==null&&t!==void 0?t:s;(s==o?this.view.posAtCoords(this.lastMove)!=s:!iT(this.view,s,o,e.clientX,e.clientY))&&(this.view.dispatch({effects:this.setHover.of(null)}),this.pending=null)}}mouseleave(e){clearTimeout(this.hoverTimeout),this.hoverTimeout=-1;let{active:t}=this;if(t){let{tooltip:i}=this;i&&i.dom.contains(e.relatedTarget)?this.watchTooltipLeave(i.dom):this.view.dispatch({effects:this.setHover.of(null)})}}watchTooltipLeave(e){let t=i=>{e.removeEventListener("mouseleave",t),this.active&&!this.view.dom.contains(i.relatedTarget)&&this.view.dispatch({effects:this.setHover.of(null)})};e.addEventListener("mouseleave",t)}destroy(){clearTimeout(this.hoverTimeout),this.view.dom.removeEventListener("mouseleave",this.mouseleave),this.view.dom.removeEventListener("mousemove",this.mousemove)}}const ma=4;function tT(n,e){let t=n.getBoundingClientRect();return e.clientX>=t.left-ma&&e.clientX<=t.right+ma&&e.clientY>=t.top-ma&&e.clientY<=t.bottom+ma}function iT(n,e,t,i,r,s){let o=n.scrollDOM.getBoundingClientRect(),a=n.documentTop+n.documentPadding.top+n.contentHeight;if(o.left>i||o.rightr||Math.min(o.bottom,a)=e&&l<=t}function nT(n,e={}){let t=z.define(),i=Re.define({create(){return null},update(r,s){if(r&&(e.hideOnChange&&(s.docChanged||s.selection)||e.hideOn&&e.hideOn(s,r)))return null;if(r&&s.docChanged){let o=s.changes.mapPos(r.pos,-1,qe.TrackDel);if(o==null)return null;let a=Object.assign(Object.create(null),r);a.pos=o,r.end!=null&&(a.end=s.changes.mapPos(r.end)),r=a}for(let o of s.effects)o.is(t)&&(r=o.value),o.is(sT)&&(r=null);return r},provide:r=>Pl.from(r)});return[i,ke.define(r=>new eT(r,n,i,t,e.hoverTime||300)),Kx]}function rT(n,e){let t=n.plugin(wf);if(!t)return null;let i=t.manager.tooltips.indexOf(e);return i<0?null:t.manager.tooltipViews[i]}const sT=z.define(),Up=B.define({combine(n){let e,t;for(let i of n)e=e||i.topContainer,t=t||i.bottomContainer;return{topContainer:e,bottomContainer:t}}});function Qo(n,e){let t=n.plugin(Y0),i=t?t.specs.indexOf(e):-1;return i>-1?t.panels[i]:null}const Y0=ke.fromClass(class{constructor(n){this.input=n.state.facet(Po),this.specs=this.input.filter(t=>t),this.panels=this.specs.map(t=>t(n));let e=n.state.facet(Up);this.top=new Oa(n,!0,e.topContainer),this.bottom=new Oa(n,!1,e.bottomContainer),this.top.sync(this.panels.filter(t=>t.top)),this.bottom.sync(this.panels.filter(t=>!t.top));for(let t of this.panels)t.dom.classList.add("cm-panel"),t.mount&&t.mount()}update(n){let e=n.state.facet(Up);this.top.container!=e.topContainer&&(this.top.sync([]),this.top=new Oa(n.view,!0,e.topContainer)),this.bottom.container!=e.bottomContainer&&(this.bottom.sync([]),this.bottom=new Oa(n.view,!1,e.bottomContainer)),this.top.syncClasses(),this.bottom.syncClasses();let t=n.state.facet(Po);if(t!=this.input){let i=t.filter(l=>l),r=[],s=[],o=[],a=[];for(let l of i){let h=this.specs.indexOf(l),c;h<0?(c=l(n.view),a.push(c)):(c=this.panels[h],c.update&&c.update(n)),r.push(c),(c.top?s:o).push(c)}this.specs=i,this.panels=r,this.top.sync(s),this.bottom.sync(o);for(let l of a)l.dom.classList.add("cm-panel"),l.mount&&l.mount()}else for(let i of this.panels)i.update&&i.update(n)}destroy(){this.top.sync([]),this.bottom.sync([])}},{provide:n=>N.scrollMargins.of(e=>{let t=e.plugin(n);return t&&{top:t.top.scrollMargin(),bottom:t.bottom.scrollMargin()}})});class Oa{constructor(e,t,i){this.view=e,this.top=t,this.container=i,this.dom=void 0,this.classes="",this.panels=[],this.syncClasses()}sync(e){for(let t of this.panels)t.destroy&&e.indexOf(t)<0&&t.destroy();this.panels=e,this.syncDOM()}syncDOM(){if(this.panels.length==0){this.dom&&(this.dom.remove(),this.dom=void 0);return}if(!this.dom){this.dom=document.createElement("div"),this.dom.className=this.top?"cm-panels cm-panels-top":"cm-panels cm-panels-bottom",this.dom.style[this.top?"top":"bottom"]="0";let t=this.container||this.view.dom;t.insertBefore(this.dom,this.top?t.firstChild:null)}let e=this.dom.firstChild;for(let t of this.panels)if(t.dom.parentNode==this.dom){for(;e!=t.dom;)e=Zp(e);e=e.nextSibling}else this.dom.insertBefore(t.dom,e);for(;e;)e=Zp(e)}scrollMargin(){return!this.dom||this.container?0:Math.max(0,this.top?this.dom.getBoundingClientRect().bottom-Math.max(0,this.view.scrollDOM.getBoundingClientRect().top):Math.min(innerHeight,this.view.scrollDOM.getBoundingClientRect().bottom)-this.dom.getBoundingClientRect().top)}syncClasses(){if(!(!this.container||this.classes==this.view.themeClasses)){for(let e of this.classes.split(" "))e&&this.container.classList.remove(e);for(let e of(this.classes=this.view.themeClasses).split(" "))e&&this.container.classList.add(e)}}}function Zp(n){let e=n.nextSibling;return n.remove(),e}const Po=B.define({enables:Y0});class Zn extends Br{compare(e){return this==e||this.constructor==e.constructor&&this.eq(e)}eq(e){return!1}destroy(e){}}Zn.prototype.elementClass="";Zn.prototype.toDOM=void 0;Zn.prototype.mapMode=qe.TrackBefore;Zn.prototype.startSide=Zn.prototype.endSide=-1;Zn.prototype.point=!0;const Fa=B.define(),oT={class:"",renderEmptyElements:!1,elementStyle:"",markers:()=>J.empty,lineMarker:()=>null,widgetMarker:()=>null,lineMarkerChange:null,initialSpacer:null,updateSpacer:null,domEventHandlers:{}},ro=B.define();function aT(n){return[H0(),ro.of(Object.assign(Object.assign({},oT),n))]}const Wp=B.define({combine:n=>n.some(e=>e)});function H0(n){return[lT]}const lT=ke.fromClass(class{constructor(n){this.view=n,this.prevViewport=n.viewport,this.dom=document.createElement("div"),this.dom.className="cm-gutters",this.dom.setAttribute("aria-hidden","true"),this.dom.style.minHeight=this.view.contentHeight/this.view.scaleY+"px",this.gutters=n.state.facet(ro).map(e=>new Fp(n,e));for(let e of this.gutters)this.dom.appendChild(e.dom);this.fixed=!n.state.facet(Wp),this.fixed&&(this.dom.style.position="sticky"),this.syncGutters(!1),n.scrollDOM.insertBefore(this.dom,n.contentDOM)}update(n){if(this.updateGutters(n)){let e=this.prevViewport,t=n.view.viewport,i=Math.min(e.to,t.to)-Math.max(e.from,t.from);this.syncGutters(i<(t.to-t.from)*.8)}n.geometryChanged&&(this.dom.style.minHeight=this.view.contentHeight+"px"),this.view.state.facet(Wp)!=!this.fixed&&(this.fixed=!this.fixed,this.dom.style.position=this.fixed?"sticky":""),this.prevViewport=n.view.viewport}syncGutters(n){let e=this.dom.nextSibling;n&&this.dom.remove();let t=J.iter(this.view.state.facet(Fa),this.view.viewport.from),i=[],r=this.gutters.map(s=>new hT(s,this.view.viewport,-this.view.documentPadding.top));for(let s of this.view.viewportLineBlocks)if(i.length&&(i=[]),Array.isArray(s.type)){let o=!0;for(let a of s.type)if(a.type==Je.Text&&o){vu(t,i,a.from);for(let l of r)l.line(this.view,a,i);o=!1}else if(a.widget)for(let l of r)l.widget(this.view,a)}else if(s.type==Je.Text){vu(t,i,s.from);for(let o of r)o.line(this.view,s,i)}else if(s.widget)for(let o of r)o.widget(this.view,s);for(let s of r)s.finish();n&&this.view.scrollDOM.insertBefore(this.dom,e)}updateGutters(n){let e=n.startState.facet(ro),t=n.state.facet(ro),i=n.docChanged||n.heightChanged||n.viewportChanged||!J.eq(n.startState.facet(Fa),n.state.facet(Fa),n.view.viewport.from,n.view.viewport.to);if(e==t)for(let r of this.gutters)r.update(n)&&(i=!0);else{i=!0;let r=[];for(let s of t){let o=e.indexOf(s);o<0?r.push(new Fp(this.view,s)):(this.gutters[o].update(n),r.push(this.gutters[o]))}for(let s of this.gutters)s.dom.remove(),r.indexOf(s)<0&&s.destroy();for(let s of r)this.dom.appendChild(s.dom);this.gutters=r}return i}destroy(){for(let n of this.gutters)n.destroy();this.dom.remove()}},{provide:n=>N.scrollMargins.of(e=>{let t=e.plugin(n);return!t||t.gutters.length==0||!t.fixed?null:e.textDirection==ge.LTR?{left:t.dom.offsetWidth*e.scaleX}:{right:t.dom.offsetWidth*e.scaleX}})});function jp(n){return Array.isArray(n)?n:[n]}function vu(n,e,t){for(;n.value&&n.from<=t;)n.from==t&&e.push(n.value),n.next()}class hT{constructor(e,t,i){this.gutter=e,this.height=i,this.i=0,this.cursor=J.iter(e.markers,t.from)}addElement(e,t,i){let{gutter:r}=this,s=(t.top-this.height)/e.scaleY,o=t.height/e.scaleY;if(this.i==r.elements.length){let a=new K0(e,o,s,i);r.elements.push(a),r.dom.appendChild(a.dom)}else r.elements[this.i].update(e,o,s,i);this.height=t.bottom,this.i++}line(e,t,i){let r=[];vu(this.cursor,r,t.from),i.length&&(r=r.concat(i));let s=this.gutter.config.lineMarker(e,t,r);s&&r.unshift(s);let o=this.gutter;r.length==0&&!o.config.renderEmptyElements||this.addElement(e,t,r)}widget(e,t){let i=this.gutter.config.widgetMarker(e,t.widget,t);i&&this.addElement(e,t,[i])}finish(){let e=this.gutter;for(;e.elements.length>this.i;){let t=e.elements.pop();e.dom.removeChild(t.dom),t.destroy()}}}class Fp{constructor(e,t){this.view=e,this.config=t,this.elements=[],this.spacer=null,this.dom=document.createElement("div"),this.dom.className="cm-gutter"+(this.config.class?" "+this.config.class:"");for(let i in t.domEventHandlers)this.dom.addEventListener(i,r=>{let s=r.target,o;if(s!=this.dom&&this.dom.contains(s)){for(;s.parentNode!=this.dom;)s=s.parentNode;let l=s.getBoundingClientRect();o=(l.top+l.bottom)/2}else o=r.clientY;let a=e.lineBlockAtHeight(o-e.documentTop);t.domEventHandlers[i](e,a,r)&&r.preventDefault()});this.markers=jp(t.markers(e)),t.initialSpacer&&(this.spacer=new K0(e,0,0,[t.initialSpacer(e)]),this.dom.appendChild(this.spacer.dom),this.spacer.dom.style.cssText+="visibility: hidden; pointer-events: none")}update(e){let t=this.markers;if(this.markers=jp(this.config.markers(e.view)),this.spacer&&this.config.updateSpacer){let r=this.config.updateSpacer(this.spacer.markers[0],e);r!=this.spacer.markers[0]&&this.spacer.update(e.view,0,0,[r])}let i=e.view.viewport;return!J.eq(this.markers,t,i.from,i.to)||(this.config.lineMarkerChange?this.config.lineMarkerChange(e):!1)}destroy(){for(let e of this.elements)e.destroy()}}class K0{constructor(e,t,i,r){this.height=-1,this.above=0,this.markers=[],this.dom=document.createElement("div"),this.dom.className="cm-gutterElement",this.update(e,t,i,r)}update(e,t,i,r){this.height!=t&&(this.height=t,this.dom.style.height=t+"px"),this.above!=i&&(this.dom.style.marginTop=(this.above=i)?i+"px":""),cT(this.markers,r)||this.setMarkers(e,r)}setMarkers(e,t){let i="cm-gutterElement",r=this.dom.firstChild;for(let s=0,o=0;;){let a=o,l=ss(a,l,h)||o(a,l,h):o}return i}})}});class Zh extends Zn{constructor(e){super(),this.number=e}eq(e){return this.number==e.number}toDOM(){return document.createTextNode(this.number)}}function Wh(n,e){return n.state.facet(Yr).formatNumber(e,n.state)}const fT=ro.compute([Yr],n=>({class:"cm-lineNumbers",renderEmptyElements:!1,markers(e){return e.state.facet(uT)},lineMarker(e,t,i){return i.some(r=>r.toDOM)?null:new Zh(Wh(e,e.state.doc.lineAt(t.from).number))},widgetMarker:()=>null,lineMarkerChange:e=>e.startState.facet(Yr)!=e.state.facet(Yr),initialSpacer(e){return new Zh(Wh(e,zp(e.state.doc.lines)))},updateSpacer(e,t){let i=Wh(t.view,zp(t.view.state.doc.lines));return i==e.number?e:new Zh(i)},domEventHandlers:n.facet(Yr).domEventHandlers}));function dT(n={}){return[Yr.of(n),H0(),fT]}function zp(n){let e=9;for(;e{let e=[],t=-1;for(let i of n.selection.ranges){let r=n.doc.lineAt(i.head).from;r>t&&(t=r,e.push(pT.range(r)))}return J.of(e)});function mT(){return gT}const ey=1024;let OT=0;class Rt{constructor(e,t){this.from=e,this.to=t}}class _{constructor(e={}){this.id=OT++,this.perNode=!!e.perNode,this.deserialize=e.deserialize||(()=>{throw new Error("This node type doesn't define a deserialize function")})}add(e){if(this.perNode)throw new RangeError("Can't add per-node props to node types");return typeof e!="function"&&(e=Ie.match(e)),t=>{let i=e(t);return i===void 0?null:[this,i]}}}_.closedBy=new _({deserialize:n=>n.split(" ")});_.openedBy=new _({deserialize:n=>n.split(" ")});_.group=new _({deserialize:n=>n.split(" ")});_.contextHash=new _({perNode:!0});_.lookAhead=new _({perNode:!0});_.mounted=new _({perNode:!0});class yT{constructor(e,t,i){this.tree=e,this.overlay=t,this.parser=i}}const bT=Object.create(null);class Ie{constructor(e,t,i,r=0){this.name=e,this.props=t,this.id=i,this.flags=r}static define(e){let t=e.props&&e.props.length?Object.create(null):bT,i=(e.top?1:0)|(e.skipped?2:0)|(e.error?4:0)|(e.name==null?8:0),r=new Ie(e.name||"",t,e.id,i);if(e.props){for(let s of e.props)if(Array.isArray(s)||(s=s(r)),s){if(s[0].perNode)throw new RangeError("Can't store a per-node prop on a node type");t[s[0].id]=s[1]}}return r}prop(e){return this.props[e.id]}get isTop(){return(this.flags&1)>0}get isSkipped(){return(this.flags&2)>0}get isError(){return(this.flags&4)>0}get isAnonymous(){return(this.flags&8)>0}is(e){if(typeof e=="string"){if(this.name==e)return!0;let t=this.prop(_.group);return t?t.indexOf(e)>-1:!1}return this.id==e}static match(e){let t=Object.create(null);for(let i in e)for(let r of i.split(" "))t[r]=e[i];return i=>{for(let r=i.prop(_.group),s=-1;s<(r?r.length:0);s++){let o=t[s<0?i.name:r[s]];if(o)return o}}}}Ie.none=new Ie("",Object.create(null),0,8);class Fo{constructor(e){this.types=e;for(let t=0;t=r&&(o.type.isAnonymous||t(o)!==!1)){if(o.firstChild())continue;a=!0}for(;a&&i&&!o.type.isAnonymous&&i(o),!o.nextSibling();){if(!o.parent())return;a=!0}}}prop(e){return e.perNode?this.props?this.props[e.id]:void 0:this.type.prop(e)}get propValues(){let e=[];if(this.props)for(let t in this.props)e.push([+t,this.props[t]]);return e}balance(e={}){return this.children.length<=8?this:Tf(Ie.none,this.children,this.positions,0,this.children.length,0,this.length,(t,i,r)=>new ne(this.type,t,i,r,this.propValues),e.makeTree||((t,i,r)=>new ne(Ie.none,t,i,r)))}static build(e){return wT(e)}}ne.empty=new ne(Ie.none,[],[],0);class kf{constructor(e,t){this.buffer=e,this.index=t}get id(){return this.buffer[this.index-4]}get start(){return this.buffer[this.index-3]}get end(){return this.buffer[this.index-2]}get size(){return this.buffer[this.index-1]}get pos(){return this.index}next(){this.index-=4}fork(){return new kf(this.buffer,this.index)}}class Lr{constructor(e,t,i){this.buffer=e,this.length=t,this.set=i}get type(){return Ie.none}toString(){let e=[];for(let t=0;t0));l=o[l+3]);return a}slice(e,t,i){let r=this.buffer,s=new Uint16Array(t-e),o=0;for(let a=e,l=0;a=e&&te;case 1:return t<=e&&i>e;case 2:return i>e;case 4:return!0}}function iy(n,e){let t=n.childBefore(e);for(;t;){let i=t.lastChild;if(!i||i.to!=t.to)break;i.type.isError&&i.from==i.to?(n=t,t=i.prevSibling):t=i}return n}function bs(n,e,t,i){for(var r;n.from==n.to||(t<1?n.from>=e:n.from>e)||(t>-1?n.to<=e:n.to0?a.length:-1;e!=h;e+=t){let c=a[e],u=l[e]+o.from;if(ty(r,i,u,u+c.length)){if(c instanceof Lr){if(s&ce.ExcludeBuffers)continue;let f=c.findChild(0,c.buffer.length,t,i-u,r);if(f>-1)return new vi(new ST(o,c,e,u),null,f)}else if(s&ce.IncludeAnonymous||!c.type.isAnonymous||xf(c)){let f;if(!(s&ce.IgnoreMounts)&&c.props&&(f=c.prop(_.mounted))&&!f.overlay)return new Bt(f.tree,u,e,o);let p=new Bt(c,u,e,o);return s&ce.IncludeAnonymous||!p.type.isAnonymous?p:p.nextChild(t<0?c.children.length-1:0,t,i,r)}}}if(s&ce.IncludeAnonymous||!o.type.isAnonymous||(o.index>=0?e=o.index+t:e=t<0?-1:o._parent._tree.children.length,o=o._parent,!o))return null}}get firstChild(){return this.nextChild(0,1,0,4)}get lastChild(){return this.nextChild(this._tree.children.length-1,-1,0,4)}childAfter(e){return this.nextChild(0,1,e,2)}childBefore(e){return this.nextChild(this._tree.children.length-1,-1,e,-2)}enter(e,t,i=0){let r;if(!(i&ce.IgnoreOverlays)&&(r=this._tree.prop(_.mounted))&&r.overlay){let s=e-this.from;for(let{from:o,to:a}of r.overlay)if((t>0?o<=s:o=s:a>s))return new Bt(r.tree,r.overlay[0].from+this.from,-1,this)}return this.nextChild(0,1,e,t,i)}nextSignificantParent(){let e=this;for(;e.type.isAnonymous&&e._parent;)e=e._parent;return e}get parent(){return this._parent?this._parent.nextSignificantParent():null}get nextSibling(){return this._parent&&this.index>=0?this._parent.nextChild(this.index+1,1,0,4):null}get prevSibling(){return this._parent&&this.index>=0?this._parent.nextChild(this.index-1,-1,0,4):null}cursor(e=0){return new Ao(this,e)}get tree(){return this._tree}toTree(){return this._tree}resolve(e,t=0){return bs(this,e,t,!1)}resolveInner(e,t=0){return bs(this,e,t,!0)}enterUnfinishedNodesBefore(e){return iy(this,e)}getChild(e,t=null,i=null){let r=Al(this,e,t,i);return r.length?r[0]:null}getChildren(e,t=null,i=null){return Al(this,e,t,i)}toString(){return this._tree.toString()}get node(){return this}matchContext(e){return $l(this,e)}}function Al(n,e,t,i){let r=n.cursor(),s=[];if(!r.firstChild())return s;if(t!=null){for(;!r.type.is(t);)if(!r.nextSibling())return s}for(;;){if(i!=null&&r.type.is(i))return s;if(r.type.is(e)&&s.push(r.node),!r.nextSibling())return i==null?s:[]}}function $l(n,e,t=e.length-1){for(let i=n.parent;t>=0;i=i.parent){if(!i)return!1;if(!i.type.isAnonymous){if(e[t]&&e[t]!=i.name)return!1;t--}}return!0}class ST{constructor(e,t,i,r){this.parent=e,this.buffer=t,this.index=i,this.start=r}}class vi{get name(){return this.type.name}get from(){return this.context.start+this.context.buffer.buffer[this.index+1]}get to(){return this.context.start+this.context.buffer.buffer[this.index+2]}constructor(e,t,i){this.context=e,this._parent=t,this.index=i,this.type=e.buffer.set.types[e.buffer.buffer[i]]}child(e,t,i){let{buffer:r}=this.context,s=r.findChild(this.index+4,r.buffer[this.index+3],e,t-this.context.start,i);return s<0?null:new vi(this.context,this,s)}get firstChild(){return this.child(1,0,4)}get lastChild(){return this.child(-1,0,4)}childAfter(e){return this.child(1,e,2)}childBefore(e){return this.child(-1,e,-2)}enter(e,t,i=0){if(i&ce.ExcludeBuffers)return null;let{buffer:r}=this.context,s=r.findChild(this.index+4,r.buffer[this.index+3],t>0?1:-1,e-this.context.start,t);return s<0?null:new vi(this.context,this,s)}get parent(){return this._parent||this.context.parent.nextSignificantParent()}externalSibling(e){return this._parent?null:this.context.parent.nextChild(this.context.index+e,e,0,4)}get nextSibling(){let{buffer:e}=this.context,t=e.buffer[this.index+3];return t<(this._parent?e.buffer[this._parent.index+3]:e.buffer.length)?new vi(this.context,this._parent,t):this.externalSibling(1)}get prevSibling(){let{buffer:e}=this.context,t=this._parent?this._parent.index+4:0;return this.index==t?this.externalSibling(-1):new vi(this.context,this._parent,e.findChild(t,this.index,-1,0,4))}cursor(e=0){return new Ao(this,e)}get tree(){return null}toTree(){let e=[],t=[],{buffer:i}=this.context,r=this.index+4,s=i.buffer[this.index+3];if(s>r){let o=i.buffer[this.index+1];e.push(i.slice(r,s,o)),t.push(0)}return new ne(this.type,e,t,this.to-this.from)}resolve(e,t=0){return bs(this,e,t,!1)}resolveInner(e,t=0){return bs(this,e,t,!0)}enterUnfinishedNodesBefore(e){return iy(this,e)}toString(){return this.context.buffer.childString(this.index)}getChild(e,t=null,i=null){let r=Al(this,e,t,i);return r.length?r[0]:null}getChildren(e,t=null,i=null){return Al(this,e,t,i)}get node(){return this}matchContext(e){return $l(this,e)}}class Ao{get name(){return this.type.name}constructor(e,t=0){if(this.mode=t,this.buffer=null,this.stack=[],this.index=0,this.bufferNode=null,e instanceof Bt)this.yieldNode(e);else{this._tree=e.context.parent,this.buffer=e.context;for(let i=e._parent;i;i=i._parent)this.stack.unshift(i.index);this.bufferNode=e,this.yieldBuf(e.index)}}yieldNode(e){return e?(this._tree=e,this.type=e.type,this.from=e.from,this.to=e.to,!0):!1}yieldBuf(e,t){this.index=e;let{start:i,buffer:r}=this.buffer;return this.type=t||r.set.types[r.buffer[e]],this.from=i+r.buffer[e+1],this.to=i+r.buffer[e+2],!0}yield(e){return e?e instanceof Bt?(this.buffer=null,this.yieldNode(e)):(this.buffer=e.context,this.yieldBuf(e.index,e.type)):!1}toString(){return this.buffer?this.buffer.buffer.childString(this.index):this._tree.toString()}enterChild(e,t,i){if(!this.buffer)return this.yield(this._tree.nextChild(e<0?this._tree._tree.children.length-1:0,e,t,i,this.mode));let{buffer:r}=this.buffer,s=r.findChild(this.index+4,r.buffer[this.index+3],e,t-this.buffer.start,i);return s<0?!1:(this.stack.push(this.index),this.yieldBuf(s))}firstChild(){return this.enterChild(1,0,4)}lastChild(){return this.enterChild(-1,0,4)}childAfter(e){return this.enterChild(1,e,2)}childBefore(e){return this.enterChild(-1,e,-2)}enter(e,t,i=this.mode){return this.buffer?i&ce.ExcludeBuffers?!1:this.enterChild(1,e,t):this.yield(this._tree.enter(e,t,i))}parent(){if(!this.buffer)return this.yieldNode(this.mode&ce.IncludeAnonymous?this._tree._parent:this._tree.parent);if(this.stack.length)return this.yieldBuf(this.stack.pop());let e=this.mode&ce.IncludeAnonymous?this.buffer.parent:this.buffer.parent.nextSignificantParent();return this.buffer=null,this.yieldNode(e)}sibling(e){if(!this.buffer)return this._tree._parent?this.yield(this._tree.index<0?null:this._tree._parent.nextChild(this._tree.index+e,e,0,4,this.mode)):!1;let{buffer:t}=this.buffer,i=this.stack.length-1;if(e<0){let r=i<0?0:this.stack[i]+4;if(this.index!=r)return this.yieldBuf(t.findChild(r,this.index,-1,0,4))}else{let r=t.buffer[this.index+3];if(r<(i<0?t.buffer.length:t.buffer[this.stack[i]+3]))return this.yieldBuf(r)}return i<0?this.yield(this.buffer.parent.nextChild(this.buffer.index+e,e,0,4,this.mode)):!1}nextSibling(){return this.sibling(1)}prevSibling(){return this.sibling(-1)}atLastNode(e){let t,i,{buffer:r}=this;if(r){if(e>0){if(this.index-1)for(let s=t+e,o=e<0?-1:i._tree.children.length;s!=o;s+=e){let a=i._tree.children[s];if(this.mode&ce.IncludeAnonymous||a instanceof Lr||!a.type.isAnonymous||xf(a))return!1}return!0}move(e,t){if(t&&this.enterChild(e,0,4))return!0;for(;;){if(this.sibling(e))return!0;if(this.atLastNode(e)||!this.parent())return!1}}next(e=!0){return this.move(1,e)}prev(e=!0){return this.move(-1,e)}moveTo(e,t=0){for(;(this.from==this.to||(t<1?this.from>=e:this.from>e)||(t>-1?this.to<=e:this.to=0;){for(let o=e;o;o=o._parent)if(o.index==r){if(r==this.index)return o;t=o,i=s+1;break e}r=this.stack[--s]}for(let r=i;r=0;s--){if(s<0)return $l(this.node,e,r);let o=i[t.buffer[this.stack[s]]];if(!o.isAnonymous){if(e[r]&&e[r]!=o.name)return!1;r--}}return!0}}function xf(n){return n.children.some(e=>e instanceof Lr||!e.type.isAnonymous||xf(e))}function wT(n){var e;let{buffer:t,nodeSet:i,maxBufferLength:r=ey,reused:s=[],minRepeatType:o=i.types.length}=n,a=Array.isArray(t)?new kf(t,t.length):t,l=i.types,h=0,c=0;function u(x,Q,A,R,j){let{id:W,start:G,end:re,size:Qe}=a,Ve=c;for(;Qe<0;)if(a.next(),Qe==-1){let Ke=s[W];A.push(Ke),R.push(G-x);return}else if(Qe==-3){h=W;return}else if(Qe==-4){c=W;return}else throw new RangeError(`Unrecognized record size: ${Qe}`);let He=l[W],Ee,Xe,ni=G-x;if(re-G<=r&&(Xe=y(a.pos-Q,j))){let Ke=new Uint16Array(Xe.size-Xe.skip),be=a.pos-Xe.size,Pe=Ke.length;for(;a.pos>be;)Pe=O(Xe.start,Ke,Pe);Ee=new Lr(Ke,re-Xe.start,i),ni=Xe.start-x}else{let Ke=a.pos-Qe;a.next();let be=[],Pe=[],br=W>=o?W:-1,Ur=0,Ho=re;for(;a.pos>Ke;)br>=0&&a.id==br&&a.size>=0?(a.end<=Ho-r&&(p(be,Pe,G,Ur,a.end,Ho,br,Ve),Ur=be.length,Ho=a.end),a.next()):u(G,Ke,be,Pe,br);if(br>=0&&Ur>0&&Ur-1&&Ur>0){let Hf=f(He);Ee=Tf(He,be,Pe,0,be.length,0,re-G,Hf,Hf)}else Ee=g(He,be,Pe,re-G,Ve-re)}A.push(Ee),R.push(ni)}function f(x){return(Q,A,R)=>{let j=0,W=Q.length-1,G,re;if(W>=0&&(G=Q[W])instanceof ne){if(!W&&G.type==x&&G.length==R)return G;(re=G.prop(_.lookAhead))&&(j=A[W]+G.length+re)}return g(x,Q,A,R,j)}}function p(x,Q,A,R,j,W,G,re){let Qe=[],Ve=[];for(;x.length>R;)Qe.push(x.pop()),Ve.push(Q.pop()+A-j);x.push(g(i.types[G],Qe,Ve,W-j,re-W)),Q.push(j-A)}function g(x,Q,A,R,j=0,W){if(h){let G=[_.contextHash,h];W=W?[G].concat(W):[G]}if(j>25){let G=[_.lookAhead,j];W=W?[G].concat(W):[G]}return new ne(x,Q,A,R,W)}function y(x,Q){let A=a.fork(),R=0,j=0,W=0,G=A.end-r,re={size:0,start:0,skip:0};e:for(let Qe=A.pos-x;A.pos>Qe;){let Ve=A.size;if(A.id==Q&&Ve>=0){re.size=R,re.start=j,re.skip=W,W+=4,R+=4,A.next();continue}let He=A.pos-Ve;if(Ve<0||He=o?4:0,Xe=A.start;for(A.next();A.pos>He;){if(A.size<0)if(A.size==-3)Ee+=4;else break e;else A.id>=o&&(Ee+=4);A.next()}j=Xe,R+=Ve,W+=Ee}return(Q<0||R==x)&&(re.size=R,re.start=j,re.skip=W),re.size>4?re:void 0}function O(x,Q,A){let{id:R,start:j,end:W,size:G}=a;if(a.next(),G>=0&&R4){let Qe=a.pos-(G-4);for(;a.pos>Qe;)A=O(x,Q,A)}Q[--A]=re,Q[--A]=W-x,Q[--A]=j-x,Q[--A]=R}else G==-3?h=R:G==-4&&(c=R);return A}let S=[],k=[];for(;a.pos>0;)u(n.start||0,n.bufferStart||0,S,k,-1);let $=(e=n.length)!==null&&e!==void 0?e:S.length?k[0]+S[0].length:0;return new ne(l[n.topID],S.reverse(),k.reverse(),$)}const Gp=new WeakMap;function za(n,e){if(!n.isAnonymous||e instanceof Lr||e.type!=n)return 1;let t=Gp.get(e);if(t==null){t=1;for(let i of e.children){if(i.type!=n||!(i instanceof ne)){t=1;break}t+=za(n,i)}Gp.set(e,t)}return t}function Tf(n,e,t,i,r,s,o,a,l){let h=0;for(let g=i;g=c)break;A+=R}if($==x+1){if(A>c){let R=g[x];p(R.children,R.positions,0,R.children.length,y[x]+k);continue}u.push(g[x])}else{let R=y[$-1]+g[$-1].length-Q;u.push(Tf(n,g,y,x,$,Q,R,null,l))}f.push(Q+k-s)}}return p(e,t,i,r,0),(a||l)(u,f,o)}class vT{constructor(){this.map=new WeakMap}setBuffer(e,t,i){let r=this.map.get(e);r||this.map.set(e,r=new Map),r.set(t,i)}getBuffer(e,t){let i=this.map.get(e);return i&&i.get(t)}set(e,t){e instanceof vi?this.setBuffer(e.context.buffer,e.index,t):e instanceof Bt&&this.map.set(e.tree,t)}get(e){return e instanceof vi?this.getBuffer(e.context.buffer,e.index):e instanceof Bt?this.map.get(e.tree):void 0}cursorSet(e,t){e.buffer?this.setBuffer(e.buffer.buffer,e.index,t):this.map.set(e.tree,t)}cursorGet(e){return e.buffer?this.getBuffer(e.buffer.buffer,e.index):this.map.get(e.tree)}}class Bn{constructor(e,t,i,r,s=!1,o=!1){this.from=e,this.to=t,this.tree=i,this.offset=r,this.open=(s?1:0)|(o?2:0)}get openStart(){return(this.open&1)>0}get openEnd(){return(this.open&2)>0}static addTree(e,t=[],i=!1){let r=[new Bn(0,e.length,e,0,!1,i)];for(let s of t)s.to>e.length&&r.push(s);return r}static applyChanges(e,t,i=128){if(!t.length)return e;let r=[],s=1,o=e.length?e[0]:null;for(let a=0,l=0,h=0;;a++){let c=a=i)for(;o&&o.from=f.from||u<=f.to||h){let p=Math.max(f.from,l)-h,g=Math.min(f.to,u)-h;f=p>=g?null:new Bn(p,g,f.tree,f.offset+h,a>0,!!c)}if(f&&r.push(f),o.to>u)break;o=snew Rt(r.from,r.to)):[new Rt(0,0)]:[new Rt(0,e.length)],this.createParse(e,t||[],i)}parse(e,t,i){let r=this.startParse(e,t,i);for(;;){let s=r.advance();if(s)return s}}}class kT{constructor(e){this.string=e}get length(){return this.string.length}chunk(e){return this.string.slice(e)}get lineChunks(){return!1}read(e,t){return this.string.slice(e,t)}}function ny(n){return(e,t,i,r)=>new TT(e,n,t,i,r)}class Jp{constructor(e,t,i,r,s){this.parser=e,this.parse=t,this.overlay=i,this.target=r,this.ranges=s}}class xT{constructor(e,t,i,r,s,o,a){this.parser=e,this.predicate=t,this.mounts=i,this.index=r,this.start=s,this.target=o,this.prev=a,this.depth=0,this.ranges=[]}}const ku=new _({perNode:!0});class TT{constructor(e,t,i,r,s){this.nest=t,this.input=i,this.fragments=r,this.ranges=s,this.inner=[],this.innerDone=0,this.baseTree=null,this.stoppedAt=null,this.baseParse=e}advance(){if(this.baseParse){let i=this.baseParse.advance();if(!i)return null;if(this.baseParse=null,this.baseTree=i,this.startInner(),this.stoppedAt!=null)for(let r of this.inner)r.parse.stopAt(this.stoppedAt)}if(this.innerDone==this.inner.length){let i=this.baseTree;return this.stoppedAt!=null&&(i=new ne(i.type,i.children,i.positions,i.length,i.propValues.concat([[ku,this.stoppedAt]]))),i}let e=this.inner[this.innerDone],t=e.parse.advance();if(t){this.innerDone++;let i=Object.assign(Object.create(null),e.target.props);i[_.mounted.id]=new yT(t,e.overlay,e.parser),e.target.props=i}return null}get parsedPos(){if(this.baseParse)return 0;let e=this.input.length;for(let t=this.innerDone;tc.frag.from<=r.from&&c.frag.to>=r.to&&c.mount.overlay);if(h)for(let c of h.mount.overlay){let u=c.from+h.pos,f=c.to+h.pos;u>=r.from&&f<=r.to&&!t.ranges.some(p=>p.fromu)&&t.ranges.push({from:u,to:f})}}a=!1}else if(i&&(o=QT(i.ranges,r.from,r.to)))a=o!=2;else if(!r.type.isAnonymous&&r.fromnew Rt(u.from-r.from,u.to-r.from)):null,r.tree,c)),s.overlay?c.length&&(i={ranges:c,depth:0,prev:i}):a=!1}}else t&&(l=t.predicate(r))&&(l===!0&&(l=new Rt(r.from,r.to)),l.fromnew Rt(c.from-t.start,c.to-t.start)),t.target,h)),t=t.prev}i&&!--i.depth&&(i=i.prev)}}}}function QT(n,e,t){for(let i of n){if(i.from>=t)break;if(i.to>e)return i.from<=e&&i.to>=t?2:1}return 0}function Yp(n,e,t,i,r,s){if(e=e.to);i++);let o=r.children[i],a=o.buffer;function l(h,c,u,f,p){let g=h;for(;a[g+2]+s<=e.from;)g=a[g+3];let y=[],O=[];Yp(o,h,g,y,O,f);let S=a[g+1],k=a[g+2],$=S+s==e.from&&k+s==e.to&&a[g]==e.type.id;return y.push($?e.toTree():l(g+4,a[g+3],o.set.types[a[g]],S,k-S)),O.push(S-f),Yp(o,a[g+3],c,y,O,f),new ne(u,y,O,p)}r.children[i]=l(0,a.length,Ie.none,0,o.length);for(let h=0;h<=t;h++)n.childAfter(e.from)}class Hp{constructor(e,t){this.offset=t,this.done=!1,this.cursor=e.cursor(ce.IncludeAnonymous|ce.IgnoreMounts)}moveTo(e){let{cursor:t}=this,i=e-this.offset;for(;!this.done&&t.from=e&&t.enter(i,1,ce.IgnoreOverlays|ce.ExcludeBuffers)||t.next(!1)||(this.done=!0)}hasNode(e){if(this.moveTo(e.from),!this.done&&this.cursor.from+this.offset==e.from&&this.cursor.tree)for(let t=this.cursor.tree;;){if(t==e.tree)return!0;if(t.children.length&&t.positions[0]==0&&t.children[0]instanceof ne)t=t.children[0];else break}return!1}}let AT=class{constructor(e){var t;if(this.fragments=e,this.curTo=0,this.fragI=0,e.length){let i=this.curFrag=e[0];this.curTo=(t=i.tree.prop(ku))!==null&&t!==void 0?t:i.to,this.inner=new Hp(i.tree,-i.offset)}else this.curFrag=this.inner=null}hasNode(e){for(;this.curFrag&&e.from>=this.curTo;)this.nextFrag();return this.curFrag&&this.curFrag.from<=e.from&&this.curTo>=e.to&&this.inner.hasNode(e)}nextFrag(){var e;if(this.fragI++,this.fragI==this.fragments.length)this.curFrag=this.inner=null;else{let t=this.curFrag=this.fragments[this.fragI];this.curTo=(e=t.tree.prop(ku))!==null&&e!==void 0?e:t.to,this.inner=new Hp(t.tree,-t.offset)}}findMounts(e,t){var i;let r=[];if(this.inner){this.inner.cursor.moveTo(e,1);for(let s=this.inner.cursor.node;s;s=s.parent){let o=(i=s.tree)===null||i===void 0?void 0:i.prop(_.mounted);if(o&&o.parser==t)for(let a=this.fragI;a=s.to)break;l.tree==this.curFrag.tree&&r.push({frag:l,pos:s.from-l.offset,mount:o})}}}return r}};function Kp(n,e){let t=null,i=e;for(let r=1,s=0;r=a)break;l.to<=o||(t||(i=t=e.slice()),l.froma&&t.splice(s+1,0,new Rt(a,l.to))):l.to>a?t[s--]=new Rt(a,l.to):t.splice(s--,1))}}return i}function $T(n,e,t,i){let r=0,s=0,o=!1,a=!1,l=-1e9,h=[];for(;;){let c=r==n.length?1e9:o?n[r].to:n[r].from,u=s==e.length?1e9:a?e[s].to:e[s].from;if(o!=a){let f=Math.max(l,t),p=Math.min(c,u,i);fnew Rt(f.from+i,f.to+i)),u=$T(e,c,l,h);for(let f=0,p=l;;f++){let g=f==u.length,y=g?h:u[f].from;if(y>p&&t.push(new Bn(p,y,r.tree,-o,s.from>=p||s.openStart,s.to<=y||s.openEnd)),g)break;p=u[f].to}}else t.push(new Bn(l,h,r.tree,-o,s.from>=o||s.openStart,s.to<=a||s.openEnd))}return t}let CT=0;class jt{constructor(e,t,i){this.set=e,this.base=t,this.modified=i,this.id=CT++}static define(e){if(e!=null&&e.base)throw new Error("Can not derive from a modified tag");let t=new jt([],null,[]);if(t.set.push(t),e)for(let i of e.set)t.set.push(i);return t}static defineModifier(){let e=new Cl;return t=>t.modified.indexOf(e)>-1?t:Cl.get(t.base||t,t.modified.concat(e).sort((i,r)=>i.id-r.id))}}let IT=0;class Cl{constructor(){this.instances=[],this.id=IT++}static get(e,t){if(!t.length)return e;let i=t[0].instances.find(a=>a.base==e&&RT(t,a.modified));if(i)return i;let r=[],s=new jt(r,e,t);for(let a of t)a.instances.push(s);let o=ET(t);for(let a of e.set)if(!a.modified.length)for(let l of o)r.push(Cl.get(a,l));return s}}function RT(n,e){return n.length==e.length&&n.every((t,i)=>t==e[i])}function ET(n){let e=[[]];for(let t=0;ti.length-t.length)}function $s(n){let e=Object.create(null);for(let t in n){let i=n[t];Array.isArray(i)||(i=[i]);for(let r of t.split(" "))if(r){let s=[],o=2,a=r;for(let u=0;;){if(a=="..."&&u>0&&u+3==r.length){o=1;break}let f=/^"(?:[^"\\]|\\.)*?"|[^\/!]+/.exec(a);if(!f)throw new RangeError("Invalid path: "+r);if(s.push(f[0]=="*"?"":f[0][0]=='"'?JSON.parse(f[0]):f[0]),u+=f[0].length,u==r.length)break;let p=r[u++];if(u==r.length&&p=="!"){o=0;break}if(p!="/")throw new RangeError("Invalid path: "+r);a=r.slice(u)}let l=s.length-1,h=s[l];if(!h)throw new RangeError("Invalid path: "+r);let c=new Il(i,o,l>0?s.slice(0,l):null);e[h]=c.sort(e[h])}}return ry.add(e)}const ry=new _;class Il{constructor(e,t,i,r){this.tags=e,this.mode=t,this.context=i,this.next=r}get opaque(){return this.mode==0}get inherit(){return this.mode==1}sort(e){return!e||e.depth{let o=r;for(let a of s)for(let l of a.set){let h=t[l.id];if(h){o=o?o+" "+h:h;break}}return o},scope:i}}function DT(n,e){let t=null;for(let i of n){let r=i.style(e);r&&(t=t?t+" "+r:r)}return t}function NT(n,e,t,i=0,r=n.length){let s=new BT(i,Array.isArray(e)?e:[e],t);s.highlightRange(n.cursor(),i,r,"",s.highlighters),s.flush(r)}class BT{constructor(e,t,i){this.at=e,this.highlighters=t,this.span=i,this.class=""}startSpan(e,t){t!=this.class&&(this.flush(e),e>this.at&&(this.at=e),this.class=t)}flush(e){e>this.at&&this.class&&this.span(this.at,e,this.class)}highlightRange(e,t,i,r,s){let{type:o,from:a,to:l}=e;if(a>=i||l<=t)return;o.isTop&&(s=this.highlighters.filter(p=>!p.scope||p.scope(o)));let h=r,c=qT(e)||Il.empty,u=DT(s,c.tags);if(u&&(h&&(h+=" "),h+=u,c.mode==1&&(r+=(r?" ":"")+u)),this.startSpan(e.from,h),c.opaque)return;let f=e.tree&&e.tree.prop(_.mounted);if(f&&f.overlay){let p=e.node.enter(f.overlay[0].from+a,1),g=this.highlighters.filter(O=>!O.scope||O.scope(f.tree.type)),y=e.firstChild();for(let O=0,S=a;;O++){let k=O=$||!e.nextSibling())););if(!k||$>i)break;S=k.to+a,S>t&&(this.highlightRange(p.cursor(),Math.max(t,k.from+a),Math.min(i,S),r,g),this.startSpan(S,h))}y&&e.parent()}else if(e.firstChild()){do if(!(e.to<=t)){if(e.from>=i)break;this.highlightRange(e,t,i,r,s),this.startSpan(Math.min(i,e.to),h)}while(e.nextSibling());e.parent()}}}function qT(n){let e=n.type.prop(ry);for(;e&&e.context&&!n.matchContext(e.context);)e=e.next;return e||null}const E=jt.define,ba=E(),Jn=E(),tg=E(Jn),ig=E(Jn),Yn=E(),Sa=E(Yn),jh=E(Yn),ai=E(),Sr=E(ai),si=E(),oi=E(),xu=E(),qs=E(xu),wa=E(),b={comment:ba,lineComment:E(ba),blockComment:E(ba),docComment:E(ba),name:Jn,variableName:E(Jn),typeName:tg,tagName:E(tg),propertyName:ig,attributeName:E(ig),className:E(Jn),labelName:E(Jn),namespace:E(Jn),macroName:E(Jn),literal:Yn,string:Sa,docString:E(Sa),character:E(Sa),attributeValue:E(Sa),number:jh,integer:E(jh),float:E(jh),bool:E(Yn),regexp:E(Yn),escape:E(Yn),color:E(Yn),url:E(Yn),keyword:si,self:E(si),null:E(si),atom:E(si),unit:E(si),modifier:E(si),operatorKeyword:E(si),controlKeyword:E(si),definitionKeyword:E(si),moduleKeyword:E(si),operator:oi,derefOperator:E(oi),arithmeticOperator:E(oi),logicOperator:E(oi),bitwiseOperator:E(oi),compareOperator:E(oi),updateOperator:E(oi),definitionOperator:E(oi),typeOperator:E(oi),controlOperator:E(oi),punctuation:xu,separator:E(xu),bracket:qs,angleBracket:E(qs),squareBracket:E(qs),paren:E(qs),brace:E(qs),content:ai,heading:Sr,heading1:E(Sr),heading2:E(Sr),heading3:E(Sr),heading4:E(Sr),heading5:E(Sr),heading6:E(Sr),contentSeparator:E(ai),list:E(ai),quote:E(ai),emphasis:E(ai),strong:E(ai),link:E(ai),monospace:E(ai),strikethrough:E(ai),inserted:E(),deleted:E(),changed:E(),invalid:E(),meta:wa,documentMeta:E(wa),annotation:E(wa),processingInstruction:E(wa),definition:jt.defineModifier(),constant:jt.defineModifier(),function:jt.defineModifier(),standard:jt.defineModifier(),local:jt.defineModifier(),special:jt.defineModifier()};sy([{tag:b.link,class:"tok-link"},{tag:b.heading,class:"tok-heading"},{tag:b.emphasis,class:"tok-emphasis"},{tag:b.strong,class:"tok-strong"},{tag:b.keyword,class:"tok-keyword"},{tag:b.atom,class:"tok-atom"},{tag:b.bool,class:"tok-bool"},{tag:b.url,class:"tok-url"},{tag:b.labelName,class:"tok-labelName"},{tag:b.inserted,class:"tok-inserted"},{tag:b.deleted,class:"tok-deleted"},{tag:b.literal,class:"tok-literal"},{tag:b.string,class:"tok-string"},{tag:b.number,class:"tok-number"},{tag:[b.regexp,b.escape,b.special(b.string)],class:"tok-string2"},{tag:b.variableName,class:"tok-variableName"},{tag:b.local(b.variableName),class:"tok-variableName tok-local"},{tag:b.definition(b.variableName),class:"tok-variableName tok-definition"},{tag:b.special(b.variableName),class:"tok-variableName2"},{tag:b.definition(b.propertyName),class:"tok-propertyName tok-definition"},{tag:b.typeName,class:"tok-typeName"},{tag:b.namespace,class:"tok-namespace"},{tag:b.className,class:"tok-className"},{tag:b.macroName,class:"tok-macroName"},{tag:b.propertyName,class:"tok-propertyName"},{tag:b.operator,class:"tok-operator"},{tag:b.comment,class:"tok-comment"},{tag:b.meta,class:"tok-meta"},{tag:b.invalid,class:"tok-invalid"},{tag:b.punctuation,class:"tok-punctuation"}]);const Tu="ͼ",ng=typeof Symbol>"u"?"__"+Tu:Symbol.for(Tu),Qu=typeof Symbol>"u"?"__styleSet"+Math.floor(Math.random()*1e8):Symbol("styleSet"),rg=typeof globalThis<"u"?globalThis:typeof window<"u"?window:{};class sg{constructor(e,t){this.rules=[];let{finish:i}=t||{};function r(o){return/^@/.test(o)?[o]:o.split(/,\s*/)}function s(o,a,l,h){let c=[],u=/^@(\w+)\b/.exec(o[0]),f=u&&u[1]=="keyframes";if(u&&a==null)return l.push(o[0]+";");for(let p in a){let g=a[p];if(/&/.test(p))s(p.split(/,\s*/).map(y=>o.map(O=>y.replace(/&/,O))).reduce((y,O)=>y.concat(O)),g,l);else if(g&&typeof g=="object"){if(!u)throw new RangeError("The value of a property ("+p+") should be a primitive value.");s(r(p),g,c,f)}else g!=null&&c.push(p.replace(/_.*/,"").replace(/[A-Z]/g,y=>"-"+y.toLowerCase())+": "+g+";")}(c.length||f)&&l.push((i&&!u&&!h?o.map(i):o).join(", ")+" {"+c.join(" ")+"}")}for(let o in e)s(r(o),e[o],this.rules)}getRules(){return this.rules.join(` +`;this.styleTag.textContent=o;let a=t.head||t;this.styleTag.parentNode!=a&&a.insertBefore(this.styleTag,a.firstChild)}}setNonce(e){this.styleTag&&this.styleTag.getAttribute("nonce")!=e&&this.styleTag.setAttribute("nonce",e)}};var dr={8:"Backspace",9:"Tab",10:"Enter",12:"NumLock",13:"Enter",16:"Shift",17:"Control",18:"Alt",20:"CapsLock",27:"Escape",32:" ",33:"PageUp",34:"PageDown",35:"End",36:"Home",37:"ArrowLeft",38:"ArrowUp",39:"ArrowRight",40:"ArrowDown",44:"PrintScreen",45:"Insert",46:"Delete",59:";",61:"=",91:"Meta",92:"Meta",106:"*",107:"+",108:",",109:"-",110:".",111:"/",144:"NumLock",145:"ScrollLock",160:"Shift",161:"Shift",162:"Control",163:"Control",164:"Alt",165:"Alt",173:"-",186:";",187:"=",188:",",189:"-",190:".",191:"/",192:"`",219:"[",220:"\\",221:"]",222:"'"},wo={48:")",49:"!",50:"@",51:"#",52:"$",53:"%",54:"^",55:"&",56:"*",57:"(",59:":",61:"+",173:"_",186:":",187:"+",188:"<",189:"_",190:">",191:"?",192:"~",219:"{",220:"|",221:"}",222:'"'},ep=typeof navigator<"u"&&/Chrome\/(\d+)/.exec(navigator.userAgent),Xv=typeof navigator<"u"&&/Mac/.test(navigator.platform),Lv=typeof navigator<"u"&&/MSIE \d|Trident\/(?:[7-9]|\d{2,})\..*rv:(\d+)/.exec(navigator.userAgent),Uv=Xv||ep&&+ep[1]<57;for(var Be=0;Be<10;Be++)dr[48+Be]=dr[96+Be]=String(Be);for(var Be=1;Be<=24;Be++)dr[Be+111]="F"+Be;for(var Be=65;Be<=90;Be++)dr[Be]=String.fromCharCode(Be+32),wo[Be]=String.fromCharCode(Be);for(var Dh in dr)wo.hasOwnProperty(Dh)||(wo[Dh]=dr[Dh]);function Zv(n){var e=Uv&&(n.ctrlKey||n.altKey||n.metaKey)||Lv&&n.shiftKey&&n.key&&n.key.length==1||n.key=="Unidentified",t=!e&&n.key||(n.shiftKey?wo:dr)[n.keyCode]||n.key||"Unidentified";return t=="Esc"&&(t="Escape"),t=="Del"&&(t="Delete"),t=="Left"&&(t="ArrowLeft"),t=="Up"&&(t="ArrowUp"),t=="Right"&&(t="ArrowRight"),t=="Down"&&(t="ArrowDown"),t}function xl(n){let e;return n.nodeType==11?e=n.getSelection?n:n.ownerDocument:e=n,e.getSelection()}function iu(n,e){return e?n==e||n.contains(e.nodeType!=1?e.parentNode:e):!1}function Wv(n){let e=n.activeElement;for(;e&&e.shadowRoot;)e=e.shadowRoot.activeElement;return e}function La(n,e){if(!e.anchorNode)return!1;try{return iu(n,e.anchorNode)}catch{return!1}}function vo(n){return n.nodeType==3?qr(n,0,n.nodeValue.length).getClientRects():n.nodeType==1?n.getClientRects():[]}function io(n,e,t,i){return t?tp(n,e,t,i,-1)||tp(n,e,t,i,1):!1}function ko(n){for(var e=0;;e++)if(n=n.previousSibling,!n)return e}function tp(n,e,t,i,r){for(;;){if(n==t&&e==i)return!0;if(e==(r<0?0:Xn(n))){if(n.nodeName=="DIV")return!1;let s=n.parentNode;if(!s||s.nodeType!=1)return!1;e=ko(n)+(r<0?0:1),n=s}else if(n.nodeType==1){if(n=n.childNodes[e+(r<0?-1:0)],n.nodeType==1&&n.contentEditable=="false")return!1;e=r<0?Xn(n):0}else return!1}}function Xn(n){return n.nodeType==3?n.nodeValue.length:n.childNodes.length}function pf(n,e){let t=e?n.left:n.right;return{left:t,right:t,top:n.top,bottom:n.bottom}}function jv(n){return{left:0,right:n.innerWidth,top:0,bottom:n.innerHeight}}function GO(n,e){let t=e.width/n.offsetWidth,i=e.height/n.offsetHeight;return(t>.995&&t<1.005||!isFinite(t)||Math.abs(e.width-n.offsetWidth)<1)&&(t=1),(i>.995&&i<1.005||!isFinite(i)||Math.abs(e.height-n.offsetHeight)<1)&&(i=1),{scaleX:t,scaleY:i}}function Fv(n,e,t,i,r,s,o,a){let l=n.ownerDocument,h=l.defaultView||window;for(let c=n,u=!1;c&&!u;)if(c.nodeType==1){let f,p=c==l.body,g=1,O=1;if(p)f=jv(h);else{if(/^(fixed|sticky)$/.test(getComputedStyle(c).position)&&(u=!0),c.scrollHeight<=c.clientHeight&&c.scrollWidth<=c.clientWidth){c=c.assignedSlot||c.parentNode;continue}let k=c.getBoundingClientRect();({scaleX:g,scaleY:O}=GO(c,k)),f={left:k.left,right:k.left+c.clientWidth*g,top:k.top,bottom:k.top+c.clientHeight*O}}let y=0,S=0;if(r=="nearest")e.top0&&e.bottom>f.bottom+S&&(S=e.bottom-f.bottom+S+o)):e.bottom>f.bottom&&(S=e.bottom-f.bottom+o,t<0&&e.top-S0&&e.right>f.right+y&&(y=e.right-f.right+y+s)):e.right>f.right&&(y=e.right-f.right+s,t<0&&e.leftt.clientHeight||t.scrollWidth>t.clientWidth)return t;t=t.assignedSlot||t.parentNode}else if(t.nodeType==11)t=t.host;else break;return null}class _v{constructor(){this.anchorNode=null,this.anchorOffset=0,this.focusNode=null,this.focusOffset=0}eq(e){return this.anchorNode==e.anchorNode&&this.anchorOffset==e.anchorOffset&&this.focusNode==e.focusNode&&this.focusOffset==e.focusOffset}setRange(e){let{anchorNode:t,focusNode:i}=e;this.set(t,Math.min(e.anchorOffset,t?Xn(t):0),i,Math.min(e.focusOffset,i?Xn(i):0))}set(e,t,i,r){this.anchorNode=e,this.anchorOffset=t,this.focusNode=i,this.focusOffset=r}}let jr=null;function JO(n){if(n.setActive)return n.setActive();if(jr)return n.focus(jr);let e=[];for(let t=n;t&&(e.push(t,t.scrollTop,t.scrollLeft),t!=t.ownerDocument);t=t.parentNode);if(n.focus(jr==null?{get preventScroll(){return jr={preventScroll:!0},!0}}:void 0),!jr){jr=!1;for(let t=0;tMath.max(1,n.scrollHeight-n.clientHeight-4)}class Ze{constructor(e,t,i=!0){this.node=e,this.offset=t,this.precise=i}static before(e,t){return new Ze(e.parentNode,ko(e),t)}static after(e,t){return new Ze(e.parentNode,ko(e)+1,t)}}const gf=[];class he{constructor(){this.parent=null,this.dom=null,this.flags=2}get overrideDOMText(){return null}get posAtStart(){return this.parent?this.parent.posBefore(this):0}get posAtEnd(){return this.posAtStart+this.length}posBefore(e){let t=this.posAtStart;for(let i of this.children){if(i==e)return t;t+=i.length+i.breakAfter}throw new RangeError("Invalid child in posBefore")}posAfter(e){return this.posBefore(e)+e.length}sync(e,t){if(this.flags&2){let i=this.dom,r=null,s;for(let o of this.children){if(o.flags&7){if(!o.dom&&(s=r?r.nextSibling:i.firstChild)){let a=he.get(s);(!a||!a.parent&&a.canReuseDOM(o))&&o.reuseDOM(s)}o.sync(e,t),o.flags&=-8}if(s=r?r.nextSibling:i.firstChild,t&&!t.written&&t.node==i&&s!=o.dom&&(t.written=!0),o.dom.parentNode==i)for(;s&&s!=o.dom;)s=np(s);else i.insertBefore(o.dom,s);r=o.dom}for(s=r?r.nextSibling:i.firstChild,s&&t&&t.node==i&&(t.written=!0);s;)s=np(s)}else if(this.flags&1)for(let i of this.children)i.flags&7&&(i.sync(e,t),i.flags&=-8)}reuseDOM(e){}localPosFromDOM(e,t){let i;if(e==this.dom)i=this.dom.childNodes[t];else{let r=Xn(e)==0?0:t==0?-1:1;for(;;){let s=e.parentNode;if(s==this.dom)break;r==0&&s.firstChild!=s.lastChild&&(e==s.firstChild?r=-1:r=1),e=s}r<0?i=e:i=e.nextSibling}if(i==this.dom.firstChild)return 0;for(;i&&!he.get(i);)i=i.nextSibling;if(!i)return this.length;for(let r=0,s=0;;r++){let o=this.children[r];if(o.dom==i)return s;s+=o.length+o.breakAfter}}domBoundsAround(e,t,i=0){let r=-1,s=-1,o=-1,a=-1;for(let l=0,h=i,c=i;lt)return u.domBoundsAround(e,t,h);if(f>=e&&r==-1&&(r=l,s=h),h>t&&u.dom.parentNode==this.dom){o=l,a=c;break}c=f,h=f+u.breakAfter}return{from:s,to:a<0?i+this.length:a,startDOM:(r?this.children[r-1].dom.nextSibling:null)||this.dom.firstChild,endDOM:o=0?this.children[o].dom:null}}markDirty(e=!1){this.flags|=2,this.markParentsDirty(e)}markParentsDirty(e){for(let t=this.parent;t;t=t.parent){if(e&&(t.flags|=2),t.flags&1)return;t.flags|=1,e=!1}}setParent(e){this.parent!=e&&(this.parent=e,this.flags&7&&this.markParentsDirty(!0))}setDOM(e){this.dom!=e&&(this.dom&&(this.dom.cmView=null),this.dom=e,e.cmView=this)}get rootView(){for(let e=this;;){let t=e.parent;if(!t)return e;e=t}}replaceChildren(e,t,i=gf){this.markDirty();for(let r=e;rthis.pos||e==this.pos&&(t>0||this.i==0||this.children[this.i-1].breakAfter))return this.off=e-this.pos,this;let i=this.children[--this.i];this.pos-=i.length+i.breakAfter}}}function e0(n,e,t,i,r,s,o,a,l){let{children:h}=n,c=h.length?h[e]:null,u=s.length?s[s.length-1]:null,f=u?u.breakAfter:o;if(!(e==i&&c&&!o&&!f&&s.length<2&&c.merge(t,r,s.length?u:null,t==0,a,l))){if(i0&&(!o&&s.length&&c.merge(t,c.length,s[0],!1,a,0)?c.breakAfter=s.shift().breakAfter:(t2);var q={mac:op||/Mac/.test(ht.platform),windows:/Win/.test(ht.platform),linux:/Linux|X11/.test(ht.platform),ie:ah,ie_version:i0?nu.documentMode||6:su?+su[1]:ru?+ru[1]:0,gecko:rp,gecko_version:rp?+(/Firefox\/(\d+)/.exec(ht.userAgent)||[0,0])[1]:0,chrome:!!Nh,chrome_version:Nh?+Nh[1]:0,ios:op,android:/Android\b/.test(ht.userAgent),webkit:sp,safari:n0,webkit_version:sp?+(/\bAppleWebKit\/(\d+)/.exec(navigator.userAgent)||[0,0])[1]:0,tabSize:nu.documentElement.style.tabSize!=null?"tab-size":"-moz-tab-size"};const Yv=256;class Ln extends he{constructor(e){super(),this.text=e}get length(){return this.text.length}createDOM(e){this.setDOM(e||document.createTextNode(this.text))}sync(e,t){this.dom||this.createDOM(),this.dom.nodeValue!=this.text&&(t&&t.node==this.dom&&(t.written=!0),this.dom.nodeValue=this.text)}reuseDOM(e){e.nodeType==3&&this.createDOM(e)}merge(e,t,i){return this.flags&8||i&&(!(i instanceof Ln)||this.length-(t-e)+i.length>Yv||i.flags&8)?!1:(this.text=this.text.slice(0,e)+(i?i.text:"")+this.text.slice(t),this.markDirty(),!0)}split(e){let t=new Ln(this.text.slice(e));return this.text=this.text.slice(0,e),this.markDirty(),t.flags|=this.flags&8,t}localPosFromDOM(e,t){return e==this.dom?t:t?this.text.length:0}domAtPos(e){return new Ze(this.dom,e)}domBoundsAround(e,t,i){return{from:i,to:i+this.length,startDOM:this.dom,endDOM:this.dom.nextSibling}}coordsAt(e,t){return Hv(this.dom,e,t)}}class Un extends he{constructor(e,t=[],i=0){super(),this.mark=e,this.children=t,this.length=i;for(let r of t)r.setParent(this)}setAttrs(e){if(YO(e),this.mark.class&&(e.className=this.mark.class),this.mark.attrs)for(let t in this.mark.attrs)e.setAttribute(t,this.mark.attrs[t]);return e}canReuseDOM(e){return super.canReuseDOM(e)&&!((this.flags|e.flags)&8)}reuseDOM(e){e.nodeName==this.mark.tagName.toUpperCase()&&(this.setDOM(e),this.flags|=6)}sync(e,t){this.dom?this.flags&4&&this.setAttrs(this.dom):this.setDOM(this.setAttrs(document.createElement(this.mark.tagName))),super.sync(e,t)}merge(e,t,i,r,s,o){return i&&(!(i instanceof Un&&i.mark.eq(this.mark))||e&&s<=0||te&&t.push(i=e&&(r=s),i=l,s++}let o=this.length-e;return this.length=e,r>-1&&(this.children.length=r,this.markDirty()),new Un(this.mark,t,o)}domAtPos(e){return r0(this,e)}coordsAt(e,t){return o0(this,e,t)}}function Hv(n,e,t){let i=n.nodeValue.length;e>i&&(e=i);let r=e,s=e,o=0;e==0&&t<0||e==i&&t>=0?q.chrome||q.gecko||(e?(r--,o=1):s=0)?0:a.length-1];return q.safari&&!o&&l.width==0&&(l=Array.prototype.find.call(a,h=>h.width)||l),o?pf(l,o<0):l||null}class tr extends he{static create(e,t,i){return new tr(e,t,i)}constructor(e,t,i){super(),this.widget=e,this.length=t,this.side=i,this.prevWidget=null}split(e){let t=tr.create(this.widget,this.length-e,this.side);return this.length-=e,t}sync(e){(!this.dom||!this.widget.updateDOM(this.dom,e))&&(this.dom&&this.prevWidget&&this.prevWidget.destroy(this.dom),this.prevWidget=null,this.setDOM(this.widget.toDOM(e)),this.widget.editable||(this.dom.contentEditable="false"))}getSide(){return this.side}merge(e,t,i,r,s,o){return i&&(!(i instanceof tr)||!this.widget.compare(i.widget)||e>0&&s<=0||t0)?Ze.before(this.dom):Ze.after(this.dom,e==this.length)}domBoundsAround(){return null}coordsAt(e,t){let i=this.widget.coordsAt(this.dom,e,t);if(i)return i;let r=this.dom.getClientRects(),s=null;if(!r.length)return null;let o=this.side?this.side<0:e>0;for(let a=o?r.length-1:0;s=r[a],!(e>0?a==0:a==r.length-1||s.top0?Ze.before(this.dom):Ze.after(this.dom)}localPosFromDOM(){return 0}domBoundsAround(){return null}coordsAt(e){return this.dom.getBoundingClientRect()}get overrideDOMText(){return K.empty}get isHidden(){return!0}}Ln.prototype.children=tr.prototype.children=ys.prototype.children=gf;function r0(n,e){let t=n.dom,{children:i}=n,r=0;for(let s=0;rs&&e0;s--){let o=i[s-1];if(o.dom.parentNode==t)return o.domAtPos(o.length)}for(let s=r;s0&&e instanceof Un&&r.length&&(i=r[r.length-1])instanceof Un&&i.mark.eq(e.mark)?s0(i,e.children[0],t-1):(r.push(e),e.setParent(n)),n.length+=e.length}function o0(n,e,t){let i=null,r=-1,s=null,o=-1;function a(h,c){for(let u=0,f=0;u=c&&(p.children.length?a(p,c-f):(!s||s.isHidden&&t>0)&&(g>c||f==g&&p.getSide()>0)?(s=p,o=c-f):(f-1?1:0)!=r.length-(t&&r.indexOf(t)>-1?1:0))return!1;for(let s of i)if(s!=t&&(r.indexOf(s)==-1||n[s]!==e[s]))return!1;return!0}function au(n,e,t){let i=!1;if(e)for(let r in e)t&&r in t||(i=!0,r=="style"?n.style.cssText="":n.removeAttribute(r));if(t)for(let r in t)e&&e[r]==t[r]||(i=!0,r=="style"?n.style.cssText=t[r]:n.setAttribute(r,t[r]));return i}function ek(n){let e=Object.create(null);for(let t=0;t0&&this.children[i-1].length==0;)this.children[--i].destroy();return this.children.length=i,this.markDirty(),this.length=e,t}transferDOM(e){this.dom&&(this.markDirty(),e.setDOM(this.dom),e.prevAttrs=this.prevAttrs===void 0?this.attrs:this.prevAttrs,this.prevAttrs=void 0,this.dom=null)}setDeco(e){mf(this.attrs,e)||(this.dom&&(this.prevAttrs=this.attrs,this.markDirty()),this.attrs=e)}append(e,t){s0(this,e,t)}addLineDeco(e){let t=e.spec.attributes,i=e.spec.class;t&&(this.attrs=ou(t,this.attrs||{})),i&&(this.attrs=ou({class:i},this.attrs||{}))}domAtPos(e){return r0(this,e)}reuseDOM(e){e.nodeName=="DIV"&&(this.setDOM(e),this.flags|=6)}sync(e,t){var i;this.dom?this.flags&4&&(YO(this.dom),this.dom.className="cm-line",this.prevAttrs=this.attrs?null:void 0):(this.setDOM(document.createElement("div")),this.dom.className="cm-line",this.prevAttrs=this.attrs?null:void 0),this.prevAttrs!==void 0&&(au(this.dom,this.prevAttrs,this.attrs),this.dom.classList.add("cm-line"),this.prevAttrs=void 0),super.sync(e,t);let r=this.dom.lastChild;for(;r&&he.get(r)instanceof Un;)r=r.lastChild;if(!r||!this.length||r.nodeName!="BR"&&((i=he.get(r))===null||i===void 0?void 0:i.isEditable)==!1&&(!q.ios||!this.children.some(s=>s instanceof Ln))){let s=document.createElement("BR");s.cmIgnore=!0,this.dom.appendChild(s)}}measureTextSize(){if(this.children.length==0||this.length>20)return null;let e=0,t;for(let i of this.children){if(!(i instanceof Ln)||/[^ -~]/.test(i.text))return null;let r=vo(i.dom);if(r.length!=1)return null;e+=r[0].width,t=r[0].height}return e?{lineHeight:this.dom.getBoundingClientRect().height,charWidth:e/this.length,textHeight:t}:null}coordsAt(e,t){let i=o0(this,e,t);if(!this.children.length&&i&&this.parent){let{heightOracle:r}=this.parent.view.viewState,s=i.bottom-i.top;if(Math.abs(s-r.lineHeight)<2&&r.textHeight=t){if(s instanceof Ae)return s;if(o>t)break}r=o+s.breakAfter}return null}}class or extends he{constructor(e,t,i){super(),this.widget=e,this.length=t,this.deco=i,this.breakAfter=0,this.prevWidget=null}merge(e,t,i,r,s,o){return i&&(!(i instanceof or)||!this.widget.compare(i.widget)||e>0&&s<=0||t0}}class Or{eq(e){return!1}updateDOM(e,t){return!1}compare(e){return this==e||this.constructor==e.constructor&&this.eq(e)}get estimatedHeight(){return-1}get lineBreaks(){return 0}ignoreEvent(e){return!0}coordsAt(e,t,i){return null}get isHidden(){return!1}get editable(){return!1}destroy(e){}}var Je=function(n){return n[n.Text=0]="Text",n[n.WidgetBefore=1]="WidgetBefore",n[n.WidgetAfter=2]="WidgetAfter",n[n.WidgetRange=3]="WidgetRange",n}(Je||(Je={}));class Z extends Br{constructor(e,t,i,r){super(),this.startSide=e,this.endSide=t,this.widget=i,this.spec=r}get heightRelevant(){return!1}static mark(e){return new Zo(e)}static widget(e){let t=Math.max(-1e4,Math.min(1e4,e.side||0)),i=!!e.block;return t+=i&&!e.inlineOrder?t>0?3e8:-4e8:t>0?1e8:-1e8,new pr(e,t,t,i,e.widget||null,!1)}static replace(e){let t=!!e.block,i,r;if(e.isBlockGap)i=-5e8,r=4e8;else{let{start:s,end:o}=a0(e,t);i=(s?t?-3e8:-1:5e8)-1,r=(o?t?2e8:1:-6e8)+1}return new pr(e,i,r,t,e.widget||null,!0)}static line(e){return new Wo(e)}static set(e,t=!1){return J.of(e,t)}hasHeight(){return this.widget?this.widget.estimatedHeight>-1:!1}}Z.none=J.empty;class Zo extends Z{constructor(e){let{start:t,end:i}=a0(e);super(t?-1:5e8,i?1:-6e8,null,e),this.tagName=e.tagName||"span",this.class=e.class||"",this.attrs=e.attributes||null}eq(e){var t,i;return this==e||e instanceof Zo&&this.tagName==e.tagName&&(this.class||((t=this.attrs)===null||t===void 0?void 0:t.class))==(e.class||((i=e.attrs)===null||i===void 0?void 0:i.class))&&mf(this.attrs,e.attrs,"class")}range(e,t=e){if(e>=t)throw new RangeError("Mark decorations may not be empty");return super.range(e,t)}}Zo.prototype.point=!1;class Wo extends Z{constructor(e){super(-2e8,-2e8,null,e)}eq(e){return e instanceof Wo&&this.spec.class==e.spec.class&&mf(this.spec.attributes,e.spec.attributes)}range(e,t=e){if(t!=e)throw new RangeError("Line decoration ranges must be zero-length");return super.range(e,t)}}Wo.prototype.mapMode=qe.TrackBefore;Wo.prototype.point=!0;class pr extends Z{constructor(e,t,i,r,s,o){super(t,i,s,e),this.block=r,this.isReplace=o,this.mapMode=r?t<=0?qe.TrackBefore:qe.TrackAfter:qe.TrackDel}get type(){return this.startSide!=this.endSide?Je.WidgetRange:this.startSide<=0?Je.WidgetBefore:Je.WidgetAfter}get heightRelevant(){return this.block||!!this.widget&&(this.widget.estimatedHeight>=5||this.widget.lineBreaks>0)}eq(e){return e instanceof pr&&tk(this.widget,e.widget)&&this.block==e.block&&this.startSide==e.startSide&&this.endSide==e.endSide}range(e,t=e){if(this.isReplace&&(e>t||e==t&&this.startSide>0&&this.endSide<=0))throw new RangeError("Invalid range for replacement decoration");if(!this.isReplace&&t!=e)throw new RangeError("Widget decorations can only have zero-length ranges");return super.range(e,t)}}pr.prototype.point=!0;function a0(n,e=!1){let{inclusiveStart:t,inclusiveEnd:i}=n;return t==null&&(t=n.inclusive),i==null&&(i=n.inclusive),{start:t??e,end:i??e}}function tk(n,e){return n==e||!!(n&&e&&n.compare(e))}function lu(n,e,t,i=0){let r=t.length-1;r>=0&&t[r]+i>=n?t[r]=Math.max(t[r],e):t.push(n,e)}class no{constructor(e,t,i,r){this.doc=e,this.pos=t,this.end=i,this.disallowBlockEffectsFor=r,this.content=[],this.curLine=null,this.breakAtStart=0,this.pendingBuffer=0,this.bufferMarks=[],this.atCursorPos=!0,this.openStart=-1,this.openEnd=-1,this.text="",this.textOff=0,this.cursor=e.iter(),this.skip=t}posCovered(){if(this.content.length==0)return!this.breakAtStart&&this.doc.lineAt(this.pos).from!=this.pos;let e=this.content[this.content.length-1];return!(e.breakAfter||e instanceof or&&e.deco.endSide<0)}getLine(){return this.curLine||(this.content.push(this.curLine=new Ae),this.atCursorPos=!0),this.curLine}flushBuffer(e=this.bufferMarks){this.pendingBuffer&&(this.curLine.append(aa(new ys(-1),e),e.length),this.pendingBuffer=0)}addBlockWidget(e){this.flushBuffer(),this.curLine=null,this.content.push(e)}finish(e){this.pendingBuffer&&e<=this.bufferMarks.length?this.flushBuffer():this.pendingBuffer=0,!this.posCovered()&&!(e&&this.content.length&&this.content[this.content.length-1]instanceof or)&&this.getLine()}buildText(e,t,i){for(;e>0;){if(this.textOff==this.text.length){let{value:s,lineBreak:o,done:a}=this.cursor.next(this.skip);if(this.skip=0,a)throw new Error("Ran out of text content when drawing inline views");if(o){this.posCovered()||this.getLine(),this.content.length?this.content[this.content.length-1].breakAfter=1:this.breakAtStart=1,this.flushBuffer(),this.curLine=null,this.atCursorPos=!0,e--;continue}else this.text=s,this.textOff=0}let r=Math.min(this.text.length-this.textOff,e,512);this.flushBuffer(t.slice(t.length-i)),this.getLine().append(aa(new Ln(this.text.slice(this.textOff,this.textOff+r)),t),i),this.atCursorPos=!0,this.textOff+=r,e-=r,i=0}}span(e,t,i,r){this.buildText(t-e,i,r),this.pos=t,this.openStart<0&&(this.openStart=r)}point(e,t,i,r,s,o){if(this.disallowBlockEffectsFor[o]&&i instanceof pr){if(i.block)throw new RangeError("Block decorations may not be specified via plugins");if(t>this.doc.lineAt(this.pos).to)throw new RangeError("Decorations that replace line breaks may not be specified via plugins")}let a=t-e;if(i instanceof pr)if(i.block)i.startSide>0&&!this.posCovered()&&this.getLine(),this.addBlockWidget(new or(i.widget||new lp("div"),a,i));else{let l=tr.create(i.widget||new lp("span"),a,a?0:i.startSide),h=this.atCursorPos&&!l.isEditable&&s<=r.length&&(e0),c=!l.isEditable&&(er.length||i.startSide<=0),u=this.getLine();this.pendingBuffer==2&&!h&&!l.isEditable&&(this.pendingBuffer=0),this.flushBuffer(r),h&&(u.append(aa(new ys(1),r),s),s=r.length+Math.max(0,s-r.length)),u.append(aa(l,r),s),this.atCursorPos=c,this.pendingBuffer=c?er.length?1:2:0,this.pendingBuffer&&(this.bufferMarks=r.slice())}else this.doc.lineAt(this.pos).from==this.pos&&this.getLine().addLineDeco(i);a&&(this.textOff+a<=this.text.length?this.textOff+=a:(this.skip+=a-(this.text.length-this.textOff),this.text="",this.textOff=0),this.pos=t),this.openStart<0&&(this.openStart=s)}static build(e,t,i,r,s){let o=new no(e,t,i,s);return o.openEnd=J.spans(r,t,i,o),o.openStart<0&&(o.openStart=o.openEnd),o.finish(o.openEnd),o}}function aa(n,e){for(let t of e)n=new Un(t,[n],n.length);return n}class lp extends Or{constructor(e){super(),this.tag=e}eq(e){return e.tag==this.tag}toDOM(){return document.createElement(this.tag)}updateDOM(e){return e.nodeName.toLowerCase()==this.tag}get isHidden(){return!0}}var ge=function(n){return n[n.LTR=0]="LTR",n[n.RTL=1]="RTL",n}(ge||(ge={}));const Mr=ge.LTR,Of=ge.RTL;function l0(n){let e=[];for(let t=0;t=t){if(a.level==i)return o;(s<0||(r!=0?r<0?a.fromt:e[s].level>a.level))&&(s=o)}}if(s<0)throw new RangeError("Index out of range");return s}}function c0(n,e){if(n.length!=e.length)return!1;for(let t=0;t=0;O-=3)if(ri[O+1]==-p){let y=ri[O+2],S=y&2?r:y&4?y&1?s:r:0;S&&(oe[u]=oe[ri[O]]=S),a=O;break}}else{if(ri.length==189)break;ri[a++]=u,ri[a++]=f,ri[a++]=l}else if((g=oe[u])==2||g==1){let O=g==r;l=O?0:1;for(let y=a-3;y>=0;y-=3){let S=ri[y+2];if(S&2)break;if(O)ri[y+2]|=2;else{if(S&4)break;ri[y+2]|=4}}}}}function ak(n,e,t,i){for(let r=0,s=i;r<=t.length;r++){let o=r?t[r-1].to:n,a=rl;)g==y&&(g=t[--O].from,y=O?t[O-1].to:n),oe[--g]=p;l=c}else s=h,l++}}}function cu(n,e,t,i,r,s,o){let a=i%2?2:1;if(i%2==r%2)for(let l=e,h=0;ll&&o.push(new ir(l,O.from,p));let y=O.direction==Mr!=!(p%2);uu(n,y?i+1:i,r,O.inner,O.from,O.to,o),l=O.to}g=O.to}else{if(g==t||(c?oe[g]!=a:oe[g]==a))break;g++}f?cu(n,l,g,i+1,r,f,o):le;){let c=!0,u=!1;if(!h||l>s[h-1].to){let O=oe[l-1];O!=a&&(c=!1,u=O==16)}let f=!c&&a==1?[]:null,p=c?i:i+1,g=l;e:for(;;)if(h&&g==s[h-1].to){if(u)break e;let O=s[--h];if(!c)for(let y=O.from,S=h;;){if(y==e)break e;if(S&&s[S-1].to==y)y=s[--S].from;else{if(oe[y-1]==a)break e;break}}if(f)f.push(O);else{O.tooe.length;)oe[oe.length]=256;let i=[],r=e==Mr?0:1;return uu(n,r,r,t,0,n.length,i),i}function u0(n){return[new ir(0,n,0)]}let f0="";function hk(n,e,t,i,r){var s;let o=i.head-n.from,a=ir.find(e,o,(s=i.bidiLevel)!==null&&s!==void 0?s:-1,i.assoc),l=e[a],h=l.side(r,t);if(o==h){let f=a+=r?1:-1;if(f<0||f>=e.length)return null;l=e[a=f],o=l.side(!r,t),h=l.side(r,t)}let c=We(n.text,o,l.forward(r,t));(cl.to)&&(c=h),f0=n.text.slice(Math.min(o,c),Math.max(o,c));let u=a==(r?e.length-1:0)?null:e[a+(r?1:-1)];return u&&c==h&&u.level+(r?0:1)n.some(e=>e)}),S0=B.define({combine:n=>n.some(e=>e)});class os{constructor(e,t="nearest",i="nearest",r=5,s=5,o=!1){this.range=e,this.y=t,this.x=i,this.yMargin=r,this.xMargin=s,this.isSnapshot=o}map(e){return e.empty?this:new os(this.range.map(e),this.y,this.x,this.yMargin,this.xMargin,this.isSnapshot)}clip(e){return this.range.to<=e.doc.length?this:new os(P.cursor(e.doc.length),this.y,this.x,this.yMargin,this.xMargin,this.isSnapshot)}}const la=z.define({map:(n,e)=>n.map(e)});function mt(n,e,t){let i=n.facet(m0);i.length?i[0](e):window.onerror?window.onerror(String(e),t,void 0,void 0,e):t?console.error(t+":",e):console.error(e)}const lh=B.define({combine:n=>n.length?n[0]:!0});let uk=0;const Ws=B.define();class ke{constructor(e,t,i,r,s){this.id=e,this.create=t,this.domEventHandlers=i,this.domEventObservers=r,this.extension=s(this)}static define(e,t){const{eventHandlers:i,eventObservers:r,provide:s,decorations:o}=t||{};return new ke(uk++,e,i,r,a=>{let l=[Ws.of(a)];return o&&l.push(xo.of(h=>{let c=h.plugin(a);return c?o(c):Z.none})),s&&l.push(s(a)),l})}static fromClass(e,t){return ke.define(i=>new e(i),t)}}class Bh{constructor(e){this.spec=e,this.mustUpdate=null,this.value=null}update(e){if(this.value){if(this.mustUpdate){let t=this.mustUpdate;if(this.mustUpdate=null,this.value.update)try{this.value.update(t)}catch(i){if(mt(t.state,i,"CodeMirror plugin crashed"),this.value.destroy)try{this.value.destroy()}catch{}this.deactivate()}}}else if(this.spec)try{this.value=this.spec.create(e)}catch(t){mt(e.state,t,"CodeMirror plugin crashed"),this.deactivate()}return this}destroy(e){var t;if(!((t=this.value)===null||t===void 0)&&t.destroy)try{this.value.destroy()}catch(i){mt(e.state,i,"CodeMirror plugin crashed")}}deactivate(){this.spec=this.value=null}}const w0=B.define(),yf=B.define(),xo=B.define(),v0=B.define(),bf=B.define(),k0=B.define();function hp(n,e){let t=n.state.facet(k0);if(!t.length)return t;let i=t.map(s=>s instanceof Function?s(n):s),r=[];return J.spans(i,e.from,e.to,{point(){},span(s,o,a,l){let h=s-e.from,c=o-e.from,u=r;for(let f=a.length-1;f>=0;f--,l--){let p=a[f].spec.bidiIsolate,g;if(p==null&&(p=ck(e.text,h,c)),l>0&&u.length&&(g=u[u.length-1]).to==h&&g.direction==p)g.to=c,u=g.inner;else{let O={from:h,to:c,direction:p,inner:[]};u.push(O),u=O.inner}}}}),r}const x0=B.define();function T0(n){let e=0,t=0,i=0,r=0;for(let s of n.state.facet(x0)){let o=s(n);o&&(o.left!=null&&(e=Math.max(e,o.left)),o.right!=null&&(t=Math.max(t,o.right)),o.top!=null&&(i=Math.max(i,o.top)),o.bottom!=null&&(r=Math.max(r,o.bottom)))}return{left:e,right:t,top:i,bottom:r}}const js=B.define();class Nt{constructor(e,t,i,r){this.fromA=e,this.toA=t,this.fromB=i,this.toB=r}join(e){return new Nt(Math.min(this.fromA,e.fromA),Math.max(this.toA,e.toA),Math.min(this.fromB,e.fromB),Math.max(this.toB,e.toB))}addToSet(e){let t=e.length,i=this;for(;t>0;t--){let r=e[t-1];if(!(r.fromA>i.toA)){if(r.toAc)break;s+=2}if(!l)return i;new Nt(l.fromA,l.toA,l.fromB,l.toB).addToSet(i),o=l.toA,a=l.toB}}}class Tl{constructor(e,t,i){this.view=e,this.state=t,this.transactions=i,this.flags=0,this.startState=e.state,this.changes=Ce.empty(this.startState.doc.length);for(let s of i)this.changes=this.changes.compose(s.changes);let r=[];this.changes.iterChangedRanges((s,o,a,l)=>r.push(new Nt(s,o,a,l))),this.changedRanges=r}static create(e,t,i){return new Tl(e,t,i)}get viewportChanged(){return(this.flags&4)>0}get heightChanged(){return(this.flags&2)>0}get geometryChanged(){return this.docChanged||(this.flags&10)>0}get focusChanged(){return(this.flags&1)>0}get docChanged(){return!this.changes.empty}get selectionSet(){return this.transactions.some(e=>e.selection)}get empty(){return this.flags==0&&this.transactions.length==0}}class cp extends he{get length(){return this.view.state.doc.length}constructor(e){super(),this.view=e,this.decorations=[],this.dynamicDecorationMap=[],this.domChanged=null,this.hasComposition=null,this.markedForComposition=new Set,this.minWidth=0,this.minWidthFrom=0,this.minWidthTo=0,this.impreciseAnchor=null,this.impreciseHead=null,this.forceSelection=!1,this.lastUpdate=Date.now(),this.setDOM(e.contentDOM),this.children=[new Ae],this.children[0].setParent(this),this.updateDeco(),this.updateInner([new Nt(0,0,0,e.state.doc.length)],0,null)}update(e){var t;let i=e.changedRanges;this.minWidth>0&&i.length&&(i.every(({fromA:h,toA:c})=>cthis.minWidthTo)?(this.minWidthFrom=e.changes.mapPos(this.minWidthFrom,1),this.minWidthTo=e.changes.mapPos(this.minWidthTo,1)):this.minWidth=this.minWidthFrom=this.minWidthTo=0);let r=-1;this.view.inputState.composing>=0&&(!((t=this.domChanged)===null||t===void 0)&&t.newSel?r=this.domChanged.newSel.head:!yk(e.changes,this.hasComposition)&&!e.selectionSet&&(r=e.state.selection.main.head));let s=r>-1?dk(this.view,e.changes,r):null;if(this.domChanged=null,this.hasComposition){this.markedForComposition.clear();let{from:h,to:c}=this.hasComposition;i=new Nt(h,c,e.changes.mapPos(h,-1),e.changes.mapPos(c,1)).addToSet(i.slice())}this.hasComposition=s?{from:s.range.fromB,to:s.range.toB}:null,(q.ie||q.chrome)&&!s&&e&&e.state.doc.lines!=e.startState.doc.lines&&(this.forceSelection=!0);let o=this.decorations,a=this.updateDeco(),l=mk(o,a,e.changes);return i=Nt.extendWithRanges(i,l),!(this.flags&7)&&i.length==0?!1:(this.updateInner(i,e.startState.doc.length,s),e.transactions.length&&(this.lastUpdate=Date.now()),!0)}updateInner(e,t,i){this.view.viewState.mustMeasureContent=!0,this.updateChildren(e,t,i);let{observer:r}=this.view;r.ignore(()=>{this.dom.style.height=this.view.viewState.contentHeight/this.view.scaleY+"px",this.dom.style.flexBasis=this.minWidth?this.minWidth+"px":"";let o=q.chrome||q.ios?{node:r.selectionRange.focusNode,written:!1}:void 0;this.sync(this.view,o),this.flags&=-8,o&&(o.written||r.selectionRange.focusNode!=o.node)&&(this.forceSelection=!0),this.dom.style.height=""}),this.markedForComposition.forEach(o=>o.flags&=-9);let s=[];if(this.view.viewport.from||this.view.viewport.to=0?r[o]:null;if(!a)break;let{fromA:l,toA:h,fromB:c,toB:u}=a,f,p,g,O;if(i&&i.range.fromBc){let x=no.build(this.view.state.doc,c,i.range.fromB,this.decorations,this.dynamicDecorationMap),Q=no.build(this.view.state.doc,i.range.toB,u,this.decorations,this.dynamicDecorationMap);p=x.breakAtStart,g=x.openStart,O=Q.openEnd;let A=this.compositionView(i);Q.breakAtStart?A.breakAfter=1:Q.content.length&&A.merge(A.length,A.length,Q.content[0],!1,Q.openStart,0)&&(A.breakAfter=Q.content[0].breakAfter,Q.content.shift()),x.content.length&&A.merge(0,0,x.content[x.content.length-1],!0,0,x.openEnd)&&x.content.pop(),f=x.content.concat(A).concat(Q.content)}else({content:f,breakAtStart:p,openStart:g,openEnd:O}=no.build(this.view.state.doc,c,u,this.decorations,this.dynamicDecorationMap));let{i:y,off:S}=s.findPos(h,1),{i:k,off:$}=s.findPos(l,-1);e0(this,k,$,y,S,f,p,g,O)}i&&this.fixCompositionDOM(i)}compositionView(e){let t=new Ln(e.text.nodeValue);t.flags|=8;for(let{deco:r}of e.marks)t=new Un(r,[t],t.length);let i=new Ae;return i.append(t,0),i}fixCompositionDOM(e){let t=(s,o)=>{o.flags|=8|(o.children.some(l=>l.flags&7)?1:0),this.markedForComposition.add(o);let a=he.get(s);a&&a!=o&&(a.dom=null),o.setDOM(s)},i=this.childPos(e.range.fromB,1),r=this.children[i.i];t(e.line,r);for(let s=e.marks.length-1;s>=-1;s--)i=r.childPos(i.off,1),r=r.children[i.i],t(s>=0?e.marks[s].node:e.text,r)}updateSelection(e=!1,t=!1){(e||!this.view.observer.selectionRange.focusNode)&&this.view.observer.readSelectionRange();let i=this.view.root.activeElement,r=i==this.dom,s=!r&&La(this.dom,this.view.observer.selectionRange)&&!(i&&this.dom.contains(i));if(!(r||t||s))return;let o=this.forceSelection;this.forceSelection=!1;let a=this.view.state.selection.main,l=this.moveToLine(this.domAtPos(a.anchor)),h=a.empty?l:this.moveToLine(this.domAtPos(a.head));if(q.gecko&&a.empty&&!this.hasComposition&&fk(l)){let u=document.createTextNode("");this.view.observer.ignore(()=>l.node.insertBefore(u,l.node.childNodes[l.offset]||null)),l=h=new Ze(u,0),o=!0}let c=this.view.observer.selectionRange;(o||!c.focusNode||(!io(l.node,l.offset,c.anchorNode,c.anchorOffset)||!io(h.node,h.offset,c.focusNode,c.focusOffset))&&!this.suppressWidgetCursorChange(c,a))&&(this.view.observer.ignore(()=>{q.android&&q.chrome&&this.dom.contains(c.focusNode)&&Ok(c.focusNode,this.dom)&&(this.dom.blur(),this.dom.focus({preventScroll:!0}));let u=xl(this.view.root);if(u)if(a.empty){if(q.gecko){let f=pk(l.node,l.offset);if(f&&f!=3){let p=P0(l.node,l.offset,f==1?1:-1);p&&(l=new Ze(p.node,p.offset))}}u.collapse(l.node,l.offset),a.bidiLevel!=null&&u.caretBidiLevel!==void 0&&(u.caretBidiLevel=a.bidiLevel)}else if(u.extend){u.collapse(l.node,l.offset);try{u.extend(h.node,h.offset)}catch{}}else{let f=document.createRange();a.anchor>a.head&&([l,h]=[h,l]),f.setEnd(h.node,h.offset),f.setStart(l.node,l.offset),u.removeAllRanges(),u.addRange(f)}s&&this.view.root.activeElement==this.dom&&(this.dom.blur(),i&&i.focus())}),this.view.observer.setSelectionRange(l,h)),this.impreciseAnchor=l.precise?null:new Ze(c.anchorNode,c.anchorOffset),this.impreciseHead=h.precise?null:new Ze(c.focusNode,c.focusOffset)}suppressWidgetCursorChange(e,t){return this.hasComposition&&t.empty&&io(e.focusNode,e.focusOffset,e.anchorNode,e.anchorOffset)&&this.posFromDOM(e.focusNode,e.focusOffset)==t.head}enforceCursorAssoc(){if(this.hasComposition)return;let{view:e}=this,t=e.state.selection.main,i=xl(e.root),{anchorNode:r,anchorOffset:s}=e.observer.selectionRange;if(!i||!t.empty||!t.assoc||!i.modify)return;let o=Ae.find(this,t.head);if(!o)return;let a=o.posAtStart;if(t.head==a||t.head==a+o.length)return;let l=this.coordsAt(t.head,-1),h=this.coordsAt(t.head,1);if(!l||!h||l.bottom>h.top)return;let c=this.domAtPos(t.head+t.assoc);i.collapse(c.node,c.offset),i.modify("move",t.assoc<0?"forward":"backward","lineboundary"),e.observer.readSelectionRange();let u=e.observer.selectionRange;e.docView.posFromDOM(u.anchorNode,u.anchorOffset)!=t.from&&i.collapse(r,s)}moveToLine(e){let t=this.dom,i;if(e.node!=t)return e;for(let r=e.offset;!i&&r=0;r--){let s=he.get(t.childNodes[r]);s instanceof Ae&&(i=s.domAtPos(s.length))}return i?new Ze(i.node,i.offset,!0):e}nearest(e){for(let t=e;t;){let i=he.get(t);if(i&&i.rootView==this)return i;t=t.parentNode}return null}posFromDOM(e,t){let i=this.nearest(e);if(!i)throw new RangeError("Trying to find position for a DOM position outside of the document");return i.localPosFromDOM(e,t)+i.posAtStart}domAtPos(e){let{i:t,off:i}=this.childCursor().findPos(e,-1);for(;t=0;o--){let a=this.children[o],l=s-a.breakAfter,h=l-a.length;if(le||a.covers(1))&&(!i||a instanceof Ae&&!(i instanceof Ae&&t>=0))&&(i=a,r=h),s=h}return i?i.coordsAt(e-r,t):null}coordsForChar(e){let{i:t,off:i}=this.childPos(e,1),r=this.children[t];if(!(r instanceof Ae))return null;for(;r.children.length;){let{i:a,off:l}=r.childPos(i,1);for(;;a++){if(a==r.children.length)return null;if((r=r.children[a]).length)break}i=l}if(!(r instanceof Ln))return null;let s=We(r.text,i);if(s==i)return null;let o=qr(r.dom,i,s).getClientRects();for(let a=0;aMath.max(this.view.scrollDOM.clientWidth,this.minWidth)+1,a=-1,l=this.view.textDirection==ge.LTR;for(let h=0,c=0;cr)break;if(h>=i){let p=u.dom.getBoundingClientRect();if(t.push(p.height),o){let g=u.dom.lastChild,O=g?vo(g):[];if(O.length){let y=O[O.length-1],S=l?y.right-p.left:p.right-y.left;S>a&&(a=S,this.minWidth=s,this.minWidthFrom=h,this.minWidthTo=f)}}}h=f+u.breakAfter}return t}textDirectionAt(e){let{i:t}=this.childPos(e,1);return getComputedStyle(this.children[t].dom).direction=="rtl"?ge.RTL:ge.LTR}measureTextSize(){for(let s of this.children)if(s instanceof Ae){let o=s.measureTextSize();if(o)return o}let e=document.createElement("div"),t,i,r;return e.className="cm-line",e.style.width="99999px",e.style.position="absolute",e.textContent="abc def ghi jkl mno pqr stu",this.view.observer.ignore(()=>{this.dom.appendChild(e);let s=vo(e.firstChild)[0];t=e.getBoundingClientRect().height,i=s?s.width/27:7,r=s?s.height:t,e.remove()}),{lineHeight:t,charWidth:i,textHeight:r}}childCursor(e=this.length){let t=this.children.length;return t&&(e-=this.children[--t].length),new KO(this.children,e,t)}computeBlockGapDeco(){let e=[],t=this.view.viewState;for(let i=0,r=0;;r++){let s=r==t.viewports.length?null:t.viewports[r],o=s?s.from-1:this.length;if(o>i){let a=(t.lineBlockAt(o).bottom-t.lineBlockAt(i).top)/this.view.scaleY;e.push(Z.replace({widget:new up(a),block:!0,inclusive:!0,isBlockGap:!0}).range(i,o))}if(!s)break;i=s.to+1}return Z.set(e)}updateDeco(){let e=this.view.state.facet(xo).map((r,s)=>(this.dynamicDecorationMap[s]=typeof r=="function")?r(this.view):r),t=!1,i=this.view.state.facet(v0).map((r,s)=>{let o=typeof r=="function";return o&&(t=!0),o?r(this.view):r});i.length&&(this.dynamicDecorationMap[e.length]=t,e.push(J.join(i)));for(let r=e.length;rt.anchor?-1:1),r;if(!i)return;!t.empty&&(r=this.coordsAt(t.anchor,t.anchor>t.head?-1:1))&&(i={left:Math.min(i.left,r.left),top:Math.min(i.top,r.top),right:Math.max(i.right,r.right),bottom:Math.max(i.bottom,r.bottom)});let s=T0(this.view),o={left:i.left-s.left,top:i.top-s.top,right:i.right+s.right,bottom:i.bottom+s.bottom},{offsetWidth:a,offsetHeight:l}=this.view.scrollDOM;Fv(this.view.scrollDOM,o,t.head0)i=i.childNodes[r-1],r=Xn(i);else break}if(t>=0)for(let i=n,r=e;;){if(i.nodeType==3)return{node:i,offset:r};if(i.nodeType==1&&r=0)i=i.childNodes[r],r=0;else break}return null}function pk(n,e){return n.nodeType!=1?0:(e&&n.childNodes[e-1].contentEditable=="false"?1:0)|(e{ie.from&&(t=!0)}),t}function bk(n,e,t=1){let i=n.charCategorizer(e),r=n.doc.lineAt(e),s=e-r.from;if(r.length==0)return P.cursor(e);s==0?t=1:s==r.length&&(t=-1);let o=s,a=s;t<0?o=We(r.text,s,!1):a=We(r.text,s);let l=i(r.text.slice(o,a));for(;o>0;){let h=We(r.text,o,!1);if(i(r.text.slice(h,o))!=l)break;o=h}for(;an?e.left-n:Math.max(0,n-e.right)}function wk(n,e){return e.top>n?e.top-n:Math.max(0,n-e.bottom)}function qh(n,e){return n.tope.top+1}function fp(n,e){return en.bottom?{top:n.top,left:n.left,right:n.right,bottom:e}:n}function du(n,e,t){let i,r,s,o,a=!1,l,h,c,u;for(let g=n.firstChild;g;g=g.nextSibling){let O=vo(g);for(let y=0;y$||o==$&&s>k){i=g,r=S,s=k,o=$;let x=$?t0?y0)}k==0?t>S.bottom&&(!c||c.bottomS.top)&&(h=g,u=S):c&&qh(c,S)?c=dp(c,S.bottom):u&&qh(u,S)&&(u=fp(u,S.top))}}if(c&&c.bottom>=t?(i=l,r=c):u&&u.top<=t&&(i=h,r=u),!i)return{node:n,offset:0};let f=Math.max(r.left,Math.min(r.right,e));if(i.nodeType==3)return pp(i,f,t);if(a&&i.contentEditable!="false")return du(i,f,t);let p=Array.prototype.indexOf.call(n.childNodes,i)+(e>=(r.left+r.right)/2?1:0);return{node:n,offset:p}}function pp(n,e,t){let i=n.nodeValue.length,r=-1,s=1e9,o=0;for(let a=0;at?c.top-t:t-c.bottom)-1;if(c.left-1<=e&&c.right+1>=e&&u=(c.left+c.right)/2,p=f;if((q.chrome||q.gecko)&&qr(n,a).getBoundingClientRect().left==c.right&&(p=!f),u<=0)return{node:n,offset:a+(p?1:0)};r=a+(p?1:0),s=u}}}return{node:n,offset:r>-1?r:o>0?n.nodeValue.length:0}}function A0(n,e,t,i=-1){var r,s;let o=n.contentDOM.getBoundingClientRect(),a=o.top+n.viewState.paddingTop,l,{docHeight:h}=n.viewState,{x:c,y:u}=e,f=u-a;if(f<0)return 0;if(f>h)return n.state.doc.length;for(let x=n.viewState.heightOracle.textHeight/2,Q=!1;l=n.elementAtHeight(f),l.type!=Je.Text;)for(;f=i>0?l.bottom+x:l.top-x,!(f>=0&&f<=h);){if(Q)return t?null:0;Q=!0,i=-i}u=a+f;let p=l.from;if(pn.viewport.to)return n.viewport.to==n.state.doc.length?n.state.doc.length:t?null:gp(n,o,l,c,u);let g=n.dom.ownerDocument,O=n.root.elementFromPoint?n.root:g,y=O.elementFromPoint(c,u);y&&!n.contentDOM.contains(y)&&(y=null),y||(c=Math.max(o.left+1,Math.min(o.right-1,c)),y=O.elementFromPoint(c,u),y&&!n.contentDOM.contains(y)&&(y=null));let S,k=-1;if(y&&((r=n.docView.nearest(y))===null||r===void 0?void 0:r.isEditable)!=!1){if(g.caretPositionFromPoint){let x=g.caretPositionFromPoint(c,u);x&&({offsetNode:S,offset:k}=x)}else if(g.caretRangeFromPoint){let x=g.caretRangeFromPoint(c,u);x&&({startContainer:S,startOffset:k}=x,(!n.contentDOM.contains(S)||q.safari&&vk(S,k,c)||q.chrome&&kk(S,k,c))&&(S=void 0))}}if(!S||!n.docView.dom.contains(S)){let x=Ae.find(n.docView,p);if(!x)return f>l.top+l.height/2?l.to:l.from;({node:S,offset:k}=du(x.dom,c,u))}let $=n.docView.nearest(S);if(!$)return null;if($.isWidget&&((s=$.dom)===null||s===void 0?void 0:s.nodeType)==1){let x=$.dom.getBoundingClientRect();return e.yn.defaultLineHeight*1.5){let a=n.viewState.heightOracle.textHeight,l=Math.floor((r-t.top-(n.defaultLineHeight-a)*.5)/a);s+=l*n.viewState.heightOracle.lineLength}let o=n.state.sliceDoc(t.from,t.to);return t.from+Kc(o,s,n.state.tabSize)}function vk(n,e,t){let i;if(n.nodeType!=3||e!=(i=n.nodeValue.length))return!1;for(let r=n.nextSibling;r;r=r.nextSibling)if(r.nodeType!=1||r.nodeName!="BR")return!1;return qr(n,i-1,i).getBoundingClientRect().left>t}function kk(n,e,t){if(e!=0)return!1;for(let r=n;;){let s=r.parentNode;if(!s||s.nodeType!=1||s.firstChild!=r)return!1;if(s.classList.contains("cm-line"))break;r=s}let i=n.nodeType==1?n.getBoundingClientRect():qr(n,0,Math.max(n.nodeValue.length,1)).getBoundingClientRect();return t-i.left>5}function pu(n,e){let t=n.lineBlockAt(e);if(Array.isArray(t.type)){for(let i of t.type)if(i.to>e||i.to==e&&(i.to==t.to||i.type==Je.Text))return i}return t}function xk(n,e,t,i){let r=pu(n,e.head),s=!i||r.type!=Je.Text||!(n.lineWrapping||r.widgetLineBreaks)?null:n.coordsAtPos(e.assoc<0&&e.head>r.from?e.head-1:e.head);if(s){let o=n.dom.getBoundingClientRect(),a=n.textDirectionAt(r.from),l=n.posAtCoords({x:t==(a==ge.LTR)?o.right-1:o.left+1,y:(s.top+s.bottom)/2});if(l!=null)return P.cursor(l,t?-1:1)}return P.cursor(t?r.to:r.from,t?-1:1)}function mp(n,e,t,i){let r=n.state.doc.lineAt(e.head),s=n.bidiSpans(r),o=n.textDirectionAt(r.from);for(let a=e,l=null;;){let h=hk(r,s,o,a,t),c=f0;if(!h){if(r.number==(t?n.state.doc.lines:1))return a;c=` +`,r=n.state.doc.line(r.number+(t?1:-1)),s=n.bidiSpans(r),h=n.visualLineSide(r,!t)}if(l){if(!l(c))return a}else{if(!i)return h;l=i(c)}a=h}}function Tk(n,e,t){let i=n.state.charCategorizer(e),r=i(t);return s=>{let o=i(s);return r==fe.Space&&(r=o),r==o}}function Qk(n,e,t,i){let r=e.head,s=t?1:-1;if(r==(t?n.state.doc.length:0))return P.cursor(r,e.assoc);let o=e.goalColumn,a,l=n.contentDOM.getBoundingClientRect(),h=n.coordsAtPos(r,e.assoc||-1),c=n.documentTop;if(h)o==null&&(o=h.left-l.left),a=s<0?h.top:h.bottom;else{let p=n.viewState.lineBlockAt(r);o==null&&(o=Math.min(l.right-l.left,n.defaultCharacterWidth*(r-p.from))),a=(s<0?p.top:p.bottom)+c}let u=l.left+o,f=i??n.viewState.heightOracle.textHeight>>1;for(let p=0;;p+=10){let g=a+(f+p)*s,O=A0(n,{x:u,y:g},!1,s);if(gl.bottom||(s<0?Or)){let y=n.docView.coordsForChar(O),S=!y||g{if(e>s&&er(n)),t.from,e.head>t.from?-1:1);return i==t.from?t:P.cursor(i,inull),q.gecko&&Zk(e.contentDOM.ownerDocument)}handleEvent(e){!Nk(this.view,e)||this.ignoreDuringComposition(e)||e.type=="keydown"&&this.keydown(e)||this.runHandlers(e.type,e)}runHandlers(e,t){let i=this.handlers[e];if(i){for(let r of i.observers)r(this.view,t);for(let r of i.handlers){if(t.defaultPrevented)break;if(r(this.view,t)){t.preventDefault();break}}}}ensureHandlers(e){let t=Ak(e),i=this.handlers,r=this.view.contentDOM;for(let s in t)if(s!="scroll"){let o=!t[s].handlers.length,a=i[s];a&&o!=!a.handlers.length&&(r.removeEventListener(s,this.handleEvent),a=null),a||r.addEventListener(s,this.handleEvent,{passive:o})}for(let s in i)s!="scroll"&&!t[s]&&r.removeEventListener(s,this.handleEvent);this.handlers=t}keydown(e){if(this.lastKeyCode=e.keyCode,this.lastKeyTime=Date.now(),e.keyCode==9&&Date.now()i.keyCode==e.keyCode))&&!e.ctrlKey||$k.indexOf(e.key)>-1&&e.ctrlKey&&!e.shiftKey)?(this.pendingIOSKey=t||e,setTimeout(()=>this.flushIOSKey(),250),!0):(e.keyCode!=229&&this.view.observer.forceFlush(),!1)}flushIOSKey(){let e=this.pendingIOSKey;return e?(this.pendingIOSKey=void 0,ss(this.view.contentDOM,e.key,e.keyCode)):!1}ignoreDuringComposition(e){return/^key/.test(e.type)?this.composing>0?!0:q.safari&&!q.ios&&this.compositionPendingKey&&Date.now()-this.compositionEndedAt<100?(this.compositionPendingKey=!1,!0):!1:!1}startMouseSelection(e){this.mouseSelection&&this.mouseSelection.destroy(),this.mouseSelection=e}update(e){this.mouseSelection&&this.mouseSelection.update(e),this.draggedContent&&e.docChanged&&(this.draggedContent=this.draggedContent.map(e.changes)),e.transactions.length&&(this.lastKeyCode=this.lastSelectionTime=0)}destroy(){this.mouseSelection&&this.mouseSelection.destroy()}}function Op(n,e){return(t,i)=>{try{return e.call(n,i,t)}catch(r){mt(t.state,r)}}}function Ak(n){let e=Object.create(null);function t(i){return e[i]||(e[i]={observers:[],handlers:[]})}for(let i of n){let r=i.spec;if(r&&r.domEventHandlers)for(let s in r.domEventHandlers){let o=r.domEventHandlers[s];o&&t(s).handlers.push(Op(i.value,o))}if(r&&r.domEventObservers)for(let s in r.domEventObservers){let o=r.domEventObservers[s];o&&t(s).observers.push(Op(i.value,o))}}for(let i in Ht)t(i).handlers.push(Ht[i]);for(let i in Kt)t(i).observers.push(Kt[i]);return e}const $0=[{key:"Backspace",keyCode:8,inputType:"deleteContentBackward"},{key:"Enter",keyCode:13,inputType:"insertParagraph"},{key:"Enter",keyCode:13,inputType:"insertLineBreak"},{key:"Delete",keyCode:46,inputType:"deleteContentForward"}],$k="dthko",C0=[16,17,18,20,91,92,224,225],ha=6;function ca(n){return Math.max(0,n)*.7+8}function Ck(n,e){return Math.max(Math.abs(n.clientX-e.clientX),Math.abs(n.clientY-e.clientY))}class Ik{constructor(e,t,i,r){this.view=e,this.startEvent=t,this.style=i,this.mustSelect=r,this.scrollSpeed={x:0,y:0},this.scrolling=-1,this.lastEvent=t,this.scrollParent=zv(e.contentDOM),this.atoms=e.state.facet(bf).map(o=>o(e));let s=e.contentDOM.ownerDocument;s.addEventListener("mousemove",this.move=this.move.bind(this)),s.addEventListener("mouseup",this.up=this.up.bind(this)),this.extend=t.shiftKey,this.multiple=e.state.facet(H.allowMultipleSelections)&&Rk(e,t),this.dragging=Dk(e,t)&&D0(t)==1?null:!1}start(e){this.dragging===!1&&this.select(e)}move(e){var t;if(e.buttons==0)return this.destroy();if(this.dragging||this.dragging==null&&Ck(this.startEvent,e)<10)return;this.select(this.lastEvent=e);let i=0,r=0,s=((t=this.scrollParent)===null||t===void 0?void 0:t.getBoundingClientRect())||{left:0,top:0,right:this.view.win.innerWidth,bottom:this.view.win.innerHeight},o=T0(this.view);e.clientX-o.left<=s.left+ha?i=-ca(s.left-e.clientX):e.clientX+o.right>=s.right-ha&&(i=ca(e.clientX-s.right)),e.clientY-o.top<=s.top+ha?r=-ca(s.top-e.clientY):e.clientY+o.bottom>=s.bottom-ha&&(r=ca(e.clientY-s.bottom)),this.setScrollSpeed(i,r)}up(e){this.dragging==null&&this.select(this.lastEvent),this.dragging||e.preventDefault(),this.destroy()}destroy(){this.setScrollSpeed(0,0);let e=this.view.contentDOM.ownerDocument;e.removeEventListener("mousemove",this.move),e.removeEventListener("mouseup",this.up),this.view.inputState.mouseSelection=this.view.inputState.draggedContent=null}setScrollSpeed(e,t){this.scrollSpeed={x:e,y:t},e||t?this.scrolling<0&&(this.scrolling=setInterval(()=>this.scroll(),50)):this.scrolling>-1&&(clearInterval(this.scrolling),this.scrolling=-1)}scroll(){this.scrollParent?(this.scrollParent.scrollLeft+=this.scrollSpeed.x,this.scrollParent.scrollTop+=this.scrollSpeed.y):this.view.win.scrollBy(this.scrollSpeed.x,this.scrollSpeed.y),this.dragging===!1&&this.select(this.lastEvent)}skipAtoms(e){let t=null;for(let i=0;ithis.select(this.lastEvent),20)}}function Rk(n,e){let t=n.state.facet(d0);return t.length?t[0](e):q.mac?e.metaKey:e.ctrlKey}function Ek(n,e){let t=n.state.facet(p0);return t.length?t[0](e):q.mac?!e.altKey:!e.ctrlKey}function Dk(n,e){let{main:t}=n.state.selection;if(t.empty)return!1;let i=xl(n.root);if(!i||i.rangeCount==0)return!0;let r=i.getRangeAt(0).getClientRects();for(let s=0;s=e.clientX&&o.top<=e.clientY&&o.bottom>=e.clientY)return!0}return!1}function Nk(n,e){if(!e.bubbles)return!0;if(e.defaultPrevented)return!1;for(let t=e.target,i;t!=n.contentDOM;t=t.parentNode)if(!t||t.nodeType==11||(i=he.get(t))&&i.ignoreEvent(e))return!1;return!0}const Ht=Object.create(null),Kt=Object.create(null),I0=q.ie&&q.ie_version<15||q.ios&&q.webkit_version<604;function Bk(n){let e=n.dom.parentNode;if(!e)return;let t=e.appendChild(document.createElement("textarea"));t.style.cssText="position: fixed; left: -10000px; top: 10px",t.focus(),setTimeout(()=>{n.focus(),t.remove(),R0(n,t.value)},50)}function R0(n,e){let{state:t}=n,i,r=1,s=t.toText(e),o=s.lines==t.selection.ranges.length;if(gu!=null&&t.selection.ranges.every(l=>l.empty)&&gu==s.toString()){let l=-1;i=t.changeByRange(h=>{let c=t.doc.lineAt(h.from);if(c.from==l)return{range:h};l=c.from;let u=t.toText((o?s.line(r++).text:e)+t.lineBreak);return{changes:{from:c.from,insert:u},range:P.cursor(h.from+u.length)}})}else o?i=t.changeByRange(l=>{let h=s.line(r++);return{changes:{from:l.from,to:l.to,insert:h.text},range:P.cursor(l.from+h.length)}}):i=t.replaceSelection(s);n.dispatch(i,{userEvent:"input.paste",scrollIntoView:!0})}Kt.scroll=n=>{n.inputState.lastScrollTop=n.scrollDOM.scrollTop,n.inputState.lastScrollLeft=n.scrollDOM.scrollLeft};Ht.keydown=(n,e)=>(n.inputState.setSelectionOrigin("select"),e.keyCode==27&&(n.inputState.lastEscPress=Date.now()),!1);Kt.touchstart=(n,e)=>{n.inputState.lastTouchTime=Date.now(),n.inputState.setSelectionOrigin("select.pointer")};Kt.touchmove=n=>{n.inputState.setSelectionOrigin("select.pointer")};Ht.mousedown=(n,e)=>{if(n.observer.flush(),n.inputState.lastTouchTime>Date.now()-2e3)return!1;let t=null;for(let i of n.state.facet(g0))if(t=i(n,e),t)break;if(!t&&e.button==0&&(t=Vk(n,e)),t){let i=!n.hasFocus;n.inputState.startMouseSelection(new Ik(n,e,t,i)),i&&n.observer.ignore(()=>JO(n.contentDOM));let r=n.inputState.mouseSelection;if(r)return r.start(e),r.dragging===!1}return!1};function yp(n,e,t,i){if(i==1)return P.cursor(e,t);if(i==2)return bk(n.state,e,t);{let r=Ae.find(n.docView,e),s=n.state.doc.lineAt(r?r.posAtEnd:e),o=r?r.posAtStart:s.from,a=r?r.posAtEnd:s.to;return an>=e.top&&n<=e.bottom,bp=(n,e,t)=>E0(e,t)&&n>=t.left&&n<=t.right;function qk(n,e,t,i){let r=Ae.find(n.docView,e);if(!r)return 1;let s=e-r.posAtStart;if(s==0)return 1;if(s==r.length)return-1;let o=r.coordsAt(s,-1);if(o&&bp(t,i,o))return-1;let a=r.coordsAt(s,1);return a&&bp(t,i,a)?1:o&&E0(i,o)?-1:1}function Sp(n,e){let t=n.posAtCoords({x:e.clientX,y:e.clientY},!1);return{pos:t,bias:qk(n,t,e.clientX,e.clientY)}}const Mk=q.ie&&q.ie_version<=11;let wp=null,vp=0,kp=0;function D0(n){if(!Mk)return n.detail;let e=wp,t=kp;return wp=n,kp=Date.now(),vp=!e||t>Date.now()-400&&Math.abs(e.clientX-n.clientX)<2&&Math.abs(e.clientY-n.clientY)<2?(vp+1)%3:1}function Vk(n,e){let t=Sp(n,e),i=D0(e),r=n.state.selection;return{update(s){s.docChanged&&(t.pos=s.changes.mapPos(t.pos),r=r.map(s.changes))},get(s,o,a){let l=Sp(n,s),h,c=yp(n,l.pos,l.bias,i);if(t.pos!=l.pos&&!o){let u=yp(n,t.pos,t.bias,i),f=Math.min(u.from,c.from),p=Math.max(u.to,c.to);c=f1&&(h=Xk(r,l.pos))?h:a?r.addRange(c):P.create([c])}}}function Xk(n,e){for(let t=0;t=e)return P.create(n.ranges.slice(0,t).concat(n.ranges.slice(t+1)),n.mainIndex==t?0:n.mainIndex-(n.mainIndex>t?1:0))}return null}Ht.dragstart=(n,e)=>{let{selection:{main:t}}=n.state;if(e.target.draggable){let r=n.docView.nearest(e.target);if(r&&r.isWidget){let s=r.posAtStart,o=s+r.length;(s>=t.to||o<=t.from)&&(t=P.range(s,o))}}let{inputState:i}=n;return i.mouseSelection&&(i.mouseSelection.dragging=!0),i.draggedContent=t,e.dataTransfer&&(e.dataTransfer.setData("Text",n.state.sliceDoc(t.from,t.to)),e.dataTransfer.effectAllowed="copyMove"),!1};Ht.dragend=n=>(n.inputState.draggedContent=null,!1);function xp(n,e,t,i){if(!t)return;let r=n.posAtCoords({x:e.clientX,y:e.clientY},!1),{draggedContent:s}=n.inputState,o=i&&s&&Ek(n,e)?{from:s.from,to:s.to}:null,a={from:r,insert:t},l=n.state.changes(o?[o,a]:a);n.focus(),n.dispatch({changes:l,selection:{anchor:l.mapPos(r,-1),head:l.mapPos(r,1)},userEvent:o?"move.drop":"input.drop"}),n.inputState.draggedContent=null}Ht.drop=(n,e)=>{if(!e.dataTransfer)return!1;if(n.state.readOnly)return!0;let t=e.dataTransfer.files;if(t&&t.length){let i=Array(t.length),r=0,s=()=>{++r==t.length&&xp(n,e,i.filter(o=>o!=null).join(n.state.lineBreak),!1)};for(let o=0;o{/[\x00-\x08\x0e-\x1f]{2}/.test(a.result)||(i[o]=a.result),s()},a.readAsText(t[o])}return!0}else{let i=e.dataTransfer.getData("Text");if(i)return xp(n,e,i,!0),!0}return!1};Ht.paste=(n,e)=>{if(n.state.readOnly)return!0;n.observer.flush();let t=I0?null:e.clipboardData;return t?(R0(n,t.getData("text/plain")||t.getData("text/uri-text")),!0):(Bk(n),!1)};function Lk(n,e){let t=n.dom.parentNode;if(!t)return;let i=t.appendChild(document.createElement("textarea"));i.style.cssText="position: fixed; left: -10000px; top: 10px",i.value=e,i.focus(),i.selectionEnd=e.length,i.selectionStart=0,setTimeout(()=>{i.remove(),n.focus()},50)}function Uk(n){let e=[],t=[],i=!1;for(let r of n.selection.ranges)r.empty||(e.push(n.sliceDoc(r.from,r.to)),t.push(r));if(!e.length){let r=-1;for(let{from:s}of n.selection.ranges){let o=n.doc.lineAt(s);o.number>r&&(e.push(o.text),t.push({from:o.from,to:Math.min(n.doc.length,o.to+1)})),r=o.number}i=!0}return{text:e.join(n.lineBreak),ranges:t,linewise:i}}let gu=null;Ht.copy=Ht.cut=(n,e)=>{let{text:t,ranges:i,linewise:r}=Uk(n.state);if(!t&&!r)return!1;gu=r?t:null,e.type=="cut"&&!n.state.readOnly&&n.dispatch({changes:i,scrollIntoView:!0,userEvent:"delete.cut"});let s=I0?null:e.clipboardData;return s?(s.clearData(),s.setData("text/plain",t),!0):(Lk(n,t),!1)};const N0=jn.define();function B0(n,e){let t=[];for(let i of n.facet(y0)){let r=i(n,e);r&&t.push(r)}return t?n.update({effects:t,annotations:N0.of(!0)}):null}function q0(n){setTimeout(()=>{let e=n.hasFocus;if(e!=n.inputState.notifiedFocused){let t=B0(n.state,e);t?n.dispatch(t):n.update([])}},10)}Kt.focus=n=>{n.inputState.lastFocusTime=Date.now(),!n.scrollDOM.scrollTop&&(n.inputState.lastScrollTop||n.inputState.lastScrollLeft)&&(n.scrollDOM.scrollTop=n.inputState.lastScrollTop,n.scrollDOM.scrollLeft=n.inputState.lastScrollLeft),q0(n)};Kt.blur=n=>{n.observer.clearSelectionRange(),q0(n)};Kt.compositionstart=Kt.compositionupdate=n=>{n.inputState.compositionFirstChange==null&&(n.inputState.compositionFirstChange=!0),n.inputState.composing<0&&(n.inputState.composing=0)};Kt.compositionend=n=>{n.inputState.composing=-1,n.inputState.compositionEndedAt=Date.now(),n.inputState.compositionPendingKey=!0,n.inputState.compositionPendingChange=n.observer.pendingRecords().length>0,n.inputState.compositionFirstChange=null,q.chrome&&q.android?n.observer.flushSoon():n.inputState.compositionPendingChange?Promise.resolve().then(()=>n.observer.flush()):setTimeout(()=>{n.inputState.composing<0&&n.docView.hasComposition&&n.update([])},50)};Kt.contextmenu=n=>{n.inputState.lastContextMenu=Date.now()};Ht.beforeinput=(n,e)=>{var t;let i;if(q.chrome&&q.android&&(i=$0.find(r=>r.inputType==e.inputType))&&(n.observer.delayAndroidKey(i.key,i.keyCode),i.key=="Backspace"||i.key=="Delete")){let r=((t=window.visualViewport)===null||t===void 0?void 0:t.height)||0;setTimeout(()=>{var s;(((s=window.visualViewport)===null||s===void 0?void 0:s.height)||0)>r+10&&n.hasFocus&&(n.contentDOM.blur(),n.focus())},100)}return!1};const Tp=new Set;function Zk(n){Tp.has(n)||(Tp.add(n),n.addEventListener("copy",()=>{}),n.addEventListener("cut",()=>{}))}const Qp=["pre-wrap","normal","pre-line","break-spaces"];class Wk{constructor(e){this.lineWrapping=e,this.doc=K.empty,this.heightSamples={},this.lineHeight=14,this.charWidth=7,this.textHeight=14,this.lineLength=30,this.heightChanged=!1}heightForGap(e,t){let i=this.doc.lineAt(t).number-this.doc.lineAt(e).number+1;return this.lineWrapping&&(i+=Math.max(0,Math.ceil((t-e-i*this.lineLength*.5)/this.lineLength))),this.lineHeight*i}heightForLine(e){return this.lineWrapping?(1+Math.max(0,Math.ceil((e-this.lineLength)/(this.lineLength-5))))*this.lineHeight:this.lineHeight}setDoc(e){return this.doc=e,this}mustRefreshForWrapping(e){return Qp.indexOf(e)>-1!=this.lineWrapping}mustRefreshForHeights(e){let t=!1;for(let i=0;i-1,l=Math.round(t)!=Math.round(this.lineHeight)||this.lineWrapping!=a;if(this.lineWrapping=a,this.lineHeight=t,this.charWidth=i,this.textHeight=r,this.lineLength=s,l){this.heightSamples={};for(let h=0;h0}set outdated(e){this.flags=(e?2:0)|this.flags&-3}setHeight(e,t){this.height!=t&&(Math.abs(this.height-t)>Za&&(e.heightChanged=!0),this.height=t)}replace(e,t,i){return Ye.of(i)}decomposeLeft(e,t){t.push(this)}decomposeRight(e,t){t.push(this)}applyChanges(e,t,i,r){let s=this,o=i.doc;for(let a=r.length-1;a>=0;a--){let{fromA:l,toA:h,fromB:c,toB:u}=r[a],f=s.lineAt(l,le.ByPosNoHeight,i.setDoc(t),0,0),p=f.to>=h?f:s.lineAt(h,le.ByPosNoHeight,i,0,0);for(u+=p.to-h,h=p.to;a>0&&f.from<=r[a-1].toA;)l=r[a-1].fromA,c=r[a-1].fromB,a--,ls*2){let a=e[t-1];a.break?e.splice(--t,1,a.left,null,a.right):e.splice(--t,1,a.left,a.right),i+=1+a.break,r-=a.size}else if(s>r*2){let a=e[i];a.break?e.splice(i,1,a.left,null,a.right):e.splice(i,1,a.left,a.right),i+=2+a.break,s-=a.size}else break;else if(r=s&&o(this.blockAt(0,i,r,s))}updateHeight(e,t=0,i=!1,r){return r&&r.from<=t&&r.more&&this.setHeight(e,r.heights[r.index++]),this.outdated=!1,this}toString(){return`block(${this.length})`}}class at extends M0{constructor(e,t){super(e,t,null),this.collapsed=0,this.widgetHeight=0,this.breaks=0}blockAt(e,t,i,r){return new fi(r,this.length,i,this.height,this.breaks)}replace(e,t,i){let r=i[0];return i.length==1&&(r instanceof at||r instanceof De&&r.flags&4)&&Math.abs(this.length-r.length)<10?(r instanceof De?r=new at(r.length,this.height):r.height=this.height,this.outdated||(r.outdated=!1),r):Ye.of(i)}updateHeight(e,t=0,i=!1,r){return r&&r.from<=t&&r.more?this.setHeight(e,r.heights[r.index++]):(i||this.outdated)&&this.setHeight(e,Math.max(this.widgetHeight,e.heightForLine(this.length-this.collapsed))+this.breaks*e.lineHeight),this.outdated=!1,this}toString(){return`line(${this.length}${this.collapsed?-this.collapsed:""}${this.widgetHeight?":"+this.widgetHeight:""})`}}class De extends Ye{constructor(e){super(e,0)}heightMetrics(e,t){let i=e.doc.lineAt(t).number,r=e.doc.lineAt(t+this.length).number,s=r-i+1,o,a=0;if(e.lineWrapping){let l=Math.min(this.height,e.lineHeight*s);o=l/s,this.length>s+1&&(a=(this.height-l)/(this.length-s-1))}else o=this.height/s;return{firstLine:i,lastLine:r,perLine:o,perChar:a}}blockAt(e,t,i,r){let{firstLine:s,lastLine:o,perLine:a,perChar:l}=this.heightMetrics(t,r);if(t.lineWrapping){let h=r+Math.round(Math.max(0,Math.min(1,(e-i)/this.height))*this.length),c=t.doc.lineAt(h),u=a+c.length*l,f=Math.max(i,e-u/2);return new fi(c.from,c.length,f,u,0)}else{let h=Math.max(0,Math.min(o-s,Math.floor((e-i)/a))),{from:c,length:u}=t.doc.line(s+h);return new fi(c,u,i+a*h,a,0)}}lineAt(e,t,i,r,s){if(t==le.ByHeight)return this.blockAt(e,i,r,s);if(t==le.ByPosNoHeight){let{from:p,to:g}=i.doc.lineAt(e);return new fi(p,g-p,0,0,0)}let{firstLine:o,perLine:a,perChar:l}=this.heightMetrics(i,s),h=i.doc.lineAt(e),c=a+h.length*l,u=h.number-o,f=r+a*u+l*(h.from-s-u);return new fi(h.from,h.length,Math.max(r,Math.min(f,r+this.height-c)),c,0)}forEachLine(e,t,i,r,s,o){e=Math.max(e,s),t=Math.min(t,s+this.length);let{firstLine:a,perLine:l,perChar:h}=this.heightMetrics(i,s);for(let c=e,u=r;c<=t;){let f=i.doc.lineAt(c);if(c==e){let g=f.number-a;u+=l*g+h*(e-s-g)}let p=l+h*f.length;o(new fi(f.from,f.length,u,p,0)),u+=p,c=f.to+1}}replace(e,t,i){let r=this.length-t;if(r>0){let s=i[i.length-1];s instanceof De?i[i.length-1]=new De(s.length+r):i.push(null,new De(r-1))}if(e>0){let s=i[0];s instanceof De?i[0]=new De(e+s.length):i.unshift(new De(e-1),null)}return Ye.of(i)}decomposeLeft(e,t){t.push(new De(e-1),null)}decomposeRight(e,t){t.push(null,new De(this.length-e-1))}updateHeight(e,t=0,i=!1,r){let s=t+this.length;if(r&&r.from<=t+this.length&&r.more){let o=[],a=Math.max(t,r.from),l=-1;for(r.from>t&&o.push(new De(r.from-t-1).updateHeight(e,t));a<=s&&r.more;){let c=e.doc.lineAt(a).length;o.length&&o.push(null);let u=r.heights[r.index++];l==-1?l=u:Math.abs(u-l)>=Za&&(l=-2);let f=new at(c,u);f.outdated=!1,o.push(f),a+=c+1}a<=s&&o.push(null,new De(s-a).updateHeight(e,a));let h=Ye.of(o);return(l<0||Math.abs(h.height-this.height)>=Za||Math.abs(l-this.heightMetrics(e,t).perLine)>=Za)&&(e.heightChanged=!0),h}else(i||this.outdated)&&(this.setHeight(e,e.heightForGap(t,t+this.length)),this.outdated=!1);return this}toString(){return`gap(${this.length})`}}class Fk extends Ye{constructor(e,t,i){super(e.length+t+i.length,e.height+i.height,t|(e.outdated||i.outdated?2:0)),this.left=e,this.right=i,this.size=e.size+i.size}get break(){return this.flags&1}blockAt(e,t,i,r){let s=i+this.left.height;return ea))return h;let c=t==le.ByPosNoHeight?le.ByPosNoHeight:le.ByPos;return l?h.join(this.right.lineAt(a,c,i,o,a)):this.left.lineAt(a,c,i,r,s).join(h)}forEachLine(e,t,i,r,s,o){let a=r+this.left.height,l=s+this.left.length+this.break;if(this.break)e=l&&this.right.forEachLine(e,t,i,a,l,o);else{let h=this.lineAt(l,le.ByPos,i,r,s);e=e&&h.from<=t&&o(h),t>h.to&&this.right.forEachLine(h.to+1,t,i,a,l,o)}}replace(e,t,i){let r=this.left.length+this.break;if(tthis.left.length)return this.balanced(this.left,this.right.replace(e-r,t-r,i));let s=[];e>0&&this.decomposeLeft(e,s);let o=s.length;for(let a of i)s.push(a);if(e>0&&Pp(s,o-1),t=i&&t.push(null)),e>i&&this.right.decomposeLeft(e-i,t)}decomposeRight(e,t){let i=this.left.length,r=i+this.break;if(e>=r)return this.right.decomposeRight(e-r,t);e2*t.size||t.size>2*e.size?Ye.of(this.break?[e,null,t]:[e,t]):(this.left=e,this.right=t,this.height=e.height+t.height,this.outdated=e.outdated||t.outdated,this.size=e.size+t.size,this.length=e.length+this.break+t.length,this)}updateHeight(e,t=0,i=!1,r){let{left:s,right:o}=this,a=t+s.length+this.break,l=null;return r&&r.from<=t+s.length&&r.more?l=s=s.updateHeight(e,t,i,r):s.updateHeight(e,t,i),r&&r.from<=a+o.length&&r.more?l=o=o.updateHeight(e,a,i,r):o.updateHeight(e,a,i),l?this.balanced(s,o):(this.height=this.left.height+this.right.height,this.outdated=!1,this)}toString(){return this.left+(this.break?" ":"-")+this.right}}function Pp(n,e){let t,i;n[e]==null&&(t=n[e-1])instanceof De&&(i=n[e+1])instanceof De&&n.splice(e-1,3,new De(t.length+1+i.length))}const zk=5;class Sf{constructor(e,t){this.pos=e,this.oracle=t,this.nodes=[],this.lineStart=-1,this.lineEnd=-1,this.covering=null,this.writtenTo=e}get isCovered(){return this.covering&&this.nodes[this.nodes.length-1]==this.covering}span(e,t){if(this.lineStart>-1){let i=Math.min(t,this.lineEnd),r=this.nodes[this.nodes.length-1];r instanceof at?r.length+=i-this.pos:(i>this.pos||!this.isCovered)&&this.nodes.push(new at(i-this.pos,-1)),this.writtenTo=i,t>i&&(this.nodes.push(null),this.writtenTo++,this.lineStart=-1)}this.pos=t}point(e,t,i){if(e=zk)&&this.addLineDeco(r,s,o)}else t>e&&this.span(e,t);this.lineEnd>-1&&this.lineEnd-1)return;let{from:e,to:t}=this.oracle.doc.lineAt(this.pos);this.lineStart=e,this.lineEnd=t,this.writtenToe&&this.nodes.push(new at(this.pos-e,-1)),this.writtenTo=this.pos}blankContent(e,t){let i=new De(t-e);return this.oracle.doc.lineAt(e).to==t&&(i.flags|=4),i}ensureLine(){this.enterLine();let e=this.nodes.length?this.nodes[this.nodes.length-1]:null;if(e instanceof at)return e;let t=new at(0,-1);return this.nodes.push(t),t}addBlock(e){this.enterLine();let t=e.deco;t&&t.startSide>0&&!this.isCovered&&this.ensureLine(),this.nodes.push(e),this.writtenTo=this.pos=this.pos+e.length,t&&t.endSide>0&&(this.covering=e)}addLineDeco(e,t,i){let r=this.ensureLine();r.length+=i,r.collapsed+=i,r.widgetHeight=Math.max(r.widgetHeight,e),r.breaks+=t,this.writtenTo=this.pos=this.pos+i}finish(e){let t=this.nodes.length==0?null:this.nodes[this.nodes.length-1];this.lineStart>-1&&!(t instanceof at)&&!this.isCovered?this.nodes.push(new at(0,-1)):(this.writtenToc.clientHeight||c.scrollWidth>c.clientWidth)&&u.overflow!="visible"){let f=c.getBoundingClientRect();s=Math.max(s,f.left),o=Math.min(o,f.right),a=Math.max(a,f.top),l=h==n.parentNode?f.bottom:Math.min(l,f.bottom)}h=u.position=="absolute"||u.position=="fixed"?c.offsetParent:c.parentNode}else if(h.nodeType==11)h=h.host;else break;return{left:s-t.left,right:Math.max(s,o)-t.left,top:a-(t.top+e),bottom:Math.max(a,l)-(t.top+e)}}function Yk(n,e){let t=n.getBoundingClientRect();return{left:0,right:t.right-t.left,top:e,bottom:t.bottom-(t.top+e)}}class Vh{constructor(e,t,i){this.from=e,this.to=t,this.size=i}static same(e,t){if(e.length!=t.length)return!1;for(let i=0;itypeof i!="function"&&i.class=="cm-lineWrapping");this.heightOracle=new Wk(t),this.stateDeco=e.facet(xo).filter(i=>typeof i!="function"),this.heightMap=Ye.empty().applyChanges(this.stateDeco,K.empty,this.heightOracle.setDoc(e.doc),[new Nt(0,0,0,e.doc.length)]),this.viewport=this.getViewport(0,null),this.updateViewportLines(),this.updateForViewport(),this.lineGaps=this.ensureLineGaps([]),this.lineGapDeco=Z.set(this.lineGaps.map(i=>i.draw(this,!1))),this.computeVisibleRanges()}updateForViewport(){let e=[this.viewport],{main:t}=this.state.selection;for(let i=0;i<=1;i++){let r=i?t.head:t.anchor;if(!e.some(({from:s,to:o})=>r>=s&&r<=o)){let{from:s,to:o}=this.lineBlockAt(r);e.push(new ua(s,o))}}this.viewports=e.sort((i,r)=>i.from-r.from),this.scaler=this.heightMap.height<=7e6?$p:new tx(this.heightOracle,this.heightMap,this.viewports)}updateViewportLines(){this.viewportLines=[],this.heightMap.forEachLine(this.viewport.from,this.viewport.to,this.heightOracle.setDoc(this.state.doc),0,0,e=>{this.viewportLines.push(this.scaler.scale==1?e:Fs(e,this.scaler))})}update(e,t=null){this.state=e.state;let i=this.stateDeco;this.stateDeco=this.state.facet(xo).filter(c=>typeof c!="function");let r=e.changedRanges,s=Nt.extendWithRanges(r,_k(i,this.stateDeco,e?e.changes:Ce.empty(this.state.doc.length))),o=this.heightMap.height,a=this.scrolledToBottom?null:this.scrollAnchorAt(this.scrollTop);this.heightMap=this.heightMap.applyChanges(this.stateDeco,e.startState.doc,this.heightOracle.setDoc(this.state.doc),s),this.heightMap.height!=o&&(e.flags|=2),a?(this.scrollAnchorPos=e.changes.mapPos(a.from,-1),this.scrollAnchorHeight=a.top):(this.scrollAnchorPos=-1,this.scrollAnchorHeight=this.heightMap.height);let l=s.length?this.mapViewport(this.viewport,e.changes):this.viewport;(t&&(t.range.headl.to)||!this.viewportIsAppropriate(l))&&(l=this.getViewport(0,t));let h=!e.changes.empty||e.flags&2||l.from!=this.viewport.from||l.to!=this.viewport.to;this.viewport=l,this.updateForViewport(),h&&this.updateViewportLines(),(this.lineGaps.length||this.viewport.to-this.viewport.from>4e3)&&this.updateLineGaps(this.ensureLineGaps(this.mapLineGaps(this.lineGaps,e.changes))),e.flags|=this.computeVisibleRanges(),t&&(this.scrollTarget=t),!this.mustEnforceCursorAssoc&&e.selectionSet&&e.view.lineWrapping&&e.state.selection.main.empty&&e.state.selection.main.assoc&&!e.state.facet(S0)&&(this.mustEnforceCursorAssoc=!0)}measure(e){let t=e.contentDOM,i=window.getComputedStyle(t),r=this.heightOracle,s=i.whiteSpace;this.defaultTextDirection=i.direction=="rtl"?ge.RTL:ge.LTR;let o=this.heightOracle.mustRefreshForWrapping(s),a=t.getBoundingClientRect(),l=o||this.mustMeasureContent||this.contentDOMHeight!=a.height;this.contentDOMHeight=a.height,this.mustMeasureContent=!1;let h=0,c=0;if(a.width&&a.height){let{scaleX:x,scaleY:Q}=GO(t,a);(this.scaleX!=x||this.scaleY!=Q)&&(this.scaleX=x,this.scaleY=Q,h|=8,o=l=!0)}let u=(parseInt(i.paddingTop)||0)*this.scaleY,f=(parseInt(i.paddingBottom)||0)*this.scaleY;(this.paddingTop!=u||this.paddingBottom!=f)&&(this.paddingTop=u,this.paddingBottom=f,h|=10),this.editorWidth!=e.scrollDOM.clientWidth&&(r.lineWrapping&&(l=!0),this.editorWidth=e.scrollDOM.clientWidth,h|=8);let p=e.scrollDOM.scrollTop*this.scaleY;this.scrollTop!=p&&(this.scrollAnchorHeight=-1,this.scrollTop=p),this.scrolledToBottom=HO(e.scrollDOM);let g=(this.printing?Yk:Jk)(t,this.paddingTop),O=g.top-this.pixelViewport.top,y=g.bottom-this.pixelViewport.bottom;this.pixelViewport=g;let S=this.pixelViewport.bottom>this.pixelViewport.top&&this.pixelViewport.right>this.pixelViewport.left;if(S!=this.inView&&(this.inView=S,S&&(l=!0)),!this.inView&&!this.scrollTarget)return 0;let k=a.width;if((this.contentDOMWidth!=k||this.editorHeight!=e.scrollDOM.clientHeight)&&(this.contentDOMWidth=a.width,this.editorHeight=e.scrollDOM.clientHeight,h|=8),l){let x=e.docView.measureVisibleLineHeights(this.viewport);if(r.mustRefreshForHeights(x)&&(o=!0),o||r.lineWrapping&&Math.abs(k-this.contentDOMWidth)>r.charWidth){let{lineHeight:Q,charWidth:A,textHeight:R}=e.docView.measureTextSize();o=Q>0&&r.refresh(s,Q,A,R,k/A,x),o&&(e.docView.minWidth=0,h|=8)}O>0&&y>0?c=Math.max(O,y):O<0&&y<0&&(c=Math.min(O,y)),r.heightChanged=!1;for(let Q of this.viewports){let A=Q.from==this.viewport.from?x:e.docView.measureVisibleLineHeights(Q);this.heightMap=(o?Ye.empty().applyChanges(this.stateDeco,K.empty,this.heightOracle,[new Nt(0,0,0,e.state.doc.length)]):this.heightMap).updateHeight(r,0,o,new jk(Q.from,A))}r.heightChanged&&(h|=2)}let $=!this.viewportIsAppropriate(this.viewport,c)||this.scrollTarget&&(this.scrollTarget.range.headthis.viewport.to);return $&&(this.viewport=this.getViewport(c,this.scrollTarget)),this.updateForViewport(),(h&2||$)&&this.updateViewportLines(),(this.lineGaps.length||this.viewport.to-this.viewport.from>4e3)&&this.updateLineGaps(this.ensureLineGaps(o?[]:this.lineGaps,e)),h|=this.computeVisibleRanges(),this.mustEnforceCursorAssoc&&(this.mustEnforceCursorAssoc=!1,e.docView.enforceCursorAssoc()),h}get visibleTop(){return this.scaler.fromDOM(this.pixelViewport.top)}get visibleBottom(){return this.scaler.fromDOM(this.pixelViewport.bottom)}getViewport(e,t){let i=.5-Math.max(-.5,Math.min(.5,e/1e3/2)),r=this.heightMap,s=this.heightOracle,{visibleTop:o,visibleBottom:a}=this,l=new ua(r.lineAt(o-i*1e3,le.ByHeight,s,0,0).from,r.lineAt(a+(1-i)*1e3,le.ByHeight,s,0,0).to);if(t){let{head:h}=t.range;if(hl.to){let c=Math.min(this.editorHeight,this.pixelViewport.bottom-this.pixelViewport.top),u=r.lineAt(h,le.ByPos,s,0,0),f;t.y=="center"?f=(u.top+u.bottom)/2-c/2:t.y=="start"||t.y=="nearest"&&h=a+Math.max(10,Math.min(i,250)))&&r>o-2*1e3&&s>1,o=r<<1;if(this.defaultTextDirection!=ge.LTR&&!i)return[];let a=[],l=(h,c,u,f)=>{if(c-hh&&yy.from>=u.from&&y.to<=u.to&&Math.abs(y.from-h)y.fromS));if(!O){if(cy.from<=c&&y.to>=c)){let y=t.moveToLineBoundary(P.cursor(c),!1,!0).head;y>h&&(c=y)}O=new Vh(h,c,this.gapSize(u,h,c,f))}a.push(O)};for(let h of this.viewportLines){if(h.lengthh.from&&l(h.from,f,h,c),pt.draw(this,this.heightOracle.lineWrapping))))}computeVisibleRanges(){let e=this.stateDeco;this.lineGaps.length&&(e=e.concat(this.lineGapDeco));let t=[];J.spans(e,this.viewport.from,this.viewport.to,{span(r,s){t.push({from:r,to:s})},point(){}},20);let i=t.length!=this.visibleRanges.length||this.visibleRanges.some((r,s)=>r.from!=t[s].from||r.to!=t[s].to);return this.visibleRanges=t,i?4:0}lineBlockAt(e){return e>=this.viewport.from&&e<=this.viewport.to&&this.viewportLines.find(t=>t.from<=e&&t.to>=e)||Fs(this.heightMap.lineAt(e,le.ByPos,this.heightOracle,0,0),this.scaler)}lineBlockAtHeight(e){return Fs(this.heightMap.lineAt(this.scaler.fromDOM(e),le.ByHeight,this.heightOracle,0,0),this.scaler)}scrollAnchorAt(e){let t=this.lineBlockAtHeight(e+8);return t.from>=this.viewport.from||this.viewportLines[0].top-e>200?t:this.viewportLines[0]}elementAtHeight(e){return Fs(this.heightMap.blockAt(this.scaler.fromDOM(e),this.heightOracle,0,0),this.scaler)}get docHeight(){return this.scaler.toDOM(this.heightMap.height)}get contentHeight(){return this.docHeight+this.paddingTop+this.paddingBottom}}class ua{constructor(e,t){this.from=e,this.to=t}}function Kk(n,e,t){let i=[],r=n,s=0;return J.spans(t,n,e,{span(){},point(o,a){o>r&&(i.push({from:r,to:o}),s+=o-r),r=a}},20),r=1)return e[e.length-1].to;let i=Math.floor(n*t);for(let r=0;;r++){let{from:s,to:o}=e[r],a=o-s;if(i<=a)return s+i;i-=a}}function da(n,e){let t=0;for(let{from:i,to:r}of n.ranges){if(e<=r){t+=e-i;break}t+=r-i}return t/n.total}function ex(n,e){for(let t of n)if(e(t))return t}const $p={toDOM(n){return n},fromDOM(n){return n},scale:1};class tx{constructor(e,t,i){let r=0,s=0,o=0;this.viewports=i.map(({from:a,to:l})=>{let h=t.lineAt(a,le.ByPos,e,0,0).top,c=t.lineAt(l,le.ByPos,e,0,0).bottom;return r+=c-h,{from:a,to:l,top:h,bottom:c,domTop:0,domBottom:0}}),this.scale=(7e6-r)/(t.height-r);for(let a of this.viewports)a.domTop=o+(a.top-s)*this.scale,o=a.domBottom=a.domTop+(a.bottom-a.top),s=a.bottom}toDOM(e){for(let t=0,i=0,r=0;;t++){let s=tFs(r,e)):n._content)}const pa=B.define({combine:n=>n.join(" ")}),mu=B.define({combine:n=>n.indexOf(!0)>-1}),Ou=Os.newName(),V0=Os.newName(),X0=Os.newName(),L0={"&light":"."+V0,"&dark":"."+X0};function yu(n,e,t){return new Os(e,{finish(i){return/&/.test(i)?i.replace(/&\w*/,r=>{if(r=="&")return n;if(!t||!t[r])throw new RangeError(`Unsupported selector: ${r}`);return t[r]}):n+" "+i}})}const ix=yu("."+Ou,{"&":{position:"relative !important",boxSizing:"border-box","&.cm-focused":{outline:"1px dotted #212121"},display:"flex !important",flexDirection:"column"},".cm-scroller":{display:"flex !important",alignItems:"flex-start !important",fontFamily:"monospace",lineHeight:1.4,height:"100%",overflowX:"auto",position:"relative",zIndex:0},".cm-content":{margin:0,flexGrow:2,flexShrink:0,display:"block",whiteSpace:"pre",wordWrap:"normal",boxSizing:"border-box",minHeight:"100%",padding:"4px 0",outline:"none","&[contenteditable=true]":{WebkitUserModify:"read-write-plaintext-only"}},".cm-lineWrapping":{whiteSpace_fallback:"pre-wrap",whiteSpace:"break-spaces",wordBreak:"break-word",overflowWrap:"anywhere",flexShrink:1},"&light .cm-content":{caretColor:"black"},"&dark .cm-content":{caretColor:"white"},".cm-line":{display:"block",padding:"0 2px 0 6px"},".cm-layer":{position:"absolute",left:0,top:0,contain:"size style","& > *":{position:"absolute"}},"&light .cm-selectionBackground":{background:"#d9d9d9"},"&dark .cm-selectionBackground":{background:"#222"},"&light.cm-focused > .cm-scroller > .cm-selectionLayer .cm-selectionBackground":{background:"#d7d4f0"},"&dark.cm-focused > .cm-scroller > .cm-selectionLayer .cm-selectionBackground":{background:"#233"},".cm-cursorLayer":{pointerEvents:"none"},"&.cm-focused > .cm-scroller > .cm-cursorLayer":{animation:"steps(1) cm-blink 1.2s infinite"},"@keyframes cm-blink":{"0%":{},"50%":{opacity:0},"100%":{}},"@keyframes cm-blink2":{"0%":{},"50%":{opacity:0},"100%":{}},".cm-cursor, .cm-dropCursor":{borderLeft:"1.2px solid black",marginLeft:"-0.6px",pointerEvents:"none"},".cm-cursor":{display:"none"},"&dark .cm-cursor":{borderLeftColor:"#444"},".cm-dropCursor":{position:"absolute"},"&.cm-focused > .cm-scroller > .cm-cursorLayer .cm-cursor":{display:"block"},".cm-iso":{unicodeBidi:"isolate"},".cm-announced":{position:"fixed",top:"-10000px"},"@media print":{".cm-announced":{display:"none"}},"&light .cm-activeLine":{backgroundColor:"#cceeff44"},"&dark .cm-activeLine":{backgroundColor:"#99eeff33"},"&light .cm-specialChar":{color:"red"},"&dark .cm-specialChar":{color:"#f78"},".cm-gutters":{flexShrink:0,display:"flex",height:"100%",boxSizing:"border-box",insetInlineStart:0,zIndex:200},"&light .cm-gutters":{backgroundColor:"#f5f5f5",color:"#6c6c6c",borderRight:"1px solid #ddd"},"&dark .cm-gutters":{backgroundColor:"#333338",color:"#ccc"},".cm-gutter":{display:"flex !important",flexDirection:"column",flexShrink:0,boxSizing:"border-box",minHeight:"100%",overflow:"hidden"},".cm-gutterElement":{boxSizing:"border-box"},".cm-lineNumbers .cm-gutterElement":{padding:"0 3px 0 5px",minWidth:"20px",textAlign:"right",whiteSpace:"nowrap"},"&light .cm-activeLineGutter":{backgroundColor:"#e2f2ff"},"&dark .cm-activeLineGutter":{backgroundColor:"#222227"},".cm-panels":{boxSizing:"border-box",position:"sticky",left:0,right:0},"&light .cm-panels":{backgroundColor:"#f5f5f5",color:"black"},"&light .cm-panels-top":{borderBottom:"1px solid #ddd"},"&light .cm-panels-bottom":{borderTop:"1px solid #ddd"},"&dark .cm-panels":{backgroundColor:"#333338",color:"white"},".cm-tab":{display:"inline-block",overflow:"hidden",verticalAlign:"bottom"},".cm-widgetBuffer":{verticalAlign:"text-top",height:"1em",width:0,display:"inline"},".cm-placeholder":{color:"#888",display:"inline-block",verticalAlign:"top"},".cm-highlightSpace:before":{content:"attr(data-display)",position:"absolute",pointerEvents:"none",color:"#888"},".cm-highlightTab":{backgroundImage:`url('data:image/svg+xml,')`,backgroundSize:"auto 100%",backgroundPosition:"right 90%",backgroundRepeat:"no-repeat"},".cm-trailingSpace":{backgroundColor:"#ff332255"},".cm-button":{verticalAlign:"middle",color:"inherit",fontSize:"70%",padding:".2em 1em",borderRadius:"1px"},"&light .cm-button":{backgroundImage:"linear-gradient(#eff1f5, #d9d9df)",border:"1px solid #888","&:active":{backgroundImage:"linear-gradient(#b4b4b4, #d0d3d6)"}},"&dark .cm-button":{backgroundImage:"linear-gradient(#393939, #111)",border:"1px solid #888","&:active":{backgroundImage:"linear-gradient(#111, #333)"}},".cm-textfield":{verticalAlign:"middle",color:"inherit",fontSize:"70%",border:"1px solid silver",padding:".2em .5em"},"&light .cm-textfield":{backgroundColor:"white"},"&dark .cm-textfield":{border:"1px solid #555",backgroundColor:"inherit"}},L0),zs="￿";class nx{constructor(e,t){this.points=e,this.text="",this.lineSeparator=t.facet(H.lineSeparator)}append(e){this.text+=e}lineBreak(){this.text+=zs}readRange(e,t){if(!e)return this;let i=e.parentNode;for(let r=e;;){this.findPointBefore(i,r);let s=this.text.length;this.readNode(r);let o=r.nextSibling;if(o==t)break;let a=he.get(r),l=he.get(o);(a&&l?a.breakAfter:(a?a.breakAfter:Cp(r))||Cp(o)&&(r.nodeName!="BR"||r.cmIgnore)&&this.text.length>s)&&this.lineBreak(),r=o}return this.findPointBefore(i,t),this}readTextNode(e){let t=e.nodeValue;for(let i of this.points)i.node==e&&(i.pos=this.text.length+Math.min(i.offset,t.length));for(let i=0,r=this.lineSeparator?null:/\r\n?|\n/g;;){let s=-1,o=1,a;if(this.lineSeparator?(s=t.indexOf(this.lineSeparator,i),o=this.lineSeparator.length):(a=r.exec(t))&&(s=a.index,o=a[0].length),this.append(t.slice(i,s<0?t.length:s)),s<0)break;if(this.lineBreak(),o>1)for(let l of this.points)l.node==e&&l.pos>this.text.length&&(l.pos-=o-1);i=s+o}}readNode(e){if(e.cmIgnore)return;let t=he.get(e),i=t&&t.overrideDOMText;if(i!=null){this.findPointInside(e,i.length);for(let r=i.iter();!r.next().done;)r.lineBreak?this.lineBreak():this.append(r.value)}else e.nodeType==3?this.readTextNode(e):e.nodeName=="BR"?e.nextSibling&&this.lineBreak():e.nodeType==1&&this.readRange(e.firstChild,null)}findPointBefore(e,t){for(let i of this.points)i.node==e&&e.childNodes[i.offset]==t&&(i.pos=this.text.length)}findPointInside(e,t){for(let i of this.points)(e.nodeType==3?i.node==e:e.contains(i.node))&&(i.pos=this.text.length+(rx(e,i.node,i.offset)?t:0))}}function rx(n,e,t){for(;;){if(!e||t-1)this.newSel=null;else if(t>-1&&(this.bounds=e.docView.domBoundsAround(t,i,0))){let a=s||o?[]:lx(e),l=new nx(a,e.state);l.readRange(this.bounds.startDOM,this.bounds.endDOM),this.text=l.text,this.newSel=hx(a,this.bounds.from)}else{let a=e.observer.selectionRange,l=s&&s.node==a.focusNode&&s.offset==a.focusOffset||!iu(e.contentDOM,a.focusNode)?e.state.selection.main.head:e.docView.posFromDOM(a.focusNode,a.focusOffset),h=o&&o.node==a.anchorNode&&o.offset==a.anchorOffset||!iu(e.contentDOM,a.anchorNode)?e.state.selection.main.anchor:e.docView.posFromDOM(a.anchorNode,a.anchorOffset),c=e.viewport;if(q.ios&&e.state.selection.main.empty&&l!=h&&(c.from>0||c.toDate.now()-100?n.inputState.lastKeyCode:-1;if(e.bounds){let{from:o,to:a}=e.bounds,l=r.from,h=null;(s===8||q.android&&e.text.length=r.from&&t.to<=r.to&&(t.from!=r.from||t.to!=r.to)&&r.to-r.from-(t.to-t.from)<=4?t={from:r.from,to:r.to,insert:n.state.doc.slice(r.from,t.from).append(t.insert).append(n.state.doc.slice(t.to,r.to))}:(q.mac||q.android)&&t&&t.from==t.to&&t.from==r.head-1&&/^\. ?$/.test(t.insert.toString())&&n.contentDOM.getAttribute("autocorrect")=="off"?(i&&t.insert.length==2&&(i=P.single(i.main.anchor-1,i.main.head-1)),t={from:r.from,to:r.to,insert:K.of([" "])}):q.chrome&&t&&t.from==t.to&&t.from==r.head&&t.insert.toString()==` + `&&n.lineWrapping&&(i&&(i=P.single(i.main.anchor-1,i.main.head-1)),t={from:r.from,to:r.to,insert:K.of([" "])}),t){if(q.ios&&n.inputState.flushIOSKey()||q.android&&(t.from==r.from&&t.to==r.to&&t.insert.length==1&&t.insert.lines==2&&ss(n.contentDOM,"Enter",13)||(t.from==r.from-1&&t.to==r.to&&t.insert.length==0||s==8&&t.insert.lengthr.head)&&ss(n.contentDOM,"Backspace",8)||t.from==r.from&&t.to==r.to+1&&t.insert.length==0&&ss(n.contentDOM,"Delete",46)))return!0;let o=t.insert.toString();n.inputState.composing>=0&&n.inputState.composing++;let a,l=()=>a||(a=ox(n,t,i));return n.state.facet(O0).some(h=>h(n,t.from,t.to,o,l))||n.dispatch(l()),!0}else if(i&&!i.main.eq(r)){let o=!1,a="select";return n.inputState.lastSelectionTime>Date.now()-50&&(n.inputState.lastSelectionOrigin=="select"&&(o=!0),a=n.inputState.lastSelectionOrigin),n.dispatch({selection:i,scrollIntoView:o,userEvent:a}),!0}else return!1}function ox(n,e,t){let i,r=n.state,s=r.selection.main;if(e.from>=s.from&&e.to<=s.to&&e.to-e.from>=(s.to-s.from)/3&&(!t||t.main.empty&&t.main.from==e.from+e.insert.length)&&n.inputState.composing<0){let a=s.frome.to?r.sliceDoc(e.to,s.to):"";i=r.replaceSelection(n.state.toText(a+e.insert.sliceString(0,void 0,n.state.lineBreak)+l))}else{let a=r.changes(e),l=t&&t.main.to<=a.newLength?t.main:void 0;if(r.selection.ranges.length>1&&n.inputState.composing>=0&&e.to<=s.to&&e.to>=s.to-10){let h=n.state.sliceDoc(e.from,e.to),c,u=t&&Q0(n,t.main.head);if(u){let g=e.insert.length-(e.to-e.from);c={from:u.from,to:u.to-g}}else c=n.state.doc.lineAt(s.head);let f=s.to-e.to,p=s.to-s.from;i=r.changeByRange(g=>{if(g.from==s.from&&g.to==s.to)return{changes:a,range:l||g.map(a)};let O=g.to-f,y=O-h.length;if(g.to-g.from!=p||n.state.sliceDoc(y,O)!=h||g.to>=c.from&&g.from<=c.to)return{range:g};let S=r.changes({from:y,to:O,insert:e.insert}),k=g.to-s.to;return{changes:S,range:l?P.range(Math.max(0,l.anchor+k),Math.max(0,l.head+k)):g.map(S)}})}else i={changes:a,selection:l&&r.selection.replaceRange(l)}}let o="input.type";return(n.composing||n.inputState.compositionPendingChange&&n.inputState.compositionEndedAt>Date.now()-50)&&(n.inputState.compositionPendingChange=!1,o+=".compose",n.inputState.compositionFirstChange&&(o+=".start",n.inputState.compositionFirstChange=!1)),r.update(i,{userEvent:o,scrollIntoView:!0})}function ax(n,e,t,i){let r=Math.min(n.length,e.length),s=0;for(;s0&&a>0&&n.charCodeAt(o-1)==e.charCodeAt(a-1);)o--,a--;if(i=="end"){let l=Math.max(0,s-Math.min(o,a));t-=o+l-s}if(o=o?s-t:0;s-=l,a=s+(a-o),o=s}else if(a=a?s-t:0;s-=l,o=s+(o-a),a=s}return{from:s,toA:o,toB:a}}function lx(n){let e=[];if(n.root.activeElement!=n.contentDOM)return e;let{anchorNode:t,anchorOffset:i,focusNode:r,focusOffset:s}=n.observer.selectionRange;return t&&(e.push(new Ip(t,i)),(r!=t||s!=i)&&e.push(new Ip(r,s))),e}function hx(n,e){if(n.length==0)return null;let t=n[0].pos,i=n.length==2?n[1].pos:t;return t>-1&&i>-1?P.single(t+e,i+e):null}const cx={childList:!0,characterData:!0,subtree:!0,attributes:!0,characterDataOldValue:!0},Xh=q.ie&&q.ie_version<=11;class ux{constructor(e){this.view=e,this.active=!1,this.selectionRange=new _v,this.selectionChanged=!1,this.delayedFlush=-1,this.resizeTimeout=-1,this.queue=[],this.delayedAndroidKey=null,this.flushingAndroidKey=-1,this.lastChange=0,this.scrollTargets=[],this.intersection=null,this.resizeScroll=null,this.intersecting=!1,this.gapIntersection=null,this.gaps=[],this.parentCheck=-1,this.dom=e.contentDOM,this.observer=new MutationObserver(t=>{for(let i of t)this.queue.push(i);(q.ie&&q.ie_version<=11||q.ios&&e.composing)&&t.some(i=>i.type=="childList"&&i.removedNodes.length||i.type=="characterData"&&i.oldValue.length>i.target.nodeValue.length)?this.flushSoon():this.flush()}),Xh&&(this.onCharData=t=>{this.queue.push({target:t.target,type:"characterData",oldValue:t.prevValue}),this.flushSoon()}),this.onSelectionChange=this.onSelectionChange.bind(this),this.onResize=this.onResize.bind(this),this.onPrint=this.onPrint.bind(this),this.onScroll=this.onScroll.bind(this),typeof ResizeObserver=="function"&&(this.resizeScroll=new ResizeObserver(()=>{var t;((t=this.view.docView)===null||t===void 0?void 0:t.lastUpdate){this.parentCheck<0&&(this.parentCheck=setTimeout(this.listenForScroll.bind(this),1e3)),t.length>0&&t[t.length-1].intersectionRatio>0!=this.intersecting&&(this.intersecting=!this.intersecting,this.intersecting!=this.view.inView&&this.onScrollChanged(document.createEvent("Event")))},{threshold:[0,.001]}),this.intersection.observe(this.dom),this.gapIntersection=new IntersectionObserver(t=>{t.length>0&&t[t.length-1].intersectionRatio>0&&this.onScrollChanged(document.createEvent("Event"))},{})),this.listenForScroll(),this.readSelectionRange()}onScrollChanged(e){this.view.inputState.runHandlers("scroll",e),this.intersecting&&this.view.measure()}onScroll(e){this.intersecting&&this.flush(!1),this.onScrollChanged(e)}onResize(){this.resizeTimeout<0&&(this.resizeTimeout=setTimeout(()=>{this.resizeTimeout=-1,this.view.requestMeasure()},50))}onPrint(){this.view.viewState.printing=!0,this.view.measure(),setTimeout(()=>{this.view.viewState.printing=!1,this.view.requestMeasure()},500)}updateGaps(e){if(this.gapIntersection&&(e.length!=this.gaps.length||this.gaps.some((t,i)=>t!=e[i]))){this.gapIntersection.disconnect();for(let t of e)this.gapIntersection.observe(t);this.gaps=e}}onSelectionChange(e){let t=this.selectionChanged;if(!this.readSelectionRange()||this.delayedAndroidKey)return;let{view:i}=this,r=this.selectionRange;if(i.state.facet(lh)?i.root.activeElement!=this.dom:!La(i.dom,r))return;let s=r.anchorNode&&i.docView.nearest(r.anchorNode);if(s&&s.ignoreEvent(e)){t||(this.selectionChanged=!1);return}(q.ie&&q.ie_version<=11||q.android&&q.chrome)&&!i.state.selection.main.empty&&r.focusNode&&io(r.focusNode,r.focusOffset,r.anchorNode,r.anchorOffset)?this.flushSoon():this.flush(!1)}readSelectionRange(){let{view:e}=this,t=q.safari&&e.root.nodeType==11&&Wv(this.dom.ownerDocument)==this.dom&&fx(this.view)||xl(e.root);if(!t||this.selectionRange.eq(t))return!1;let i=La(this.dom,t);return i&&!this.selectionChanged&&e.inputState.lastFocusTime>Date.now()-200&&e.inputState.lastTouchTime{let s=this.delayedAndroidKey;s&&(this.clearDelayedAndroidKey(),this.view.inputState.lastKeyCode=s.keyCode,this.view.inputState.lastKeyTime=Date.now(),!this.flush()&&s.force&&ss(this.dom,s.key,s.keyCode))};this.flushingAndroidKey=this.view.win.requestAnimationFrame(r)}(!this.delayedAndroidKey||e=="Enter")&&(this.delayedAndroidKey={key:e,keyCode:t,force:this.lastChange{this.delayedFlush=-1,this.flush()}))}forceFlush(){this.delayedFlush>=0&&(this.view.win.cancelAnimationFrame(this.delayedFlush),this.delayedFlush=-1),this.flush()}pendingRecords(){for(let e of this.observer.takeRecords())this.queue.push(e);return this.queue}processRecords(){let e=this.pendingRecords();e.length&&(this.queue=[]);let t=-1,i=-1,r=!1;for(let s of e){let o=this.readMutation(s);o&&(o.typeOver&&(r=!0),t==-1?{from:t,to:i}=o:(t=Math.min(o.from,t),i=Math.max(o.to,i)))}return{from:t,to:i,typeOver:r}}readChange(){let{from:e,to:t,typeOver:i}=this.processRecords(),r=this.selectionChanged&&La(this.dom,this.selectionRange);if(e<0&&!r)return null;e>-1&&(this.lastChange=Date.now()),this.view.inputState.lastFocusTime=0,this.selectionChanged=!1;let s=new sx(this.view,e,t,i);return this.view.docView.domChanged={newSel:s.newSel?s.newSel.main:null},s}flush(e=!0){if(this.delayedFlush>=0||this.delayedAndroidKey)return!1;e&&this.readSelectionRange();let t=this.readChange();if(!t)return this.view.requestMeasure(),!1;let i=this.view.state,r=U0(this.view,t);return this.view.state==i&&this.view.update([]),r}readMutation(e){let t=this.view.docView.nearest(e.target);if(!t||t.ignoreMutation(e))return null;if(t.markDirty(e.type=="attributes"),e.type=="attributes"&&(t.flags|=4),e.type=="childList"){let i=Rp(t,e.previousSibling||e.target.previousSibling,-1),r=Rp(t,e.nextSibling||e.target.nextSibling,1);return{from:i?t.posAfter(i):t.posAtStart,to:r?t.posBefore(r):t.posAtEnd,typeOver:!1}}else return e.type=="characterData"?{from:t.posAtStart,to:t.posAtEnd,typeOver:e.target.nodeValue==e.oldValue}:null}setWindow(e){e!=this.win&&(this.removeWindowListeners(this.win),this.win=e,this.addWindowListeners(this.win))}addWindowListeners(e){e.addEventListener("resize",this.onResize),e.addEventListener("beforeprint",this.onPrint),e.addEventListener("scroll",this.onScroll),e.document.addEventListener("selectionchange",this.onSelectionChange)}removeWindowListeners(e){e.removeEventListener("scroll",this.onScroll),e.removeEventListener("resize",this.onResize),e.removeEventListener("beforeprint",this.onPrint),e.document.removeEventListener("selectionchange",this.onSelectionChange)}destroy(){var e,t,i;this.stop(),(e=this.intersection)===null||e===void 0||e.disconnect(),(t=this.gapIntersection)===null||t===void 0||t.disconnect(),(i=this.resizeScroll)===null||i===void 0||i.disconnect();for(let r of this.scrollTargets)r.removeEventListener("scroll",this.onScroll);this.removeWindowListeners(this.win),clearTimeout(this.parentCheck),clearTimeout(this.resizeTimeout),this.win.cancelAnimationFrame(this.delayedFlush),this.win.cancelAnimationFrame(this.flushingAndroidKey)}}function Rp(n,e,t){for(;e;){let i=he.get(e);if(i&&i.parent==n)return i;let r=e.parentNode;e=r!=n.dom?r:t>0?e.nextSibling:e.previousSibling}return null}function fx(n){let e=null;function t(l){l.preventDefault(),l.stopImmediatePropagation(),e=l.getTargetRanges()[0]}if(n.contentDOM.addEventListener("beforeinput",t,!0),n.dom.ownerDocument.execCommand("indent"),n.contentDOM.removeEventListener("beforeinput",t,!0),!e)return null;let i=e.startContainer,r=e.startOffset,s=e.endContainer,o=e.endOffset,a=n.docView.domAtPos(n.state.selection.main.anchor);return io(a.node,a.offset,s,o)&&([i,r,s,o]=[s,o,i,r]),{anchorNode:i,anchorOffset:r,focusNode:s,focusOffset:o}}class N{get state(){return this.viewState.state}get viewport(){return this.viewState.viewport}get visibleRanges(){return this.viewState.visibleRanges}get inView(){return this.viewState.inView}get composing(){return this.inputState.composing>0}get compositionStarted(){return this.inputState.composing>=0}get root(){return this._root}get win(){return this.dom.ownerDocument.defaultView||window}constructor(e={}){this.plugins=[],this.pluginMap=new Map,this.editorAttrs={},this.contentAttrs={},this.bidiCache=[],this.destroyed=!1,this.updateState=2,this.measureScheduled=-1,this.measureRequests=[],this.contentDOM=document.createElement("div"),this.scrollDOM=document.createElement("div"),this.scrollDOM.tabIndex=-1,this.scrollDOM.className="cm-scroller",this.scrollDOM.appendChild(this.contentDOM),this.announceDOM=document.createElement("div"),this.announceDOM.className="cm-announced",this.announceDOM.setAttribute("aria-live","polite"),this.dom=document.createElement("div"),this.dom.appendChild(this.announceDOM),this.dom.appendChild(this.scrollDOM),e.parent&&e.parent.appendChild(this.dom);let{dispatch:t}=e;this.dispatchTransactions=e.dispatchTransactions||t&&(i=>i.forEach(r=>t(r,this)))||(i=>this.update(i)),this.dispatch=this.dispatch.bind(this),this._root=e.root||Gv(e.parent)||document,this.viewState=new Ap(e.state||H.create(e)),e.scrollTo&&e.scrollTo.is(la)&&(this.viewState.scrollTarget=e.scrollTo.value.clip(this.viewState.state)),this.plugins=this.state.facet(Ws).map(i=>new Bh(i));for(let i of this.plugins)i.update(this);this.observer=new ux(this),this.inputState=new Pk(this),this.inputState.ensureHandlers(this.plugins),this.docView=new cp(this),this.mountStyles(),this.updateAttrs(),this.updateState=0,this.requestMeasure()}dispatch(...e){let t=e.length==1&&e[0]instanceof ye?e:e.length==1&&Array.isArray(e[0])?e[0]:[this.state.update(...e)];this.dispatchTransactions(t,this)}update(e){if(this.updateState!=0)throw new Error("Calls to EditorView.update are not allowed while an update is in progress");let t=!1,i=!1,r,s=this.state;for(let f of e){if(f.startState!=s)throw new RangeError("Trying to update state with a transaction that doesn't start from the previous state.");s=f.state}if(this.destroyed){this.viewState.state=s;return}let o=this.hasFocus,a=0,l=null;e.some(f=>f.annotation(N0))?(this.inputState.notifiedFocused=o,a=1):o!=this.inputState.notifiedFocused&&(this.inputState.notifiedFocused=o,l=B0(s,o),l||(a=1));let h=this.observer.delayedAndroidKey,c=null;if(h?(this.observer.clearDelayedAndroidKey(),c=this.observer.readChange(),(c&&!this.state.doc.eq(s.doc)||!this.state.selection.eq(s.selection))&&(c=null)):this.observer.clear(),s.facet(H.phrases)!=this.state.facet(H.phrases))return this.setState(s);r=Tl.create(this,s,e),r.flags|=a;let u=this.viewState.scrollTarget;try{this.updateState=2;for(let f of e){if(u&&(u=u.map(f.changes)),f.scrollIntoView){let{main:p}=f.state.selection;u=new os(p.empty?p:P.cursor(p.head,p.head>p.anchor?-1:1))}for(let p of f.effects)p.is(la)&&(u=p.value.clip(this.state))}this.viewState.update(r,u),this.bidiCache=Ql.update(this.bidiCache,r.changes),r.empty||(this.updatePlugins(r),this.inputState.update(r)),t=this.docView.update(r),this.state.facet(js)!=this.styleModules&&this.mountStyles(),i=this.updateAttrs(),this.showAnnouncements(e),this.docView.updateSelection(t,e.some(f=>f.isUserEvent("select.pointer")))}finally{this.updateState=0}if(r.startState.facet(pa)!=r.state.facet(pa)&&(this.viewState.mustMeasureContent=!0),(t||i||u||this.viewState.mustEnforceCursorAssoc||this.viewState.mustMeasureContent)&&this.requestMeasure(),!r.empty)for(let f of this.state.facet(fu))try{f(r)}catch(p){mt(this.state,p,"update listener")}(l||c)&&Promise.resolve().then(()=>{l&&this.state==l.startState&&this.dispatch(l),c&&!U0(this,c)&&h.force&&ss(this.contentDOM,h.key,h.keyCode)})}setState(e){if(this.updateState!=0)throw new Error("Calls to EditorView.setState are not allowed while an update is in progress");if(this.destroyed){this.viewState.state=e;return}this.updateState=2;let t=this.hasFocus;try{for(let i of this.plugins)i.destroy(this);this.viewState=new Ap(e),this.plugins=e.facet(Ws).map(i=>new Bh(i)),this.pluginMap.clear();for(let i of this.plugins)i.update(this);this.docView.destroy(),this.docView=new cp(this),this.inputState.ensureHandlers(this.plugins),this.mountStyles(),this.updateAttrs(),this.bidiCache=[]}finally{this.updateState=0}t&&this.focus(),this.requestMeasure()}updatePlugins(e){let t=e.startState.facet(Ws),i=e.state.facet(Ws);if(t!=i){let r=[];for(let s of i){let o=t.indexOf(s);if(o<0)r.push(new Bh(s));else{let a=this.plugins[o];a.mustUpdate=e,r.push(a)}}for(let s of this.plugins)s.mustUpdate!=e&&s.destroy(this);this.plugins=r,this.pluginMap.clear()}else for(let r of this.plugins)r.mustUpdate=e;for(let r=0;r-1&&this.win.cancelAnimationFrame(this.measureScheduled),this.observer.delayedAndroidKey){this.measureScheduled=-1,this.requestMeasure();return}this.measureScheduled=0,e&&this.observer.forceFlush();let t=null,i=this.scrollDOM,r=i.scrollTop*this.scaleY,{scrollAnchorPos:s,scrollAnchorHeight:o}=this.viewState;Math.abs(r-this.viewState.scrollTop)>1&&(o=-1),this.viewState.scrollAnchorHeight=-1;try{for(let a=0;;a++){if(o<0)if(HO(i))s=-1,o=this.viewState.heightMap.height;else{let p=this.viewState.scrollAnchorAt(r);s=p.from,o=p.top}this.updateState=1;let l=this.viewState.measure(this);if(!l&&!this.measureRequests.length&&this.viewState.scrollTarget==null)break;if(a>5){console.warn(this.measureRequests.length?"Measure loop restarted more than 5 times":"Viewport failed to stabilize");break}let h=[];l&4||([this.measureRequests,h]=[h,this.measureRequests]);let c=h.map(p=>{try{return p.read(this)}catch(g){return mt(this.state,g),Ep}}),u=Tl.create(this,this.state,[]),f=!1;u.flags|=l,t?t.flags|=l:t=u,this.updateState=2,u.empty||(this.updatePlugins(u),this.inputState.update(u),this.updateAttrs(),f=this.docView.update(u));for(let p=0;p1||g<-1){r=r+g,i.scrollTop=r/this.scaleY,o=-1;continue}}break}}}finally{this.updateState=0,this.measureScheduled=-1}if(t&&!t.empty)for(let a of this.state.facet(fu))a(t)}get themeClasses(){return Ou+" "+(this.state.facet(mu)?X0:V0)+" "+this.state.facet(pa)}updateAttrs(){let e=Dp(this,w0,{class:"cm-editor"+(this.hasFocus?" cm-focused ":" ")+this.themeClasses}),t={spellcheck:"false",autocorrect:"off",autocapitalize:"off",translate:"no",contenteditable:this.state.facet(lh)?"true":"false",class:"cm-content",style:`${q.tabSize}: ${this.state.tabSize}`,role:"textbox","aria-multiline":"true"};this.state.readOnly&&(t["aria-readonly"]="true"),Dp(this,yf,t);let i=this.observer.ignore(()=>{let r=au(this.contentDOM,this.contentAttrs,t),s=au(this.dom,this.editorAttrs,e);return r||s});return this.editorAttrs=e,this.contentAttrs=t,i}showAnnouncements(e){let t=!0;for(let i of e)for(let r of i.effects)if(r.is(N.announce)){t&&(this.announceDOM.textContent=""),t=!1;let s=this.announceDOM.appendChild(document.createElement("div"));s.textContent=r.value}}mountStyles(){this.styleModules=this.state.facet(js);let e=this.state.facet(N.cspNonce);Os.mount(this.root,this.styleModules.concat(ix).reverse(),e?{nonce:e}:void 0)}readMeasured(){if(this.updateState==2)throw new Error("Reading the editor layout isn't allowed during an update");this.updateState==0&&this.measureScheduled>-1&&this.measure(!1)}requestMeasure(e){if(this.measureScheduled<0&&(this.measureScheduled=this.win.requestAnimationFrame(()=>this.measure())),e){if(this.measureRequests.indexOf(e)>-1)return;if(e.key!=null){for(let t=0;ti.spec==e)||null),t&&t.update(this).value}get documentTop(){return this.contentDOM.getBoundingClientRect().top+this.viewState.paddingTop}get documentPadding(){return{top:this.viewState.paddingTop,bottom:this.viewState.paddingBottom}}get scaleX(){return this.viewState.scaleX}get scaleY(){return this.viewState.scaleY}elementAtHeight(e){return this.readMeasured(),this.viewState.elementAtHeight(e)}lineBlockAtHeight(e){return this.readMeasured(),this.viewState.lineBlockAtHeight(e)}get viewportLineBlocks(){return this.viewState.viewportLines}lineBlockAt(e){return this.viewState.lineBlockAt(e)}get contentHeight(){return this.viewState.contentHeight}moveByChar(e,t,i){return Mh(this,e,mp(this,e,t,i))}moveByGroup(e,t){return Mh(this,e,mp(this,e,t,i=>Tk(this,e.head,i)))}visualLineSide(e,t){let i=this.bidiSpans(e),r=this.textDirectionAt(e.from),s=i[t?i.length-1:0];return P.cursor(s.side(t,r)+e.from,s.forward(!t,r)?1:-1)}moveToLineBoundary(e,t,i=!0){return xk(this,e,t,i)}moveVertically(e,t,i){return Mh(this,e,Qk(this,e,t,i))}domAtPos(e){return this.docView.domAtPos(e)}posAtDOM(e,t=0){return this.docView.posFromDOM(e,t)}posAtCoords(e,t=!0){return this.readMeasured(),A0(this,e,t)}coordsAtPos(e,t=1){this.readMeasured();let i=this.docView.coordsAt(e,t);if(!i||i.left==i.right)return i;let r=this.state.doc.lineAt(e),s=this.bidiSpans(r),o=s[ir.find(s,e-r.from,-1,t)];return pf(i,o.dir==ge.LTR==t>0)}coordsForChar(e){return this.readMeasured(),this.docView.coordsForChar(e)}get defaultCharacterWidth(){return this.viewState.heightOracle.charWidth}get defaultLineHeight(){return this.viewState.heightOracle.lineHeight}get textDirection(){return this.viewState.defaultTextDirection}textDirectionAt(e){return!this.state.facet(b0)||ethis.viewport.to?this.textDirection:(this.readMeasured(),this.docView.textDirectionAt(e))}get lineWrapping(){return this.viewState.heightOracle.lineWrapping}bidiSpans(e){if(e.length>dx)return u0(e.length);let t=this.textDirectionAt(e.from),i;for(let s of this.bidiCache)if(s.from==e.from&&s.dir==t&&(s.fresh||c0(s.isolates,i=hp(this,e))))return s.order;i||(i=hp(this,e));let r=lk(e.text,t,i);return this.bidiCache.push(new Ql(e.from,e.to,t,i,!0,r)),r}get hasFocus(){var e;return(this.dom.ownerDocument.hasFocus()||q.safari&&((e=this.inputState)===null||e===void 0?void 0:e.lastContextMenu)>Date.now()-3e4)&&this.root.activeElement==this.contentDOM}focus(){this.observer.ignore(()=>{JO(this.contentDOM),this.docView.updateSelection()})}setRoot(e){this._root!=e&&(this._root=e,this.observer.setWindow((e.nodeType==9?e:e.ownerDocument).defaultView||window),this.mountStyles())}destroy(){for(let e of this.plugins)e.destroy(this);this.plugins=[],this.inputState.destroy(),this.docView.destroy(),this.dom.remove(),this.observer.destroy(),this.measureScheduled>-1&&this.win.cancelAnimationFrame(this.measureScheduled),this.destroyed=!0}static scrollIntoView(e,t={}){return la.of(new os(typeof e=="number"?P.cursor(e):e,t.y,t.x,t.yMargin,t.xMargin))}scrollSnapshot(){let{scrollTop:e,scrollLeft:t}=this.scrollDOM,i=this.viewState.scrollAnchorAt(e);return la.of(new os(P.cursor(i.from),"start","start",i.top-e,t,!0))}static domEventHandlers(e){return ke.define(()=>({}),{eventHandlers:e})}static domEventObservers(e){return ke.define(()=>({}),{eventObservers:e})}static theme(e,t){let i=Os.newName(),r=[pa.of(i),js.of(yu(`.${i}`,e))];return t&&t.dark&&r.push(mu.of(!0)),r}static baseTheme(e){return mr.lowest(js.of(yu("."+Ou,e,L0)))}static findFromDOM(e){var t;let i=e.querySelector(".cm-content"),r=i&&he.get(i)||he.get(e);return((t=r==null?void 0:r.rootView)===null||t===void 0?void 0:t.view)||null}}N.styleModule=js;N.inputHandler=O0;N.focusChangeEffect=y0;N.perLineTextDirection=b0;N.exceptionSink=m0;N.updateListener=fu;N.editable=lh;N.mouseSelectionStyle=g0;N.dragMovesSelection=p0;N.clickAddsSelectionRange=d0;N.decorations=xo;N.outerDecorations=v0;N.atomicRanges=bf;N.bidiIsolatedRanges=k0;N.scrollMargins=x0;N.darkTheme=mu;N.cspNonce=B.define({combine:n=>n.length?n[0]:""});N.contentAttributes=yf;N.editorAttributes=w0;N.lineWrapping=N.contentAttributes.of({class:"cm-lineWrapping"});N.announce=z.define();const dx=4096,Ep={};class Ql{constructor(e,t,i,r,s,o){this.from=e,this.to=t,this.dir=i,this.isolates=r,this.fresh=s,this.order=o}static update(e,t){if(t.empty&&!e.some(s=>s.fresh))return e;let i=[],r=e.length?e[e.length-1].dir:ge.LTR;for(let s=Math.max(0,e.length-10);s=0;r--){let s=i[r],o=typeof s=="function"?s(n):s;o&&ou(o,t)}return t}const px=q.mac?"mac":q.windows?"win":q.linux?"linux":"key";function gx(n,e){const t=n.split(/-(?!$)/);let i=t[t.length-1];i=="Space"&&(i=" ");let r,s,o,a;for(let l=0;li.concat(r),[]))),t}function Ox(n,e,t){return W0(Z0(n.state),e,n,t)}let Hn=null;const yx=4e3;function bx(n,e=px){let t=Object.create(null),i=Object.create(null),r=(o,a)=>{let l=i[o];if(l==null)i[o]=a;else if(l!=a)throw new Error("Key binding "+o+" is used both as a regular binding and as a multi-stroke prefix")},s=(o,a,l,h,c)=>{var u,f;let p=t[o]||(t[o]=Object.create(null)),g=a.split(/ (?!$)/).map(S=>gx(S,e));for(let S=1;S{let x=Hn={view:$,prefix:k,scope:o};return setTimeout(()=>{Hn==x&&(Hn=null)},yx),!0}]})}let O=g.join(" ");r(O,!1);let y=p[O]||(p[O]={preventDefault:!1,stopPropagation:!1,run:((f=(u=p._any)===null||u===void 0?void 0:u.run)===null||f===void 0?void 0:f.slice())||[]});l&&y.run.push(l),h&&(y.preventDefault=!0),c&&(y.stopPropagation=!0)};for(let o of n){let a=o.scope?o.scope.split(" "):["editor"];if(o.any)for(let h of a){let c=t[h]||(t[h]=Object.create(null));c._any||(c._any={preventDefault:!1,stopPropagation:!1,run:[]});for(let u in c)c[u].run.push(o.any)}let l=o[e]||o.key;if(l)for(let h of a)s(h,l,o.run,o.preventDefault,o.stopPropagation),o.shift&&s(h,"Shift-"+l,o.shift,o.preventDefault,o.stopPropagation)}return t}function W0(n,e,t,i){let r=Zv(e),s=Ne(r,0),o=lt(s)==r.length&&r!=" ",a="",l=!1,h=!1,c=!1;Hn&&Hn.view==t&&Hn.scope==i&&(a=Hn.prefix+" ",C0.indexOf(e.keyCode)<0&&(h=!0,Hn=null));let u=new Set,f=y=>{if(y){for(let S of y.run)if(!u.has(S)&&(u.add(S),S(t,e)))return y.stopPropagation&&(c=!0),!0;y.preventDefault&&(y.stopPropagation&&(c=!0),h=!0)}return!1},p=n[i],g,O;return p&&(f(p[a+ga(r,e,!o)])?l=!0:o&&(e.altKey||e.metaKey||e.ctrlKey)&&!(q.windows&&e.ctrlKey&&e.altKey)&&(g=dr[e.keyCode])&&g!=r?(f(p[a+ga(g,e,!0)])||e.shiftKey&&(O=wo[e.keyCode])!=r&&O!=g&&f(p[a+ga(O,e,!1)]))&&(l=!0):o&&e.shiftKey&&f(p[a+ga(r,e,!0)])&&(l=!0),!l&&f(p._any)&&(l=!0)),h&&(l=!0),l&&c&&e.stopPropagation(),l}class jo{constructor(e,t,i,r,s){this.className=e,this.left=t,this.top=i,this.width=r,this.height=s}draw(){let e=document.createElement("div");return e.className=this.className,this.adjust(e),e}update(e,t){return t.className!=this.className?!1:(this.adjust(e),!0)}adjust(e){e.style.left=this.left+"px",e.style.top=this.top+"px",this.width!=null&&(e.style.width=this.width+"px"),e.style.height=this.height+"px"}eq(e){return this.left==e.left&&this.top==e.top&&this.width==e.width&&this.height==e.height&&this.className==e.className}static forRange(e,t,i){if(i.empty){let r=e.coordsAtPos(i.head,i.assoc||1);if(!r)return[];let s=j0(e);return[new jo(t,r.left-s.left,r.top-s.top,null,r.bottom-r.top)]}else return Sx(e,t,i)}}function j0(n){let e=n.scrollDOM.getBoundingClientRect();return{left:(n.textDirection==ge.LTR?e.left:e.right-n.scrollDOM.clientWidth*n.scaleX)-n.scrollDOM.scrollLeft*n.scaleX,top:e.top-n.scrollDOM.scrollTop*n.scaleY}}function Bp(n,e,t){let i=P.cursor(e);return{from:Math.max(t.from,n.moveToLineBoundary(i,!1,!0).from),to:Math.min(t.to,n.moveToLineBoundary(i,!0,!0).from),type:Je.Text}}function Sx(n,e,t){if(t.to<=n.viewport.from||t.from>=n.viewport.to)return[];let i=Math.max(t.from,n.viewport.from),r=Math.min(t.to,n.viewport.to),s=n.textDirection==ge.LTR,o=n.contentDOM,a=o.getBoundingClientRect(),l=j0(n),h=o.querySelector(".cm-line"),c=h&&window.getComputedStyle(h),u=a.left+(c?parseInt(c.paddingLeft)+Math.min(0,parseInt(c.textIndent)):0),f=a.right-(c?parseInt(c.paddingRight):0),p=pu(n,i),g=pu(n,r),O=p.type==Je.Text?p:null,y=g.type==Je.Text?g:null;if(O&&(n.lineWrapping||p.widgetLineBreaks)&&(O=Bp(n,i,O)),y&&(n.lineWrapping||g.widgetLineBreaks)&&(y=Bp(n,r,y)),O&&y&&O.from==y.from)return k($(t.from,t.to,O));{let Q=O?$(t.from,null,O):x(p,!1),A=y?$(null,t.to,y):x(g,!0),R=[];return(O||p).to<(y||g).from-(O&&y?1:0)||p.widgetLineBreaks>1&&Q.bottom+n.defaultLineHeight/2Qe&&He.from=Xe)break;Pe>Ee&&re(Math.max(be,Ee),Q==null&&be<=Qe,Math.min(Pe,Xe),A==null&&Pe>=Ve,Ke.dir)}if(Ee=ni.to+1,Ee>=Xe)break}return G.length==0&&re(Qe,Q==null,Ve,A==null,n.textDirection),{top:j,bottom:W,horizontal:G}}function x(Q,A){let R=a.top+(A?Q.top:Q.bottom);return{top:R,bottom:R,horizontal:[]}}}function wx(n,e){return n.constructor==e.constructor&&n.eq(e)}class vx{constructor(e,t){this.view=e,this.layer=t,this.drawn=[],this.scaleX=1,this.scaleY=1,this.measureReq={read:this.measure.bind(this),write:this.draw.bind(this)},this.dom=e.scrollDOM.appendChild(document.createElement("div")),this.dom.classList.add("cm-layer"),t.above&&this.dom.classList.add("cm-layer-above"),t.class&&this.dom.classList.add(t.class),this.scale(),this.dom.setAttribute("aria-hidden","true"),this.setOrder(e.state),e.requestMeasure(this.measureReq),t.mount&&t.mount(this.dom,e)}update(e){e.startState.facet(Wa)!=e.state.facet(Wa)&&this.setOrder(e.state),(this.layer.update(e,this.dom)||e.geometryChanged)&&(this.scale(),e.view.requestMeasure(this.measureReq))}setOrder(e){let t=0,i=e.facet(Wa);for(;t!wx(t,this.drawn[i]))){let t=this.dom.firstChild,i=0;for(let r of e)r.update&&t&&r.constructor&&this.drawn[i].constructor&&r.update(t,this.drawn[i])?(t=t.nextSibling,i++):this.dom.insertBefore(r.draw(),t);for(;t;){let r=t.nextSibling;t.remove(),t=r}this.drawn=e}}destroy(){this.layer.destroy&&this.layer.destroy(this.dom,this.view),this.dom.remove()}}const Wa=B.define();function F0(n){return[ke.define(e=>new vx(e,n)),Wa.of(n)]}const z0=!q.ios,To=B.define({combine(n){return Ai(n,{cursorBlinkRate:1200,drawRangeCursor:!0},{cursorBlinkRate:(e,t)=>Math.min(e,t),drawRangeCursor:(e,t)=>e||t})}});function kx(n={}){return[To.of(n),xx,Tx,Qx,S0.of(!0)]}function _0(n){return n.startState.facet(To)!=n.state.facet(To)}const xx=F0({above:!0,markers(n){let{state:e}=n,t=e.facet(To),i=[];for(let r of e.selection.ranges){let s=r==e.selection.main;if(r.empty?!s||z0:t.drawRangeCursor){let o=s?"cm-cursor cm-cursor-primary":"cm-cursor cm-cursor-secondary",a=r.empty?r:P.cursor(r.head,r.head>r.anchor?-1:1);for(let l of jo.forRange(n,o,a))i.push(l)}}return i},update(n,e){n.transactions.some(i=>i.selection)&&(e.style.animationName=e.style.animationName=="cm-blink"?"cm-blink2":"cm-blink");let t=_0(n);return t&&qp(n.state,e),n.docChanged||n.selectionSet||t},mount(n,e){qp(e.state,n)},class:"cm-cursorLayer"});function qp(n,e){e.style.animationDuration=n.facet(To).cursorBlinkRate+"ms"}const Tx=F0({above:!1,markers(n){return n.state.selection.ranges.map(e=>e.empty?[]:jo.forRange(n,"cm-selectionBackground",e)).reduce((e,t)=>e.concat(t))},update(n,e){return n.docChanged||n.selectionSet||n.viewportChanged||_0(n)},class:"cm-selectionLayer"}),bu={".cm-line":{"& ::selection":{backgroundColor:"transparent !important"},"&::selection":{backgroundColor:"transparent !important"}}};z0&&(bu[".cm-line"].caretColor="transparent !important",bu[".cm-content"]={caretColor:"transparent !important"});const Qx=mr.highest(N.theme(bu)),G0=z.define({map(n,e){return n==null?null:e.mapPos(n)}}),_s=Re.define({create(){return null},update(n,e){return n!=null&&(n=e.changes.mapPos(n)),e.effects.reduce((t,i)=>i.is(G0)?i.value:t,n)}}),Px=ke.fromClass(class{constructor(n){this.view=n,this.cursor=null,this.measureReq={read:this.readPos.bind(this),write:this.drawCursor.bind(this)}}update(n){var e;let t=n.state.field(_s);t==null?this.cursor!=null&&((e=this.cursor)===null||e===void 0||e.remove(),this.cursor=null):(this.cursor||(this.cursor=this.view.scrollDOM.appendChild(document.createElement("div")),this.cursor.className="cm-dropCursor"),(n.startState.field(_s)!=t||n.docChanged||n.geometryChanged)&&this.view.requestMeasure(this.measureReq))}readPos(){let{view:n}=this,e=n.state.field(_s),t=e!=null&&n.coordsAtPos(e);if(!t)return null;let i=n.scrollDOM.getBoundingClientRect();return{left:t.left-i.left+n.scrollDOM.scrollLeft*n.scaleX,top:t.top-i.top+n.scrollDOM.scrollTop*n.scaleY,height:t.bottom-t.top}}drawCursor(n){if(this.cursor){let{scaleX:e,scaleY:t}=this.view;n?(this.cursor.style.left=n.left/e+"px",this.cursor.style.top=n.top/t+"px",this.cursor.style.height=n.height/t+"px"):this.cursor.style.left="-100000px"}}destroy(){this.cursor&&this.cursor.remove()}setDropPos(n){this.view.state.field(_s)!=n&&this.view.dispatch({effects:G0.of(n)})}},{eventObservers:{dragover(n){this.setDropPos(this.view.posAtCoords({x:n.clientX,y:n.clientY}))},dragleave(n){(n.target==this.view.contentDOM||!this.view.contentDOM.contains(n.relatedTarget))&&this.setDropPos(null)},dragend(){this.setDropPos(null)},drop(){this.setDropPos(null)}}});function Ax(){return[_s,Px]}function Mp(n,e,t,i,r){e.lastIndex=0;for(let s=n.iterRange(t,i),o=t,a;!s.next().done;o+=s.value.length)if(!s.lineBreak)for(;a=e.exec(s.value);)r(o+a.index,a)}function $x(n,e){let t=n.visibleRanges;if(t.length==1&&t[0].from==n.viewport.from&&t[0].to==n.viewport.to)return t;let i=[];for(let{from:r,to:s}of t)r=Math.max(n.state.doc.lineAt(r).from,r-e),s=Math.min(n.state.doc.lineAt(s).to,s+e),i.length&&i[i.length-1].to>=r?i[i.length-1].to=s:i.push({from:r,to:s});return i}class Cx{constructor(e){const{regexp:t,decoration:i,decorate:r,boundary:s,maxLength:o=1e3}=e;if(!t.global)throw new RangeError("The regular expression given to MatchDecorator should have its 'g' flag set");if(this.regexp=t,r)this.addMatch=(a,l,h,c)=>r(c,h,h+a[0].length,a,l);else if(typeof i=="function")this.addMatch=(a,l,h,c)=>{let u=i(a,l,h);u&&c(h,h+a[0].length,u)};else if(i)this.addMatch=(a,l,h,c)=>c(h,h+a[0].length,i);else throw new RangeError("Either 'decorate' or 'decoration' should be provided to MatchDecorator");this.boundary=s,this.maxLength=o}createDeco(e){let t=new fr,i=t.add.bind(t);for(let{from:r,to:s}of $x(e,this.maxLength))Mp(e.state.doc,this.regexp,r,s,(o,a)=>this.addMatch(a,e,o,i));return t.finish()}updateDeco(e,t){let i=1e9,r=-1;return e.docChanged&&e.changes.iterChanges((s,o,a,l)=>{l>e.view.viewport.from&&a1e3?this.createDeco(e.view):r>-1?this.updateRange(e.view,t.map(e.changes),i,r):t}updateRange(e,t,i,r){for(let s of e.visibleRanges){let o=Math.max(s.from,i),a=Math.min(s.to,r);if(a>o){let l=e.state.doc.lineAt(o),h=l.tol.from;o--)if(this.boundary.test(l.text[o-1-l.from])){c=o;break}for(;af.push(S.range(O,y));if(l==h)for(this.regexp.lastIndex=c-l.from;(p=this.regexp.exec(l.text))&&p.indexthis.addMatch(y,e,O,g));t=t.update({filterFrom:c,filterTo:u,filter:(O,y)=>Ou,add:f})}}return t}}const Su=/x/.unicode!=null?"gu":"g",Ix=new RegExp(`[\0-\b +--Ÿ­؜​‎‏\u2028\u2029‭‮⁦⁧⁩\uFEFF-]`,Su),Rx={0:"null",7:"bell",8:"backspace",10:"newline",11:"vertical tab",13:"carriage return",27:"escape",8203:"zero width space",8204:"zero width non-joiner",8205:"zero width joiner",8206:"left-to-right mark",8207:"right-to-left mark",8232:"line separator",8237:"left-to-right override",8238:"right-to-left override",8294:"left-to-right isolate",8295:"right-to-left isolate",8297:"pop directional isolate",8233:"paragraph separator",65279:"zero width no-break space",65532:"object replacement"};let Lh=null;function Ex(){var n;if(Lh==null&&typeof document<"u"&&document.body){let e=document.body.style;Lh=((n=e.tabSize)!==null&&n!==void 0?n:e.MozTabSize)!=null}return Lh||!1}const ja=B.define({combine(n){let e=Ai(n,{render:null,specialChars:Ix,addSpecialChars:null});return(e.replaceTabs=!Ex())&&(e.specialChars=new RegExp(" |"+e.specialChars.source,Su)),e.addSpecialChars&&(e.specialChars=new RegExp(e.specialChars.source+"|"+e.addSpecialChars.source,Su)),e}});function Dx(n={}){return[ja.of(n),Nx()]}let Vp=null;function Nx(){return Vp||(Vp=ke.fromClass(class{constructor(n){this.view=n,this.decorations=Z.none,this.decorationCache=Object.create(null),this.decorator=this.makeDecorator(n.state.facet(ja)),this.decorations=this.decorator.createDeco(n)}makeDecorator(n){return new Cx({regexp:n.specialChars,decoration:(e,t,i)=>{let{doc:r}=t.state,s=Ne(e[0],0);if(s==9){let o=r.lineAt(i),a=t.state.tabSize,l=Uo(o.text,a,i-o.from);return Z.replace({widget:new Vx((a-l%a)*this.view.defaultCharacterWidth/this.view.scaleX)})}return this.decorationCache[s]||(this.decorationCache[s]=Z.replace({widget:new Mx(n,s)}))},boundary:n.replaceTabs?void 0:/[^]/})}update(n){let e=n.state.facet(ja);n.startState.facet(ja)!=e?(this.decorator=this.makeDecorator(e),this.decorations=this.decorator.createDeco(n.view)):this.decorations=this.decorator.updateDeco(n,this.decorations)}},{decorations:n=>n.decorations}))}const Bx="•";function qx(n){return n>=32?Bx:n==10?"␤":String.fromCharCode(9216+n)}class Mx extends Or{constructor(e,t){super(),this.options=e,this.code=t}eq(e){return e.code==this.code}toDOM(e){let t=qx(this.code),i=e.state.phrase("Control character")+" "+(Rx[this.code]||"0x"+this.code.toString(16)),r=this.options.render&&this.options.render(this.code,i,t);if(r)return r;let s=document.createElement("span");return s.textContent=t,s.title=i,s.setAttribute("aria-label",i),s.className="cm-specialChar",s}ignoreEvent(){return!1}}class Vx extends Or{constructor(e){super(),this.width=e}eq(e){return e.width==this.width}toDOM(){let e=document.createElement("span");return e.textContent=" ",e.className="cm-tab",e.style.width=this.width+"px",e}ignoreEvent(){return!1}}function Xx(){return Ux}const Lx=Z.line({class:"cm-activeLine"}),Ux=ke.fromClass(class{constructor(n){this.decorations=this.getDeco(n)}update(n){(n.docChanged||n.selectionSet)&&(this.decorations=this.getDeco(n.view))}getDeco(n){let e=-1,t=[];for(let i of n.state.selection.ranges){let r=n.lineBlockAt(i.head);r.from>e&&(t.push(Lx.range(r.from)),e=r.from)}return Z.set(t)}},{decorations:n=>n.decorations}),wu=2e3;function Zx(n,e,t){let i=Math.min(e.line,t.line),r=Math.max(e.line,t.line),s=[];if(e.off>wu||t.off>wu||e.col<0||t.col<0){let o=Math.min(e.off,t.off),a=Math.max(e.off,t.off);for(let l=i;l<=r;l++){let h=n.doc.line(l);h.length<=a&&s.push(P.range(h.from+o,h.to+a))}}else{let o=Math.min(e.col,t.col),a=Math.max(e.col,t.col);for(let l=i;l<=r;l++){let h=n.doc.line(l),c=Kc(h.text,o,n.tabSize,!0);if(c<0)s.push(P.cursor(h.to));else{let u=Kc(h.text,a,n.tabSize);s.push(P.range(h.from+c,h.from+u))}}}return s}function Wx(n,e){let t=n.coordsAtPos(n.viewport.from);return t?Math.round(Math.abs((t.left-e)/n.defaultCharacterWidth)):-1}function Xp(n,e){let t=n.posAtCoords({x:e.clientX,y:e.clientY},!1),i=n.state.doc.lineAt(t),r=t-i.from,s=r>wu?-1:r==i.length?Wx(n,e.clientX):Uo(i.text,n.state.tabSize,t-i.from);return{line:i.number,col:s,off:r}}function jx(n,e){let t=Xp(n,e),i=n.state.selection;return t?{update(r){if(r.docChanged){let s=r.changes.mapPos(r.startState.doc.line(t.line).from),o=r.state.doc.lineAt(s);t={line:o.number,col:t.col,off:Math.min(t.off,o.length)},i=i.map(r.changes)}},get(r,s,o){let a=Xp(n,r);if(!a)return i;let l=Zx(n.state,t,a);return l.length?o?P.create(l.concat(i.ranges)):P.create(l):i}}:null}function Fx(n){let e=t=>t.altKey&&t.button==0;return N.mouseSelectionStyle.of((t,i)=>e(i)?jx(t,i):null)}const zx={Alt:[18,n=>!!n.altKey],Control:[17,n=>!!n.ctrlKey],Shift:[16,n=>!!n.shiftKey],Meta:[91,n=>!!n.metaKey]},_x={style:"cursor: crosshair"};function Gx(n={}){let[e,t]=zx[n.key||"Alt"],i=ke.fromClass(class{constructor(r){this.view=r,this.isDown=!1}set(r){this.isDown!=r&&(this.isDown=r,this.view.update([]))}},{eventObservers:{keydown(r){this.set(r.keyCode==e||t(r))},keyup(r){(r.keyCode==e||!t(r))&&this.set(!1)},mousemove(r){this.set(t(r))}}});return[i,N.contentAttributes.of(r=>{var s;return!((s=r.plugin(i))===null||s===void 0)&&s.isDown?_x:null})]}const Bs="-10000px";class J0{constructor(e,t,i,r){this.facet=t,this.createTooltipView=i,this.removeTooltipView=r,this.input=e.state.facet(t),this.tooltips=this.input.filter(s=>s),this.tooltipViews=this.tooltips.map(i)}update(e,t){var i;let r=e.state.facet(this.facet),s=r.filter(l=>l);if(r===this.input){for(let l of this.tooltipViews)l.update&&l.update(e);return!1}let o=[],a=t?[]:null;for(let l=0;lt[h]=l),t.length=a.length),this.input=r,this.tooltips=s,this.tooltipViews=o,!0}}function Jx(n){let{win:e}=n;return{top:0,left:0,bottom:e.innerHeight,right:e.innerWidth}}const Uh=B.define({combine:n=>{var e,t,i;return{position:q.ios?"absolute":((e=n.find(r=>r.position))===null||e===void 0?void 0:e.position)||"fixed",parent:((t=n.find(r=>r.parent))===null||t===void 0?void 0:t.parent)||null,tooltipSpace:((i=n.find(r=>r.tooltipSpace))===null||i===void 0?void 0:i.tooltipSpace)||Jx}}}),Lp=new WeakMap,wf=ke.fromClass(class{constructor(n){this.view=n,this.above=[],this.inView=!0,this.madeAbsolute=!1,this.lastTransaction=0,this.measureTimeout=-1;let e=n.state.facet(Uh);this.position=e.position,this.parent=e.parent,this.classes=n.themeClasses,this.createContainer(),this.measureReq={read:this.readMeasure.bind(this),write:this.writeMeasure.bind(this),key:this},this.resizeObserver=typeof ResizeObserver=="function"?new ResizeObserver(()=>this.measureSoon()):null,this.manager=new J0(n,vf,t=>this.createTooltip(t),t=>{this.resizeObserver&&this.resizeObserver.unobserve(t.dom),t.dom.remove()}),this.above=this.manager.tooltips.map(t=>!!t.above),this.intersectionObserver=typeof IntersectionObserver=="function"?new IntersectionObserver(t=>{Date.now()>this.lastTransaction-50&&t.length>0&&t[t.length-1].intersectionRatio<1&&this.measureSoon()},{threshold:[1]}):null,this.observeIntersection(),n.win.addEventListener("resize",this.measureSoon=this.measureSoon.bind(this)),this.maybeMeasure()}createContainer(){this.parent?(this.container=document.createElement("div"),this.container.style.position="relative",this.container.className=this.view.themeClasses,this.parent.appendChild(this.container)):this.container=this.view.dom}observeIntersection(){if(this.intersectionObserver){this.intersectionObserver.disconnect();for(let n of this.manager.tooltipViews)this.intersectionObserver.observe(n.dom)}}measureSoon(){this.measureTimeout<0&&(this.measureTimeout=setTimeout(()=>{this.measureTimeout=-1,this.maybeMeasure()},50))}update(n){n.transactions.length&&(this.lastTransaction=Date.now());let e=this.manager.update(n,this.above);e&&this.observeIntersection();let t=e||n.geometryChanged,i=n.state.facet(Uh);if(i.position!=this.position&&!this.madeAbsolute){this.position=i.position;for(let r of this.manager.tooltipViews)r.dom.style.position=this.position;t=!0}if(i.parent!=this.parent){this.parent&&this.container.remove(),this.parent=i.parent,this.createContainer();for(let r of this.manager.tooltipViews)this.container.appendChild(r.dom);t=!0}else this.parent&&this.view.themeClasses!=this.classes&&(this.classes=this.container.className=this.view.themeClasses);t&&this.maybeMeasure()}createTooltip(n){let e=n.create(this.view);if(e.dom.classList.add("cm-tooltip"),n.arrow&&!e.dom.querySelector(".cm-tooltip > .cm-tooltip-arrow")){let t=document.createElement("div");t.className="cm-tooltip-arrow",e.dom.appendChild(t)}return e.dom.style.position=this.position,e.dom.style.top=Bs,e.dom.style.left="0px",this.container.appendChild(e.dom),e.mount&&e.mount(this.view),this.resizeObserver&&this.resizeObserver.observe(e.dom),e}destroy(){var n,e,t;this.view.win.removeEventListener("resize",this.measureSoon);for(let i of this.manager.tooltipViews)i.dom.remove(),(n=i.destroy)===null||n===void 0||n.call(i);this.parent&&this.container.remove(),(e=this.resizeObserver)===null||e===void 0||e.disconnect(),(t=this.intersectionObserver)===null||t===void 0||t.disconnect(),clearTimeout(this.measureTimeout)}readMeasure(){let n=this.view.dom.getBoundingClientRect(),e=1,t=1,i=!1;if(this.position=="fixed"&&this.manager.tooltipViews.length){let{dom:r}=this.manager.tooltipViews[0];if(q.gecko)i=r.offsetParent!=this.container.ownerDocument.body;else if(r.style.top==Bs&&r.style.left=="0px"){let s=r.getBoundingClientRect();i=Math.abs(s.top+1e4)>1||Math.abs(s.left)>1}}if(i||this.position=="absolute")if(this.parent){let r=this.parent.getBoundingClientRect();r.width&&r.height&&(e=r.width/this.parent.offsetWidth,t=r.height/this.parent.offsetHeight)}else({scaleX:e,scaleY:t}=this.view.viewState);return{editor:n,parent:this.parent?this.container.getBoundingClientRect():n,pos:this.manager.tooltips.map((r,s)=>{let o=this.manager.tooltipViews[s];return o.getCoords?o.getCoords(r.pos):this.view.coordsAtPos(r.pos)}),size:this.manager.tooltipViews.map(({dom:r})=>r.getBoundingClientRect()),space:this.view.state.facet(Uh).tooltipSpace(this.view),scaleX:e,scaleY:t,makeAbsolute:i}}writeMeasure(n){var e;if(n.makeAbsolute){this.madeAbsolute=!0,this.position="absolute";for(let a of this.manager.tooltipViews)a.dom.style.position="absolute"}let{editor:t,space:i,scaleX:r,scaleY:s}=n,o=[];for(let a=0;a=Math.min(t.bottom,i.bottom)||u.rightMath.min(t.right,i.right)+.1){c.style.top=Bs;continue}let p=l.arrow?h.dom.querySelector(".cm-tooltip-arrow"):null,g=p?7:0,O=f.right-f.left,y=(e=Lp.get(h))!==null&&e!==void 0?e:f.bottom-f.top,S=h.offset||Hx,k=this.view.textDirection==ge.LTR,$=f.width>i.right-i.left?k?i.left:i.right-f.width:k?Math.min(u.left-(p?14:0)+S.x,i.right-O):Math.max(i.left,u.left-O+(p?14:0)-S.x),x=this.above[a];!l.strictSide&&(x?u.top-(f.bottom-f.top)-S.yi.bottom)&&x==i.bottom-u.bottom>u.top-i.top&&(x=this.above[a]=!x);let Q=(x?u.top-i.top:i.bottom-u.bottom)-g;if(Q$&&j.topA&&(A=x?j.top-y-2-g:j.bottom+g+2);if(this.position=="absolute"?(c.style.top=(A-n.parent.top)/s+"px",c.style.left=($-n.parent.left)/r+"px"):(c.style.top=A/s+"px",c.style.left=$/r+"px"),p){let j=u.left+(k?S.x:-S.x)-($+14-7);p.style.left=j/r+"px"}h.overlap!==!0&&o.push({left:$,top:A,right:R,bottom:A+y}),c.classList.toggle("cm-tooltip-above",x),c.classList.toggle("cm-tooltip-below",!x),h.positioned&&h.positioned(n.space)}}maybeMeasure(){if(this.manager.tooltips.length&&(this.view.inView&&this.view.requestMeasure(this.measureReq),this.inView!=this.view.inView&&(this.inView=this.view.inView,!this.inView)))for(let n of this.manager.tooltipViews)n.dom.style.top=Bs}},{eventObservers:{scroll(){this.maybeMeasure()}}}),Yx=N.baseTheme({".cm-tooltip":{zIndex:100,boxSizing:"border-box"},"&light .cm-tooltip":{border:"1px solid #bbb",backgroundColor:"#f5f5f5"},"&light .cm-tooltip-section:not(:first-child)":{borderTop:"1px solid #bbb"},"&dark .cm-tooltip":{backgroundColor:"#333338",color:"white"},".cm-tooltip-arrow":{height:"7px",width:`${7*2}px`,position:"absolute",zIndex:-1,overflow:"hidden","&:before, &:after":{content:"''",position:"absolute",width:0,height:0,borderLeft:"7px solid transparent",borderRight:"7px solid transparent"},".cm-tooltip-above &":{bottom:"-7px","&:before":{borderTop:"7px solid #bbb"},"&:after":{borderTop:"7px solid #f5f5f5",bottom:"1px"}},".cm-tooltip-below &":{top:"-7px","&:before":{borderBottom:"7px solid #bbb"},"&:after":{borderBottom:"7px solid #f5f5f5",top:"1px"}}},"&dark .cm-tooltip .cm-tooltip-arrow":{"&:before":{borderTopColor:"#333338",borderBottomColor:"#333338"},"&:after":{borderTopColor:"transparent",borderBottomColor:"transparent"}}}),Hx={x:0,y:0},vf=B.define({enables:[wf,Yx]}),Pl=B.define();class hh{static create(e){return new hh(e)}constructor(e){this.view=e,this.mounted=!1,this.dom=document.createElement("div"),this.dom.classList.add("cm-tooltip-hover"),this.manager=new J0(e,Pl,t=>this.createHostedView(t),t=>t.dom.remove())}createHostedView(e){let t=e.create(this.view);return t.dom.classList.add("cm-tooltip-section"),this.dom.appendChild(t.dom),this.mounted&&t.mount&&t.mount(this.view),t}mount(e){for(let t of this.manager.tooltipViews)t.mount&&t.mount(e);this.mounted=!0}positioned(e){for(let t of this.manager.tooltipViews)t.positioned&&t.positioned(e)}update(e){this.manager.update(e)}destroy(){var e;for(let t of this.manager.tooltipViews)(e=t.destroy)===null||e===void 0||e.call(t)}passProp(e){let t;for(let i of this.manager.tooltipViews){let r=i[e];if(r!==void 0){if(t===void 0)t=r;else if(t!==r)return}}return t}get offset(){return this.passProp("offset")}get getCoords(){return this.passProp("getCoords")}get overlap(){return this.passProp("overlap")}get resize(){return this.passProp("resize")}}const Kx=vf.compute([Pl],n=>{let e=n.facet(Pl).filter(t=>t);return e.length===0?null:{pos:Math.min(...e.map(t=>t.pos)),end:Math.max(...e.map(t=>{var i;return(i=t.end)!==null&&i!==void 0?i:t.pos})),create:hh.create,above:e[0].above,arrow:e.some(t=>t.arrow)}});class eT{constructor(e,t,i,r,s){this.view=e,this.source=t,this.field=i,this.setHover=r,this.hoverTime=s,this.hoverTimeout=-1,this.restartTimeout=-1,this.pending=null,this.lastMove={x:0,y:0,target:e.dom,time:0},this.checkHover=this.checkHover.bind(this),e.dom.addEventListener("mouseleave",this.mouseleave=this.mouseleave.bind(this)),e.dom.addEventListener("mousemove",this.mousemove=this.mousemove.bind(this))}update(){this.pending&&(this.pending=null,clearTimeout(this.restartTimeout),this.restartTimeout=setTimeout(()=>this.startHover(),20))}get active(){return this.view.state.field(this.field)}checkHover(){if(this.hoverTimeout=-1,this.active)return;let e=Date.now()-this.lastMove.time;ea.bottom||t.xa.right+e.defaultCharacterWidth)return;let l=e.bidiSpans(e.state.doc.lineAt(r)).find(c=>c.from<=r&&c.to>=r),h=l&&l.dir==ge.RTL?-1:1;s=t.x{this.pending==a&&(this.pending=null,l&&e.dispatch({effects:this.setHover.of(l)}))},l=>mt(e.state,l,"hover tooltip"))}else o&&e.dispatch({effects:this.setHover.of(o)})}get tooltip(){let e=this.view.plugin(wf),t=e?e.manager.tooltips.findIndex(i=>i.create==hh.create):-1;return t>-1?e.manager.tooltipViews[t]:null}mousemove(e){var t;this.lastMove={x:e.clientX,y:e.clientY,target:e.target,time:Date.now()},this.hoverTimeout<0&&(this.hoverTimeout=setTimeout(this.checkHover,this.hoverTime));let{active:i,tooltip:r}=this;if(i&&r&&!tT(r.dom,e)||this.pending){let{pos:s}=i||this.pending,o=(t=i==null?void 0:i.end)!==null&&t!==void 0?t:s;(s==o?this.view.posAtCoords(this.lastMove)!=s:!iT(this.view,s,o,e.clientX,e.clientY))&&(this.view.dispatch({effects:this.setHover.of(null)}),this.pending=null)}}mouseleave(e){clearTimeout(this.hoverTimeout),this.hoverTimeout=-1;let{active:t}=this;if(t){let{tooltip:i}=this;i&&i.dom.contains(e.relatedTarget)?this.watchTooltipLeave(i.dom):this.view.dispatch({effects:this.setHover.of(null)})}}watchTooltipLeave(e){let t=i=>{e.removeEventListener("mouseleave",t),this.active&&!this.view.dom.contains(i.relatedTarget)&&this.view.dispatch({effects:this.setHover.of(null)})};e.addEventListener("mouseleave",t)}destroy(){clearTimeout(this.hoverTimeout),this.view.dom.removeEventListener("mouseleave",this.mouseleave),this.view.dom.removeEventListener("mousemove",this.mousemove)}}const ma=4;function tT(n,e){let t=n.getBoundingClientRect();return e.clientX>=t.left-ma&&e.clientX<=t.right+ma&&e.clientY>=t.top-ma&&e.clientY<=t.bottom+ma}function iT(n,e,t,i,r,s){let o=n.scrollDOM.getBoundingClientRect(),a=n.documentTop+n.documentPadding.top+n.contentHeight;if(o.left>i||o.rightr||Math.min(o.bottom,a)=e&&l<=t}function nT(n,e={}){let t=z.define(),i=Re.define({create(){return null},update(r,s){if(r&&(e.hideOnChange&&(s.docChanged||s.selection)||e.hideOn&&e.hideOn(s,r)))return null;if(r&&s.docChanged){let o=s.changes.mapPos(r.pos,-1,qe.TrackDel);if(o==null)return null;let a=Object.assign(Object.create(null),r);a.pos=o,r.end!=null&&(a.end=s.changes.mapPos(r.end)),r=a}for(let o of s.effects)o.is(t)&&(r=o.value),o.is(sT)&&(r=null);return r},provide:r=>Pl.from(r)});return[i,ke.define(r=>new eT(r,n,i,t,e.hoverTime||300)),Kx]}function rT(n,e){let t=n.plugin(wf);if(!t)return null;let i=t.manager.tooltips.indexOf(e);return i<0?null:t.manager.tooltipViews[i]}const sT=z.define(),Up=B.define({combine(n){let e,t;for(let i of n)e=e||i.topContainer,t=t||i.bottomContainer;return{topContainer:e,bottomContainer:t}}});function Qo(n,e){let t=n.plugin(Y0),i=t?t.specs.indexOf(e):-1;return i>-1?t.panels[i]:null}const Y0=ke.fromClass(class{constructor(n){this.input=n.state.facet(Po),this.specs=this.input.filter(t=>t),this.panels=this.specs.map(t=>t(n));let e=n.state.facet(Up);this.top=new Oa(n,!0,e.topContainer),this.bottom=new Oa(n,!1,e.bottomContainer),this.top.sync(this.panels.filter(t=>t.top)),this.bottom.sync(this.panels.filter(t=>!t.top));for(let t of this.panels)t.dom.classList.add("cm-panel"),t.mount&&t.mount()}update(n){let e=n.state.facet(Up);this.top.container!=e.topContainer&&(this.top.sync([]),this.top=new Oa(n.view,!0,e.topContainer)),this.bottom.container!=e.bottomContainer&&(this.bottom.sync([]),this.bottom=new Oa(n.view,!1,e.bottomContainer)),this.top.syncClasses(),this.bottom.syncClasses();let t=n.state.facet(Po);if(t!=this.input){let i=t.filter(l=>l),r=[],s=[],o=[],a=[];for(let l of i){let h=this.specs.indexOf(l),c;h<0?(c=l(n.view),a.push(c)):(c=this.panels[h],c.update&&c.update(n)),r.push(c),(c.top?s:o).push(c)}this.specs=i,this.panels=r,this.top.sync(s),this.bottom.sync(o);for(let l of a)l.dom.classList.add("cm-panel"),l.mount&&l.mount()}else for(let i of this.panels)i.update&&i.update(n)}destroy(){this.top.sync([]),this.bottom.sync([])}},{provide:n=>N.scrollMargins.of(e=>{let t=e.plugin(n);return t&&{top:t.top.scrollMargin(),bottom:t.bottom.scrollMargin()}})});class Oa{constructor(e,t,i){this.view=e,this.top=t,this.container=i,this.dom=void 0,this.classes="",this.panels=[],this.syncClasses()}sync(e){for(let t of this.panels)t.destroy&&e.indexOf(t)<0&&t.destroy();this.panels=e,this.syncDOM()}syncDOM(){if(this.panels.length==0){this.dom&&(this.dom.remove(),this.dom=void 0);return}if(!this.dom){this.dom=document.createElement("div"),this.dom.className=this.top?"cm-panels cm-panels-top":"cm-panels cm-panels-bottom",this.dom.style[this.top?"top":"bottom"]="0";let t=this.container||this.view.dom;t.insertBefore(this.dom,this.top?t.firstChild:null)}let e=this.dom.firstChild;for(let t of this.panels)if(t.dom.parentNode==this.dom){for(;e!=t.dom;)e=Zp(e);e=e.nextSibling}else this.dom.insertBefore(t.dom,e);for(;e;)e=Zp(e)}scrollMargin(){return!this.dom||this.container?0:Math.max(0,this.top?this.dom.getBoundingClientRect().bottom-Math.max(0,this.view.scrollDOM.getBoundingClientRect().top):Math.min(innerHeight,this.view.scrollDOM.getBoundingClientRect().bottom)-this.dom.getBoundingClientRect().top)}syncClasses(){if(!(!this.container||this.classes==this.view.themeClasses)){for(let e of this.classes.split(" "))e&&this.container.classList.remove(e);for(let e of(this.classes=this.view.themeClasses).split(" "))e&&this.container.classList.add(e)}}}function Zp(n){let e=n.nextSibling;return n.remove(),e}const Po=B.define({enables:Y0});class Zn extends Br{compare(e){return this==e||this.constructor==e.constructor&&this.eq(e)}eq(e){return!1}destroy(e){}}Zn.prototype.elementClass="";Zn.prototype.toDOM=void 0;Zn.prototype.mapMode=qe.TrackBefore;Zn.prototype.startSide=Zn.prototype.endSide=-1;Zn.prototype.point=!0;const Fa=B.define(),oT={class:"",renderEmptyElements:!1,elementStyle:"",markers:()=>J.empty,lineMarker:()=>null,widgetMarker:()=>null,lineMarkerChange:null,initialSpacer:null,updateSpacer:null,domEventHandlers:{}},ro=B.define();function aT(n){return[H0(),ro.of(Object.assign(Object.assign({},oT),n))]}const Wp=B.define({combine:n=>n.some(e=>e)});function H0(n){return[lT]}const lT=ke.fromClass(class{constructor(n){this.view=n,this.prevViewport=n.viewport,this.dom=document.createElement("div"),this.dom.className="cm-gutters",this.dom.setAttribute("aria-hidden","true"),this.dom.style.minHeight=this.view.contentHeight/this.view.scaleY+"px",this.gutters=n.state.facet(ro).map(e=>new Fp(n,e));for(let e of this.gutters)this.dom.appendChild(e.dom);this.fixed=!n.state.facet(Wp),this.fixed&&(this.dom.style.position="sticky"),this.syncGutters(!1),n.scrollDOM.insertBefore(this.dom,n.contentDOM)}update(n){if(this.updateGutters(n)){let e=this.prevViewport,t=n.view.viewport,i=Math.min(e.to,t.to)-Math.max(e.from,t.from);this.syncGutters(i<(t.to-t.from)*.8)}n.geometryChanged&&(this.dom.style.minHeight=this.view.contentHeight+"px"),this.view.state.facet(Wp)!=!this.fixed&&(this.fixed=!this.fixed,this.dom.style.position=this.fixed?"sticky":""),this.prevViewport=n.view.viewport}syncGutters(n){let e=this.dom.nextSibling;n&&this.dom.remove();let t=J.iter(this.view.state.facet(Fa),this.view.viewport.from),i=[],r=this.gutters.map(s=>new hT(s,this.view.viewport,-this.view.documentPadding.top));for(let s of this.view.viewportLineBlocks)if(i.length&&(i=[]),Array.isArray(s.type)){let o=!0;for(let a of s.type)if(a.type==Je.Text&&o){vu(t,i,a.from);for(let l of r)l.line(this.view,a,i);o=!1}else if(a.widget)for(let l of r)l.widget(this.view,a)}else if(s.type==Je.Text){vu(t,i,s.from);for(let o of r)o.line(this.view,s,i)}else if(s.widget)for(let o of r)o.widget(this.view,s);for(let s of r)s.finish();n&&this.view.scrollDOM.insertBefore(this.dom,e)}updateGutters(n){let e=n.startState.facet(ro),t=n.state.facet(ro),i=n.docChanged||n.heightChanged||n.viewportChanged||!J.eq(n.startState.facet(Fa),n.state.facet(Fa),n.view.viewport.from,n.view.viewport.to);if(e==t)for(let r of this.gutters)r.update(n)&&(i=!0);else{i=!0;let r=[];for(let s of t){let o=e.indexOf(s);o<0?r.push(new Fp(this.view,s)):(this.gutters[o].update(n),r.push(this.gutters[o]))}for(let s of this.gutters)s.dom.remove(),r.indexOf(s)<0&&s.destroy();for(let s of r)this.dom.appendChild(s.dom);this.gutters=r}return i}destroy(){for(let n of this.gutters)n.destroy();this.dom.remove()}},{provide:n=>N.scrollMargins.of(e=>{let t=e.plugin(n);return!t||t.gutters.length==0||!t.fixed?null:e.textDirection==ge.LTR?{left:t.dom.offsetWidth*e.scaleX}:{right:t.dom.offsetWidth*e.scaleX}})});function jp(n){return Array.isArray(n)?n:[n]}function vu(n,e,t){for(;n.value&&n.from<=t;)n.from==t&&e.push(n.value),n.next()}class hT{constructor(e,t,i){this.gutter=e,this.height=i,this.i=0,this.cursor=J.iter(e.markers,t.from)}addElement(e,t,i){let{gutter:r}=this,s=(t.top-this.height)/e.scaleY,o=t.height/e.scaleY;if(this.i==r.elements.length){let a=new K0(e,o,s,i);r.elements.push(a),r.dom.appendChild(a.dom)}else r.elements[this.i].update(e,o,s,i);this.height=t.bottom,this.i++}line(e,t,i){let r=[];vu(this.cursor,r,t.from),i.length&&(r=r.concat(i));let s=this.gutter.config.lineMarker(e,t,r);s&&r.unshift(s);let o=this.gutter;r.length==0&&!o.config.renderEmptyElements||this.addElement(e,t,r)}widget(e,t){let i=this.gutter.config.widgetMarker(e,t.widget,t);i&&this.addElement(e,t,[i])}finish(){let e=this.gutter;for(;e.elements.length>this.i;){let t=e.elements.pop();e.dom.removeChild(t.dom),t.destroy()}}}class Fp{constructor(e,t){this.view=e,this.config=t,this.elements=[],this.spacer=null,this.dom=document.createElement("div"),this.dom.className="cm-gutter"+(this.config.class?" "+this.config.class:"");for(let i in t.domEventHandlers)this.dom.addEventListener(i,r=>{let s=r.target,o;if(s!=this.dom&&this.dom.contains(s)){for(;s.parentNode!=this.dom;)s=s.parentNode;let l=s.getBoundingClientRect();o=(l.top+l.bottom)/2}else o=r.clientY;let a=e.lineBlockAtHeight(o-e.documentTop);t.domEventHandlers[i](e,a,r)&&r.preventDefault()});this.markers=jp(t.markers(e)),t.initialSpacer&&(this.spacer=new K0(e,0,0,[t.initialSpacer(e)]),this.dom.appendChild(this.spacer.dom),this.spacer.dom.style.cssText+="visibility: hidden; pointer-events: none")}update(e){let t=this.markers;if(this.markers=jp(this.config.markers(e.view)),this.spacer&&this.config.updateSpacer){let r=this.config.updateSpacer(this.spacer.markers[0],e);r!=this.spacer.markers[0]&&this.spacer.update(e.view,0,0,[r])}let i=e.view.viewport;return!J.eq(this.markers,t,i.from,i.to)||(this.config.lineMarkerChange?this.config.lineMarkerChange(e):!1)}destroy(){for(let e of this.elements)e.destroy()}}class K0{constructor(e,t,i,r){this.height=-1,this.above=0,this.markers=[],this.dom=document.createElement("div"),this.dom.className="cm-gutterElement",this.update(e,t,i,r)}update(e,t,i,r){this.height!=t&&(this.height=t,this.dom.style.height=t+"px"),this.above!=i&&(this.dom.style.marginTop=(this.above=i)?i+"px":""),cT(this.markers,r)||this.setMarkers(e,r)}setMarkers(e,t){let i="cm-gutterElement",r=this.dom.firstChild;for(let s=0,o=0;;){let a=o,l=ss(a,l,h)||o(a,l,h):o}return i}})}});class Zh extends Zn{constructor(e){super(),this.number=e}eq(e){return this.number==e.number}toDOM(){return document.createTextNode(this.number)}}function Wh(n,e){return n.state.facet(Yr).formatNumber(e,n.state)}const fT=ro.compute([Yr],n=>({class:"cm-lineNumbers",renderEmptyElements:!1,markers(e){return e.state.facet(uT)},lineMarker(e,t,i){return i.some(r=>r.toDOM)?null:new Zh(Wh(e,e.state.doc.lineAt(t.from).number))},widgetMarker:()=>null,lineMarkerChange:e=>e.startState.facet(Yr)!=e.state.facet(Yr),initialSpacer(e){return new Zh(Wh(e,zp(e.state.doc.lines)))},updateSpacer(e,t){let i=Wh(t.view,zp(t.view.state.doc.lines));return i==e.number?e:new Zh(i)},domEventHandlers:n.facet(Yr).domEventHandlers}));function dT(n={}){return[Yr.of(n),H0(),fT]}function zp(n){let e=9;for(;e{let e=[],t=-1;for(let i of n.selection.ranges){let r=n.doc.lineAt(i.head).from;r>t&&(t=r,e.push(pT.range(r)))}return J.of(e)});function mT(){return gT}const ey=1024;let OT=0;class Rt{constructor(e,t){this.from=e,this.to=t}}class _{constructor(e={}){this.id=OT++,this.perNode=!!e.perNode,this.deserialize=e.deserialize||(()=>{throw new Error("This node type doesn't define a deserialize function")})}add(e){if(this.perNode)throw new RangeError("Can't add per-node props to node types");return typeof e!="function"&&(e=Ie.match(e)),t=>{let i=e(t);return i===void 0?null:[this,i]}}}_.closedBy=new _({deserialize:n=>n.split(" ")});_.openedBy=new _({deserialize:n=>n.split(" ")});_.group=new _({deserialize:n=>n.split(" ")});_.contextHash=new _({perNode:!0});_.lookAhead=new _({perNode:!0});_.mounted=new _({perNode:!0});class yT{constructor(e,t,i){this.tree=e,this.overlay=t,this.parser=i}}const bT=Object.create(null);class Ie{constructor(e,t,i,r=0){this.name=e,this.props=t,this.id=i,this.flags=r}static define(e){let t=e.props&&e.props.length?Object.create(null):bT,i=(e.top?1:0)|(e.skipped?2:0)|(e.error?4:0)|(e.name==null?8:0),r=new Ie(e.name||"",t,e.id,i);if(e.props){for(let s of e.props)if(Array.isArray(s)||(s=s(r)),s){if(s[0].perNode)throw new RangeError("Can't store a per-node prop on a node type");t[s[0].id]=s[1]}}return r}prop(e){return this.props[e.id]}get isTop(){return(this.flags&1)>0}get isSkipped(){return(this.flags&2)>0}get isError(){return(this.flags&4)>0}get isAnonymous(){return(this.flags&8)>0}is(e){if(typeof e=="string"){if(this.name==e)return!0;let t=this.prop(_.group);return t?t.indexOf(e)>-1:!1}return this.id==e}static match(e){let t=Object.create(null);for(let i in e)for(let r of i.split(" "))t[r]=e[i];return i=>{for(let r=i.prop(_.group),s=-1;s<(r?r.length:0);s++){let o=t[s<0?i.name:r[s]];if(o)return o}}}}Ie.none=new Ie("",Object.create(null),0,8);class Fo{constructor(e){this.types=e;for(let t=0;t=r&&(o.type.isAnonymous||t(o)!==!1)){if(o.firstChild())continue;a=!0}for(;a&&i&&!o.type.isAnonymous&&i(o),!o.nextSibling();){if(!o.parent())return;a=!0}}}prop(e){return e.perNode?this.props?this.props[e.id]:void 0:this.type.prop(e)}get propValues(){let e=[];if(this.props)for(let t in this.props)e.push([+t,this.props[t]]);return e}balance(e={}){return this.children.length<=8?this:Tf(Ie.none,this.children,this.positions,0,this.children.length,0,this.length,(t,i,r)=>new ne(this.type,t,i,r,this.propValues),e.makeTree||((t,i,r)=>new ne(Ie.none,t,i,r)))}static build(e){return wT(e)}}ne.empty=new ne(Ie.none,[],[],0);class kf{constructor(e,t){this.buffer=e,this.index=t}get id(){return this.buffer[this.index-4]}get start(){return this.buffer[this.index-3]}get end(){return this.buffer[this.index-2]}get size(){return this.buffer[this.index-1]}get pos(){return this.index}next(){this.index-=4}fork(){return new kf(this.buffer,this.index)}}class Lr{constructor(e,t,i){this.buffer=e,this.length=t,this.set=i}get type(){return Ie.none}toString(){let e=[];for(let t=0;t0));l=o[l+3]);return a}slice(e,t,i){let r=this.buffer,s=new Uint16Array(t-e),o=0;for(let a=e,l=0;a=e&&te;case 1:return t<=e&&i>e;case 2:return i>e;case 4:return!0}}function iy(n,e){let t=n.childBefore(e);for(;t;){let i=t.lastChild;if(!i||i.to!=t.to)break;i.type.isError&&i.from==i.to?(n=t,t=i.prevSibling):t=i}return n}function bs(n,e,t,i){for(var r;n.from==n.to||(t<1?n.from>=e:n.from>e)||(t>-1?n.to<=e:n.to0?a.length:-1;e!=h;e+=t){let c=a[e],u=l[e]+o.from;if(ty(r,i,u,u+c.length)){if(c instanceof Lr){if(s&ce.ExcludeBuffers)continue;let f=c.findChild(0,c.buffer.length,t,i-u,r);if(f>-1)return new vi(new ST(o,c,e,u),null,f)}else if(s&ce.IncludeAnonymous||!c.type.isAnonymous||xf(c)){let f;if(!(s&ce.IgnoreMounts)&&c.props&&(f=c.prop(_.mounted))&&!f.overlay)return new Bt(f.tree,u,e,o);let p=new Bt(c,u,e,o);return s&ce.IncludeAnonymous||!p.type.isAnonymous?p:p.nextChild(t<0?c.children.length-1:0,t,i,r)}}}if(s&ce.IncludeAnonymous||!o.type.isAnonymous||(o.index>=0?e=o.index+t:e=t<0?-1:o._parent._tree.children.length,o=o._parent,!o))return null}}get firstChild(){return this.nextChild(0,1,0,4)}get lastChild(){return this.nextChild(this._tree.children.length-1,-1,0,4)}childAfter(e){return this.nextChild(0,1,e,2)}childBefore(e){return this.nextChild(this._tree.children.length-1,-1,e,-2)}enter(e,t,i=0){let r;if(!(i&ce.IgnoreOverlays)&&(r=this._tree.prop(_.mounted))&&r.overlay){let s=e-this.from;for(let{from:o,to:a}of r.overlay)if((t>0?o<=s:o=s:a>s))return new Bt(r.tree,r.overlay[0].from+this.from,-1,this)}return this.nextChild(0,1,e,t,i)}nextSignificantParent(){let e=this;for(;e.type.isAnonymous&&e._parent;)e=e._parent;return e}get parent(){return this._parent?this._parent.nextSignificantParent():null}get nextSibling(){return this._parent&&this.index>=0?this._parent.nextChild(this.index+1,1,0,4):null}get prevSibling(){return this._parent&&this.index>=0?this._parent.nextChild(this.index-1,-1,0,4):null}cursor(e=0){return new Ao(this,e)}get tree(){return this._tree}toTree(){return this._tree}resolve(e,t=0){return bs(this,e,t,!1)}resolveInner(e,t=0){return bs(this,e,t,!0)}enterUnfinishedNodesBefore(e){return iy(this,e)}getChild(e,t=null,i=null){let r=Al(this,e,t,i);return r.length?r[0]:null}getChildren(e,t=null,i=null){return Al(this,e,t,i)}toString(){return this._tree.toString()}get node(){return this}matchContext(e){return $l(this,e)}}function Al(n,e,t,i){let r=n.cursor(),s=[];if(!r.firstChild())return s;if(t!=null){for(;!r.type.is(t);)if(!r.nextSibling())return s}for(;;){if(i!=null&&r.type.is(i))return s;if(r.type.is(e)&&s.push(r.node),!r.nextSibling())return i==null?s:[]}}function $l(n,e,t=e.length-1){for(let i=n.parent;t>=0;i=i.parent){if(!i)return!1;if(!i.type.isAnonymous){if(e[t]&&e[t]!=i.name)return!1;t--}}return!0}class ST{constructor(e,t,i,r){this.parent=e,this.buffer=t,this.index=i,this.start=r}}class vi{get name(){return this.type.name}get from(){return this.context.start+this.context.buffer.buffer[this.index+1]}get to(){return this.context.start+this.context.buffer.buffer[this.index+2]}constructor(e,t,i){this.context=e,this._parent=t,this.index=i,this.type=e.buffer.set.types[e.buffer.buffer[i]]}child(e,t,i){let{buffer:r}=this.context,s=r.findChild(this.index+4,r.buffer[this.index+3],e,t-this.context.start,i);return s<0?null:new vi(this.context,this,s)}get firstChild(){return this.child(1,0,4)}get lastChild(){return this.child(-1,0,4)}childAfter(e){return this.child(1,e,2)}childBefore(e){return this.child(-1,e,-2)}enter(e,t,i=0){if(i&ce.ExcludeBuffers)return null;let{buffer:r}=this.context,s=r.findChild(this.index+4,r.buffer[this.index+3],t>0?1:-1,e-this.context.start,t);return s<0?null:new vi(this.context,this,s)}get parent(){return this._parent||this.context.parent.nextSignificantParent()}externalSibling(e){return this._parent?null:this.context.parent.nextChild(this.context.index+e,e,0,4)}get nextSibling(){let{buffer:e}=this.context,t=e.buffer[this.index+3];return t<(this._parent?e.buffer[this._parent.index+3]:e.buffer.length)?new vi(this.context,this._parent,t):this.externalSibling(1)}get prevSibling(){let{buffer:e}=this.context,t=this._parent?this._parent.index+4:0;return this.index==t?this.externalSibling(-1):new vi(this.context,this._parent,e.findChild(t,this.index,-1,0,4))}cursor(e=0){return new Ao(this,e)}get tree(){return null}toTree(){let e=[],t=[],{buffer:i}=this.context,r=this.index+4,s=i.buffer[this.index+3];if(s>r){let o=i.buffer[this.index+1];e.push(i.slice(r,s,o)),t.push(0)}return new ne(this.type,e,t,this.to-this.from)}resolve(e,t=0){return bs(this,e,t,!1)}resolveInner(e,t=0){return bs(this,e,t,!0)}enterUnfinishedNodesBefore(e){return iy(this,e)}toString(){return this.context.buffer.childString(this.index)}getChild(e,t=null,i=null){let r=Al(this,e,t,i);return r.length?r[0]:null}getChildren(e,t=null,i=null){return Al(this,e,t,i)}get node(){return this}matchContext(e){return $l(this,e)}}class Ao{get name(){return this.type.name}constructor(e,t=0){if(this.mode=t,this.buffer=null,this.stack=[],this.index=0,this.bufferNode=null,e instanceof Bt)this.yieldNode(e);else{this._tree=e.context.parent,this.buffer=e.context;for(let i=e._parent;i;i=i._parent)this.stack.unshift(i.index);this.bufferNode=e,this.yieldBuf(e.index)}}yieldNode(e){return e?(this._tree=e,this.type=e.type,this.from=e.from,this.to=e.to,!0):!1}yieldBuf(e,t){this.index=e;let{start:i,buffer:r}=this.buffer;return this.type=t||r.set.types[r.buffer[e]],this.from=i+r.buffer[e+1],this.to=i+r.buffer[e+2],!0}yield(e){return e?e instanceof Bt?(this.buffer=null,this.yieldNode(e)):(this.buffer=e.context,this.yieldBuf(e.index,e.type)):!1}toString(){return this.buffer?this.buffer.buffer.childString(this.index):this._tree.toString()}enterChild(e,t,i){if(!this.buffer)return this.yield(this._tree.nextChild(e<0?this._tree._tree.children.length-1:0,e,t,i,this.mode));let{buffer:r}=this.buffer,s=r.findChild(this.index+4,r.buffer[this.index+3],e,t-this.buffer.start,i);return s<0?!1:(this.stack.push(this.index),this.yieldBuf(s))}firstChild(){return this.enterChild(1,0,4)}lastChild(){return this.enterChild(-1,0,4)}childAfter(e){return this.enterChild(1,e,2)}childBefore(e){return this.enterChild(-1,e,-2)}enter(e,t,i=this.mode){return this.buffer?i&ce.ExcludeBuffers?!1:this.enterChild(1,e,t):this.yield(this._tree.enter(e,t,i))}parent(){if(!this.buffer)return this.yieldNode(this.mode&ce.IncludeAnonymous?this._tree._parent:this._tree.parent);if(this.stack.length)return this.yieldBuf(this.stack.pop());let e=this.mode&ce.IncludeAnonymous?this.buffer.parent:this.buffer.parent.nextSignificantParent();return this.buffer=null,this.yieldNode(e)}sibling(e){if(!this.buffer)return this._tree._parent?this.yield(this._tree.index<0?null:this._tree._parent.nextChild(this._tree.index+e,e,0,4,this.mode)):!1;let{buffer:t}=this.buffer,i=this.stack.length-1;if(e<0){let r=i<0?0:this.stack[i]+4;if(this.index!=r)return this.yieldBuf(t.findChild(r,this.index,-1,0,4))}else{let r=t.buffer[this.index+3];if(r<(i<0?t.buffer.length:t.buffer[this.stack[i]+3]))return this.yieldBuf(r)}return i<0?this.yield(this.buffer.parent.nextChild(this.buffer.index+e,e,0,4,this.mode)):!1}nextSibling(){return this.sibling(1)}prevSibling(){return this.sibling(-1)}atLastNode(e){let t,i,{buffer:r}=this;if(r){if(e>0){if(this.index-1)for(let s=t+e,o=e<0?-1:i._tree.children.length;s!=o;s+=e){let a=i._tree.children[s];if(this.mode&ce.IncludeAnonymous||a instanceof Lr||!a.type.isAnonymous||xf(a))return!1}return!0}move(e,t){if(t&&this.enterChild(e,0,4))return!0;for(;;){if(this.sibling(e))return!0;if(this.atLastNode(e)||!this.parent())return!1}}next(e=!0){return this.move(1,e)}prev(e=!0){return this.move(-1,e)}moveTo(e,t=0){for(;(this.from==this.to||(t<1?this.from>=e:this.from>e)||(t>-1?this.to<=e:this.to=0;){for(let o=e;o;o=o._parent)if(o.index==r){if(r==this.index)return o;t=o,i=s+1;break e}r=this.stack[--s]}for(let r=i;r=0;s--){if(s<0)return $l(this.node,e,r);let o=i[t.buffer[this.stack[s]]];if(!o.isAnonymous){if(e[r]&&e[r]!=o.name)return!1;r--}}return!0}}function xf(n){return n.children.some(e=>e instanceof Lr||!e.type.isAnonymous||xf(e))}function wT(n){var e;let{buffer:t,nodeSet:i,maxBufferLength:r=ey,reused:s=[],minRepeatType:o=i.types.length}=n,a=Array.isArray(t)?new kf(t,t.length):t,l=i.types,h=0,c=0;function u(x,Q,A,R,j){let{id:W,start:G,end:re,size:Qe}=a,Ve=c;for(;Qe<0;)if(a.next(),Qe==-1){let Ke=s[W];A.push(Ke),R.push(G-x);return}else if(Qe==-3){h=W;return}else if(Qe==-4){c=W;return}else throw new RangeError(`Unrecognized record size: ${Qe}`);let He=l[W],Ee,Xe,ni=G-x;if(re-G<=r&&(Xe=O(a.pos-Q,j))){let Ke=new Uint16Array(Xe.size-Xe.skip),be=a.pos-Xe.size,Pe=Ke.length;for(;a.pos>be;)Pe=y(Xe.start,Ke,Pe);Ee=new Lr(Ke,re-Xe.start,i),ni=Xe.start-x}else{let Ke=a.pos-Qe;a.next();let be=[],Pe=[],br=W>=o?W:-1,Ur=0,Ho=re;for(;a.pos>Ke;)br>=0&&a.id==br&&a.size>=0?(a.end<=Ho-r&&(p(be,Pe,G,Ur,a.end,Ho,br,Ve),Ur=be.length,Ho=a.end),a.next()):u(G,Ke,be,Pe,br);if(br>=0&&Ur>0&&Ur-1&&Ur>0){let Hf=f(He);Ee=Tf(He,be,Pe,0,be.length,0,re-G,Hf,Hf)}else Ee=g(He,be,Pe,re-G,Ve-re)}A.push(Ee),R.push(ni)}function f(x){return(Q,A,R)=>{let j=0,W=Q.length-1,G,re;if(W>=0&&(G=Q[W])instanceof ne){if(!W&&G.type==x&&G.length==R)return G;(re=G.prop(_.lookAhead))&&(j=A[W]+G.length+re)}return g(x,Q,A,R,j)}}function p(x,Q,A,R,j,W,G,re){let Qe=[],Ve=[];for(;x.length>R;)Qe.push(x.pop()),Ve.push(Q.pop()+A-j);x.push(g(i.types[G],Qe,Ve,W-j,re-W)),Q.push(j-A)}function g(x,Q,A,R,j=0,W){if(h){let G=[_.contextHash,h];W=W?[G].concat(W):[G]}if(j>25){let G=[_.lookAhead,j];W=W?[G].concat(W):[G]}return new ne(x,Q,A,R,W)}function O(x,Q){let A=a.fork(),R=0,j=0,W=0,G=A.end-r,re={size:0,start:0,skip:0};e:for(let Qe=A.pos-x;A.pos>Qe;){let Ve=A.size;if(A.id==Q&&Ve>=0){re.size=R,re.start=j,re.skip=W,W+=4,R+=4,A.next();continue}let He=A.pos-Ve;if(Ve<0||He=o?4:0,Xe=A.start;for(A.next();A.pos>He;){if(A.size<0)if(A.size==-3)Ee+=4;else break e;else A.id>=o&&(Ee+=4);A.next()}j=Xe,R+=Ve,W+=Ee}return(Q<0||R==x)&&(re.size=R,re.start=j,re.skip=W),re.size>4?re:void 0}function y(x,Q,A){let{id:R,start:j,end:W,size:G}=a;if(a.next(),G>=0&&R4){let Qe=a.pos-(G-4);for(;a.pos>Qe;)A=y(x,Q,A)}Q[--A]=re,Q[--A]=W-x,Q[--A]=j-x,Q[--A]=R}else G==-3?h=R:G==-4&&(c=R);return A}let S=[],k=[];for(;a.pos>0;)u(n.start||0,n.bufferStart||0,S,k,-1);let $=(e=n.length)!==null&&e!==void 0?e:S.length?k[0]+S[0].length:0;return new ne(l[n.topID],S.reverse(),k.reverse(),$)}const Gp=new WeakMap;function za(n,e){if(!n.isAnonymous||e instanceof Lr||e.type!=n)return 1;let t=Gp.get(e);if(t==null){t=1;for(let i of e.children){if(i.type!=n||!(i instanceof ne)){t=1;break}t+=za(n,i)}Gp.set(e,t)}return t}function Tf(n,e,t,i,r,s,o,a,l){let h=0;for(let g=i;g=c)break;A+=R}if($==x+1){if(A>c){let R=g[x];p(R.children,R.positions,0,R.children.length,O[x]+k);continue}u.push(g[x])}else{let R=O[$-1]+g[$-1].length-Q;u.push(Tf(n,g,O,x,$,Q,R,null,l))}f.push(Q+k-s)}}return p(e,t,i,r,0),(a||l)(u,f,o)}class vT{constructor(){this.map=new WeakMap}setBuffer(e,t,i){let r=this.map.get(e);r||this.map.set(e,r=new Map),r.set(t,i)}getBuffer(e,t){let i=this.map.get(e);return i&&i.get(t)}set(e,t){e instanceof vi?this.setBuffer(e.context.buffer,e.index,t):e instanceof Bt&&this.map.set(e.tree,t)}get(e){return e instanceof vi?this.getBuffer(e.context.buffer,e.index):e instanceof Bt?this.map.get(e.tree):void 0}cursorSet(e,t){e.buffer?this.setBuffer(e.buffer.buffer,e.index,t):this.map.set(e.tree,t)}cursorGet(e){return e.buffer?this.getBuffer(e.buffer.buffer,e.index):this.map.get(e.tree)}}class Bn{constructor(e,t,i,r,s=!1,o=!1){this.from=e,this.to=t,this.tree=i,this.offset=r,this.open=(s?1:0)|(o?2:0)}get openStart(){return(this.open&1)>0}get openEnd(){return(this.open&2)>0}static addTree(e,t=[],i=!1){let r=[new Bn(0,e.length,e,0,!1,i)];for(let s of t)s.to>e.length&&r.push(s);return r}static applyChanges(e,t,i=128){if(!t.length)return e;let r=[],s=1,o=e.length?e[0]:null;for(let a=0,l=0,h=0;;a++){let c=a=i)for(;o&&o.from=f.from||u<=f.to||h){let p=Math.max(f.from,l)-h,g=Math.min(f.to,u)-h;f=p>=g?null:new Bn(p,g,f.tree,f.offset+h,a>0,!!c)}if(f&&r.push(f),o.to>u)break;o=snew Rt(r.from,r.to)):[new Rt(0,0)]:[new Rt(0,e.length)],this.createParse(e,t||[],i)}parse(e,t,i){let r=this.startParse(e,t,i);for(;;){let s=r.advance();if(s)return s}}}class kT{constructor(e){this.string=e}get length(){return this.string.length}chunk(e){return this.string.slice(e)}get lineChunks(){return!1}read(e,t){return this.string.slice(e,t)}}function ny(n){return(e,t,i,r)=>new TT(e,n,t,i,r)}class Jp{constructor(e,t,i,r,s){this.parser=e,this.parse=t,this.overlay=i,this.target=r,this.ranges=s}}class xT{constructor(e,t,i,r,s,o,a){this.parser=e,this.predicate=t,this.mounts=i,this.index=r,this.start=s,this.target=o,this.prev=a,this.depth=0,this.ranges=[]}}const ku=new _({perNode:!0});class TT{constructor(e,t,i,r,s){this.nest=t,this.input=i,this.fragments=r,this.ranges=s,this.inner=[],this.innerDone=0,this.baseTree=null,this.stoppedAt=null,this.baseParse=e}advance(){if(this.baseParse){let i=this.baseParse.advance();if(!i)return null;if(this.baseParse=null,this.baseTree=i,this.startInner(),this.stoppedAt!=null)for(let r of this.inner)r.parse.stopAt(this.stoppedAt)}if(this.innerDone==this.inner.length){let i=this.baseTree;return this.stoppedAt!=null&&(i=new ne(i.type,i.children,i.positions,i.length,i.propValues.concat([[ku,this.stoppedAt]]))),i}let e=this.inner[this.innerDone],t=e.parse.advance();if(t){this.innerDone++;let i=Object.assign(Object.create(null),e.target.props);i[_.mounted.id]=new yT(t,e.overlay,e.parser),e.target.props=i}return null}get parsedPos(){if(this.baseParse)return 0;let e=this.input.length;for(let t=this.innerDone;tc.frag.from<=r.from&&c.frag.to>=r.to&&c.mount.overlay);if(h)for(let c of h.mount.overlay){let u=c.from+h.pos,f=c.to+h.pos;u>=r.from&&f<=r.to&&!t.ranges.some(p=>p.fromu)&&t.ranges.push({from:u,to:f})}}a=!1}else if(i&&(o=QT(i.ranges,r.from,r.to)))a=o!=2;else if(!r.type.isAnonymous&&r.fromnew Rt(u.from-r.from,u.to-r.from)):null,r.tree,c)),s.overlay?c.length&&(i={ranges:c,depth:0,prev:i}):a=!1}}else t&&(l=t.predicate(r))&&(l===!0&&(l=new Rt(r.from,r.to)),l.fromnew Rt(c.from-t.start,c.to-t.start)),t.target,h)),t=t.prev}i&&!--i.depth&&(i=i.prev)}}}}function QT(n,e,t){for(let i of n){if(i.from>=t)break;if(i.to>e)return i.from<=e&&i.to>=t?2:1}return 0}function Yp(n,e,t,i,r,s){if(e=e.to);i++);let o=r.children[i],a=o.buffer;function l(h,c,u,f,p){let g=h;for(;a[g+2]+s<=e.from;)g=a[g+3];let O=[],y=[];Yp(o,h,g,O,y,f);let S=a[g+1],k=a[g+2],$=S+s==e.from&&k+s==e.to&&a[g]==e.type.id;return O.push($?e.toTree():l(g+4,a[g+3],o.set.types[a[g]],S,k-S)),y.push(S-f),Yp(o,a[g+3],c,O,y,f),new ne(u,O,y,p)}r.children[i]=l(0,a.length,Ie.none,0,o.length);for(let h=0;h<=t;h++)n.childAfter(e.from)}class Hp{constructor(e,t){this.offset=t,this.done=!1,this.cursor=e.cursor(ce.IncludeAnonymous|ce.IgnoreMounts)}moveTo(e){let{cursor:t}=this,i=e-this.offset;for(;!this.done&&t.from=e&&t.enter(i,1,ce.IgnoreOverlays|ce.ExcludeBuffers)||t.next(!1)||(this.done=!0)}hasNode(e){if(this.moveTo(e.from),!this.done&&this.cursor.from+this.offset==e.from&&this.cursor.tree)for(let t=this.cursor.tree;;){if(t==e.tree)return!0;if(t.children.length&&t.positions[0]==0&&t.children[0]instanceof ne)t=t.children[0];else break}return!1}}let AT=class{constructor(e){var t;if(this.fragments=e,this.curTo=0,this.fragI=0,e.length){let i=this.curFrag=e[0];this.curTo=(t=i.tree.prop(ku))!==null&&t!==void 0?t:i.to,this.inner=new Hp(i.tree,-i.offset)}else this.curFrag=this.inner=null}hasNode(e){for(;this.curFrag&&e.from>=this.curTo;)this.nextFrag();return this.curFrag&&this.curFrag.from<=e.from&&this.curTo>=e.to&&this.inner.hasNode(e)}nextFrag(){var e;if(this.fragI++,this.fragI==this.fragments.length)this.curFrag=this.inner=null;else{let t=this.curFrag=this.fragments[this.fragI];this.curTo=(e=t.tree.prop(ku))!==null&&e!==void 0?e:t.to,this.inner=new Hp(t.tree,-t.offset)}}findMounts(e,t){var i;let r=[];if(this.inner){this.inner.cursor.moveTo(e,1);for(let s=this.inner.cursor.node;s;s=s.parent){let o=(i=s.tree)===null||i===void 0?void 0:i.prop(_.mounted);if(o&&o.parser==t)for(let a=this.fragI;a=s.to)break;l.tree==this.curFrag.tree&&r.push({frag:l,pos:s.from-l.offset,mount:o})}}}return r}};function Kp(n,e){let t=null,i=e;for(let r=1,s=0;r=a)break;l.to<=o||(t||(i=t=e.slice()),l.froma&&t.splice(s+1,0,new Rt(a,l.to))):l.to>a?t[s--]=new Rt(a,l.to):t.splice(s--,1))}}return i}function $T(n,e,t,i){let r=0,s=0,o=!1,a=!1,l=-1e9,h=[];for(;;){let c=r==n.length?1e9:o?n[r].to:n[r].from,u=s==e.length?1e9:a?e[s].to:e[s].from;if(o!=a){let f=Math.max(l,t),p=Math.min(c,u,i);fnew Rt(f.from+i,f.to+i)),u=$T(e,c,l,h);for(let f=0,p=l;;f++){let g=f==u.length,O=g?h:u[f].from;if(O>p&&t.push(new Bn(p,O,r.tree,-o,s.from>=p||s.openStart,s.to<=O||s.openEnd)),g)break;p=u[f].to}}else t.push(new Bn(l,h,r.tree,-o,s.from>=o||s.openStart,s.to<=a||s.openEnd))}return t}let CT=0;class jt{constructor(e,t,i){this.set=e,this.base=t,this.modified=i,this.id=CT++}static define(e){if(e!=null&&e.base)throw new Error("Can not derive from a modified tag");let t=new jt([],null,[]);if(t.set.push(t),e)for(let i of e.set)t.set.push(i);return t}static defineModifier(){let e=new Cl;return t=>t.modified.indexOf(e)>-1?t:Cl.get(t.base||t,t.modified.concat(e).sort((i,r)=>i.id-r.id))}}let IT=0;class Cl{constructor(){this.instances=[],this.id=IT++}static get(e,t){if(!t.length)return e;let i=t[0].instances.find(a=>a.base==e&&RT(t,a.modified));if(i)return i;let r=[],s=new jt(r,e,t);for(let a of t)a.instances.push(s);let o=ET(t);for(let a of e.set)if(!a.modified.length)for(let l of o)r.push(Cl.get(a,l));return s}}function RT(n,e){return n.length==e.length&&n.every((t,i)=>t==e[i])}function ET(n){let e=[[]];for(let t=0;ti.length-t.length)}function $s(n){let e=Object.create(null);for(let t in n){let i=n[t];Array.isArray(i)||(i=[i]);for(let r of t.split(" "))if(r){let s=[],o=2,a=r;for(let u=0;;){if(a=="..."&&u>0&&u+3==r.length){o=1;break}let f=/^"(?:[^"\\]|\\.)*?"|[^\/!]+/.exec(a);if(!f)throw new RangeError("Invalid path: "+r);if(s.push(f[0]=="*"?"":f[0][0]=='"'?JSON.parse(f[0]):f[0]),u+=f[0].length,u==r.length)break;let p=r[u++];if(u==r.length&&p=="!"){o=0;break}if(p!="/")throw new RangeError("Invalid path: "+r);a=r.slice(u)}let l=s.length-1,h=s[l];if(!h)throw new RangeError("Invalid path: "+r);let c=new Il(i,o,l>0?s.slice(0,l):null);e[h]=c.sort(e[h])}}return ry.add(e)}const ry=new _;class Il{constructor(e,t,i,r){this.tags=e,this.mode=t,this.context=i,this.next=r}get opaque(){return this.mode==0}get inherit(){return this.mode==1}sort(e){return!e||e.depth{let o=r;for(let a of s)for(let l of a.set){let h=t[l.id];if(h){o=o?o+" "+h:h;break}}return o},scope:i}}function DT(n,e){let t=null;for(let i of n){let r=i.style(e);r&&(t=t?t+" "+r:r)}return t}function NT(n,e,t,i=0,r=n.length){let s=new BT(i,Array.isArray(e)?e:[e],t);s.highlightRange(n.cursor(),i,r,"",s.highlighters),s.flush(r)}class BT{constructor(e,t,i){this.at=e,this.highlighters=t,this.span=i,this.class=""}startSpan(e,t){t!=this.class&&(this.flush(e),e>this.at&&(this.at=e),this.class=t)}flush(e){e>this.at&&this.class&&this.span(this.at,e,this.class)}highlightRange(e,t,i,r,s){let{type:o,from:a,to:l}=e;if(a>=i||l<=t)return;o.isTop&&(s=this.highlighters.filter(p=>!p.scope||p.scope(o)));let h=r,c=qT(e)||Il.empty,u=DT(s,c.tags);if(u&&(h&&(h+=" "),h+=u,c.mode==1&&(r+=(r?" ":"")+u)),this.startSpan(e.from,h),c.opaque)return;let f=e.tree&&e.tree.prop(_.mounted);if(f&&f.overlay){let p=e.node.enter(f.overlay[0].from+a,1),g=this.highlighters.filter(y=>!y.scope||y.scope(f.tree.type)),O=e.firstChild();for(let y=0,S=a;;y++){let k=y=$||!e.nextSibling())););if(!k||$>i)break;S=k.to+a,S>t&&(this.highlightRange(p.cursor(),Math.max(t,k.from+a),Math.min(i,S),r,g),this.startSpan(S,h))}O&&e.parent()}else if(e.firstChild()){do if(!(e.to<=t)){if(e.from>=i)break;this.highlightRange(e,t,i,r,s),this.startSpan(Math.min(i,e.to),h)}while(e.nextSibling());e.parent()}}}function qT(n){let e=n.type.prop(ry);for(;e&&e.context&&!n.matchContext(e.context);)e=e.next;return e||null}const E=jt.define,ba=E(),Jn=E(),tg=E(Jn),ig=E(Jn),Yn=E(),Sa=E(Yn),jh=E(Yn),ai=E(),Sr=E(ai),si=E(),oi=E(),xu=E(),qs=E(xu),wa=E(),b={comment:ba,lineComment:E(ba),blockComment:E(ba),docComment:E(ba),name:Jn,variableName:E(Jn),typeName:tg,tagName:E(tg),propertyName:ig,attributeName:E(ig),className:E(Jn),labelName:E(Jn),namespace:E(Jn),macroName:E(Jn),literal:Yn,string:Sa,docString:E(Sa),character:E(Sa),attributeValue:E(Sa),number:jh,integer:E(jh),float:E(jh),bool:E(Yn),regexp:E(Yn),escape:E(Yn),color:E(Yn),url:E(Yn),keyword:si,self:E(si),null:E(si),atom:E(si),unit:E(si),modifier:E(si),operatorKeyword:E(si),controlKeyword:E(si),definitionKeyword:E(si),moduleKeyword:E(si),operator:oi,derefOperator:E(oi),arithmeticOperator:E(oi),logicOperator:E(oi),bitwiseOperator:E(oi),compareOperator:E(oi),updateOperator:E(oi),definitionOperator:E(oi),typeOperator:E(oi),controlOperator:E(oi),punctuation:xu,separator:E(xu),bracket:qs,angleBracket:E(qs),squareBracket:E(qs),paren:E(qs),brace:E(qs),content:ai,heading:Sr,heading1:E(Sr),heading2:E(Sr),heading3:E(Sr),heading4:E(Sr),heading5:E(Sr),heading6:E(Sr),contentSeparator:E(ai),list:E(ai),quote:E(ai),emphasis:E(ai),strong:E(ai),link:E(ai),monospace:E(ai),strikethrough:E(ai),inserted:E(),deleted:E(),changed:E(),invalid:E(),meta:wa,documentMeta:E(wa),annotation:E(wa),processingInstruction:E(wa),definition:jt.defineModifier(),constant:jt.defineModifier(),function:jt.defineModifier(),standard:jt.defineModifier(),local:jt.defineModifier(),special:jt.defineModifier()};sy([{tag:b.link,class:"tok-link"},{tag:b.heading,class:"tok-heading"},{tag:b.emphasis,class:"tok-emphasis"},{tag:b.strong,class:"tok-strong"},{tag:b.keyword,class:"tok-keyword"},{tag:b.atom,class:"tok-atom"},{tag:b.bool,class:"tok-bool"},{tag:b.url,class:"tok-url"},{tag:b.labelName,class:"tok-labelName"},{tag:b.inserted,class:"tok-inserted"},{tag:b.deleted,class:"tok-deleted"},{tag:b.literal,class:"tok-literal"},{tag:b.string,class:"tok-string"},{tag:b.number,class:"tok-number"},{tag:[b.regexp,b.escape,b.special(b.string)],class:"tok-string2"},{tag:b.variableName,class:"tok-variableName"},{tag:b.local(b.variableName),class:"tok-variableName tok-local"},{tag:b.definition(b.variableName),class:"tok-variableName tok-definition"},{tag:b.special(b.variableName),class:"tok-variableName2"},{tag:b.definition(b.propertyName),class:"tok-propertyName tok-definition"},{tag:b.typeName,class:"tok-typeName"},{tag:b.namespace,class:"tok-namespace"},{tag:b.className,class:"tok-className"},{tag:b.macroName,class:"tok-macroName"},{tag:b.propertyName,class:"tok-propertyName"},{tag:b.operator,class:"tok-operator"},{tag:b.comment,class:"tok-comment"},{tag:b.meta,class:"tok-meta"},{tag:b.invalid,class:"tok-invalid"},{tag:b.punctuation,class:"tok-punctuation"}]);const Tu="ͼ",ng=typeof Symbol>"u"?"__"+Tu:Symbol.for(Tu),Qu=typeof Symbol>"u"?"__styleSet"+Math.floor(Math.random()*1e8):Symbol("styleSet"),rg=typeof globalThis<"u"?globalThis:typeof window<"u"?window:{};class sg{constructor(e,t){this.rules=[];let{finish:i}=t||{};function r(o){return/^@/.test(o)?[o]:o.split(/,\s*/)}function s(o,a,l,h){let c=[],u=/^@(\w+)\b/.exec(o[0]),f=u&&u[1]=="keyframes";if(u&&a==null)return l.push(o[0]+";");for(let p in a){let g=a[p];if(/&/.test(p))s(p.split(/,\s*/).map(O=>o.map(y=>O.replace(/&/,y))).reduce((O,y)=>O.concat(y)),g,l);else if(g&&typeof g=="object"){if(!u)throw new RangeError("The value of a property ("+p+") should be a primitive value.");s(r(p),g,c,f)}else g!=null&&c.push(p.replace(/_.*/,"").replace(/[A-Z]/g,O=>"-"+O.toLowerCase())+": "+g+";")}(c.length||f)&&l.push((i&&!u&&!h?o.map(i):o).join(", ")+" {"+c.join(" ")+"}")}for(let o in e)s(r(o),e[o],this.rules)}getRules(){return this.rules.join(` `)}static newName(){let e=rg[ng]||1;return rg[ng]=e+1,Tu+e.toString(36)}static mount(e,t){(e[Qu]||new MT(e)).mount(Array.isArray(t)?t:[t])}}let va=null;class MT{constructor(e){if(!e.head&&e.adoptedStyleSheets&&typeof CSSStyleSheet<"u"){if(va)return e.adoptedStyleSheets=[va.sheet].concat(e.adoptedStyleSheets),e[Qu]=va;this.sheet=new CSSStyleSheet,e.adoptedStyleSheets=[this.sheet].concat(e.adoptedStyleSheets),va=this}else{this.styleTag=(e.ownerDocument||e).createElement("style");let t=e.head||e;t.insertBefore(this.styleTag,t.firstChild)}this.modules=[],e[Qu]=this}mount(e){let t=this.sheet,i=0,r=0;for(let s=0;s-1&&(this.modules.splice(a,1),r--,a=-1),a==-1){if(this.modules.splice(r++,0,o),t)for(let l=0;le.concat(n):void 0})}class Et{constructor(e,t,i=[],r=""){this.data=e,this.name=r,H.prototype.hasOwnProperty("tree")||Object.defineProperty(H.prototype,"tree",{get(){return de(this)}}),this.parser=t,this.extension=[gr.of(this),H.languageData.of((s,o,a)=>s.facet(og(s,o,a)))].concat(i)}isActiveAt(e,t,i=-1){return og(e,t,i)==this.data}findRegions(e){let t=e.facet(gr);if((t==null?void 0:t.data)==this.data)return[{from:0,to:e.doc.length}];if(!t||!t.allowsNesting)return[];let i=[],r=(s,o)=>{if(s.prop(Ss)==this.data){i.push({from:o,to:o+s.length});return}let a=s.prop(_.mounted);if(a){if(a.tree.prop(Ss)==this.data){if(a.overlay)for(let l of a.overlay)i.push({from:l.from+o,to:l.to+o});else i.push({from:o,to:o+s.length});return}else if(a.overlay){let l=i.length;if(r(a.tree,a.overlay[0].from+o),i.length>l)return}}for(let l=0;li.isTop?t:void 0)]}),e.name)}configure(e,t){return new ws(this.data,this.parser.configure(e),t||this.name)}get allowsNesting(){return this.parser.hasWrappers()}}function de(n){let e=n.field(Et.state,!1);return e?e.tree:ne.empty}class VT{constructor(e,t=e.length){this.doc=e,this.length=t,this.cursorPos=0,this.string="",this.cursor=e.iter()}syncTo(e){return this.string=this.cursor.next(e-this.cursorPos).value,this.cursorPos=e+this.string.length,this.cursorPos-this.string.length}chunk(e){return this.syncTo(e),this.string}get lineChunks(){return!0}read(e,t){let i=this.cursorPos-this.string.length;return e=this.cursorPos?this.doc.sliceString(e,t):this.string.slice(e-i,t-i)}}let Ms=null;class $o{constructor(e,t,i=[],r,s,o,a,l){this.parser=e,this.state=t,this.fragments=i,this.tree=r,this.treeLen=s,this.viewport=o,this.skipped=a,this.scheduleOn=l,this.parse=null,this.tempSkipped=[]}static create(e,t,i){return new $o(e,t,[],ne.empty,0,i,[],null)}startParse(){return this.parser.startParse(new VT(this.state.doc),this.fragments)}work(e,t){return t!=null&&t>=this.state.doc.length&&(t=void 0),this.tree!=ne.empty&&this.isDone(t??this.state.doc.length)?(this.takeTree(),!0):this.withContext(()=>{var i;if(typeof e=="number"){let r=Date.now()+e;e=()=>Date.now()>r}for(this.parse||(this.parse=this.startParse()),t!=null&&(this.parse.stoppedAt==null||this.parse.stoppedAt>t)&&t=this.treeLen&&((this.parse.stoppedAt==null||this.parse.stoppedAt>e)&&this.parse.stopAt(e),this.withContext(()=>{for(;!(t=this.parse.advance()););}),this.treeLen=e,this.tree=t,this.fragments=this.withoutTempSkipped(Bn.addTree(this.tree,this.fragments,!0)),this.parse=null)}withContext(e){let t=Ms;Ms=this;try{return e()}finally{Ms=t}}withoutTempSkipped(e){for(let t;t=this.tempSkipped.pop();)e=ag(e,t.from,t.to);return e}changes(e,t){let{fragments:i,tree:r,treeLen:s,viewport:o,skipped:a}=this;if(this.takeTree(),!e.empty){let l=[];if(e.iterChangedRanges((h,c,u,f)=>l.push({fromA:h,toA:c,fromB:u,toB:f})),i=Bn.applyChanges(i,l),r=ne.empty,s=0,o={from:e.mapPos(o.from,-1),to:e.mapPos(o.to,1)},this.skipped.length){a=[];for(let h of this.skipped){let c=e.mapPos(h.from,1),u=e.mapPos(h.to,-1);ce.from&&(this.fragments=ag(this.fragments,r,s),this.skipped.splice(i--,1))}return this.skipped.length>=t?!1:(this.reset(),!0)}reset(){this.parse&&(this.takeTree(),this.parse=null)}skipUntilInView(e,t){this.skipped.push({from:e,to:t})}static getSkippingParser(e){return new class extends Qf{createParse(t,i,r){let s=r[0].from,o=r[r.length-1].to;return{parsedPos:s,advance(){let l=Ms;if(l){for(let h of r)l.tempSkipped.push(h);e&&(l.scheduleOn=l.scheduleOn?Promise.all([l.scheduleOn,e]):e)}return this.parsedPos=o,new ne(Ie.none,[],[],o-s)},stoppedAt:null,stopAt(){}}}}}isDone(e){e=Math.min(e,this.state.doc.length);let t=this.fragments;return this.treeLen>=e&&t.length&&t[0].from==0&&t[0].to>=e}static get(){return Ms}}function ag(n,e,t){return Bn.applyChanges(n,[{fromA:e,toA:t,fromB:e,toB:t}])}class vs{constructor(e){this.context=e,this.tree=e.tree}apply(e){if(!e.docChanged&&this.tree==this.context.tree)return this;let t=this.context.changes(e.changes,e.state),i=this.context.treeLen==e.startState.doc.length?void 0:Math.max(e.changes.mapPos(this.context.treeLen),t.viewport.to);return t.work(20,i)||t.takeTree(),new vs(t)}static init(e){let t=Math.min(3e3,e.doc.length),i=$o.create(e.facet(gr).parser,e,{from:0,to:t});return i.work(20,t)||i.takeTree(),new vs(i)}}Et.state=Re.define({create:vs.init,update(n,e){for(let t of e.effects)if(t.is(Et.setState))return t.value;return e.startState.facet(gr)!=e.state.facet(gr)?vs.init(e.state):n.apply(e)}});let ay=n=>{let e=setTimeout(()=>n(),500);return()=>clearTimeout(e)};typeof requestIdleCallback<"u"&&(ay=n=>{let e=-1,t=setTimeout(()=>{e=requestIdleCallback(n,{timeout:400})},100);return()=>e<0?clearTimeout(t):cancelIdleCallback(e)});const zh=typeof navigator<"u"&&(!((Fh=navigator.scheduling)===null||Fh===void 0)&&Fh.isInputPending)?()=>navigator.scheduling.isInputPending():null,XT=ke.fromClass(class{constructor(e){this.view=e,this.working=null,this.workScheduled=0,this.chunkEnd=-1,this.chunkBudget=-1,this.work=this.work.bind(this),this.scheduleWork()}update(e){let t=this.view.state.field(Et.state).context;(t.updateViewport(e.view.viewport)||this.view.viewport.to>t.treeLen)&&this.scheduleWork(),e.docChanged&&(this.view.hasFocus&&(this.chunkBudget+=50),this.scheduleWork()),this.checkAsyncSchedule(t)}scheduleWork(){if(this.working)return;let{state:e}=this.view,t=e.field(Et.state);(t.tree!=t.context.tree||!t.context.isDone(e.doc.length))&&(this.working=ay(this.work))}work(e){this.working=null;let t=Date.now();if(this.chunkEndr+1e3,l=s.context.work(()=>zh&&zh()||Date.now()>o,r+(a?0:1e5));this.chunkBudget-=Date.now()-t,(l||this.chunkBudget<=0)&&(s.context.takeTree(),this.view.dispatch({effects:Et.setState.of(new vs(s.context))})),this.chunkBudget>0&&!(l&&!a)&&this.scheduleWork(),this.checkAsyncSchedule(s.context)}checkAsyncSchedule(e){e.scheduleOn&&(this.workScheduled++,e.scheduleOn.then(()=>this.scheduleWork()).catch(t=>mt(this.view.state,t)).then(()=>this.workScheduled--),e.scheduleOn=null)}destroy(){this.working&&this.working()}isWorking(){return!!(this.working||this.workScheduled>0)}},{eventHandlers:{focus(){this.scheduleWork()}}}),gr=B.define({combine(n){return n.length?n[0]:null},enables:n=>[Et.state,XT,N.contentAttributes.compute([n],e=>{let t=e.facet(n);return t&&t.name?{"data-language":t.name}:{}})]});class Co{constructor(e,t=[]){this.language=e,this.support=t,this.extension=[e,t]}}class Rl{constructor(e,t,i,r,s,o=void 0){this.name=e,this.alias=t,this.extensions=i,this.filename=r,this.loadFunc=s,this.support=o,this.loading=null}load(){return this.loading||(this.loading=this.loadFunc().then(e=>this.support=e,e=>{throw this.loading=null,e}))}static of(e){let{load:t,support:i}=e;if(!t){if(!i)throw new RangeError("Must pass either 'load' or 'support' to LanguageDescription.of");t=()=>Promise.resolve(i)}return new Rl(e.name,(e.alias||[]).concat(e.name).map(r=>r.toLowerCase()),e.extensions||[],e.filename,t,i)}static matchFilename(e,t){for(let r of e)if(r.filename&&r.filename.test(t))return r;let i=/\.([^.]+)$/.exec(t);if(i){for(let r of e)if(r.extensions.indexOf(i[1])>-1)return r}return null}static matchLanguageName(e,t,i=!0){t=t.toLowerCase();for(let r of e)if(r.alias.some(s=>s==t))return r;if(i)for(let r of e)for(let s of r.alias){let o=t.indexOf(s);if(o>-1&&(s.length>2||!/\w/.test(t[o-1])&&!/\w/.test(t[o+s.length])))return r}return null}}const LT=B.define(),ch=B.define({combine:n=>{if(!n.length)return" ";if(!/^(?: +|\t+)$/.test(n[0]))throw new Error("Invalid indent unit: "+JSON.stringify(n[0]));return n[0]}});function El(n){let e=n.facet(ch);return e.charCodeAt(0)==9?n.tabSize*e.length:e.length}function Io(n,e){let t="",i=n.tabSize;if(n.facet(ch).charCodeAt(0)==9)for(;e>=i;)t+=" ",e-=i;for(let r=0;r=i.from&&r<=i.to?s&&r==e?{text:"",from:e}:(t<0?r-1&&(s+=o-this.countColumn(i,i.search(/\S|$/))),s}countColumn(e,t=e.length){return Uo(e,this.state.tabSize,t)}lineIndent(e,t=1){let{text:i,from:r}=this.lineAt(e,t),s=this.options.overrideIndentation;if(s){let o=s(r);if(o>-1)return o}return this.countColumn(i,i.search(/\S|$/))}get simulatedBreak(){return this.options.simulateBreak||null}}const zo=new _;function UT(n,e,t){return ly(e.resolveInner(t).enterUnfinishedNodesBefore(t),t,n)}function ZT(n){return n.pos==n.options.simulateBreak&&n.options.simulateDoubleBreak}function WT(n){let e=n.type.prop(zo);if(e)return e;let t=n.firstChild,i;if(t&&(i=t.type.prop(_.closedBy))){let r=n.lastChild,s=r&&i.indexOf(r.name)>-1;return o=>hy(o,!0,1,void 0,s&&!ZT(o)?r.from:void 0)}return n.parent==null?jT:null}function ly(n,e,t){for(;n;n=n.parent){let i=WT(n);if(i)return i(Af.create(t,e,n))}return null}function jT(){return 0}class Af extends uh{constructor(e,t,i){super(e.state,e.options),this.base=e,this.pos=t,this.node=i}static create(e,t,i){return new Af(e,t,i)}get textAfter(){return this.textAfterPos(this.pos)}get baseIndent(){let e=this.state.doc.lineAt(this.node.from);for(;;){let t=this.node.resolve(e.from);for(;t.parent&&t.parent.from==t.from;)t=t.parent;if(FT(t,this.node))break;e=this.state.doc.lineAt(t.from)}return this.lineIndent(e.from)}continue(){let e=this.node.parent;return e?ly(e,this.pos,this.base):0}}function FT(n,e){for(let t=e;t;t=t.parent)if(n==t)return!0;return!1}function zT(n){let e=n.node,t=e.childAfter(e.from),i=e.lastChild;if(!t)return null;let r=n.options.simulateBreak,s=n.state.doc.lineAt(t.from),o=r==null||r<=s.from?s.to:Math.min(s.to,r);for(let a=t.to;;){let l=e.childAfter(a);if(!l||l==i)return null;if(!l.type.isSkipped)return l.fromhy(i,e,t,n)}function hy(n,e,t,i,r){let s=n.textAfter,o=s.match(/^\s*/)[0].length,a=i&&s.slice(o,o+i.length)==i||r==n.pos+o,l=e?zT(n):null;return l?a?n.column(l.from):n.column(l.to):n.baseIndent+(a?0:n.unit*t)}const GT=n=>n.baseIndent;function _a({except:n,units:e=1}={}){return t=>{let i=n&&n.test(t.textAfter);return t.baseIndent+(i?0:e*t.unit)}}const JT=200;function YT(){return H.transactionFilter.of(n=>{if(!n.docChanged||!n.isUserEvent("input.type")&&!n.isUserEvent("input.complete"))return n;let e=n.startState.languageDataAt("indentOnInput",n.startState.selection.main.head);if(!e.length)return n;let t=n.newDoc,{head:i}=n.newSelection.main,r=t.lineAt(i);if(i>r.from+JT)return n;let s=t.sliceString(r.from,i);if(!e.some(h=>h.test(s)))return n;let{state:o}=n,a=-1,l=[];for(let{head:h}of o.selection.ranges){let c=o.doc.lineAt(h);if(c.from==a)continue;a=c.from;let u=Pf(o,c.from);if(u==null)continue;let f=/^\s*/.exec(c.text)[0],p=Io(o,u);f!=p&&l.push({from:c.from,to:c.from+f.length,insert:p})}return l.length?[n,{changes:l,sequential:!0}]:n})}const HT=B.define(),_o=new _;function cy(n){let e=n.firstChild,t=n.lastChild;return e&&e.tot)continue;if(s&&o.from=e&&l.to>t&&(s=l)}}return s}function eQ(n){let e=n.lastChild;return e&&e.to==n.to&&e.type.isError}function Dl(n,e,t){for(let i of n.facet(HT)){let r=i(n,e,t);if(r)return r}return KT(n,e,t)}function uy(n,e){let t=e.mapPos(n.from,1),i=e.mapPos(n.to,-1);return t>=i?void 0:{from:t,to:i}}const fh=z.define({map:uy}),Go=z.define({map:uy});function fy(n){let e=[];for(let{head:t}of n.state.selection.ranges)e.some(i=>i.from<=t&&i.to>=t)||e.push(n.lineBlockAt(t));return e}const Vr=Re.define({create(){return Z.none},update(n,e){n=n.map(e.changes);for(let t of e.effects)t.is(fh)&&!tQ(n,t.value.from,t.value.to)?n=n.update({add:[lg.range(t.value.from,t.value.to)]}):t.is(Go)&&(n=n.update({filter:(i,r)=>t.value.from!=i||t.value.to!=r,filterFrom:t.value.from,filterTo:t.value.to}));if(e.selection){let t=!1,{head:i}=e.selection.main;n.between(i,i,(r,s)=>{ri&&(t=!0)}),t&&(n=n.update({filterFrom:i,filterTo:i,filter:(r,s)=>s<=i||r>=i}))}return n},provide:n=>N.decorations.from(n),toJSON(n,e){let t=[];return n.between(0,e.doc.length,(i,r)=>{t.push(i,r)}),t},fromJSON(n){if(!Array.isArray(n)||n.length%2)throw new RangeError("Invalid JSON for fold state");let e=[];for(let t=0;t{(!r||r.from>s)&&(r={from:s,to:o})}),r}function tQ(n,e,t){let i=!1;return n.between(e,e,(r,s)=>{r==e&&s==t&&(i=!0)}),i}function dy(n,e){return n.field(Vr,!1)?e:e.concat(z.appendConfig.of(gy()))}const iQ=n=>{for(let e of fy(n)){let t=Dl(n.state,e.from,e.to);if(t)return n.dispatch({effects:dy(n.state,[fh.of(t),py(n,t)])}),!0}return!1},nQ=n=>{if(!n.state.field(Vr,!1))return!1;let e=[];for(let t of fy(n)){let i=Nl(n.state,t.from,t.to);i&&e.push(Go.of(i),py(n,i,!1))}return e.length&&n.dispatch({effects:e}),e.length>0};function py(n,e,t=!0){let i=n.state.doc.lineAt(e.from).number,r=n.state.doc.lineAt(e.to).number;return N.announce.of(`${n.state.phrase(t?"Folded lines":"Unfolded lines")} ${i} ${n.state.phrase("to")} ${r}.`)}const rQ=n=>{let{state:e}=n,t=[];for(let i=0;i{let e=n.state.field(Vr,!1);if(!e||!e.size)return!1;let t=[];return e.between(0,n.state.doc.length,(i,r)=>{t.push(Go.of({from:i,to:r}))}),n.dispatch({effects:t}),!0},oQ=[{key:"Ctrl-Shift-[",mac:"Cmd-Alt-[",run:iQ},{key:"Ctrl-Shift-]",mac:"Cmd-Alt-]",run:nQ},{key:"Ctrl-Alt-[",run:rQ},{key:"Ctrl-Alt-]",run:sQ}],aQ={placeholderDOM:null,placeholderText:"…"},lQ=B.define({combine(n){return Ai(n,aQ)}});function gy(n){return[Vr,uQ]}const lg=Z.replace({widget:new class extends Or{toDOM(n){let{state:e}=n,t=e.facet(lQ),i=s=>{let o=n.lineBlockAt(n.posAtDOM(s.target)),a=Nl(n.state,o.from,o.to);a&&n.dispatch({effects:Go.of(a)}),s.preventDefault()};if(t.placeholderDOM)return t.placeholderDOM(n,i);let r=document.createElement("span");return r.textContent=t.placeholderText,r.setAttribute("aria-label",e.phrase("folded code")),r.title=e.phrase("unfold"),r.className="cm-foldPlaceholder",r.onclick=i,r}}}),hQ={openText:"⌄",closedText:"›",markerDOM:null,domEventHandlers:{},foldingChanged:()=>!1};class _h extends Zn{constructor(e,t){super(),this.config=e,this.open=t}eq(e){return this.config==e.config&&this.open==e.open}toDOM(e){if(this.config.markerDOM)return this.config.markerDOM(this.open);let t=document.createElement("span");return t.textContent=this.open?this.config.openText:this.config.closedText,t.title=e.state.phrase(this.open?"Fold line":"Unfold line"),t}}function cQ(n={}){let e=Object.assign(Object.assign({},hQ),n),t=new _h(e,!0),i=new _h(e,!1),r=ke.fromClass(class{constructor(o){this.from=o.viewport.from,this.markers=this.buildMarkers(o)}update(o){(o.docChanged||o.viewportChanged||o.startState.facet(gr)!=o.state.facet(gr)||o.startState.field(Vr,!1)!=o.state.field(Vr,!1)||de(o.startState)!=de(o.state)||e.foldingChanged(o))&&(this.markers=this.buildMarkers(o.view))}buildMarkers(o){let a=new fr;for(let l of o.viewportLineBlocks){let h=Nl(o.state,l.from,l.to)?i:Dl(o.state,l.from,l.to)?t:null;h&&a.add(l.from,l.from,h)}return a.finish()}}),{domEventHandlers:s}=e;return[r,aT({class:"cm-foldGutter",markers(o){var a;return((a=o.plugin(r))===null||a===void 0?void 0:a.markers)||J.empty},initialSpacer(){return new _h(e,!1)},domEventHandlers:Object.assign(Object.assign({},s),{click:(o,a,l)=>{if(s.click&&s.click(o,a,l))return!0;let h=Nl(o.state,a.from,a.to);if(h)return o.dispatch({effects:Go.of(h)}),!0;let c=Dl(o.state,a.from,a.to);return c?(o.dispatch({effects:fh.of(c)}),!0):!1}})}),gy()]}const uQ=N.baseTheme({".cm-foldPlaceholder":{backgroundColor:"#eee",border:"1px solid #ddd",color:"#888",borderRadius:".2em",margin:"0 1px",padding:"0 1px",cursor:"pointer"},".cm-foldGutter span":{padding:"0 1px",cursor:"pointer"}});class dh{constructor(e,t){this.specs=e;let i;function r(a){let l=sg.newName();return(i||(i=Object.create(null)))["."+l]=a,l}const s=typeof t.all=="string"?t.all:t.all?r(t.all):void 0,o=t.scope;this.scope=o instanceof Et?a=>a.prop(Ss)==o.data:o?a=>a==o:void 0,this.style=sy(e.map(a=>({tag:a.tag,class:a.class||r(Object.assign({},a,{tag:null}))})),{all:s}).style,this.module=i?new sg(i):null,this.themeType=t.themeType}static define(e,t){return new dh(e,t||{})}}const Pu=B.define(),my=B.define({combine(n){return n.length?[n[0]]:null}});function Gh(n){let e=n.facet(Pu);return e.length?e:n.facet(my)}function fQ(n,e){let t=[pQ],i;return n instanceof dh&&(n.module&&t.push(N.styleModule.of(n.module)),i=n.themeType),e!=null&&e.fallback?t.push(my.of(n)):i?t.push(Pu.computeN([N.darkTheme],r=>r.facet(N.darkTheme)==(i=="dark")?[n]:[])):t.push(Pu.of(n)),t}class dQ{constructor(e){this.markCache=Object.create(null),this.tree=de(e.state),this.decorations=this.buildDeco(e,Gh(e.state))}update(e){let t=de(e.state),i=Gh(e.state),r=i!=Gh(e.startState);t.length{i.add(o,a,this.markCache[l]||(this.markCache[l]=Z.mark({class:l})))},r,s);return i.finish()}}const pQ=mr.high(ke.fromClass(dQ,{decorations:n=>n.decorations})),gQ=dh.define([{tag:b.meta,color:"#7a757a"},{tag:b.link,textDecoration:"underline"},{tag:b.heading,textDecoration:"underline",fontWeight:"bold"},{tag:b.emphasis,fontStyle:"italic"},{tag:b.strong,fontWeight:"bold"},{tag:b.strikethrough,textDecoration:"line-through"},{tag:b.keyword,color:"#708"},{tag:[b.atom,b.bool,b.url,b.contentSeparator,b.labelName],color:"#219"},{tag:[b.literal,b.inserted],color:"#164"},{tag:[b.string,b.deleted],color:"#a11"},{tag:[b.regexp,b.escape,b.special(b.string)],color:"#e40"},{tag:b.definition(b.variableName),color:"#00f"},{tag:b.local(b.variableName),color:"#30a"},{tag:[b.typeName,b.namespace],color:"#085"},{tag:b.className,color:"#167"},{tag:[b.special(b.variableName),b.macroName],color:"#256"},{tag:b.definition(b.propertyName),color:"#00c"},{tag:b.comment,color:"#940"},{tag:b.invalid,color:"#f00"}]),mQ=N.baseTheme({"&.cm-focused .cm-matchingBracket":{backgroundColor:"#328c8252"},"&.cm-focused .cm-nonmatchingBracket":{backgroundColor:"#bb555544"}}),Oy=1e4,yy="()[]{}",by=B.define({combine(n){return Ai(n,{afterCursor:!0,brackets:yy,maxScanDistance:Oy,renderMatch:bQ})}}),OQ=Z.mark({class:"cm-matchingBracket"}),yQ=Z.mark({class:"cm-nonmatchingBracket"});function bQ(n){let e=[],t=n.matched?OQ:yQ;return e.push(t.range(n.start.from,n.start.to)),n.end&&e.push(t.range(n.end.from,n.end.to)),e}const SQ=Re.define({create(){return Z.none},update(n,e){if(!e.docChanged&&!e.selection)return n;let t=[],i=e.state.facet(by);for(let r of e.state.selection.ranges){if(!r.empty)continue;let s=ki(e.state,r.head,-1,i)||r.head>0&&ki(e.state,r.head-1,1,i)||i.afterCursor&&(ki(e.state,r.head,1,i)||r.headN.decorations.from(n)}),wQ=[SQ,mQ];function vQ(n={}){return[by.of(n),wQ]}function Au(n,e,t){let i=n.prop(e<0?_.openedBy:_.closedBy);if(i)return i;if(n.name.length==1){let r=t.indexOf(n.name);if(r>-1&&r%2==(e<0?1:0))return[t[r+e]]}return null}function ki(n,e,t,i={}){let r=i.maxScanDistance||Oy,s=i.brackets||yy,o=de(n),a=o.resolveInner(e,t);for(let l=a;l;l=l.parent){let h=Au(l.type,t,s);if(h&&l.from=i.to){if(l==0&&r.indexOf(h.type.name)>-1&&h.from0)return null;let h={from:t<0?e-1:e,to:t>0?e+1:e},c=n.doc.iterRange(e,t>0?n.doc.length:0),u=0;for(let f=0;!c.next().done&&f<=s;){let p=c.value;t<0&&(f+=p.length);let g=e+f*t;for(let y=t>0?0:p.length-1,O=t>0?p.length:-1;y!=O;y+=t){let S=o.indexOf(p[y]);if(!(S<0||i.resolveInner(g+y,1).type!=r))if(S%2==0==t>0)u++;else{if(u==1)return{start:h,end:{from:g+y,to:g+y+1},matched:S>>1==l>>1};u--}}t>0&&(f+=p.length)}return c.done?{start:h,matched:!1}:null}const TQ=Object.create(null),hg=[Ie.none],cg=[],QQ=Object.create(null);for(let[n,e]of[["variable","variableName"],["variable-2","variableName.special"],["string-2","string.special"],["def","variableName.definition"],["tag","tagName"],["attribute","attributeName"],["type","typeName"],["builtin","variableName.standard"],["qualifier","modifier"],["error","invalid"],["header","heading"],["property","propertyName"]])QQ[n]=PQ(TQ,e);function Jh(n,e){cg.indexOf(n)>-1||(cg.push(n),console.warn(e))}function PQ(n,e){let t=null;for(let s of e.split(".")){let o=n[s]||b[s];o?typeof o=="function"?t?t=o(t):Jh(s,`Modifier ${s} used at start of tag`):t?Jh(s,`Tag ${s} used as modifier`):t=o:Jh(s,`Unknown highlighting tag ${s}`)}if(!t)return 0;let i=e.replace(/ /g,"_"),r=Ie.define({id:hg.length,name:i,props:[$s({[i]:t})]});return hg.push(r),r.id}const AQ=n=>{let e=Cf(n.state);return e.line?$Q(n):e.block?IQ(n):!1};function $f(n,e){return({state:t,dispatch:i})=>{if(t.readOnly)return!1;let r=n(e,t);return r?(i(t.update(r)),!0):!1}}const $Q=$f(DQ,0),CQ=$f(Sy,0),IQ=$f((n,e)=>Sy(n,e,EQ(e)),0);function Cf(n,e=n.selection.main.head){let t=n.languageDataAt("commentTokens",e);return t.length?t[0]:{}}const Vs=50;function RQ(n,{open:e,close:t},i,r){let s=n.sliceDoc(i-Vs,i),o=n.sliceDoc(r,r+Vs),a=/\s*$/.exec(s)[0].length,l=/^\s*/.exec(o)[0].length,h=s.length-a;if(s.slice(h-e.length,h)==e&&o.slice(l,l+t.length)==t)return{open:{pos:i-a,margin:a&&1},close:{pos:r+l,margin:l&&1}};let c,u;r-i<=2*Vs?c=u=n.sliceDoc(i,r):(c=n.sliceDoc(i,i+Vs),u=n.sliceDoc(r-Vs,r));let f=/^\s*/.exec(c)[0].length,p=/\s*$/.exec(u)[0].length,g=u.length-p-t.length;return c.slice(f,f+e.length)==e&&u.slice(g,g+t.length)==t?{open:{pos:i+f+e.length,margin:/\s/.test(c.charAt(f+e.length))?1:0},close:{pos:r-p-t.length,margin:/\s/.test(u.charAt(g-1))?1:0}}:null}function EQ(n){let e=[];for(let t of n.selection.ranges){let i=n.doc.lineAt(t.from),r=t.to<=i.to?i:n.doc.lineAt(t.to),s=e.length-1;s>=0&&e[s].to>i.from?e[s].to=r.to:e.push({from:i.from,to:r.to})}return e}function Sy(n,e,t=e.selection.ranges){let i=t.map(s=>Cf(e,s.from).block);if(!i.every(s=>s))return null;let r=t.map((s,o)=>RQ(e,i[o],s.from,s.to));if(n!=2&&!r.every(s=>s))return{changes:e.changes(t.map((s,o)=>r[o]?[]:[{from:s.from,insert:i[o].open+" "},{from:s.to,insert:" "+i[o].close}]))};if(n!=1&&r.some(s=>s)){let s=[];for(let o=0,a;or&&(s==o||o>c.from)){r=c.from;let u=Cf(e,h).line;if(!u)continue;let f=/^\s*/.exec(c.text)[0].length,p=f==c.length,g=c.text.slice(f,f+u.length)==u?f:-1;fs.comment<0&&(!s.empty||s.single))){let s=[];for(let{line:a,token:l,indent:h,empty:c,single:u}of i)(u||!c)&&s.push({from:a.from+h,insert:l+" "});let o=e.changes(s);return{changes:o,selection:e.selection.map(o,1)}}else if(n!=1&&i.some(s=>s.comment>=0)){let s=[];for(let{line:o,comment:a,token:l}of i)if(a>=0){let h=o.from+a,c=h+l.length;o.text[c-o.from]==" "&&c++,s.push({from:h,to:c})}return{changes:s}}return null}const $u=jn.define(),NQ=jn.define(),BQ=B.define(),wy=B.define({combine(n){return Ai(n,{minDepth:100,newGroupDelay:500},{minDepth:Math.max,newGroupDelay:Math.min})}});function qQ(n){let e=0;return n.iterChangedRanges((t,i)=>e=i),e}const vy=Re.define({create(){return xi.empty},update(n,e){let t=e.state.facet(wy),i=e.annotation($u);if(i){let l=e.docChanged?P.single(qQ(e.changes)):void 0,h=it.fromTransaction(e,l),c=i.side,u=c==0?n.undone:n.done;return h?u=Bl(u,u.length,t.minDepth,h):u=Ty(u,e.startState.selection),new xi(c==0?i.rest:u,c==0?u:i.rest)}let r=e.annotation(NQ);if((r=="full"||r=="before")&&(n=n.isolate()),e.annotation(ye.addToHistory)===!1)return e.changes.empty?n:n.addMapping(e.changes.desc);let s=it.fromTransaction(e),o=e.annotation(ye.time),a=e.annotation(ye.userEvent);return s?n=n.addChanges(s,o,a,t.newGroupDelay,t.minDepth):e.selection&&(n=n.addSelection(e.startState.selection,o,a,t.newGroupDelay)),(r=="full"||r=="after")&&(n=n.isolate()),n},toJSON(n){return{done:n.done.map(e=>e.toJSON()),undone:n.undone.map(e=>e.toJSON())}},fromJSON(n){return new xi(n.done.map(it.fromJSON),n.undone.map(it.fromJSON))}});function MQ(n={}){return[vy,wy.of(n),N.domEventHandlers({beforeinput(e,t){let i=e.inputType=="historyUndo"?ky:e.inputType=="historyRedo"?Cu:null;return i?(e.preventDefault(),i(t)):!1}})]}function ph(n,e){return function({state:t,dispatch:i}){if(!e&&t.readOnly)return!1;let r=t.field(vy,!1);if(!r)return!1;let s=r.pop(n,t,e);return s?(i(s),!0):!1}}const ky=ph(0,!1),Cu=ph(1,!1),VQ=ph(0,!0),XQ=ph(1,!0);class it{constructor(e,t,i,r,s){this.changes=e,this.effects=t,this.mapped=i,this.startSelection=r,this.selectionsAfter=s}setSelAfter(e){return new it(this.changes,this.effects,this.mapped,this.startSelection,e)}toJSON(){var e,t,i;return{changes:(e=this.changes)===null||e===void 0?void 0:e.toJSON(),mapped:(t=this.mapped)===null||t===void 0?void 0:t.toJSON(),startSelection:(i=this.startSelection)===null||i===void 0?void 0:i.toJSON(),selectionsAfter:this.selectionsAfter.map(r=>r.toJSON())}}static fromJSON(e){return new it(e.changes&&Ce.fromJSON(e.changes),[],e.mapped&&Qi.fromJSON(e.mapped),e.startSelection&&P.fromJSON(e.startSelection),e.selectionsAfter.map(P.fromJSON))}static fromTransaction(e,t){let i=Dt;for(let r of e.startState.facet(BQ)){let s=r(e);s.length&&(i=i.concat(s))}return!i.length&&e.changes.empty?null:new it(e.changes.invert(e.startState.doc),i,void 0,t||e.startState.selection,Dt)}static selection(e){return new it(void 0,Dt,void 0,void 0,e)}}function Bl(n,e,t,i){let r=e+1>t+20?e-t-1:0,s=n.slice(r,e);return s.push(i),s}function LQ(n,e){let t=[],i=!1;return n.iterChangedRanges((r,s)=>t.push(r,s)),e.iterChangedRanges((r,s,o,a)=>{for(let l=0;l=h&&o<=c&&(i=!0)}}),i}function UQ(n,e){return n.ranges.length==e.ranges.length&&n.ranges.filter((t,i)=>t.empty!=e.ranges[i].empty).length===0}function xy(n,e){return n.length?e.length?n.concat(e):n:e}const Dt=[],ZQ=200;function Ty(n,e){if(n.length){let t=n[n.length-1],i=t.selectionsAfter.slice(Math.max(0,t.selectionsAfter.length-ZQ));return i.length&&i[i.length-1].eq(e)?n:(i.push(e),Bl(n,n.length-1,1e9,t.setSelAfter(i)))}else return[it.selection([e])]}function WQ(n){let e=n[n.length-1],t=n.slice();return t[n.length-1]=e.setSelAfter(e.selectionsAfter.slice(0,e.selectionsAfter.length-1)),t}function Yh(n,e){if(!n.length)return n;let t=n.length,i=Dt;for(;t;){let r=jQ(n[t-1],e,i);if(r.changes&&!r.changes.empty||r.effects.length){let s=n.slice(0,t);return s[t-1]=r,s}else e=r.mapped,t--,i=r.selectionsAfter}return i.length?[it.selection(i)]:Dt}function jQ(n,e,t){let i=xy(n.selectionsAfter.length?n.selectionsAfter.map(a=>a.map(e)):Dt,t);if(!n.changes)return it.selection(i);let r=n.changes.map(e),s=e.mapDesc(n.changes,!0),o=n.mapped?n.mapped.composeDesc(s):s;return new it(r,z.mapEffects(n.effects,e),o,n.startSelection.map(s),i)}const FQ=/^(input\.type|delete)($|\.)/;class xi{constructor(e,t,i=0,r=void 0){this.done=e,this.undone=t,this.prevTime=i,this.prevUserEvent=r}isolate(){return this.prevTime?new xi(this.done,this.undone):this}addChanges(e,t,i,r,s){let o=this.done,a=o[o.length-1];return a&&a.changes&&!a.changes.empty&&e.changes&&(!i||FQ.test(i))&&(!a.selectionsAfter.length&&t-this.prevTime0&&t-this.prevTimet.empty?n.moveByChar(t,e):gh(t,e))}function Fe(n){return n.textDirectionAt(n.state.selection.main.head)==ge.LTR}const Py=n=>Qy(n,!Fe(n)),Ay=n=>Qy(n,Fe(n));function $y(n,e){return ti(n,t=>t.empty?n.moveByGroup(t,e):gh(t,e))}const _Q=n=>$y(n,!Fe(n)),GQ=n=>$y(n,Fe(n));function JQ(n,e,t){if(e.type.prop(t))return!0;let i=e.to-e.from;return i&&(i>2||/[^\s,.;:]/.test(n.sliceDoc(e.from,e.to)))||e.firstChild}function mh(n,e,t){let i=de(n).resolveInner(e.head),r=t?_.closedBy:_.openedBy;for(let l=e.head;;){let h=t?i.childAfter(l):i.childBefore(l);if(!h)break;JQ(n,h,r)?i=h:l=t?h.to:h.from}let s=i.type.prop(r),o,a;return s&&(o=t?ki(n,i.from,1):ki(n,i.to,-1))&&o.matched?a=t?o.end.to:o.end.from:a=t?i.to:i.from,P.cursor(a,t?-1:1)}const YQ=n=>ti(n,e=>mh(n.state,e,!Fe(n))),HQ=n=>ti(n,e=>mh(n.state,e,Fe(n)));function Cy(n,e){return ti(n,t=>{if(!t.empty)return gh(t,e);let i=n.moveVertically(t,e);return i.head!=t.head?i:n.moveToLineBoundary(t,e)})}const Iy=n=>Cy(n,!1),Ry=n=>Cy(n,!0);function Ey(n){return Math.max(n.defaultLineHeight,Math.min(n.dom.clientHeight,innerHeight)-5)}function Dy(n,e){let{state:t}=n,i=Cs(t.selection,a=>a.empty?n.moveVertically(a,e,Ey(n)):gh(a,e));if(i.eq(t.selection))return!1;let r=n.coordsAtPos(t.selection.main.head),s=n.scrollDOM.getBoundingClientRect(),o;return r&&r.top>s.top&&r.bottomDy(n,!1),Iu=n=>Dy(n,!0);function yr(n,e,t){let i=n.lineBlockAt(e.head),r=n.moveToLineBoundary(e,t);if(r.head==e.head&&r.head!=(t?i.to:i.from)&&(r=n.moveToLineBoundary(e,t,!1)),!t&&r.head==i.from&&i.length){let s=/^\s*/.exec(n.state.sliceDoc(i.from,Math.min(i.from+100,i.to)))[0].length;s&&e.head!=i.from+s&&(r=P.cursor(i.from+s))}return r}const KQ=n=>ti(n,e=>yr(n,e,!0)),eP=n=>ti(n,e=>yr(n,e,!1)),tP=n=>ti(n,e=>yr(n,e,!Fe(n))),iP=n=>ti(n,e=>yr(n,e,Fe(n))),nP=n=>ti(n,e=>P.cursor(n.lineBlockAt(e.head).from,1)),rP=n=>ti(n,e=>P.cursor(n.lineBlockAt(e.head).to,-1));function sP(n,e,t){let i=!1,r=Cs(n.selection,s=>{let o=ki(n,s.head,-1)||ki(n,s.head,1)||s.head>0&&ki(n,s.head-1,1)||s.headsP(n,e);function Xt(n,e){let t=Cs(n.state.selection,i=>{let r=e(i);return P.range(i.anchor,r.head,r.goalColumn)});return t.eq(n.state.selection)?!1:(n.dispatch($i(n.state,t)),!0)}function Ny(n,e){return Xt(n,t=>n.moveByChar(t,e))}const By=n=>Ny(n,!Fe(n)),qy=n=>Ny(n,Fe(n));function My(n,e){return Xt(n,t=>n.moveByGroup(t,e))}const aP=n=>My(n,!Fe(n)),lP=n=>My(n,Fe(n)),hP=n=>Xt(n,e=>mh(n.state,e,!Fe(n))),cP=n=>Xt(n,e=>mh(n.state,e,Fe(n)));function Vy(n,e){return Xt(n,t=>n.moveVertically(t,e))}const Xy=n=>Vy(n,!1),Ly=n=>Vy(n,!0);function Uy(n,e){return Xt(n,t=>n.moveVertically(t,e,Ey(n)))}const fg=n=>Uy(n,!1),dg=n=>Uy(n,!0),uP=n=>Xt(n,e=>yr(n,e,!0)),fP=n=>Xt(n,e=>yr(n,e,!1)),dP=n=>Xt(n,e=>yr(n,e,!Fe(n))),pP=n=>Xt(n,e=>yr(n,e,Fe(n))),gP=n=>Xt(n,e=>P.cursor(n.lineBlockAt(e.head).from)),mP=n=>Xt(n,e=>P.cursor(n.lineBlockAt(e.head).to)),pg=({state:n,dispatch:e})=>(e($i(n,{anchor:0})),!0),gg=({state:n,dispatch:e})=>(e($i(n,{anchor:n.doc.length})),!0),mg=({state:n,dispatch:e})=>(e($i(n,{anchor:n.selection.main.anchor,head:0})),!0),Og=({state:n,dispatch:e})=>(e($i(n,{anchor:n.selection.main.anchor,head:n.doc.length})),!0),OP=({state:n,dispatch:e})=>(e(n.update({selection:{anchor:0,head:n.doc.length},userEvent:"select"})),!0),yP=({state:n,dispatch:e})=>{let t=yh(n).map(({from:i,to:r})=>P.range(i,Math.min(r+1,n.doc.length)));return e(n.update({selection:P.create(t),userEvent:"select"})),!0},bP=({state:n,dispatch:e})=>{let t=Cs(n.selection,i=>{var r;let s=de(n).resolveInner(i.head,1);for(;!(s.from=i.to||s.to>i.to&&s.from<=i.from||!(!((r=s.parent)===null||r===void 0)&&r.parent));)s=s.parent;return P.range(s.to,s.from)});return e($i(n,t)),!0},SP=({state:n,dispatch:e})=>{let t=n.selection,i=null;return t.ranges.length>1?i=P.create([t.main]):t.main.empty||(i=P.create([P.cursor(t.main.head)])),i?(e($i(n,i)),!0):!1};function Oh(n,e){if(n.state.readOnly)return!1;let t="delete.selection",{state:i}=n,r=i.changeByRange(s=>{let{from:o,to:a}=s;if(o==a){let l=e(o);lo&&(t="delete.forward",l=ka(n,l,!0)),o=Math.min(o,l),a=Math.max(a,l)}else o=ka(n,o,!1),a=ka(n,a,!0);return o==a?{range:s}:{changes:{from:o,to:a},range:P.cursor(o)}});return r.changes.empty?!1:(n.dispatch(i.update(r,{scrollIntoView:!0,userEvent:t,effects:t=="delete.selection"?N.announce.of(i.phrase("Selection deleted")):void 0})),!0)}function ka(n,e,t){if(n instanceof N)for(let i of n.state.facet(N.atomicRanges).map(r=>r(n)))i.between(e,e,(r,s)=>{re&&(e=t?s:r)});return e}const Zy=(n,e)=>Oh(n,t=>{let{state:i}=n,r=i.doc.lineAt(t),s,o;if(!e&&t>r.from&&tZy(n,!1),Wy=n=>Zy(n,!0),jy=(n,e)=>Oh(n,t=>{let i=t,{state:r}=n,s=r.doc.lineAt(i),o=r.charCategorizer(i);for(let a=null;;){if(i==(e?s.to:s.from)){i==t&&s.number!=(e?r.doc.lines:1)&&(i+=e?1:-1);break}let l=We(s.text,i-s.from,e)+s.from,h=s.text.slice(Math.min(i,l)-s.from,Math.max(i,l)-s.from),c=o(h);if(a!=null&&c!=a)break;(h!=" "||i!=t)&&(a=c),i=l}return i}),Fy=n=>jy(n,!1),wP=n=>jy(n,!0),zy=n=>Oh(n,e=>{let t=n.lineBlockAt(e).to;return eOh(n,e=>{let t=n.lineBlockAt(e).from;return e>t?t:Math.max(0,e-1)}),kP=({state:n,dispatch:e})=>{if(n.readOnly)return!1;let t=n.changeByRange(i=>({changes:{from:i.from,to:i.to,insert:K.of(["",""])},range:P.cursor(i.from)}));return e(n.update(t,{scrollIntoView:!0,userEvent:"input"})),!0},xP=({state:n,dispatch:e})=>{if(n.readOnly)return!1;let t=n.changeByRange(i=>{if(!i.empty||i.from==0||i.from==n.doc.length)return{range:i};let r=i.from,s=n.doc.lineAt(r),o=r==s.from?r-1:We(s.text,r-s.from,!1)+s.from,a=r==s.to?r+1:We(s.text,r-s.from,!0)+s.from;return{changes:{from:o,to:a,insert:n.doc.slice(r,a).append(n.doc.slice(o,r))},range:P.cursor(a)}});return t.changes.empty?!1:(e(n.update(t,{scrollIntoView:!0,userEvent:"move.character"})),!0)};function yh(n){let e=[],t=-1;for(let i of n.selection.ranges){let r=n.doc.lineAt(i.from),s=n.doc.lineAt(i.to);if(!i.empty&&i.to==s.from&&(s=n.doc.lineAt(i.to-1)),t>=r.number){let o=e[e.length-1];o.to=s.to,o.ranges.push(i)}else e.push({from:r.from,to:s.to,ranges:[i]});t=s.number+1}return e}function _y(n,e,t){if(n.readOnly)return!1;let i=[],r=[];for(let s of yh(n)){if(t?s.to==n.doc.length:s.from==0)continue;let o=n.doc.lineAt(t?s.to+1:s.from-1),a=o.length+1;if(t){i.push({from:s.to,to:o.to},{from:s.from,insert:o.text+n.lineBreak});for(let l of s.ranges)r.push(P.range(Math.min(n.doc.length,l.anchor+a),Math.min(n.doc.length,l.head+a)))}else{i.push({from:o.from,to:s.from},{from:s.to,insert:n.lineBreak+o.text});for(let l of s.ranges)r.push(P.range(l.anchor-a,l.head-a))}}return i.length?(e(n.update({changes:i,scrollIntoView:!0,selection:P.create(r,n.selection.mainIndex),userEvent:"move.line"})),!0):!1}const TP=({state:n,dispatch:e})=>_y(n,e,!1),QP=({state:n,dispatch:e})=>_y(n,e,!0);function Gy(n,e,t){if(n.readOnly)return!1;let i=[];for(let r of yh(n))t?i.push({from:r.from,insert:n.doc.slice(r.from,r.to)+n.lineBreak}):i.push({from:r.to,insert:n.lineBreak+n.doc.slice(r.from,r.to)});return e(n.update({changes:i,scrollIntoView:!0,userEvent:"input.copyline"})),!0}const PP=({state:n,dispatch:e})=>Gy(n,e,!1),AP=({state:n,dispatch:e})=>Gy(n,e,!0),$P=n=>{if(n.state.readOnly)return!1;let{state:e}=n,t=e.changes(yh(e).map(({from:r,to:s})=>(r>0?r--:sn.moveVertically(r,!0)).map(t);return n.dispatch({changes:t,selection:i,scrollIntoView:!0,userEvent:"delete.line"}),!0};function CP(n,e){if(/\(\)|\[\]|\{\}/.test(n.sliceDoc(e-1,e+1)))return{from:e,to:e};let t=de(n).resolveInner(e),i=t.childBefore(e),r=t.childAfter(e),s;return i&&r&&i.to<=e&&r.from>=e&&(s=i.type.prop(_.closedBy))&&s.indexOf(r.name)>-1&&n.doc.lineAt(i.to).from==n.doc.lineAt(r.from).from?{from:i.to,to:r.from}:null}const IP=Jy(!1),RP=Jy(!0);function Jy(n){return({state:e,dispatch:t})=>{if(e.readOnly)return!1;let i=e.changeByRange(r=>{let{from:s,to:o}=r,a=e.doc.lineAt(s),l=!n&&s==o&&CP(e,s);n&&(s=o=(o<=a.to?a:e.doc.lineAt(o)).to);let h=new uh(e,{simulateBreak:s,simulateDoubleBreak:!!l}),c=Pf(h,s);for(c==null&&(c=/^\s*/.exec(e.doc.lineAt(s).text)[0].length);oa.from&&s{let r=[];for(let o=i.from;o<=i.to;){let a=n.doc.lineAt(o);a.number>t&&(i.empty||i.to>a.from)&&(e(a,r,i),t=a.number),o=a.to+1}let s=n.changes(r);return{changes:r,range:P.range(s.mapPos(i.anchor,1),s.mapPos(i.head,1))}})}const EP=({state:n,dispatch:e})=>{if(n.readOnly)return!1;let t=Object.create(null),i=new uh(n,{overrideIndentation:s=>{let o=t[s];return o??-1}}),r=If(n,(s,o,a)=>{let l=Pf(i,s.from);if(l==null)return;/\S/.test(s.text)||(l=0);let h=/^\s*/.exec(s.text)[0],c=Io(n,l);(h!=c||a.fromn.readOnly?!1:(e(n.update(If(n,(t,i)=>{i.push({from:t.from,insert:n.facet(ch)})}),{userEvent:"input.indent"})),!0),NP=({state:n,dispatch:e})=>n.readOnly?!1:(e(n.update(If(n,(t,i)=>{let r=/^\s*/.exec(t.text)[0];if(!r)return;let s=Uo(r,n.tabSize),o=0,a=Io(n,Math.max(0,s-El(n)));for(;o({mac:n.key,run:n.run,shift:n.shift}))),MP=[{key:"Alt-ArrowLeft",mac:"Ctrl-ArrowLeft",run:YQ,shift:hP},{key:"Alt-ArrowRight",mac:"Ctrl-ArrowRight",run:HQ,shift:cP},{key:"Alt-ArrowUp",run:TP},{key:"Shift-Alt-ArrowUp",run:PP},{key:"Alt-ArrowDown",run:QP},{key:"Shift-Alt-ArrowDown",run:AP},{key:"Escape",run:SP},{key:"Mod-Enter",run:RP},{key:"Alt-l",mac:"Ctrl-l",run:yP},{key:"Mod-i",run:bP,preventDefault:!0},{key:"Mod-[",run:NP},{key:"Mod-]",run:DP},{key:"Mod-Alt-\\",run:EP},{key:"Shift-Mod-k",run:$P},{key:"Shift-Mod-\\",run:oP},{key:"Mod-/",run:AQ},{key:"Alt-A",run:CQ}].concat(qP);function ae(){var n=arguments[0];typeof n=="string"&&(n=document.createElement(n));var e=1,t=arguments[1];if(t&&typeof t=="object"&&t.nodeType==null&&!Array.isArray(t)){for(var i in t)if(Object.prototype.hasOwnProperty.call(t,i)){var r=t[i];typeof r=="string"?n.setAttribute(i,r):r!=null&&(n[i]=r)}e++}for(;en.normalize("NFKD"):n=>n;class ks{constructor(e,t,i=0,r=e.length,s,o){this.test=o,this.value={from:0,to:0},this.done=!1,this.matches=[],this.buffer="",this.bufferPos=0,this.iter=e.iterRange(i,r),this.bufferStart=i,this.normalize=s?a=>s(yg(a)):yg,this.query=this.normalize(t)}peek(){if(this.bufferPos==this.buffer.length){if(this.bufferStart+=this.buffer.length,this.iter.next(),this.iter.done)return-1;this.bufferPos=0,this.buffer=this.iter.value}return Ne(this.buffer,this.bufferPos)}next(){for(;this.matches.length;)this.matches.pop();return this.nextOverlapping()}nextOverlapping(){for(;;){let e=this.peek();if(e<0)return this.done=!0,this;let t=cf(e),i=this.bufferStart+this.bufferPos;this.bufferPos+=lt(e);let r=this.normalize(t);for(let s=0,o=i;;s++){let a=r.charCodeAt(s),l=this.match(a,o);if(l)return this.value=l,this;if(s==r.length-1)break;o==i&&sthis.to&&(this.curLine=this.curLine.slice(0,this.to-this.curLineStart)),this.iter.next())}nextLine(){this.curLineStart=this.curLineStart+this.curLine.length+1,this.curLineStart>this.to?this.curLine="":this.getLine(0)}next(){for(let e=this.matchPos-this.curLineStart;;){this.re.lastIndex=e;let t=this.matchPos<=this.to&&this.re.exec(this.curLine);if(t){let i=this.curLineStart+t.index,r=i+t[0].length;if(this.matchPos=ql(this.text,r+(i==r?1:0)),i==this.curLineStart+this.curLine.length&&this.nextLine(),(ithis.value.to)&&(!this.test||this.test(i,r,t)))return this.value={from:i,to:r,match:t},this;e=this.matchPos-this.curLineStart}else if(this.curLineStart+this.curLine.length=i||r.to<=t){let a=new as(t,e.sliceString(t,i));return Hh.set(e,a),a}if(r.from==t&&r.to==i)return r;let{text:s,from:o}=r;return o>t&&(s=e.sliceString(t,o)+s,o=t),r.to=this.to?this.to:this.text.lineAt(e).to}next(){for(;;){let e=this.re.lastIndex=this.matchPos-this.flat.from,t=this.re.exec(this.flat.text);if(t&&!t[0]&&t.index==e&&(this.re.lastIndex=e+1,t=this.re.exec(this.flat.text)),t){let i=this.flat.from+t.index,r=i+t[0].length;if((this.flat.to>=this.to||t.index+t[0].length<=this.flat.text.length-10)&&(!this.test||this.test(i,r,t)))return this.value={from:i,to:r,match:t},this.matchPos=ql(this.text,r+(i==r?1:0)),this}if(this.flat.to==this.to)return this.done=!0,this;this.flat=as.get(this.text,this.flat.from,this.chunkEnd(this.flat.from+this.flat.text.length*2))}}}typeof Symbol<"u"&&(Ky.prototype[Symbol.iterator]=eb.prototype[Symbol.iterator]=function(){return this});function VP(n){try{return new RegExp(n,Rf),!0}catch{return!1}}function ql(n,e){if(e>=n.length)return e;let t=n.lineAt(e),i;for(;e=56320&&i<57344;)e++;return e}function Eu(n){let e=ae("input",{class:"cm-textfield",name:"line"}),t=ae("form",{class:"cm-gotoLine",onkeydown:r=>{r.keyCode==27?(r.preventDefault(),n.dispatch({effects:Ml.of(!1)}),n.focus()):r.keyCode==13&&(r.preventDefault(),i())},onsubmit:r=>{r.preventDefault(),i()}},ae("label",n.state.phrase("Go to line"),": ",e)," ",ae("button",{class:"cm-button",type:"submit"},n.state.phrase("go")));function i(){let r=/^([+-])?(\d+)?(:\d+)?(%)?$/.exec(e.value);if(!r)return;let{state:s}=n,o=s.doc.lineAt(s.selection.main.head),[,a,l,h,c]=r,u=h?+h.slice(1):0,f=l?+l:o.number;if(l&&c){let g=f/100;a&&(g=g*(a=="-"?-1:1)+o.number/s.doc.lines),f=Math.round(s.doc.lines*g)}else l&&a&&(f=f*(a=="-"?-1:1)+o.number);let p=s.doc.line(Math.max(1,Math.min(s.doc.lines,f)));n.dispatch({effects:Ml.of(!1),selection:P.cursor(p.from+Math.max(0,Math.min(u,p.length))),scrollIntoView:!0}),n.focus()}return{dom:t}}const Ml=z.define(),bg=Re.define({create(){return!0},update(n,e){for(let t of e.effects)t.is(Ml)&&(n=t.value);return n},provide:n=>Po.from(n,e=>e?Eu:null)}),XP=n=>{let e=Qo(n,Eu);if(!e){let t=[Ml.of(!0)];n.state.field(bg,!1)==null&&t.push(z.appendConfig.of([bg,LP])),n.dispatch({effects:t}),e=Qo(n,Eu)}return e&&e.dom.querySelector("input").focus(),!0},LP=N.baseTheme({".cm-panel.cm-gotoLine":{padding:"2px 6px 4px","& label":{fontSize:"80%"}}}),UP={highlightWordAroundCursor:!1,minSelectionLength:1,maxMatches:100,wholeWords:!1},ZP=B.define({combine(n){return Ai(n,UP,{highlightWordAroundCursor:(e,t)=>e||t,minSelectionLength:Math.min,maxMatches:Math.min})}});function WP(n){return[GP,_P]}const jP=Z.mark({class:"cm-selectionMatch"}),FP=Z.mark({class:"cm-selectionMatch cm-selectionMatch-main"});function Sg(n,e,t,i){return(t==0||n(e.sliceDoc(t-1,t))!=fe.Word)&&(i==e.doc.length||n(e.sliceDoc(i,i+1))!=fe.Word)}function zP(n,e,t,i){return n(e.sliceDoc(t,t+1))==fe.Word&&n(e.sliceDoc(i-1,i))==fe.Word}const _P=ke.fromClass(class{constructor(n){this.decorations=this.getDeco(n)}update(n){(n.selectionSet||n.docChanged||n.viewportChanged)&&(this.decorations=this.getDeco(n.view))}getDeco(n){let e=n.state.facet(ZP),{state:t}=n,i=t.selection;if(i.ranges.length>1)return Z.none;let r=i.main,s,o=null;if(r.empty){if(!e.highlightWordAroundCursor)return Z.none;let l=t.wordAt(r.head);if(!l)return Z.none;o=t.charCategorizer(r.head),s=t.sliceDoc(l.from,l.to)}else{let l=r.to-r.from;if(l200)return Z.none;if(e.wholeWords){if(s=t.sliceDoc(r.from,r.to),o=t.charCategorizer(r.head),!(Sg(o,t,r.from,r.to)&&zP(o,t,r.from,r.to)))return Z.none}else if(s=t.sliceDoc(r.from,r.to).trim(),!s)return Z.none}let a=[];for(let l of n.visibleRanges){let h=new ks(t.doc,s,l.from,l.to);for(;!h.next().done;){let{from:c,to:u}=h.value;if((!o||Sg(o,t,c,u))&&(r.empty&&c<=r.from&&u>=r.to?a.push(FP.range(c,u)):(c>=r.to||u<=r.from)&&a.push(jP.range(c,u)),a.length>e.maxMatches))return Z.none}}return Z.set(a)}},{decorations:n=>n.decorations}),GP=N.baseTheme({".cm-selectionMatch":{backgroundColor:"#99ff7780"},".cm-searchMatch .cm-selectionMatch":{backgroundColor:"transparent"}}),JP=({state:n,dispatch:e})=>{let{selection:t}=n,i=P.create(t.ranges.map(r=>n.wordAt(r.head)||P.cursor(r.head)),t.mainIndex);return i.eq(t)?!1:(e(n.update({selection:i})),!0)};function YP(n,e){let{main:t,ranges:i}=n.selection,r=n.wordAt(t.head),s=r&&r.from==t.from&&r.to==t.to;for(let o=!1,a=new ks(n.doc,e,i[i.length-1].to);;)if(a.next(),a.done){if(o)return null;a=new ks(n.doc,e,0,Math.max(0,i[i.length-1].from-1)),o=!0}else{if(o&&i.some(l=>l.from==a.value.from))continue;if(s){let l=n.wordAt(a.value.from);if(!l||l.from!=a.value.from||l.to!=a.value.to)continue}return a.value}}const HP=({state:n,dispatch:e})=>{let{ranges:t}=n.selection;if(t.some(s=>s.from===s.to))return JP({state:n,dispatch:e});let i=n.sliceDoc(t[0].from,t[0].to);if(n.selection.ranges.some(s=>n.sliceDoc(s.from,s.to)!=i))return!1;let r=YP(n,i);return r?(e(n.update({selection:n.selection.addRange(P.range(r.from,r.to),!1),effects:N.scrollIntoView(r.to)})),!0):!1},Ef=B.define({combine(n){return Ai(n,{top:!1,caseSensitive:!1,literal:!1,wholeWord:!1,createPanel:e=>new cA(e)})}});class tb{constructor(e){this.search=e.search,this.caseSensitive=!!e.caseSensitive,this.literal=!!e.literal,this.regexp=!!e.regexp,this.replace=e.replace||"",this.valid=!!this.search&&(!this.regexp||VP(this.search)),this.unquoted=this.unquote(this.search),this.wholeWord=!!e.wholeWord}unquote(e){return this.literal?e:e.replace(/\\([nrt\\])/g,(t,i)=>i=="n"?` -`:i=="r"?"\r":i=="t"?" ":"\\")}eq(e){return this.search==e.search&&this.replace==e.replace&&this.caseSensitive==e.caseSensitive&&this.regexp==e.regexp&&this.wholeWord==e.wholeWord}create(){return this.regexp?new iA(this):new eA(this)}getCursor(e,t=0,i){let r=e.doc?e:H.create({doc:e});return i==null&&(i=r.doc.length),this.regexp?_r(this,r,t,i):zr(this,r,t,i)}}class ib{constructor(e){this.spec=e}}function zr(n,e,t,i){return new ks(e.doc,n.unquoted,t,i,n.caseSensitive?void 0:r=>r.toLowerCase(),n.wholeWord?KP(e.doc,e.charCategorizer(e.selection.main.head)):void 0)}function KP(n,e){return(t,i,r,s)=>((s>t||s+r.length=t)return null;r.push(i.value)}return r}highlight(e,t,i,r){let s=zr(this.spec,e,Math.max(0,t-this.spec.unquoted.length),Math.min(i+this.spec.unquoted.length,e.doc.length));for(;!s.next().done;)r(s.value.from,s.value.to)}}function _r(n,e,t,i){return new Ky(e.doc,n.search,{ignoreCase:!n.caseSensitive,test:n.wholeWord?tA(e.charCategorizer(e.selection.main.head)):void 0},t,i)}function Vl(n,e){return n.slice(We(n,e,!1),e)}function Xl(n,e){return n.slice(e,We(n,e))}function tA(n){return(e,t,i)=>!i[0].length||(n(Vl(i.input,i.index))!=fe.Word||n(Xl(i.input,i.index))!=fe.Word)&&(n(Xl(i.input,i.index+i[0].length))!=fe.Word||n(Vl(i.input,i.index+i[0].length))!=fe.Word)}class iA extends ib{nextMatch(e,t,i){let r=_r(this.spec,e,i,e.doc.length).next();return r.done&&(r=_r(this.spec,e,0,t).next()),r.done?null:r.value}prevMatchInRange(e,t,i){for(let r=1;;r++){let s=Math.max(t,i-r*1e4),o=_r(this.spec,e,s,i),a=null;for(;!o.next().done;)a=o.value;if(a&&(s==t||a.from>s+10))return a;if(s==t)return null}}prevMatch(e,t,i){return this.prevMatchInRange(e,0,t)||this.prevMatchInRange(e,i,e.doc.length)}getReplacement(e){return this.spec.unquote(this.spec.replace.replace(/\$([$&\d+])/g,(t,i)=>i=="$"?"$":i=="&"?e.match[0]:i!="0"&&+i=t)return null;r.push(i.value)}return r}highlight(e,t,i,r){let s=_r(this.spec,e,Math.max(0,t-250),Math.min(i+250,e.doc.length));for(;!s.next().done;)r(s.value.from,s.value.to)}}const Ro=z.define(),Df=z.define(),ar=Re.define({create(n){return new Kh(Du(n).create(),null)},update(n,e){for(let t of e.effects)t.is(Ro)?n=new Kh(t.value.create(),n.panel):t.is(Df)&&(n=new Kh(n.query,t.value?Nf:null));return n},provide:n=>Po.from(n,e=>e.panel)});class Kh{constructor(e,t){this.query=e,this.panel=t}}const nA=Z.mark({class:"cm-searchMatch"}),rA=Z.mark({class:"cm-searchMatch cm-searchMatch-selected"}),sA=ke.fromClass(class{constructor(n){this.view=n,this.decorations=this.highlight(n.state.field(ar))}update(n){let e=n.state.field(ar);(e!=n.startState.field(ar)||n.docChanged||n.selectionSet||n.viewportChanged)&&(this.decorations=this.highlight(e))}highlight({query:n,panel:e}){if(!e||!n.spec.valid)return Z.none;let{view:t}=this,i=new fr;for(let r=0,s=t.visibleRanges,o=s.length;rs[r+1].from-2*250;)l=s[++r].to;n.highlight(t.state,a,l,(h,c)=>{let u=t.state.selection.ranges.some(f=>f.from==h&&f.to==c);i.add(h,c,u?rA:nA)})}return i.finish()}},{decorations:n=>n.decorations});function Jo(n){return e=>{let t=e.state.field(ar,!1);return t&&t.query.spec.valid?n(e,t):nb(e)}}const Ll=Jo((n,{query:e})=>{let{to:t}=n.state.selection.main,i=e.nextMatch(n.state,t,t);return i?(n.dispatch({selection:{anchor:i.from,head:i.to},scrollIntoView:!0,effects:Bf(n,i),userEvent:"select.search"}),!0):!1}),Ul=Jo((n,{query:e})=>{let{state:t}=n,{from:i}=t.selection.main,r=e.prevMatch(t,i,i);return r?(n.dispatch({selection:{anchor:r.from,head:r.to},scrollIntoView:!0,effects:Bf(n,r),userEvent:"select.search"}),!0):!1}),oA=Jo((n,{query:e})=>{let t=e.matchAll(n.state,1e3);return!t||!t.length?!1:(n.dispatch({selection:P.create(t.map(i=>P.range(i.from,i.to))),userEvent:"select.search.matches"}),!0)}),aA=({state:n,dispatch:e})=>{let t=n.selection;if(t.ranges.length>1||t.main.empty)return!1;let{from:i,to:r}=t.main,s=[],o=0;for(let a=new ks(n.doc,n.sliceDoc(i,r));!a.next().done;){if(s.length>1e3)return!1;a.value.from==i&&(o=s.length),s.push(P.range(a.value.from,a.value.to))}return e(n.update({selection:P.create(s,o),userEvent:"select.search.matches"})),!0},wg=Jo((n,{query:e})=>{let{state:t}=n,{from:i,to:r}=t.selection.main;if(t.readOnly)return!1;let s=e.nextMatch(t,i,i);if(!s)return!1;let o=[],a,l,h=[];if(s.from==i&&s.to==r&&(l=t.toText(e.getReplacement(s)),o.push({from:s.from,to:s.to,insert:l}),s=e.nextMatch(t,s.from,s.to),h.push(N.announce.of(t.phrase("replaced match on line $",t.doc.lineAt(i).number)+"."))),s){let c=o.length==0||o[0].from>=s.to?0:s.to-s.from-l.length;a={anchor:s.from-c,head:s.to-c},h.push(Bf(n,s))}return n.dispatch({changes:o,selection:a,scrollIntoView:!!a,effects:h,userEvent:"input.replace"}),!0}),lA=Jo((n,{query:e})=>{if(n.state.readOnly)return!1;let t=e.matchAll(n.state,1e9).map(r=>{let{from:s,to:o}=r;return{from:s,to:o,insert:e.getReplacement(r)}});if(!t.length)return!1;let i=n.state.phrase("replaced $ matches",t.length)+".";return n.dispatch({changes:t,effects:N.announce.of(i),userEvent:"input.replace.all"}),!0});function Nf(n){return n.state.facet(Ef).createPanel(n)}function Du(n,e){var t,i,r,s;let o=n.selection.main,a=o.empty||o.to>o.from+100?"":n.sliceDoc(o.from,o.to);if(e&&!a)return e;let l=n.facet(Ef);return new tb({search:((t=e==null?void 0:e.literal)!==null&&t!==void 0?t:l.literal)?a:a.replace(/\n/g,"\\n"),caseSensitive:(i=e==null?void 0:e.caseSensitive)!==null&&i!==void 0?i:l.caseSensitive,literal:(r=e==null?void 0:e.literal)!==null&&r!==void 0?r:l.literal,wholeWord:(s=e==null?void 0:e.wholeWord)!==null&&s!==void 0?s:l.wholeWord})}const nb=n=>{let e=n.state.field(ar,!1);if(e&&e.panel){let t=Qo(n,Nf);if(!t)return!1;let i=t.dom.querySelector("[main-field]");if(i&&i!=n.root.activeElement){let r=Du(n.state,e.query.spec);r.valid&&n.dispatch({effects:Ro.of(r)}),i.focus(),i.select()}}else n.dispatch({effects:[Df.of(!0),e?Ro.of(Du(n.state,e.query.spec)):z.appendConfig.of(fA)]});return!0},rb=n=>{let e=n.state.field(ar,!1);if(!e||!e.panel)return!1;let t=Qo(n,Nf);return t&&t.dom.contains(n.root.activeElement)&&n.focus(),n.dispatch({effects:Df.of(!1)}),!0},hA=[{key:"Mod-f",run:nb,scope:"editor search-panel"},{key:"F3",run:Ll,shift:Ul,scope:"editor search-panel",preventDefault:!0},{key:"Mod-g",run:Ll,shift:Ul,scope:"editor search-panel",preventDefault:!0},{key:"Escape",run:rb,scope:"editor search-panel"},{key:"Mod-Shift-l",run:aA},{key:"Alt-g",run:XP},{key:"Mod-d",run:HP,preventDefault:!0}];class cA{constructor(e){this.view=e;let t=this.query=e.state.field(ar).query.spec;this.commit=this.commit.bind(this),this.searchField=ae("input",{value:t.search,placeholder:st(e,"Find"),"aria-label":st(e,"Find"),class:"cm-textfield",name:"search",form:"","main-field":"true",onchange:this.commit,onkeyup:this.commit}),this.replaceField=ae("input",{value:t.replace,placeholder:st(e,"Replace"),"aria-label":st(e,"Replace"),class:"cm-textfield",name:"replace",form:"",onchange:this.commit,onkeyup:this.commit}),this.caseField=ae("input",{type:"checkbox",name:"case",form:"",checked:t.caseSensitive,onchange:this.commit}),this.reField=ae("input",{type:"checkbox",name:"re",form:"",checked:t.regexp,onchange:this.commit}),this.wordField=ae("input",{type:"checkbox",name:"word",form:"",checked:t.wholeWord,onchange:this.commit});function i(r,s,o){return ae("button",{class:"cm-button",name:r,onclick:s,type:"button"},o)}this.dom=ae("div",{onkeydown:r=>this.keydown(r),class:"cm-search"},[this.searchField,i("next",()=>Ll(e),[st(e,"next")]),i("prev",()=>Ul(e),[st(e,"previous")]),i("select",()=>oA(e),[st(e,"all")]),ae("label",null,[this.caseField,st(e,"match case")]),ae("label",null,[this.reField,st(e,"regexp")]),ae("label",null,[this.wordField,st(e,"by word")]),...e.state.readOnly?[]:[ae("br"),this.replaceField,i("replace",()=>wg(e),[st(e,"replace")]),i("replaceAll",()=>lA(e),[st(e,"replace all")])],ae("button",{name:"close",onclick:()=>rb(e),"aria-label":st(e,"close"),type:"button"},["×"])])}commit(){let e=new tb({search:this.searchField.value,caseSensitive:this.caseField.checked,regexp:this.reField.checked,wholeWord:this.wordField.checked,replace:this.replaceField.value});e.eq(this.query)||(this.query=e,this.view.dispatch({effects:Ro.of(e)}))}keydown(e){Ox(this.view,e,"search-panel")?e.preventDefault():e.keyCode==13&&e.target==this.searchField?(e.preventDefault(),(e.shiftKey?Ul:Ll)(this.view)):e.keyCode==13&&e.target==this.replaceField&&(e.preventDefault(),wg(this.view))}update(e){for(let t of e.transactions)for(let i of t.effects)i.is(Ro)&&!i.value.eq(this.query)&&this.setQuery(i.value)}setQuery(e){this.query=e,this.searchField.value=e.search,this.replaceField.value=e.replace,this.caseField.checked=e.caseSensitive,this.reField.checked=e.regexp,this.wordField.checked=e.wholeWord}mount(){this.searchField.select()}get pos(){return 80}get top(){return this.view.state.facet(Ef).top}}function st(n,e){return n.state.phrase(e)}const xa=30,Ta=/[\s\.,:;?!]/;function Bf(n,{from:e,to:t}){let i=n.state.doc.lineAt(e),r=n.state.doc.lineAt(t).to,s=Math.max(i.from,e-xa),o=Math.min(r,t+xa),a=n.state.sliceDoc(s,o);if(s!=i.from){for(let l=0;la.length-xa;l--)if(!Ta.test(a[l-1])&&Ta.test(a[l])){a=a.slice(0,l);break}}return N.announce.of(`${n.state.phrase("current match")}. ${a} ${n.state.phrase("on line")} ${i.number}.`)}const uA=N.baseTheme({".cm-panel.cm-search":{padding:"2px 6px 4px",position:"relative","& [name=close]":{position:"absolute",top:"0",right:"4px",backgroundColor:"inherit",border:"none",font:"inherit",padding:0,margin:0},"& input, & button, & label":{margin:".2em .6em .2em 0"},"& input[type=checkbox]":{marginRight:".2em"},"& label":{fontSize:"80%",whiteSpace:"pre"}},"&light .cm-searchMatch":{backgroundColor:"#ffff0054"},"&dark .cm-searchMatch":{backgroundColor:"#00ffff8a"},"&light .cm-searchMatch-selected":{backgroundColor:"#ff6a0054"},"&dark .cm-searchMatch-selected":{backgroundColor:"#ff00ff8a"}}),fA=[ar,mr.lowest(sA),uA];class sb{constructor(e,t,i){this.state=e,this.pos=t,this.explicit=i,this.abortListeners=[]}tokenBefore(e){let t=de(this.state).resolveInner(this.pos,-1);for(;t&&e.indexOf(t.name)<0;)t=t.parent;return t?{from:t.from,to:this.pos,text:this.state.sliceDoc(t.from,this.pos),type:t.type}:null}matchBefore(e){let t=this.state.doc.lineAt(this.pos),i=Math.max(t.from,this.pos-250),r=t.text.slice(i-t.from,this.pos-t.from),s=r.search(ab(e,!1));return s<0?null:{from:i+s,to:this.pos,text:r.slice(s)}}get aborted(){return this.abortListeners==null}addEventListener(e,t){e=="abort"&&this.abortListeners&&this.abortListeners.push(t)}}function vg(n){let e=Object.keys(n).join(""),t=/\w/.test(e);return t&&(e=e.replace(/\w/g,"")),`[${t?"\\w":""}${e.replace(/[^\w\s]/g,"\\$&")}]`}function dA(n){let e=Object.create(null),t=Object.create(null);for(let{label:r}of n){e[r[0]]=!0;for(let s=1;stypeof r=="string"?{label:r}:r),[t,i]=e.every(r=>/^\w+$/.test(r.label))?[/\w*$/,/\w+$/]:dA(e);return r=>{let s=r.matchBefore(i);return s||r.explicit?{from:s?s.from:r.pos,options:e,validFor:t}:null}}function pA(n,e){return t=>{for(let i=de(t.state).resolveInner(t.pos,-1);i;i=i.parent)if(n.indexOf(i.name)>-1)return null;return e(t)}}class kg{constructor(e,t,i){this.completion=e,this.source=t,this.match=i}}function lr(n){return n.selection.main.head}function ab(n,e){var t;let{source:i}=n,r=e&&i[0]!="^",s=i[i.length-1]!="$";return!r&&!s?n:new RegExp(`${r?"^":""}(?:${i})${s?"$":""}`,(t=n.flags)!==null&&t!==void 0?t:n.ignoreCase?"i":"")}const gA=jn.define();function mA(n,e,t,i){return Object.assign(Object.assign({},n.changeByRange(r=>{if(r==n.selection.main)return{changes:{from:t,to:i,insert:e},range:P.cursor(t+e.length)};let s=i-t;return!r.empty||s&&n.sliceDoc(r.from-s,r.from)!=n.sliceDoc(t,i)?{range:r}:{changes:{from:r.from-s,to:r.from,insert:e},range:P.cursor(r.from-s+e.length)}})),{userEvent:"input.complete"})}function lb(n,e){const t=e.completion.apply||e.completion.label;let i=e.source;typeof t=="string"?n.dispatch(Object.assign(Object.assign({},mA(n.state,t,i.from,i.to)),{annotations:gA.of(e.completion)})):t(n,e.completion,i.from,i.to)}const xg=new WeakMap;function OA(n){if(!Array.isArray(n))return n;let e=xg.get(n);return e||xg.set(n,e=ob(n)),e}class yA{constructor(e){this.pattern=e,this.chars=[],this.folded=[],this.any=[],this.precise=[],this.byWord=[];for(let t=0;t=48&&Q<=57||Q>=97&&Q<=122?2:Q>=65&&Q<=90?1:0:(A=cf(Q))!=A.toLowerCase()?1:A!=A.toUpperCase()?2:0;(!k||R==1&&O||x==0&&R!=0)&&(t[u]==Q||i[u]==Q&&(f=!0)?o[u++]=k:o.length&&(S=!1)),x=R,k+=lt(Q)}return u==l&&o[0]==0&&S?this.result(-100+(f?-200:0),o,e):p==l&&g==0?[-200-e.length,0,y]:a>-1?[-700-e.length,a,a+this.pattern.length]:p==l?[-900-e.length,g,y]:u==l?this.result(-100+(f?-200:0)+-700+(S?0:-1100),o,e):t.length==2?null:this.result((r[0]?-700:0)+-200+-1100,r,e)}result(e,t,i){let r=[e-i.length],s=1;for(let o of t){let a=o+(this.astral?lt(Ne(i,o)):1);s>1&&r[s-1]==o?r[s-1]=a:(r[s++]=o,r[s++]=a)}return r}}const Vt=B.define({combine(n){return Ai(n,{activateOnTyping:!0,selectOnOpen:!0,override:null,closeOnBlur:!0,maxRenderedOptions:100,defaultKeymap:!0,optionClass:()=>"",aboveCursor:!1,icons:!0,addToOptions:[],compareCompletions:(e,t)=>e.label.localeCompare(t.label),interactionDelay:75},{defaultKeymap:(e,t)=>e&&t,closeOnBlur:(e,t)=>e&&t,icons:(e,t)=>e&&t,optionClass:(e,t)=>i=>bA(e(i),t(i)),addToOptions:(e,t)=>e.concat(t)})}});function bA(n,e){return n?e?n+" "+e:n:e}function SA(n){let e=n.addToOptions.slice();return n.icons&&e.push({render(t){let i=document.createElement("div");return i.classList.add("cm-completionIcon"),t.type&&i.classList.add(...t.type.split(/\s+/g).map(r=>"cm-completionIcon-"+r)),i.setAttribute("aria-hidden","true"),i},position:20}),e.push({render(t,i,r){let s=document.createElement("span");s.className="cm-completionLabel";let{label:o}=t,a=0;for(let l=1;la&&s.appendChild(document.createTextNode(o.slice(a,h)));let u=s.appendChild(document.createElement("span"));u.appendChild(document.createTextNode(o.slice(h,c))),u.className="cm-completionMatchedText",a=c}return at.position-i.position).map(t=>t.render)}function Tg(n,e,t){if(n<=t)return{from:0,to:n};if(e<0&&(e=0),e<=n>>1){let r=Math.floor(e/t);return{from:r*t,to:(r+1)*t}}let i=Math.floor((n-e)/t);return{from:n-(i+1)*t,to:n-i*t}}class wA{constructor(e,t){this.view=e,this.stateField=t,this.info=null,this.placeInfo={read:()=>this.measureInfo(),write:a=>this.positionInfo(a),key:this},this.space=null;let i=e.state.field(t),{options:r,selected:s}=i.open,o=e.state.facet(Vt);this.optionContent=SA(o),this.optionClass=o.optionClass,this.range=Tg(r.length,s,o.maxRenderedOptions),this.dom=document.createElement("div"),this.dom.className="cm-tooltip-autocomplete",this.dom.addEventListener("mousedown",a=>{for(let l=a.target,h;l&&l!=this.dom;l=l.parentNode)if(l.nodeName=="LI"&&(h=/-(\d+)$/.exec(l.id))&&+h[1]{this.info&&this.view.requestMeasure(this.placeInfo)})}mount(){this.updateSel()}update(e){var t,i,r;let s=e.state.field(this.stateField),o=e.startState.field(this.stateField);s!=o&&(this.updateSel(),((t=s.open)===null||t===void 0?void 0:t.disabled)!=((i=o.open)===null||i===void 0?void 0:i.disabled)&&this.dom.classList.toggle("cm-tooltip-autocomplete-disabled",!!(!((r=s.open)===null||r===void 0)&&r.disabled)))}positioned(e){this.space=e,this.info&&this.view.requestMeasure(this.placeInfo)}updateSel(){let e=this.view.state.field(this.stateField),t=e.open;if((t.selected>-1&&t.selected=this.range.to)&&(this.range=Tg(t.options.length,t.selected,this.view.state.facet(Vt).maxRenderedOptions),this.list.remove(),this.list=this.dom.appendChild(this.createListBox(t.options,e.id,this.range)),this.list.addEventListener("scroll",()=>{this.info&&this.view.requestMeasure(this.placeInfo)})),this.updateSelectedOption(t.selected)){this.info&&(this.info.remove(),this.info=null);let{completion:i}=t.options[t.selected],{info:r}=i;if(!r)return;let s=typeof r=="string"?document.createTextNode(r):r(i);if(!s)return;"then"in s?s.then(o=>{o&&this.view.state.field(this.stateField,!1)==e&&this.addInfoPane(o)}).catch(o=>mt(this.view.state,o,"completion info")):this.addInfoPane(s)}}addInfoPane(e){let t=this.info=document.createElement("div");t.className="cm-tooltip cm-completionInfo",t.appendChild(e),this.dom.appendChild(t),this.view.requestMeasure(this.placeInfo)}updateSelectedOption(e){let t=null;for(let i=this.list.firstChild,r=this.range.from;i;i=i.nextSibling,r++)r==e?i.hasAttribute("aria-selected")||(i.setAttribute("aria-selected","true"),t=i):i.hasAttribute("aria-selected")&&i.removeAttribute("aria-selected");return t&&kA(this.list,t),t}measureInfo(){let e=this.dom.querySelector("[aria-selected]");if(!e||!this.info)return null;let t=this.dom.getBoundingClientRect(),i=this.info.getBoundingClientRect(),r=e.getBoundingClientRect(),s=this.space;if(!s){let g=this.dom.ownerDocument.defaultView||window;s={left:0,top:0,right:g.innerWidth,bottom:g.innerHeight}}if(r.top>Math.min(s.bottom,t.bottom)-10||r.bottom=i.height||g>t.top?c=r.bottom-t.top+"px":u=t.bottom-r.top+"px"}return{top:c,bottom:u,maxWidth:h,class:l?o?"left-narrow":"right-narrow":a?"left":"right"}}positionInfo(e){this.info&&(e?(this.info.style.top=e.top,this.info.style.bottom=e.bottom,this.info.style.maxWidth=e.maxWidth,this.info.className="cm-tooltip cm-completionInfo cm-completionInfo-"+e.class):this.info.style.top="-1e6px")}createListBox(e,t,i){const r=document.createElement("ul");r.id=t,r.setAttribute("role","listbox"),r.setAttribute("aria-expanded","true"),r.setAttribute("aria-label",this.view.state.phrase("Completions"));for(let s=i.from;snew wA(e,n)}function kA(n,e){let t=n.getBoundingClientRect(),i=e.getBoundingClientRect();i.topt.bottom&&(n.scrollTop+=i.bottom-t.bottom)}function Qg(n){return(n.boost||0)*100+(n.apply?10:0)+(n.info?5:0)+(n.type?1:0)}function xA(n,e){let t=[],i=0;for(let a of n)if(a.hasResult())if(a.result.filter===!1){let l=a.result.getMatch;for(let h of a.result.options){let c=[1e9-i++];if(l)for(let u of l(h))c.push(u);t.push(new kg(h,a,c))}}else{let l=new yA(e.sliceDoc(a.from,a.to)),h;for(let c of a.result.options)(h=l.match(c.label))&&(c.boost!=null&&(h[0]+=c.boost),t.push(new kg(c,a,h)))}let r=[],s=null,o=e.facet(Vt).compareCompletions;for(let a of t.sort((l,h)=>h.match[0]-l.match[0]||o(l.completion,h.completion)))!s||s.label!=a.completion.label||s.detail!=a.completion.detail||s.type!=null&&a.completion.type!=null&&s.type!=a.completion.type||s.apply!=a.completion.apply?r.push(a):Qg(a.completion)>Qg(s)&&(r[r.length-1]=a),s=a.completion;return r}class Hr{constructor(e,t,i,r,s,o){this.options=e,this.attrs=t,this.tooltip=i,this.timestamp=r,this.selected=s,this.disabled=o}setSelected(e,t){return e==this.selected||e>=this.options.length?this:new Hr(this.options,Pg(t,e),this.tooltip,this.timestamp,e,this.disabled)}static build(e,t,i,r,s){let o=xA(e,t);if(!o.length)return r&&e.some(l=>l.state==1)?new Hr(r.options,r.attrs,r.tooltip,r.timestamp,r.selected,!0):null;let a=t.facet(Vt).selectOnOpen?0:-1;if(r&&r.selected!=a&&r.selected!=-1){let l=r.options[r.selected].completion;for(let h=0;hh.hasResult()?Math.min(l,h.from):l,1e8),create:vA(yt),above:s.aboveCursor},r?r.timestamp:Date.now(),a,!1)}map(e){return new Hr(this.options,this.attrs,Object.assign(Object.assign({},this.tooltip),{pos:e.mapPos(this.tooltip.pos)}),this.timestamp,this.selected,this.disabled)}}class Zl{constructor(e,t,i){this.active=e,this.id=t,this.open=i}static start(){return new Zl(PA,"cm-ac-"+Math.floor(Math.random()*2e6).toString(36),null)}update(e){let{state:t}=e,i=t.facet(Vt),s=(i.override||t.languageDataAt("autocomplete",lr(t)).map(OA)).map(a=>(this.active.find(h=>h.source==a)||new et(a,this.active.some(h=>h.state!=0)?1:0)).update(e,i));s.length==this.active.length&&s.every((a,l)=>a==this.active[l])&&(s=this.active);let o=this.open;e.selection||s.some(a=>a.hasResult()&&e.changes.touchesRange(a.from,a.to))||!TA(s,this.active)?o=Hr.build(s,t,this.id,this.open,i):o&&o.disabled&&!s.some(a=>a.state==1)?o=null:o&&e.docChanged&&(o=o.map(e.changes)),!o&&s.every(a=>a.state!=1)&&s.some(a=>a.hasResult())&&(s=s.map(a=>a.hasResult()?new et(a.source,0):a));for(let a of e.effects)a.is(cb)&&(o=o&&o.setSelected(a.value,this.id));return s==this.active&&o==this.open?this:new Zl(s,this.id,o)}get tooltip(){return this.open?this.open.tooltip:null}get attrs(){return this.open?this.open.attrs:QA}}function TA(n,e){if(n==e)return!0;for(let t=0,i=0;;){for(;t-1&&(t["aria-activedescendant"]=n+"-"+e),t}const PA=[];function Nu(n){return n.isUserEvent("input.type")?"input":n.isUserEvent("delete.backward")?"delete":null}class et{constructor(e,t,i=-1){this.source=e,this.state=t,this.explicitPos=i}hasResult(){return!1}update(e,t){let i=Nu(e),r=this;i?r=r.handleUserEvent(e,i,t):e.docChanged?r=r.handleChange(e):e.selection&&r.state!=0&&(r=new et(r.source,0));for(let s of e.effects)if(s.is(qf))r=new et(r.source,1,s.value?lr(e.state):-1);else if(s.is(Wl))r=new et(r.source,0);else if(s.is(hb))for(let o of s.value)o.source==r.source&&(r=o);return r}handleUserEvent(e,t,i){return t=="delete"||!i.activateOnTyping?this.map(e.changes):new et(this.source,1)}handleChange(e){return e.changes.touchesRange(lr(e.startState))?new et(this.source,0):this.map(e.changes)}map(e){return e.empty||this.explicitPos<0?this:new et(this.source,this.state,e.mapPos(this.explicitPos))}}class so extends et{constructor(e,t,i,r,s){super(e,2,t),this.result=i,this.from=r,this.to=s}hasResult(){return!0}handleUserEvent(e,t,i){var r;let s=e.changes.mapPos(this.from),o=e.changes.mapPos(this.to,1),a=lr(e.state);if((this.explicitPos<0?a<=s:ao||t=="delete"&&lr(e.startState)==this.from)return new et(this.source,t=="input"&&i.activateOnTyping?1:0);let l=this.explicitPos<0?-1:e.changes.mapPos(this.explicitPos),h;return AA(this.result.validFor,e.state,s,o)?new so(this.source,l,this.result,s,o):this.result.update&&(h=this.result.update(this.result,s,o,new sb(e.state,a,l>=0)))?new so(this.source,l,h,h.from,(r=h.to)!==null&&r!==void 0?r:lr(e.state)):new et(this.source,1,l)}handleChange(e){return e.changes.touchesRange(this.from,this.to)?new et(this.source,0):this.map(e.changes)}map(e){return e.empty?this:new so(this.source,this.explicitPos<0?-1:e.mapPos(this.explicitPos),this.result,e.mapPos(this.from),e.mapPos(this.to,1))}}function AA(n,e,t,i){if(!n)return!1;let r=e.sliceDoc(t,i);return typeof n=="function"?n(r,t,i,e):ab(n,!0).test(r)}const qf=z.define(),Wl=z.define(),hb=z.define({map(n,e){return n.map(t=>t.map(e))}}),cb=z.define(),yt=Re.define({create(){return Zl.start()},update(n,e){return n.update(e)},provide:n=>[vf.from(n,e=>e.tooltip),N.contentAttributes.from(n,e=>e.attrs)]});function Qa(n,e="option"){return t=>{let i=t.state.field(yt,!1);if(!i||!i.open||i.open.disabled||Date.now()-i.open.timestamp-1?i.open.selected+r*(n?1:-1):n?0:o-1;return a<0?a=e=="page"?0:o-1:a>=o&&(a=e=="page"?o-1:0),t.dispatch({effects:cb.of(a)}),!0}}const $A=n=>{let e=n.state.field(yt,!1);return n.state.readOnly||!e||!e.open||e.open.selected<0||Date.now()-e.open.timestampn.state.field(yt,!1)?(n.dispatch({effects:qf.of(!0)}),!0):!1,IA=n=>{let e=n.state.field(yt,!1);return!e||!e.active.some(t=>t.state!=0)?!1:(n.dispatch({effects:Wl.of(null)}),!0)};class RA{constructor(e,t){this.active=e,this.context=t,this.time=Date.now(),this.updates=[],this.done=void 0}}const Ag=50,EA=50,DA=1e3,NA=ke.fromClass(class{constructor(n){this.view=n,this.debounceUpdate=-1,this.running=[],this.debounceAccept=-1,this.composing=0;for(let e of n.state.field(yt).active)e.state==1&&this.startQuery(e)}update(n){let e=n.state.field(yt);if(!n.selectionSet&&!n.docChanged&&n.startState.field(yt)==e)return;let t=n.transactions.some(i=>(i.selection||i.docChanged)&&!Nu(i));for(let i=0;iEA&&Date.now()-r.time>DA){for(let s of r.context.abortListeners)try{s()}catch(o){mt(this.view.state,o)}r.context.abortListeners=null,this.running.splice(i--,1)}else r.updates.push(...n.transactions)}if(this.debounceUpdate>-1&&clearTimeout(this.debounceUpdate),this.debounceUpdate=e.active.some(i=>i.state==1&&!this.running.some(r=>r.active.source==i.source))?setTimeout(()=>this.startUpdate(),Ag):-1,this.composing!=0)for(let i of n.transactions)Nu(i)=="input"?this.composing=2:this.composing==2&&i.selection&&(this.composing=3)}startUpdate(){this.debounceUpdate=-1;let{state:n}=this.view,e=n.field(yt);for(let t of e.active)t.state==1&&!this.running.some(i=>i.active.source==t.source)&&this.startQuery(t)}startQuery(n){let{state:e}=this.view,t=lr(e),i=new sb(e,t,n.explicitPos==t),r=new RA(n,i);this.running.push(r),Promise.resolve(n.source(i)).then(s=>{r.context.aborted||(r.done=s||null,this.scheduleAccept())},s=>{this.view.dispatch({effects:Wl.of(null)}),mt(this.view.state,s)})}scheduleAccept(){this.running.every(n=>n.done!==void 0)?this.accept():this.debounceAccept<0&&(this.debounceAccept=setTimeout(()=>this.accept(),Ag))}accept(){var n;this.debounceAccept>-1&&clearTimeout(this.debounceAccept),this.debounceAccept=-1;let e=[],t=this.view.state.facet(Vt);for(let i=0;io.source==r.active.source);if(s&&s.state==1)if(r.done==null){let o=new et(r.active.source,0);for(let a of r.updates)o=o.update(a,t);o.state!=1&&e.push(o)}else this.startQuery(s)}e.length&&this.view.dispatch({effects:hb.of(e)})}},{eventHandlers:{blur(){let n=this.view.state.field(yt,!1);n&&n.tooltip&&this.view.state.facet(Vt).closeOnBlur&&this.view.dispatch({effects:Wl.of(null)})},compositionstart(){this.composing=1},compositionend(){this.composing==3&&setTimeout(()=>this.view.dispatch({effects:qf.of(!1)}),20),this.composing=0}}}),ub=N.baseTheme({".cm-tooltip.cm-tooltip-autocomplete":{"& > ul":{fontFamily:"monospace",whiteSpace:"nowrap",overflow:"hidden auto",maxWidth_fallback:"700px",maxWidth:"min(700px, 95vw)",minWidth:"250px",maxHeight:"10em",height:"100%",listStyle:"none",margin:0,padding:0,"& > li":{overflowX:"hidden",textOverflow:"ellipsis",cursor:"pointer",padding:"1px 3px",lineHeight:1.2}}},"&light .cm-tooltip-autocomplete ul li[aria-selected]":{background:"#17c",color:"white"},"&light .cm-tooltip-autocomplete-disabled ul li[aria-selected]":{background:"#777"},"&dark .cm-tooltip-autocomplete ul li[aria-selected]":{background:"#347",color:"white"},"&dark .cm-tooltip-autocomplete-disabled ul li[aria-selected]":{background:"#444"},".cm-completionListIncompleteTop:before, .cm-completionListIncompleteBottom:after":{content:'"···"',opacity:.5,display:"block",textAlign:"center"},".cm-tooltip.cm-completionInfo":{position:"absolute",padding:"3px 9px",width:"max-content",maxWidth:"400px",boxSizing:"border-box"},".cm-completionInfo.cm-completionInfo-left":{right:"100%"},".cm-completionInfo.cm-completionInfo-right":{left:"100%"},".cm-completionInfo.cm-completionInfo-left-narrow":{right:"30px"},".cm-completionInfo.cm-completionInfo-right-narrow":{left:"30px"},"&light .cm-snippetField":{backgroundColor:"#00000022"},"&dark .cm-snippetField":{backgroundColor:"#ffffff22"},".cm-snippetFieldPosition":{verticalAlign:"text-top",width:0,height:"1.15em",display:"inline-block",margin:"0 -0.7px -.7em",borderLeft:"1.4px dotted #888"},".cm-completionMatchedText":{textDecoration:"underline"},".cm-completionDetail":{marginLeft:"0.5em",fontStyle:"italic"},".cm-completionIcon":{fontSize:"90%",width:".8em",display:"inline-block",textAlign:"center",paddingRight:".6em",opacity:"0.6",boxSizing:"content-box"},".cm-completionIcon-function, .cm-completionIcon-method":{"&:after":{content:"'ƒ'"}},".cm-completionIcon-class":{"&:after":{content:"'○'"}},".cm-completionIcon-interface":{"&:after":{content:"'◌'"}},".cm-completionIcon-variable":{"&:after":{content:"'𝑥'"}},".cm-completionIcon-constant":{"&:after":{content:"'𝐶'"}},".cm-completionIcon-type":{"&:after":{content:"'𝑡'"}},".cm-completionIcon-enum":{"&:after":{content:"'∪'"}},".cm-completionIcon-property":{"&:after":{content:"'□'"}},".cm-completionIcon-keyword":{"&:after":{content:"'🔑︎'"}},".cm-completionIcon-namespace":{"&:after":{content:"'▢'"}},".cm-completionIcon-text":{"&:after":{content:"'abc'",fontSize:"50%",verticalAlign:"middle"}}});class BA{constructor(e,t,i,r){this.field=e,this.line=t,this.from=i,this.to=r}}class Mf{constructor(e,t,i){this.field=e,this.from=t,this.to=i}map(e){let t=e.mapPos(this.from,-1,qe.TrackDel),i=e.mapPos(this.to,1,qe.TrackDel);return t==null||i==null?null:new Mf(this.field,t,i)}}class Vf{constructor(e,t){this.lines=e,this.fieldPositions=t}instantiate(e,t){let i=[],r=[t],s=e.doc.lineAt(t),o=/^\s*/.exec(s.text)[0];for(let l of this.lines){if(i.length){let h=o,c=/^\t*/.exec(l)[0].length;for(let u=0;unew Mf(l.field,r[l.line]+l.from,r[l.line]+l.to));return{text:i,ranges:a}}static parse(e){let t=[],i=[],r=[],s;for(let o of e.split(/\r\n?|\n/)){for(;s=/[#$]\{(?:(\d+)(?::([^}]*))?|([^}]*))\}/.exec(o);){let a=s[1]?+s[1]:null,l=s[2]||s[3]||"",h=-1;for(let c=0;c=h&&u.field++}r.push(new BA(h,i.length,s.index,s.index+l.length)),o=o.slice(0,s.index)+l+o.slice(s.index+s[0].length)}for(let a;a=/\\([{}])/.exec(o);){o=o.slice(0,a.index)+a[1]+o.slice(a.index+a[0].length);for(let l of r)l.line==i.length&&l.from>a.index&&(l.from--,l.to--)}i.push(o)}return new Vf(i,r)}}let qA=Z.widget({widget:new class extends Or{toDOM(){let n=document.createElement("span");return n.className="cm-snippetFieldPosition",n}ignoreEvent(){return!1}}}),MA=Z.mark({class:"cm-snippetField"});class Is{constructor(e,t){this.ranges=e,this.active=t,this.deco=Z.set(e.map(i=>(i.from==i.to?qA:MA).range(i.from,i.to)))}map(e){let t=[];for(let i of this.ranges){let r=i.map(e);if(!r)return null;t.push(r)}return new Is(t,this.active)}selectionInsideField(e){return e.ranges.every(t=>this.ranges.some(i=>i.field==this.active&&i.from<=t.from&&i.to>=t.to))}}const Yo=z.define({map(n,e){return n&&n.map(e)}}),VA=z.define(),Eo=Re.define({create(){return null},update(n,e){for(let t of e.effects){if(t.is(Yo))return t.value;if(t.is(VA)&&n)return new Is(n.ranges,t.value)}return n&&e.docChanged&&(n=n.map(e.changes)),n&&e.selection&&!n.selectionInsideField(e.selection)&&(n=null),n},provide:n=>N.decorations.from(n,e=>e?e.deco:Z.none)});function Xf(n,e){return P.create(n.filter(t=>t.field==e).map(t=>P.range(t.from,t.to)))}function XA(n){let e=Vf.parse(n);return(t,i,r,s)=>{let{text:o,ranges:a}=e.instantiate(t.state,r),l={changes:{from:r,to:s,insert:K.of(o)},scrollIntoView:!0};if(a.length&&(l.selection=Xf(a,0)),a.length>1){let h=new Is(a,0),c=l.effects=[Yo.of(h)];t.state.field(Eo,!1)===void 0&&c.push(z.appendConfig.of([Eo,jA,FA,ub]))}t.dispatch(t.state.update(l))}}function fb(n){return({state:e,dispatch:t})=>{let i=e.field(Eo,!1);if(!i||n<0&&i.active==0)return!1;let r=i.active+n,s=n>0&&!i.ranges.some(o=>o.field==r+n);return t(e.update({selection:Xf(i.ranges,r),effects:Yo.of(s?null:new Is(i.ranges,r))})),!0}}const LA=({state:n,dispatch:e})=>n.field(Eo,!1)?(e(n.update({effects:Yo.of(null)})),!0):!1,UA=fb(1),ZA=fb(-1),WA=[{key:"Tab",run:UA,shift:ZA},{key:"Escape",run:LA}],$g=B.define({combine(n){return n.length?n[0]:WA}}),jA=mr.highest(As.compute([$g],n=>n.facet($g)));function Ut(n,e){return Object.assign(Object.assign({},e),{apply:XA(n)})}const FA=N.domEventHandlers({mousedown(n,e){let t=e.state.field(Eo,!1),i;if(!t||(i=e.posAtCoords({x:n.clientX,y:n.clientY}))==null)return!1;let r=t.ranges.find(s=>s.from<=i&&s.to>=i);return!r||r.field==t.active?!1:(e.dispatch({selection:Xf(t.ranges,r.field),effects:Yo.of(t.ranges.some(s=>s.field>r.field)?new Is(t.ranges,r.field):null)}),!0)}}),Do={brackets:["(","[","{","'",'"'],before:")]}:;>",stringPrefixes:[]},Cr=z.define({map(n,e){let t=e.mapPos(n,-1,qe.TrackAfter);return t??void 0}}),Lf=z.define({map(n,e){return e.mapPos(n)}}),Uf=new class extends Br{};Uf.startSide=1;Uf.endSide=-1;const db=Re.define({create(){return J.empty},update(n,e){if(e.selection){let t=e.state.doc.lineAt(e.selection.main.head).from,i=e.startState.doc.lineAt(e.startState.selection.main.head).from;t!=e.changes.mapPos(i,-1)&&(n=J.empty)}n=n.map(e.changes);for(let t of e.effects)t.is(Cr)?n=n.update({add:[Uf.range(t.value,t.value+1)]}):t.is(Lf)&&(n=n.update({filter:i=>i!=t.value}));return n}});function zA(){return[GA,db]}const ec="()[]{}<>";function pb(n){for(let e=0;e{if((_A?n.composing:n.compositionStarted)||n.state.readOnly)return!1;let r=n.state.selection.main;if(i.length>2||i.length==2&<(Ne(i,0))==1||e!=r.from||t!=r.to)return!1;let s=HA(n.state,i);return s?(n.dispatch(s),!0):!1}),JA=({state:n,dispatch:e})=>{if(n.readOnly)return!1;let i=gb(n,n.selection.main.head).brackets||Do.brackets,r=null,s=n.changeByRange(o=>{if(o.empty){let a=KA(n.doc,o.head);for(let l of i)if(l==a&&bh(n.doc,o.head)==pb(Ne(l,0)))return{changes:{from:o.head-l.length,to:o.head+l.length},range:P.cursor(o.head-l.length)}}return{range:r=o}});return r||e(n.update(s,{scrollIntoView:!0,userEvent:"delete.backward"})),!r},YA=[{key:"Backspace",run:JA}];function HA(n,e){let t=gb(n,n.selection.main.head),i=t.brackets||Do.brackets;for(let r of i){let s=pb(Ne(r,0));if(e==r)return s==r?i$(n,r,i.indexOf(r+r+r)>-1,t):e$(n,r,s,t.before||Do.before);if(e==s&&mb(n,n.selection.main.from))return t$(n,r,s)}return null}function mb(n,e){let t=!1;return n.field(db).between(0,n.doc.length,i=>{i==e&&(t=!0)}),t}function bh(n,e){let t=n.sliceString(e,e+2);return t.slice(0,lt(Ne(t,0)))}function KA(n,e){let t=n.sliceString(e-2,e);return lt(Ne(t,0))==t.length?t:t.slice(1)}function e$(n,e,t,i){let r=null,s=n.changeByRange(o=>{if(!o.empty)return{changes:[{insert:e,from:o.from},{insert:t,from:o.to}],effects:Cr.of(o.to+e.length),range:P.range(o.anchor+e.length,o.head+e.length)};let a=bh(n.doc,o.head);return!a||/\s/.test(a)||i.indexOf(a)>-1?{changes:{insert:e+t,from:o.head},effects:Cr.of(o.head+e.length),range:P.cursor(o.head+e.length)}:{range:r=o}});return r?null:n.update(s,{scrollIntoView:!0,userEvent:"input.type"})}function t$(n,e,t){let i=null,r=n.selection.ranges.map(s=>s.empty&&bh(n.doc,s.head)==t?P.cursor(s.head+t.length):i=s);return i?null:n.update({selection:P.create(r,n.selection.mainIndex),scrollIntoView:!0,effects:n.selection.ranges.map(({from:s})=>Lf.of(s))})}function i$(n,e,t,i){let r=i.stringPrefixes||Do.stringPrefixes,s=null,o=n.changeByRange(a=>{if(!a.empty)return{changes:[{insert:e,from:a.from},{insert:e,from:a.to}],effects:Cr.of(a.to+e.length),range:P.range(a.anchor+e.length,a.head+e.length)};let l=a.head,h=bh(n.doc,l),c;if(h==e){if(Cg(n,l))return{changes:{insert:e+e,from:l},effects:Cr.of(l+e.length),range:P.cursor(l+e.length)};if(mb(n,l)){let u=t&&n.sliceDoc(l,l+e.length*3)==e+e+e;return{range:P.cursor(l+e.length*(u?3:1)),effects:Lf.of(l)}}}else{if(t&&n.sliceDoc(l-2*e.length,l)==e+e&&(c=Ig(n,l-2*e.length,r))>-1&&Cg(n,c))return{changes:{insert:e+e+e+e,from:l},effects:Cr.of(l+e.length),range:P.cursor(l+e.length)};if(n.charCategorizer(l)(h)!=fe.Word&&Ig(n,l,r)>-1&&!n$(n,l,e,r))return{changes:{insert:e+e,from:l},effects:Cr.of(l+e.length),range:P.cursor(l+e.length)}}return{range:s=a}});return s?null:n.update(o,{scrollIntoView:!0,userEvent:"input.type"})}function Cg(n,e){let t=de(n).resolveInner(e+1);return t.parent&&t.from==e}function n$(n,e,t,i){let r=de(n).resolveInner(e,-1),s=i.reduce((o,a)=>Math.max(o,a.length),0);for(let o=0;o<5;o++){let a=n.sliceDoc(r.from,Math.min(r.to,r.from+t.length+s)),l=a.indexOf(t);if(!l||l>-1&&i.indexOf(a.slice(0,l))>-1){let c=r.firstChild;for(;c&&c.from==r.from&&c.to-c.from>t.length+l;){if(n.sliceDoc(c.to-t.length,c.to)==t)return!1;c=c.firstChild}return!0}let h=r.to==e&&r.parent;if(!h)break;r=h}return!1}function Ig(n,e,t){let i=n.charCategorizer(e);if(i(n.sliceDoc(e-1,e))!=fe.Word)return e;for(let r of t){let s=e-r.length;if(n.sliceDoc(s,e)==r&&i(n.sliceDoc(s-1,s))!=fe.Word)return s}return-1}function r$(n={}){return[yt,Vt.of(n),NA,s$,ub]}const Ob=[{key:"Ctrl-Space",run:CA},{key:"Escape",run:IA},{key:"ArrowDown",run:Qa(!0)},{key:"ArrowUp",run:Qa(!1)},{key:"PageDown",run:Qa(!0,"page")},{key:"PageUp",run:Qa(!1,"page")},{key:"Enter",run:$A}],s$=mr.highest(As.computeN([Vt],n=>n.facet(Vt).defaultKeymap?[Ob]:[]));class o${constructor(e,t,i){this.from=e,this.to=t,this.diagnostic=i}}class Qr{constructor(e,t,i){this.diagnostics=e,this.panel=t,this.selected=i}static init(e,t,i){let r=e,s=i.facet(Kr).markerFilter;s&&(r=s(r));let o=Z.set(r.map(a=>a.from==a.to||a.from==a.to-1&&i.doc.lineAt(a.from).to==a.from?Z.widget({widget:new m$(a),diagnostic:a}).range(a.from):Z.mark({attributes:{class:"cm-lintRange cm-lintRange-"+a.severity},diagnostic:a}).range(a.from,a.to)),!0);return new Qr(o,t,xs(o))}}function xs(n,e=null,t=0){let i=null;return n.between(t,1e9,(r,s,{spec:o})=>{if(!(e&&o.diagnostic!=e))return i=new o$(r,s,o.diagnostic),!1}),i}function a$(n,e){return!!(n.effects.some(t=>t.is(Zf))||n.changes.touchesRange(e.pos))}function yb(n,e){return n.field(ft,!1)?e:e.concat(z.appendConfig.of([ft,N.decorations.compute([ft],t=>{let{selected:i,panel:r}=t.field(ft);return!i||!r||i.from==i.to?Z.none:Z.set([h$.range(i.from,i.to)])}),nT(c$,{hideOn:a$}),y$]))}function l$(n,e){return{effects:yb(n,[Zf.of(e)])}}const Zf=z.define(),Wf=z.define(),bb=z.define(),ft=Re.define({create(){return new Qr(Z.none,null,null)},update(n,e){if(e.docChanged){let t=n.diagnostics.map(e.changes),i=null;if(n.selected){let r=e.changes.mapPos(n.selected.from,1);i=xs(t,n.selected.diagnostic,r)||xs(t,null,r)}n=new Qr(t,n.panel,i)}for(let t of e.effects)t.is(Zf)?n=Qr.init(t.value,n.panel,e.state):t.is(Wf)?n=new Qr(n.diagnostics,t.value?Sh.open:null,n.selected):t.is(bb)&&(n=new Qr(n.diagnostics,n.panel,t.value));return n},provide:n=>[Po.from(n,e=>e.panel),N.decorations.from(n,e=>e.diagnostics)]}),h$=Z.mark({class:"cm-lintRange cm-lintRange-active"});function c$(n,e,t){let{diagnostics:i}=n.state.field(ft),r=[],s=2e8,o=0;i.between(e-(t<0?1:0),e+(t>0?1:0),(l,h,{spec:c})=>{e>=l&&e<=h&&(l==h||(e>l||t>0)&&(ewb(n,t,!1)))}const f$=n=>{let e=n.state.field(ft,!1);(!e||!e.panel)&&n.dispatch({effects:yb(n.state,[Wf.of(!0)])});let t=Qo(n,Sh.open);return t&&t.dom.querySelector(".cm-panel-lint ul").focus(),!0},Rg=n=>{let e=n.state.field(ft,!1);return!e||!e.panel?!1:(n.dispatch({effects:Wf.of(!1)}),!0)},d$=n=>{let e=n.state.field(ft,!1);if(!e)return!1;let t=n.state.selection.main,i=e.diagnostics.iter(t.to+1);return!i.value&&(i=e.diagnostics.iter(0),!i.value||i.from==t.from&&i.to==t.to)?!1:(n.dispatch({selection:{anchor:i.from,head:i.to},scrollIntoView:!0}),!0)},p$=[{key:"Mod-Shift-m",run:f$,preventDefault:!0},{key:"F8",run:d$}],g$=ke.fromClass(class{constructor(n){this.view=n,this.timeout=-1,this.set=!0;let{delay:e}=n.state.facet(Kr);this.lintTime=Date.now()+e,this.run=this.run.bind(this),this.timeout=setTimeout(this.run,e)}run(){let n=Date.now();if(nPromise.resolve(i(this.view)))).then(i=>{let r=i.reduce((s,o)=>s.concat(o));this.view.state.doc==e.doc&&this.view.dispatch(l$(this.view.state,r))},i=>{mt(this.view.state,i)})}}update(n){let e=n.state.facet(Kr);(n.docChanged||e!=n.startState.facet(Kr))&&(this.lintTime=Date.now()+e.delay,this.set||(this.set=!0,this.timeout=setTimeout(this.run,e.delay)))}force(){this.set&&(this.lintTime=Date.now(),this.run())}destroy(){clearTimeout(this.timeout)}}),Kr=B.define({combine(n){return Object.assign({sources:n.map(e=>e.source)},Ai(n.map(e=>e.config),{delay:750,markerFilter:null,tooltipFilter:null}))},enables:g$});function Sb(n){let e=[];if(n)e:for(let{name:t}of n){for(let i=0;is.toLowerCase()==r.toLowerCase())){e.push(r);continue e}}e.push("")}return e}function wb(n,e,t){var i;let r=t?Sb(e.actions):[];return ae("li",{class:"cm-diagnostic cm-diagnostic-"+e.severity},ae("span",{class:"cm-diagnosticText"},e.renderMessage?e.renderMessage():e.message),(i=e.actions)===null||i===void 0?void 0:i.map((s,o)=>{let a=u=>{u.preventDefault();let f=xs(n.state.field(ft).diagnostics,e);f&&s.apply(n,f.from,f.to)},{name:l}=s,h=r[o]?l.indexOf(r[o]):-1,c=h<0?l:[l.slice(0,h),ae("u",l.slice(h,h+1)),l.slice(h+1)];return ae("button",{type:"button",class:"cm-diagnosticAction",onclick:a,onmousedown:a,"aria-label":` Action: ${l}${h<0?"":` (access key "${r[o]})"`}.`},c)}),e.source&&ae("div",{class:"cm-diagnosticSource"},e.source))}class m$ extends Or{constructor(e){super(),this.diagnostic=e}eq(e){return e.diagnostic==this.diagnostic}toDOM(){return ae("span",{class:"cm-lintPoint cm-lintPoint-"+this.diagnostic.severity})}}class Eg{constructor(e,t){this.diagnostic=t,this.id="item_"+Math.floor(Math.random()*4294967295).toString(16),this.dom=wb(e,t,!0),this.dom.id=this.id,this.dom.setAttribute("role","option")}}class Sh{constructor(e){this.view=e,this.items=[];let t=r=>{if(r.keyCode==27)Rg(this.view),this.view.focus();else if(r.keyCode==38||r.keyCode==33)this.moveSelection((this.selectedIndex-1+this.items.length)%this.items.length);else if(r.keyCode==40||r.keyCode==34)this.moveSelection((this.selectedIndex+1)%this.items.length);else if(r.keyCode==36)this.moveSelection(0);else if(r.keyCode==35)this.moveSelection(this.items.length-1);else if(r.keyCode==13)this.view.focus();else if(r.keyCode>=65&&r.keyCode<=90&&this.selectedIndex>=0){let{diagnostic:s}=this.items[this.selectedIndex],o=Sb(s.actions);for(let a=0;a{for(let s=0;sRg(this.view)},"×")),this.update()}get selectedIndex(){let e=this.view.state.field(ft).selected;if(!e)return-1;for(let t=0;t{let h=-1,c;for(let u=i;ui&&(this.items.splice(i,h-i),r=!0)),t&&c.diagnostic==t.diagnostic?c.dom.hasAttribute("aria-selected")||(c.dom.setAttribute("aria-selected","true"),s=c):c.dom.hasAttribute("aria-selected")&&c.dom.removeAttribute("aria-selected"),i++});i({sel:s.dom.getBoundingClientRect(),panel:this.list.getBoundingClientRect()}),write:({sel:o,panel:a})=>{o.topa.bottom&&(this.list.scrollTop+=o.bottom-a.bottom)}})):this.selectedIndex<0&&this.list.removeAttribute("aria-activedescendant"),r&&this.sync()}sync(){let e=this.list.firstChild;function t(){let i=e;e=i.nextSibling,i.remove()}for(let i of this.items)if(i.dom.parentNode==this.list){for(;e!=i.dom;)t();e=i.dom.nextSibling}else this.list.insertBefore(i.dom,e);for(;e;)t()}moveSelection(e){if(this.selectedIndex<0)return;let t=this.view.state.field(ft),i=xs(t.diagnostics,this.items[e].diagnostic);i&&this.view.dispatch({selection:{anchor:i.from,head:i.to},scrollIntoView:!0,effects:bb.of(i)})}static open(e){return new Sh(e)}}function O$(n,e='viewBox="0 0 40 40"'){return`url('data:image/svg+xml,${encodeURIComponent(n)}')`}function tc(n){return O$(``,'width="6" height="3"')}const y$=N.baseTheme({".cm-diagnostic":{padding:"3px 6px 3px 8px",marginLeft:"-1px",display:"block",whiteSpace:"pre-wrap"},".cm-diagnostic-error":{borderLeft:"5px solid #d11"},".cm-diagnostic-warning":{borderLeft:"5px solid orange"},".cm-diagnostic-info":{borderLeft:"5px solid #999"},".cm-diagnosticAction":{font:"inherit",border:"none",padding:"2px 4px",backgroundColor:"#444",color:"white",borderRadius:"3px",marginLeft:"8px"},".cm-diagnosticSource":{fontSize:"70%",opacity:.7},".cm-lintRange":{backgroundPosition:"left bottom",backgroundRepeat:"repeat-x",paddingBottom:"0.7px"},".cm-lintRange-error":{backgroundImage:tc("#d11")},".cm-lintRange-warning":{backgroundImage:tc("orange")},".cm-lintRange-info":{backgroundImage:tc("#999")},".cm-lintRange-active":{backgroundColor:"#ffdd9980"},".cm-tooltip-lint":{padding:0,margin:0},".cm-lintPoint":{position:"relative","&:after":{content:'""',position:"absolute",bottom:0,left:"-2px",borderLeft:"3px solid transparent",borderRight:"3px solid transparent",borderBottom:"4px solid #d11"}},".cm-lintPoint-warning":{"&:after":{borderBottomColor:"orange"}},".cm-lintPoint-info":{"&:after":{borderBottomColor:"#999"}},".cm-panel.cm-panel-lint":{position:"relative","& ul":{maxHeight:"100px",overflowY:"auto","& [aria-selected]":{backgroundColor:"#ddd","& u":{textDecoration:"underline"}},"&:focus [aria-selected]":{background_fallback:"#bdf",backgroundColor:"Highlight",color_fallback:"white",color:"HighlightText"},"& u":{textDecoration:"none"},padding:0,margin:0},"& [name=close]":{position:"absolute",top:"0",right:"2px",background:"inherit",border:"none",font:"inherit",padding:0,margin:0}}}),b$=[dT(),mT(),Dx(),MQ(),cQ(),kx(),Ax(),H.allowMultipleSelections.of(!0),YT(),fQ(gQ,{fallback:!0}),vQ(),zA(),r$(),Fx(),Gx(),Xx(),WP(),As.of([...YA,...MP,...hA,...zQ,...oQ,...Ob,...p$])];class jl{constructor(e,t,i,r,s,o,a){this.type=e,this.value=t,this.from=i,this.hash=r,this.end=s,this.children=o,this.positions=a,this.hashProp=[[_.contextHash,r]]}static create(e,t,i,r,s){let o=r+(r<<8)+e+(t<<4)|0;return new jl(e,t,i,o,s,[],[])}addChild(e,t){e.prop(_.contextHash)!=this.hash&&(e=new ne(e.type,e.children,e.positions,e.length,this.hashProp)),this.children.push(e),this.positions.push(t)}toTree(e,t=this.end){let i=this.children.length-1;return i>=0&&(t=Math.max(t,this.positions[i]+this.children[i].length+this.from)),new ne(e.types[this.type],this.children,this.positions,t-this.from).balance({makeTree:(s,o,a)=>new ne(Ie.none,s,o,a,this.hashProp)})}}var I;(function(n){n[n.Document=1]="Document",n[n.CodeBlock=2]="CodeBlock",n[n.FencedCode=3]="FencedCode",n[n.Blockquote=4]="Blockquote",n[n.HorizontalRule=5]="HorizontalRule",n[n.BulletList=6]="BulletList",n[n.OrderedList=7]="OrderedList",n[n.ListItem=8]="ListItem",n[n.ATXHeading1=9]="ATXHeading1",n[n.ATXHeading2=10]="ATXHeading2",n[n.ATXHeading3=11]="ATXHeading3",n[n.ATXHeading4=12]="ATXHeading4",n[n.ATXHeading5=13]="ATXHeading5",n[n.ATXHeading6=14]="ATXHeading6",n[n.SetextHeading1=15]="SetextHeading1",n[n.SetextHeading2=16]="SetextHeading2",n[n.HTMLBlock=17]="HTMLBlock",n[n.LinkReference=18]="LinkReference",n[n.Paragraph=19]="Paragraph",n[n.CommentBlock=20]="CommentBlock",n[n.ProcessingInstructionBlock=21]="ProcessingInstructionBlock",n[n.Escape=22]="Escape",n[n.Entity=23]="Entity",n[n.HardBreak=24]="HardBreak",n[n.Emphasis=25]="Emphasis",n[n.StrongEmphasis=26]="StrongEmphasis",n[n.Link=27]="Link",n[n.Image=28]="Image",n[n.InlineCode=29]="InlineCode",n[n.HTMLTag=30]="HTMLTag",n[n.Comment=31]="Comment",n[n.ProcessingInstruction=32]="ProcessingInstruction",n[n.URL=33]="URL",n[n.HeaderMark=34]="HeaderMark",n[n.QuoteMark=35]="QuoteMark",n[n.ListMark=36]="ListMark",n[n.LinkMark=37]="LinkMark",n[n.EmphasisMark=38]="EmphasisMark",n[n.CodeMark=39]="CodeMark",n[n.CodeText=40]="CodeText",n[n.CodeInfo=41]="CodeInfo",n[n.LinkTitle=42]="LinkTitle",n[n.LinkLabel=43]="LinkLabel"})(I||(I={}));class S${constructor(e,t){this.start=e,this.content=t,this.marks=[],this.parsers=[]}}class w${constructor(){this.text="",this.baseIndent=0,this.basePos=0,this.depth=0,this.markers=[],this.pos=0,this.indent=0,this.next=-1}forward(){this.basePos>this.pos&&this.forwardInner()}forwardInner(){let e=this.skipSpace(this.basePos);this.indent=this.countIndent(e,this.pos,this.indent),this.pos=e,this.next=e==this.text.length?-1:this.text.charCodeAt(e)}skipSpace(e){return oo(this.text,e)}reset(e){for(this.text=e,this.baseIndent=this.basePos=this.pos=this.indent=0,this.forwardInner(),this.depth=1;this.markers.length;)this.markers.pop()}moveBase(e){this.basePos=e,this.baseIndent=this.countIndent(e,this.pos,this.indent)}moveBaseColumn(e){this.baseIndent=e,this.basePos=this.findColumn(e)}addMarker(e){this.markers.push(e)}countIndent(e,t=0,i=0){for(let r=t;r=e.stack[t.depth+1].value+t.baseIndent)return!0;if(t.indent>=t.baseIndent+4)return!1;let i=(n.type==I.OrderedList?zf:Ff)(t,e,!1);return i>0&&(n.type!=I.BulletList||jf(t,e,!1)<0)&&t.text.charCodeAt(t.pos+i-1)==n.value}const vb={[I.Blockquote](n,e,t){return t.next!=62?!1:(t.markers.push(te(I.QuoteMark,e.lineStart+t.pos,e.lineStart+t.pos+1)),t.moveBase(t.pos+(Lt(t.text.charCodeAt(t.pos+1))?2:1)),n.end=e.lineStart+t.text.length,!0)},[I.ListItem](n,e,t){return t.indent-1?!1:(t.moveBaseColumn(t.baseIndent+n.value),!0)},[I.OrderedList]:Dg,[I.BulletList]:Dg,[I.Document](){return!0}};function Lt(n){return n==32||n==9||n==10||n==13}function oo(n,e=0){for(;et&&Lt(n.charCodeAt(e-1));)e--;return e}function kb(n){if(n.next!=96&&n.next!=126)return-1;let e=n.pos+1;for(;e-1&&n.depth==e.stack.length||i<3?-1:1}function Tb(n,e){for(let t=n.stack.length-1;t>=0;t--)if(n.stack[t].type==e)return!0;return!1}function Ff(n,e,t){return(n.next==45||n.next==43||n.next==42)&&(n.pos==n.text.length-1||Lt(n.text.charCodeAt(n.pos+1)))&&(!t||Tb(e,I.BulletList)||n.skipSpace(n.pos+2)=48&&r<=57;){i++;if(i==n.text.length)return-1;r=n.text.charCodeAt(i)}return i==n.pos||i>n.pos+9||r!=46&&r!=41||in.pos+1||n.next!=49)?-1:i+1-n.pos}function Qb(n){if(n.next!=35)return-1;let e=n.pos+1;for(;e6?-1:t}function Pb(n){if(n.next!=45&&n.next!=61||n.indent>=n.baseIndent+4)return-1;let e=n.pos+1;for(;e/,$b=/\?>/,qu=[[/^<(?:script|pre|style)(?:\s|>|$)/i,/<\/(?:script|pre|style)>/i],[/^\s*/,$b=/\?>/,qu=[[/^<(?:script|pre|style)(?:\s|>|$)/i,/<\/(?:script|pre|style)>/i],[/^\s*/i.exec(i);if(s)return n.append(te(I.Comment,t,t+1+s[0].length));let o=/^\?[^]*?\?>/.exec(i);if(o)return n.append(te(I.ProcessingInstruction,t,t+1+o[0].length));let a=/^(?:![A-Z][^]*?>|!\[CDATA\[[^]*?\]\]>|\/\s*[a-zA-Z][\w-]*\s*>|\s*[a-zA-Z][\w-]*(\s+[a-zA-Z:_][\w-.:]*(?:\s*=\s*(?:[^\s"'=<>`]+|'[^']*'|"[^"]*"))?)*\s*(\/\s*)?>)/.exec(i);return a?n.append(te(I.HTMLTag,t,t+1+a[0].length)):-1},Emphasis(n,e,t){if(e!=95&&e!=42)return-1;let i=t+1;for(;n.char(i)==e;)i++;let r=n.slice(t-1,t),s=n.slice(i,i+1),o=Bo.test(r),a=Bo.test(s),l=/\s|^$/.test(r),h=/\s|^$/.test(s),c=!h&&(!a||l||o),u=!l&&(!o||h||a),f=c&&(e==42||!u||o),p=u&&(e==42||!c||a);return n.append(new Ft(e==95?Nb:Bb,t,i,(f?1:0)|(p?2:0)))},HardBreak(n,e,t){if(e==92&&n.char(t+1)==10)return n.append(te(I.HardBreak,t,t+2));if(e==32){let i=t+1;for(;n.char(i)==32;)i++;if(n.char(i)==10&&i>=t+2)return n.append(te(I.HardBreak,t,i+1))}return-1},Link(n,e,t){return e==91?n.append(new Ft(Ls,t,t+1,1)):-1},Image(n,e,t){return e==33&&n.char(t+1)==91?n.append(new Ft(qg,t,t+2,1)):-1},LinkEnd(n,e,t){if(e!=93)return-1;for(let i=n.parts.length-1;i>=0;i--){let r=n.parts[i];if(r instanceof Ft&&(r.type==Ls||r.type==qg)){if(!r.side||n.skipSpace(r.to)==t&&!/[(\[]/.test(n.slice(t+1,t+2)))return n.parts[i]=null,-1;let s=n.takeContent(i),o=n.parts[i]=A$(n,s,r.type==Ls?I.Link:I.Image,r.from,t+1);if(r.type==Ls)for(let a=0;ae?te(I.URL,e+t,s+t):s==n.length?null:!1}}function Mb(n,e,t){let i=n.charCodeAt(e);if(i!=39&&i!=34&&i!=40)return!1;let r=i==40?41:i;for(let s=e+1,o=!1;s=this.end?-1:this.text.charCodeAt(e-this.offset)}get end(){return this.offset+this.text.length}slice(e,t){return this.text.slice(e-this.offset,t-this.offset)}append(e){return this.parts.push(e),e.to}addDelimiter(e,t,i,r,s){return this.append(new Ft(e,t,i,(r?1:0)|(s?2:0)))}addElement(e){return this.append(e)}resolveMarkers(e){for(let i=e;i=e;l--){let y=this.parts[l];if(y instanceof Ft&&y.side&1&&y.type==r.type&&!(s&&(r.side&1||y.side&2)&&(y.to-y.from+o)%3==0&&((y.to-y.from)%3||o%3))){a=y;break}}if(!a)continue;let h=r.type.resolve,c=[],u=a.from,f=r.to;if(s){let y=Math.min(2,a.to-a.from,o);u=a.to-y,f=r.from+y,h=y==1?"Emphasis":"StrongEmphasis"}a.type.mark&&c.push(this.elt(a.type.mark,u,a.to));for(let y=l+1;y=0;t--){let i=this.parts[t];if(i instanceof Ft&&i.type==e)return t}return null}takeContent(e){let t=this.resolveMarkers(e);return this.parts.length=e,t}skipSpace(e){return oo(this.text,e-this.offset)+this.offset}elt(e,t,i,r){return typeof e=="string"?te(this.parser.getNodeType(e),t,i,r):new Db(e,t)}}function Vu(n,e){if(!e.length)return n;if(!n.length)return e;let t=n.slice(),i=0;for(let r of e){for(;i(e?e-1:0))return!1;if(this.fragmentEnd<0){let s=this.fragment.to;for(;s>0&&this.input.read(s-1,s)!=` -`;)s--;this.fragmentEnd=s?s-1:0}let i=this.cursor;i||(i=this.cursor=this.fragment.tree.cursor(),i.firstChild());let r=e+this.fragment.offset;for(;i.to<=r;)if(!i.parent())return!1;for(;;){if(i.from>=r)return this.fragment.from<=t;if(!i.childAfter(r))return!1}}matches(e){let t=this.cursor.tree;return t&&t.prop(_.contextHash)==e}takeNodes(e){let t=this.cursor,i=this.fragment.offset,r=this.fragmentEnd-(this.fragment.openEnd?1:0),s=e.absoluteLineStart,o=s,a=e.block.children.length,l=o,h=a;for(;;){if(t.to-i>r){if(t.type.isAnonymous&&t.firstChild())continue;break}if(e.dontInject.add(t.tree),e.addNode(t.tree,t.from-i),t.type.is("Block")&&(C$.indexOf(t.type.id)<0?(o=t.to-i,a=e.block.children.length):(o=l,a=h,l=t.to-i,h=e.block.children.length)),!t.nextSibling())break}for(;e.block.children.length>a;)e.block.children.pop(),e.block.positions.pop();return o-s}};const R$=$s({"Blockquote/...":b.quote,HorizontalRule:b.contentSeparator,"ATXHeading1/... SetextHeading1/...":b.heading1,"ATXHeading2/... SetextHeading2/...":b.heading2,"ATXHeading3/...":b.heading3,"ATXHeading4/...":b.heading4,"ATXHeading5/...":b.heading5,"ATXHeading6/...":b.heading6,"Comment CommentBlock":b.comment,Escape:b.escape,Entity:b.character,"Emphasis/...":b.emphasis,"StrongEmphasis/...":b.strong,"Link/... Image/...":b.link,"OrderedList/... BulletList/...":b.list,"BlockQuote/...":b.quote,"InlineCode CodeText":b.monospace,URL:b.url,"HeaderMark HardBreak QuoteMark ListMark LinkMark EmphasisMark CodeMark":b.processingInstruction,"CodeInfo LinkLabel":b.labelName,LinkTitle:b.string,Paragraph:b.content}),E$=new wh(new Fo(Rb).extend(R$),Object.keys(Pa).map(n=>Pa[n]),Object.keys(Pa).map(n=>x$[n]),Object.keys(Pa),T$,vb,Object.keys(nc).map(n=>nc[n]),Object.keys(nc),[]);function D$(n,e,t){let i=[];for(let r=n.firstChild,s=e;;r=r.nextSibling){let o=r?r.from:t;if(o>s&&i.push({from:s,to:o}),!r)break;s=r.to}return i}function N$(n){let{codeParser:e,htmlParser:t}=n;return{wrap:ny((r,s)=>{let o=r.type.id;if(e&&(o==I.CodeBlock||o==I.FencedCode)){let a="";if(o==I.FencedCode){let h=r.node.getChild(I.CodeInfo);h&&(a=s.read(h.from,h.to))}let l=e(a);if(l)return{parser:l,overlay:h=>h.type.id==I.CodeText}}else if(t&&(o==I.HTMLBlock||o==I.HTMLTag))return{parser:t,overlay:D$(r.node,r.from,r.to)};return null})}}const B$={resolve:"Strikethrough",mark:"StrikethroughMark"},q$={defineNodes:[{name:"Strikethrough",style:{"Strikethrough/...":b.strikethrough}},{name:"StrikethroughMark",style:b.processingInstruction}],parseInline:[{name:"Strikethrough",parse(n,e,t){if(e!=126||n.char(t+1)!=126||n.char(t+2)==126)return-1;let i=n.slice(t-1,t),r=n.slice(t+2,t+3),s=/\s|^$/.test(i),o=/\s|^$/.test(r),a=Bo.test(i),l=Bo.test(r);return n.addDelimiter(B$,t,t+2,!o&&(!l||s||a),!s&&(!a||o||l))},after:"Emphasis"}]};function ao(n,e,t=0,i,r=0){let s=0,o=!0,a=-1,l=-1,h=!1,c=()=>{i.push(n.elt("TableCell",r+a,r+l,n.parser.parseInline(e.slice(a,l),r+a)))};for(let u=t;u-1)&&s++,o=!1,i&&(a>-1&&c(),i.push(n.elt("TableDelimiter",u+r,u+r+1))),a=l=-1):(h||f!=32&&f!=9)&&(a<0&&(a=u),l=u+1),h=!h&&f==92}return a>-1&&(s++,i&&c()),s}function Vg(n,e){for(let t=e;tr instanceof Xg)||!Vg(e.text,e.basePos))return!1;let i=n.scanLine(n.absoluteLineEnd+1).text;return Xb.test(i)&&ao(n,e.text,e.basePos)==ao(n,i,e.basePos)},before:"SetextHeading"}]};class V${nextLine(){return!1}finish(e,t){return e.addLeafElement(t,e.elt("Task",t.start,t.start+t.content.length,[e.elt("TaskMarker",t.start,t.start+3),...e.parser.parseInline(t.content.slice(3),t.start+3)])),!0}}const X$={defineNodes:[{name:"Task",block:!0,style:b.list},{name:"TaskMarker",style:b.atom}],parseBlock:[{name:"TaskList",leaf(n,e){return/^\[[ xX]\]/.test(e.content)&&n.parentType().name=="ListItem"?new V$:null},after:"SetextHeading"}]},L$=[M$,X$,q$];function Lb(n,e,t){return(i,r,s)=>{if(r!=n||i.char(s+1)==n)return-1;let o=[i.elt(t,s,s+1)];for(let a=s+1;at%3==0).concat(this.state)}]@${this.pos}${this.score?"!"+this.score:""}`}static start(e,t,i=0){let r=e.parser.context;return new Fl(e,[],t,i,i,0,[],0,r?new Ug(r,r.start):null,0,null)}get context(){return this.curContext?this.curContext.context:null}pushState(e,t){this.stack.push(this.state,t,this.bufferBase+this.buffer.length),this.state=e}reduce(e){let t=e>>19,i=e&65535,{parser:r}=this.p,s=r.dynamicPrecedence(i);if(s&&(this.score+=s),t==0){this.pushState(r.getGoto(this.state,i,!0),this.reducePos),io;)this.stack.pop();this.reduceContext(i,a)}storeNode(e,t,i,r=4,s=!1){if(e==0&&(!this.stack.length||this.stack[this.stack.length-1]0&&o.buffer[a-4]==0&&o.buffer[a-1]>-1){if(t==i)return;if(o.buffer[a-2]>=t){o.buffer[a-2]=i;return}}}if(!s||this.pos==i)this.buffer.push(e,t,i,r);else{let o=this.buffer.length;if(o>0&&this.buffer[o-4]!=0)for(;o>0&&this.buffer[o-2]>i;)this.buffer[o]=this.buffer[o-4],this.buffer[o+1]=this.buffer[o-3],this.buffer[o+2]=this.buffer[o-2],this.buffer[o+3]=this.buffer[o-1],o-=4,r>4&&(r-=4);this.buffer[o]=e,this.buffer[o+1]=t,this.buffer[o+2]=i,this.buffer[o+3]=r}}shift(e,t,i){let r=this.pos;if(e&131072)this.pushState(e&65535,this.pos);else if(e&262144)this.pos=i,this.shiftContext(t,r),t<=this.p.parser.maxNode&&this.buffer.push(t,r,i,4);else{let s=e,{parser:o}=this.p;(i>this.pos||t<=o.maxNode)&&(this.pos=i,o.stateFlag(s,1)||(this.reducePos=i)),this.pushState(s,r),this.shiftContext(t,r),t<=o.maxNode&&this.buffer.push(t,r,i,4)}}apply(e,t,i){e&65536?this.reduce(e):this.shift(e,t,i)}useNode(e,t){let i=this.p.reused.length-1;(i<0||this.p.reused[i]!=e)&&(this.p.reused.push(e),i++);let r=this.pos;this.reducePos=this.pos=r+e.length,this.pushState(t,r),this.buffer.push(i,r,this.reducePos,-1),this.curContext&&this.updateContext(this.curContext.tracker.reuse(this.curContext.context,e,this,this.p.stream.reset(this.pos-e.length)))}split(){let e=this,t=e.buffer.length;for(;t>0&&e.buffer[t-2]>e.reducePos;)t-=4;let i=e.buffer.slice(t),r=e.bufferBase+t;for(;e&&r==e.bufferBase;)e=e.parent;return new Fl(this.p,this.stack.slice(),this.state,this.reducePos,this.pos,this.score,i,r,this.curContext,this.lookAhead,e)}recoverByDelete(e,t){let i=e<=this.p.parser.maxNode;i&&this.storeNode(e,this.pos,t,4),this.storeNode(0,this.pos,t,i?8:4),this.pos=this.reducePos=t,this.score-=190}canShift(e){for(let t=new j$(this);;){let i=this.p.parser.stateSlot(t.state,4)||this.p.parser.hasAction(t.state,e);if(i==0)return!1;if(!(i&65536))return!0;t.reduce(i)}}recoverByInsert(e){if(this.stack.length>=300)return[];let t=this.p.parser.nextStates(this.state);if(t.length>8||this.stack.length>=120){let r=[];for(let s=0,o;sl&1&&a==o)||r.push(t[s],o)}t=r}let i=[];for(let r=0;r>19,r=e&65535,s=this.stack.length-i*3;if(s<0||t.getGoto(this.stack[s],r,!1)<0)return!1;this.storeNode(0,this.reducePos,this.reducePos,4,!0),this.score-=100}return this.reducePos=this.pos,this.reduce(e),!0}forceAll(){for(;!this.p.parser.stateFlag(this.state,2);)if(!this.forceReduce()){this.storeNode(0,this.pos,this.pos,4,!0);break}return this}get deadEnd(){if(this.stack.length!=3)return!1;let{parser:e}=this.p;return e.data[e.stateSlot(this.state,1)]==65535&&!e.stateSlot(this.state,4)}restart(){this.state=this.stack[0],this.stack.length=0}sameState(e){if(this.state!=e.state||this.stack.length!=e.stack.length)return!1;for(let t=0;tthis.lookAhead&&(this.emitLookAhead(),this.lookAhead=e)}close(){this.curContext&&this.curContext.tracker.strict&&this.emitContext(),this.lookAhead>0&&this.emitLookAhead()}}class Ug{constructor(e,t){this.tracker=e,this.context=t,this.hash=e.strict?e.hash(t):0}}var Zg;(function(n){n[n.Insert=200]="Insert",n[n.Delete=190]="Delete",n[n.Reduce=100]="Reduce",n[n.MaxNext=4]="MaxNext",n[n.MaxInsertStackDepth=300]="MaxInsertStackDepth",n[n.DampenInsertStackDepth=120]="DampenInsertStackDepth"})(Zg||(Zg={}));class j${constructor(e){this.start=e,this.state=e.state,this.stack=e.stack,this.base=this.stack.length}reduce(e){let t=e&65535,i=e>>19;i==0?(this.stack==this.start.stack&&(this.stack=this.stack.slice()),this.stack.push(this.state,0,0),this.base+=3):this.base-=(i-1)*3;let r=this.start.p.parser.getGoto(this.stack[this.base-3],t,!0);this.state=r}}class zl{constructor(e,t,i){this.stack=e,this.pos=t,this.index=i,this.buffer=e.buffer,this.index==0&&this.maybeNext()}static create(e,t=e.bufferBase+e.buffer.length){return new zl(e,t,t-e.bufferBase)}maybeNext(){let e=this.stack.parent;e!=null&&(this.index=this.stack.bufferBase-e.bufferBase,this.stack=e,this.buffer=e.buffer)}get id(){return this.buffer[this.index-4]}get start(){return this.buffer[this.index-3]}get end(){return this.buffer[this.index-2]}get size(){return this.buffer[this.index-1]}next(){this.index-=4,this.pos-=4,this.index==0&&this.maybeNext()}fork(){return new zl(this.stack,this.pos,this.index)}}class Ga{constructor(){this.start=-1,this.value=-1,this.end=-1,this.extended=-1,this.lookAhead=0,this.mask=0,this.context=0}}const Wg=new Ga;class F${constructor(e,t){this.input=e,this.ranges=t,this.chunk="",this.chunkOff=0,this.chunk2="",this.chunk2Pos=0,this.next=-1,this.token=Wg,this.rangeIndex=0,this.pos=this.chunkPos=t[0].from,this.range=t[0],this.end=t[t.length-1].to,this.readNext()}resolveOffset(e,t){let i=this.range,r=this.rangeIndex,s=this.pos+e;for(;si.to:s>=i.to;){if(r==this.ranges.length-1)return null;let o=this.ranges[++r];s+=o.from-i.to,i=o}return s}clipPos(e){if(e>=this.range.from&&ee)return Math.max(e,t.from);return this.end}peek(e){let t=this.chunkOff+e,i,r;if(t>=0&&t=this.chunk2Pos&&ia.to&&(this.chunk2=this.chunk2.slice(0,a.to-i)),r=this.chunk2.charCodeAt(0)}}return i>=this.token.lookAhead&&(this.token.lookAhead=i+1),r}acceptToken(e,t=0){let i=t?this.resolveOffset(t,-1):this.pos;if(i==null||i=this.chunk2Pos&&this.posthis.range.to?e.slice(0,this.range.to-this.pos):e,this.chunkPos=this.pos,this.chunkOff=0}}readNext(){return this.chunkOff>=this.chunk.length&&(this.getChunk(),this.chunkOff==this.chunk.length)?this.next=-1:this.next=this.chunk.charCodeAt(this.chunkOff)}advance(e=1){for(this.chunkOff+=e;this.pos+e>=this.range.to;){if(this.rangeIndex==this.ranges.length-1)return this.setDone();e-=this.range.to-this.pos,this.range=this.ranges[++this.rangeIndex],this.pos=this.range.from}return this.pos+=e,this.pos>=this.token.lookAhead&&(this.token.lookAhead=this.pos+1),this.readNext()}setDone(){return this.pos=this.chunkPos=this.end,this.range=this.ranges[this.rangeIndex=this.ranges.length-1],this.chunk="",this.next=-1}reset(e,t){if(t?(this.token=t,t.start=e,t.lookAhead=e+1,t.value=t.extended=-1):this.token=Wg,this.pos!=e){if(this.pos=e,e==this.end)return this.setDone(),this;for(;e=this.range.to;)this.range=this.ranges[++this.rangeIndex];e>=this.chunkPos&&e=this.chunkPos&&t<=this.chunkPos+this.chunk.length)return this.chunk.slice(e-this.chunkPos,t-this.chunkPos);if(e>=this.chunk2Pos&&t<=this.chunk2Pos+this.chunk2.length)return this.chunk2.slice(e-this.chunk2Pos,t-this.chunk2Pos);if(e>=this.range.from&&t<=this.range.to)return this.input.read(e,t);let i="";for(let r of this.ranges){if(r.from>=t)break;r.to>e&&(i+=this.input.read(Math.max(r.from,e),Math.min(r.to,t)))}return i}}class Ja{constructor(e,t){this.data=e,this.id=t}token(e,t){z$(this.data,e,t,this.id)}}Ja.prototype.contextual=Ja.prototype.fallback=Ja.prototype.extend=!1;class ii{constructor(e,t={}){this.token=e,this.contextual=!!t.contextual,this.fallback=!!t.fallback,this.extend=!!t.extend}}function z$(n,e,t,i){let r=0,s=1<0){let p=n[f];if(a.allows(p)&&(e.token.value==-1||e.token.value==p||o.overrides(p,e.token.value))){e.acceptToken(p);break}}let h=e.next,c=0,u=n[r+2];if(e.next<0&&u>c&&n[l+u*3-3]==65535&&n[l+u*3-3]==65535){r=n[l+u*3-1];continue e}for(;c>1,p=l+f+(f<<1),g=n[p],y=n[p+1]||65536;if(h=y)c=f+1;else{r=n[p+2],e.advance();continue e}}break}}function $a(n,e=Uint16Array){if(typeof n!="string")return n;let t=null;for(let i=0,r=0;i=92&&o--,o>=34&&o--;let l=o-32;if(l>=46&&(l-=46,a=!0),s+=l,a)break;s*=46}t?t[r++]=s:t=new e(s)}return t}const Zt=typeof process<"u"&&Lg&&/\bparse\b/.test(Lg.LOG);let rc=null;var jg;(function(n){n[n.Margin=25]="Margin"})(jg||(jg={}));function Fg(n,e,t){let i=n.cursor(ce.IncludeAnonymous);for(i.moveTo(e);;)if(!(t<0?i.childBefore(e):i.childAfter(e)))for(;;){if((t<0?i.toe)&&!i.type.isError)return t<0?Math.max(0,Math.min(i.to-1,e-25)):Math.min(n.length,Math.max(i.from+1,e+25));if(t<0?i.prevSibling():i.nextSibling())break;if(!i.parent())return t<0?0:n.length}}class _${constructor(e,t){this.fragments=e,this.nodeSet=t,this.i=0,this.fragment=null,this.safeFrom=-1,this.safeTo=-1,this.trees=[],this.start=[],this.index=[],this.nextFragment()}nextFragment(){let e=this.fragment=this.i==this.fragments.length?null:this.fragments[this.i++];if(e){for(this.safeFrom=e.openStart?Fg(e.tree,e.from+e.offset,1)-e.offset:e.from,this.safeTo=e.openEnd?Fg(e.tree,e.to+e.offset,-1)-e.offset:e.to;this.trees.length;)this.trees.pop(),this.start.pop(),this.index.pop();this.trees.push(e.tree),this.start.push(-e.offset),this.index.push(0),this.nextStart=this.safeFrom}else this.nextStart=1e9}nodeAt(e){if(ee)return this.nextStart=o,null;if(s instanceof ne){if(o==e){if(o=Math.max(this.safeFrom,e)&&(this.trees.push(s),this.start.push(o),this.index.push(0))}else this.index[t]++,this.nextStart=o+s.length}}}class G${constructor(e,t){this.stream=t,this.tokens=[],this.mainToken=null,this.actions=[],this.tokens=e.tokenizers.map(i=>new Ga)}getActions(e){let t=0,i=null,{parser:r}=e.p,{tokenizers:s}=r,o=r.stateSlot(e.state,3),a=e.curContext?e.curContext.hash:0,l=0;for(let h=0;hu.end+25&&(l=Math.max(u.lookAhead,l)),u.value!=0)){let f=t;if(u.extended>-1&&(t=this.addActions(e,u.extended,u.end,t)),t=this.addActions(e,u.value,u.end,t),!c.extend&&(i=u,t>f))break}}for(;this.actions.length>t;)this.actions.pop();return l&&e.setLookAhead(l),!i&&e.pos==this.stream.end&&(i=new Ga,i.value=e.p.parser.eofTerm,i.start=i.end=e.pos,t=this.addActions(e,i.value,i.end,t)),this.mainToken=i,this.actions}getMainToken(e){if(this.mainToken)return this.mainToken;let t=new Ga,{pos:i,p:r}=e;return t.start=i,t.end=Math.min(i+1,r.stream.end),t.value=i==r.stream.end?r.parser.eofTerm:0,t}updateCachedToken(e,t,i){let r=this.stream.clipPos(i.pos);if(t.token(this.stream.reset(r,e),i),e.value>-1){let{parser:s}=i.p;for(let o=0;o=0&&i.p.parser.dialect.allows(a>>1)){a&1?e.extended=a>>1:e.value=a>>1;break}}}else e.value=0,e.end=this.stream.clipPos(r+1)}putAction(e,t,i,r){for(let s=0;se.bufferLength*4?new _$(i,e.nodeSet):null}get parsedPos(){return this.minStackPos}advance(){let e=this.stacks,t=this.minStackPos,i=this.stacks=[],r,s;for(let o=0;ot)i.push(a);else{if(this.advanceStack(a,i,e))continue;{r||(r=[],s=[]),r.push(a);let l=this.tokens.getMainToken(a);s.push(l.value,l.end)}}break}}if(!i.length){let o=r&&H$(r);if(o)return this.stackToTree(o);if(this.parser.strict)throw Zt&&r&&console.log("Stuck with token "+(this.tokens.mainToken?this.parser.getName(this.tokens.mainToken.value):"none")),new SyntaxError("No parse at "+t);this.recovering||(this.recovering=5)}if(this.recovering&&r){let o=this.stoppedAt!=null&&r[0].pos>this.stoppedAt?r[0]:this.runRecovery(r,s,i);if(o)return this.stackToTree(o.forceAll())}if(this.recovering){let o=this.recovering==1?1:this.recovering*3;if(i.length>o)for(i.sort((a,l)=>l.score-a.score);i.length>o;)i.pop();i.some(a=>a.reducePos>t)&&this.recovering--}else if(i.length>1)e:for(let o=0;o500&&h.buffer.length>500)if((a.score-h.score||a.buffer.length-h.buffer.length)>0)i.splice(l--,1);else{i.splice(o--,1);continue e}}}this.minStackPos=i[0].pos;for(let o=1;o ":"";if(this.stoppedAt!=null&&r>this.stoppedAt)return e.forceReduce()?e:null;if(this.fragments){let h=e.curContext&&e.curContext.tracker.strict,c=h?e.curContext.hash:0;for(let u=this.fragments.nodeAt(r);u;){let f=this.parser.nodeSet.types[u.type.id]==u.type?s.getGoto(e.state,u.type.id):-1;if(f>-1&&u.length&&(!h||(u.prop(_.contextHash)||0)==c))return e.useNode(u,f),Zt&&console.log(o+this.stackID(e)+` (via reuse of ${s.getName(u.type.id)})`),!0;if(!(u instanceof ne)||u.children.length==0||u.positions[0]>0)break;let p=u.children[0];if(p instanceof ne&&u.positions[0]==0)u=p;else break}}let a=s.stateSlot(e.state,4);if(a>0)return e.reduce(a),Zt&&console.log(o+this.stackID(e)+` (via always-reduce ${s.getName(a&65535)})`),!0;if(e.stack.length>=15e3)for(;e.stack.length>9e3&&e.forceReduce(););let l=this.tokens.getActions(e);for(let h=0;hr?t.push(g):i.push(g)}return!1}advanceFully(e,t){let i=e.pos;for(;;){if(!this.advanceStack(e,null,null))return!1;if(e.pos>i)return _g(e,t),!0}}runRecovery(e,t,i){let r=null,s=!1;for(let o=0;o ":"";if(a.deadEnd&&(s||(s=!0,a.restart(),Zt&&console.log(c+this.stackID(a)+" (restarted)"),this.advanceFully(a,i))))continue;let u=a.split(),f=c;for(let p=0;u.forceReduce()&&p<10&&(Zt&&console.log(f+this.stackID(u)+" (via force-reduce)"),!this.advanceFully(u,i));p++)Zt&&(f=this.stackID(u)+" -> ");for(let p of a.recoverByInsert(l))Zt&&console.log(c+this.stackID(p)+" (via recover-insert)"),this.advanceFully(p,i);this.stream.end>a.pos?(h==a.pos&&(h++,l=0),a.recoverByDelete(l,h),Zt&&console.log(c+this.stackID(a)+` (via recover-delete ${this.parser.getName(l)})`),_g(a,i)):(!r||r.scoren;class Ub{constructor(e){this.start=e.start,this.shift=e.shift||sc,this.reduce=e.reduce||sc,this.reuse=e.reuse||sc,this.hash=e.hash||(()=>0),this.strict=e.strict!==!1}}class Qs extends Qf{constructor(e){if(super(),this.wrappers=[],e.version!=14)throw new RangeError(`Parser version (${e.version}) doesn't match runtime version (14)`);let t=e.nodeNames.split(" ");this.minRepeatTerm=t.length;for(let a=0;ae.topRules[a][1]),r=[];for(let a=0;a=0)s(c,l,a[h++]);else{let u=a[h+-c];for(let f=-c;f>0;f--)s(a[h++],l,u);h++}}}this.nodeSet=new Fo(t.map((a,l)=>Ie.define({name:l>=this.minRepeatTerm?void 0:a,id:l,props:r[l],top:i.indexOf(l)>-1,error:l==0,skipped:e.skippedNodes&&e.skippedNodes.indexOf(l)>-1}))),e.propSources&&(this.nodeSet=this.nodeSet.extend(...e.propSources)),this.strict=!1,this.bufferLength=ey;let o=$a(e.tokenData);this.context=e.context,this.specializerSpecs=e.specialized||[],this.specialized=new Uint16Array(this.specializerSpecs.length);for(let a=0;atypeof a=="number"?new Ja(o,a):a),this.topRules=e.topRules,this.dialects=e.dialects||{},this.dynamicPrecedences=e.dynamicPrecedences||null,this.tokenPrecTable=e.tokenPrec,this.termNames=e.termNames||null,this.maxNode=this.nodeSet.types.length-1,this.dialect=this.parseDialect(),this.top=this.topRules[Object.keys(this.topRules)[0]]}createParse(e,t,i){let r=new J$(this,e,t,i);for(let s of this.wrappers)r=s(r,e,t,i);return r}getGoto(e,t,i=!1){let r=this.goto;if(t>=r[0])return-1;for(let s=r[t+1];;){let o=r[s++],a=o&1,l=r[s++];if(a&&i)return l;for(let h=s+(o>>1);s0}validAction(e,t){if(t==this.stateSlot(e,4))return!0;for(let i=this.stateSlot(e,1);;i+=3){if(this.data[i]==65535)if(this.data[i+1]==1)i=$n(this.data,i+2);else return!1;if(t==$n(this.data,i+1))return!0}}nextStates(e){let t=[];for(let i=this.stateSlot(e,1);;i+=3){if(this.data[i]==65535)if(this.data[i+1]==1)i=$n(this.data,i+2);else break;if(!(this.data[i+2]&1)){let r=this.data[i+1];t.some((s,o)=>o&1&&s==r)||t.push(this.data[i],r)}}return t}overrides(e,t){let i=Gg(this.data,this.tokenPrecTable,t);return i<0||Gg(this.data,this.tokenPrecTable,e){let r=e.tokenizers.find(s=>s.from==i);return r?r.to:i})),e.specializers&&(t.specializers=this.specializers.slice(),t.specializerSpecs=this.specializerSpecs.map((i,r)=>{let s=e.specializers.find(a=>a.from==i.external);if(!s)return i;let o=Object.assign(Object.assign({},i),{external:s.to});return t.specializers[r]=Jg(o),o})),e.contextTracker&&(t.context=e.contextTracker),e.dialect&&(t.dialect=this.parseDialect(e.dialect)),e.strict!=null&&(t.strict=e.strict),e.wrap&&(t.wrappers=t.wrappers.concat(e.wrap)),e.bufferLength!=null&&(t.bufferLength=e.bufferLength),t}hasWrappers(){return this.wrappers.length>0}getName(e){return this.termNames?this.termNames[e]:String(e<=this.maxNode&&this.nodeSet.types[e].name||e)}get eofTerm(){return this.maxNode+1}get topNode(){return this.nodeSet.types[this.top[1]]}dynamicPrecedence(e){let t=this.dynamicPrecedences;return t==null?0:t[e]||0}parseDialect(e){let t=Object.keys(this.dialects),i=t.map(()=>!1);if(e)for(let s of e.split(" ")){let o=t.indexOf(s);o>=0&&(i[o]=!0)}let r=null;for(let s=0;si)&&t.p.parser.stateFlag(t.state,2)&&(!e||e.scoren.external(t,i)<<1|e}return n.get}const K$=54,eC=1,tC=55,iC=2,nC=56,rC=3,_l=4,Zb=5,Wb=6,jb=7,Fb=8,sC=9,oC=10,aC=11,oc=57,lC=12,Yg=58,hC=18,cC=20,zb=21,uC=22,Xu=24,_b=25,fC=27,dC=30,pC=33,gC=35,mC=0,OC={area:!0,base:!0,br:!0,col:!0,command:!0,embed:!0,frame:!0,hr:!0,img:!0,input:!0,keygen:!0,link:!0,meta:!0,param:!0,source:!0,track:!0,wbr:!0,menuitem:!0},yC={dd:!0,li:!0,optgroup:!0,option:!0,p:!0,rp:!0,rt:!0,tbody:!0,td:!0,tfoot:!0,th:!0,tr:!0},Hg={dd:{dd:!0,dt:!0},dt:{dd:!0,dt:!0},li:{li:!0},option:{option:!0,optgroup:!0},optgroup:{optgroup:!0},p:{address:!0,article:!0,aside:!0,blockquote:!0,dir:!0,div:!0,dl:!0,fieldset:!0,footer:!0,form:!0,h1:!0,h2:!0,h3:!0,h4:!0,h5:!0,h6:!0,header:!0,hgroup:!0,hr:!0,menu:!0,nav:!0,ol:!0,p:!0,pre:!0,section:!0,table:!0,ul:!0},rp:{rp:!0,rt:!0},rt:{rp:!0,rt:!0},tbody:{tbody:!0,tfoot:!0},td:{td:!0,th:!0},tfoot:{tbody:!0},th:{td:!0,th:!0},thead:{tbody:!0,tfoot:!0},tr:{tr:!0}};function bC(n){return n==45||n==46||n==58||n>=65&&n<=90||n==95||n>=97&&n<=122||n>=161}function Gb(n){return n==9||n==10||n==13||n==32}let Kg=null,em=null,tm=0;function Lu(n,e){let t=n.pos+e;if(tm==t&&em==n)return Kg;let i=n.peek(e);for(;Gb(i);)i=n.peek(++e);let r="";for(;bC(i);)r+=String.fromCharCode(i),i=n.peek(++e);return em=n,tm=t,Kg=r?r.toLowerCase():i==SC||i==wC?void 0:null}const Jb=60,Yb=62,Hb=47,SC=63,wC=33,vC=45;function im(n,e){this.name=n,this.parent=e,this.hash=e?e.hash:0;for(let t=0;t-1?new im(Lu(i,1)||"",n):n},reduce(n,e){return e==hC&&n?n.parent:n},reuse(n,e,t,i){let r=e.type.id;return r==_l||r==gC?new im(Lu(i,1)||"",n):n},hash(n){return n?n.hash:0},strict:!1}),TC=new ii((n,e)=>{if(n.next!=Jb){n.next<0&&e.context&&n.acceptToken(oc);return}n.advance();let t=n.next==Hb;t&&n.advance();let i=Lu(n,0);if(i===void 0)return;if(!i)return n.acceptToken(t?lC:_l);let r=e.context?e.context.name:null;if(t){if(i==r)return n.acceptToken(sC);if(r&&yC[r])return n.acceptToken(oc,-2);if(e.dialectEnabled(mC))return n.acceptToken(oC);for(let s=e.context;s;s=s.parent)if(s.name==i)return;n.acceptToken(aC)}else{if(i=="script")return n.acceptToken(Zb);if(i=="style")return n.acceptToken(Wb);if(i=="textarea")return n.acceptToken(jb);if(OC.hasOwnProperty(i))return n.acceptToken(Fb);r&&Hg[r]&&Hg[r][i]?n.acceptToken(oc,-1):n.acceptToken(_l)}},{contextual:!0}),QC=new ii(n=>{for(let e=0,t=0;;t++){if(n.next<0){t&&n.acceptToken(Yg);break}if(n.next==vC)e++;else if(n.next==Yb&&e>=2){t>3&&n.acceptToken(Yg,-2);break}else e=0;n.advance()}});function _f(n,e,t){let i=2+n.length;return new ii(r=>{for(let s=0,o=0,a=0;;a++){if(r.next<0){a&&r.acceptToken(e);break}if(s==0&&r.next==Jb||s==1&&r.next==Hb||s>=2&&so?r.acceptToken(e,-o):r.acceptToken(t,-(o-2));break}else if((r.next==10||r.next==13)&&a){r.acceptToken(e,1);break}else s=o=0;r.advance()}})}const PC=_f("script",K$,eC),AC=_f("style",tC,iC),$C=_f("textarea",nC,rC),CC=$s({"Text RawText":b.content,"StartTag StartCloseTag SelfClosingEndTag EndTag":b.angleBracket,TagName:b.tagName,"MismatchedCloseTag/TagName":[b.tagName,b.invalid],AttributeName:b.attributeName,"AttributeValue UnquotedAttributeValue":b.attributeValue,Is:b.definitionOperator,"EntityReference CharacterReference":b.character,Comment:b.blockComment,ProcessingInst:b.processingInstruction,DoctypeDecl:b.documentMeta}),IC=Qs.deserialize({version:14,states:",xOVOxOOO!WQ!bO'#CoO!]Q!bO'#CyO!bQ!bO'#C|O!gQ!bO'#DPO!lQ!bO'#DRO!qOXO'#CnO!|OYO'#CnO#XO[O'#CnO$eOxO'#CnOOOW'#Cn'#CnO$lO!rO'#DTO$tQ!bO'#DVO$yQ!bO'#DWOOOW'#Dk'#DkOOOW'#DY'#DYQVOxOOO%OQ#tO,59ZO%WQ#tO,59eO%`Q#tO,59hO%hQ#tO,59kO%sQ#tO,59mOOOX'#D^'#D^O%{OXO'#CwO&WOXO,59YOOOY'#D_'#D_O&`OYO'#CzO&kOYO,59YOOO['#D`'#D`O&sO[O'#C}O'OO[O,59YOOOW'#Da'#DaO'WOxO,59YO'_Q!bO'#DQOOOW,59Y,59YOOO`'#Db'#DbO'dO!rO,59oOOOW,59o,59oO'lQ!bO,59qO'qQ!bO,59rOOOW-E7W-E7WO'vQ#tO'#CqOOQO'#DZ'#DZO(UQ#tO1G.uOOOX1G.u1G.uO(^Q#tO1G/POOOY1G/P1G/PO(fQ#tO1G/SOOO[1G/S1G/SO(nQ#tO1G/VOOOW1G/V1G/VOOOW1G/X1G/XO(yQ#tO1G/XOOOX-E7[-E7[O)RQ!bO'#CxOOOW1G.t1G.tOOOY-E7]-E7]O)WQ!bO'#C{OOO[-E7^-E7^O)]Q!bO'#DOOOOW-E7_-E7_O)bQ!bO,59lOOO`-E7`-E7`OOOW1G/Z1G/ZOOOW1G/]1G/]OOOW1G/^1G/^O)gQ&jO,59]OOQO-E7X-E7XOOOX7+$a7+$aOOOY7+$k7+$kOOO[7+$n7+$nOOOW7+$q7+$qOOOW7+$s7+$sO)rQ!bO,59dO)wQ!bO,59gO)|Q!bO,59jOOOW1G/W1G/WO*RO,UO'#CtO*dO7[O'#CtOOQO1G.w1G.wOOOW1G/O1G/OOOOW1G/R1G/ROOOW1G/U1G/UOOOO'#D['#D[O*uO,UO,59`OOQO,59`,59`OOOO'#D]'#D]O+WO7[O,59`OOOO-E7Y-E7YOOQO1G.z1G.zOOOO-E7Z-E7Z",stateData:"+u~O!^OS~OSSOTPOUQOVROWTOY]OZ[O[^O^^O_^O`^Oa^Ox^O{_O!dZO~OdaO~OdbO~OdcO~OddO~OdeO~O!WfOPkP!ZkP~O!XiOQnP!ZnP~O!YlORqP!ZqP~OSSOTPOUQOVROWTOXqOY]OZ[O[^O^^O_^O`^Oa^Ox^O!dZO~O!ZrO~P#dO![sO!euO~OdvO~OdwO~OfyOj|O~OfyOj!OO~OfyOj!QO~OfyOj!SOv!TO~OfyOj!TO~O!WfOPkX!ZkX~OP!WO!Z!XO~O!XiOQnX!ZnX~OQ!ZO!Z!XO~O!YlORqX!ZqX~OR!]O!Z!XO~O!Z!XO~P#dOd!_O~O![sO!e!aO~Oj!bO~Oj!cO~Og!dOfeXjeXveX~OfyOj!fO~OfyOj!gO~OfyOj!hO~OfyOj!iOv!jO~OfyOj!jO~Od!kO~Od!lO~Od!mO~Oj!nO~Oi!qO!`!oO!b!pO~Oj!rO~Oj!sO~Oj!tO~O_!uO`!uOa!uO!`!wO!a!uO~O_!xO`!xOa!xO!b!wO!c!xO~O_!uO`!uOa!uO!`!{O!a!uO~O_!xO`!xOa!xO!b!{O!c!xO~Ov~vj`!dx{_a_~",goto:"%p!`PPPPPPPPPPPPPPPPPP!a!gP!mPP!yPP!|#P#S#Y#]#`#f#i#l#r#xP!aP!a!aP$O$U$l$r$x%O%U%[%bPPPPPPPP%hX^OX`pXUOX`pezabcde{}!P!R!UR!q!dRhUR!XhXVOX`pRkVR!XkXWOX`pRnWR!XnXXOX`pQrXR!XpXYOX`pQ`ORx`Q{aQ}bQ!PcQ!RdQ!UeZ!e{}!P!R!UQ!v!oR!z!vQ!y!pR!|!yQgUR!VgQjVR!YjQmWR![mQpXR!^pQtZR!`tS_O`ToXp",nodeNames:"⚠ StartCloseTag StartCloseTag StartCloseTag StartTag StartTag StartTag StartTag StartTag StartCloseTag StartCloseTag StartCloseTag IncompleteCloseTag Document Text EntityReference CharacterReference InvalidEntity Element OpenTag TagName Attribute AttributeName Is AttributeValue UnquotedAttributeValue EndTag ScriptText CloseTag OpenTag StyleText CloseTag OpenTag TextareaText CloseTag OpenTag CloseTag SelfClosingTag SelfClosingEndTag Comment ProcessingInst MismatchedCloseTag CloseTag DoctypeDecl",maxTerm:67,context:xC,nodeProps:[["closedBy",-10,1,2,3,5,6,7,8,9,10,11,"EndTag",4,"EndTag SelfClosingEndTag",-4,19,29,32,35,"CloseTag"],["group",-9,12,15,16,17,18,39,40,41,42,"Entity",14,"Entity TextContent",-3,27,30,33,"TextContent Entity"],["openedBy",26,"StartTag StartCloseTag",-4,28,31,34,36,"OpenTag",38,"StartTag"]],propSources:[CC],skippedNodes:[0],repeatNodeCount:9,tokenData:"#(r!aR!YOX$qXY,QYZ,QZ[$q[]&X]^,Q^p$qpq,Qqr-_rs4ysv-_vw5iwxJ^x}-_}!OKP!O!P-_!P!Q!!O!Q![-_![!]!$c!]!^-_!^!_!(k!_!`#'S!`!a#'z!a!c-_!c!}!$c!}#R-_#R#S!$c#S#T3V#T#o!$c#o#s-_#s$f$q$f%W-_%W%o!$c%o%p-_%p&a!$c&a&b-_&b1p!$c1p4U-_4U4d!$c4d4e-_4e$IS!$c$IS$I`-_$I`$Ib!$c$Ib$Kh-_$Kh%#t!$c%#t&/x-_&/x&Et!$c&Et&FV-_&FV;'S!$c;'S;:j!(e;:j;=`4s<%l?&r-_?&r?Ah!$c?Ah?BY$q?BY?Mn!$c?MnO$q!Z$|c^PiW!a`!cpOX$qXZ&XZ[$q[^&X^p$qpq&Xqr$qrs&}sv$qvw+Pwx(tx!^$q!^!_*V!_!a&X!a#S$q#S#T&X#T;'S$q;'S;=`+z<%lO$q!R&bX^P!a`!cpOr&Xrs&}sv&Xwx(tx!^&X!^!_*V!_;'S&X;'S;=`*y<%lO&Xq'UV^P!cpOv&}wx'kx!^&}!^!_(V!_;'S&};'S;=`(n<%lO&}P'pT^POv'kw!^'k!_;'S'k;'S;=`(P<%lO'kP(SP;=`<%l'kp([S!cpOv(Vx;'S(V;'S;=`(h<%lO(Vp(kP;=`<%l(Vq(qP;=`<%l&}a({W^P!a`Or(trs'ksv(tw!^(t!^!_)e!_;'S(t;'S;=`*P<%lO(t`)jT!a`Or)esv)ew;'S)e;'S;=`)y<%lO)e`)|P;=`<%l)ea*SP;=`<%l(t!Q*^V!a`!cpOr*Vrs(Vsv*Vwx)ex;'S*V;'S;=`*s<%lO*V!Q*vP;=`<%l*V!R*|P;=`<%l&XW+UYiWOX+PZ[+P^p+Pqr+Psw+Px!^+P!a#S+P#T;'S+P;'S;=`+t<%lO+PW+wP;=`<%l+P!Z+}P;=`<%l$q!a,]`^P!a`!cp!^^OX&XXY,QYZ,QZ]&X]^,Q^p&Xpq,Qqr&Xrs&}sv&Xwx(tx!^&X!^!_*V!_;'S&X;'S;=`*y<%lO&X!_-ljfS^PiW!a`!cpOX$qXZ&XZ[$q[^&X^p$qpq&Xqr-_rs&}sv-_vw/^wx(tx!P-_!P!Q$q!Q!^-_!^!_1n!_!a&X!a#S-_#S#T3V#T#s-_#s$f$q$f;'S-_;'S;=`4s<%l?Ah-_?Ah?BY$q?BY?Mn-_?MnO$q[/ecfSiWOX+PZ[+P^p+Pqr/^sw/^x!P/^!P!Q+P!Q!^/^!^!_0p!a#S/^#S#T0p#T#s/^#s$f+P$f;'S/^;'S;=`1h<%l?Ah/^?Ah?BY+P?BY?Mn/^?MnO+PS0uXfSqr0psw0px!P0p!Q!_0p!a#s0p$f;'S0p;'S;=`1b<%l?Ah0p?BY?Mn0pS1eP;=`<%l0p[1kP;=`<%l/^!U1wbfS!a`!cpOq*Vqr1nrs(Vsv1nvw0pwx)ex!P1n!P!Q*V!Q!_1n!_!a*V!a#s1n#s$f*V$f;'S1n;'S;=`3P<%l?Ah1n?Ah?BY*V?BY?Mn1n?MnO*V!U3SP;=`<%l1n!V3bcfS^P!a`!cpOq&Xqr3Vrs&}sv3Vvw0pwx(tx!P3V!P!Q&X!Q!^3V!^!_1n!_!a&X!a#s3V#s$f&X$f;'S3V;'S;=`4m<%l?Ah3V?Ah?BY&X?BY?Mn3V?MnO&X!V4pP;=`<%l3V!_4vP;=`<%l-_!Z5SV!`h^P!cpOv&}wx'kx!^&}!^!_(V!_;'S&};'S;=`(n<%lO&}!_5rjfSiWa!ROX7dXZ8qZ[7d[^8q^p7dqr:crs8qst@Ttw:cwx8qx!P:c!P!Q7d!Q!]:c!]!^/^!^!_=p!_!a8q!a#S:c#S#T=p#T#s:c#s$f7d$f;'S:c;'S;=`?}<%l?Ah:c?Ah?BY7d?BY?Mn:c?MnO7d!Z7ibiWOX7dXZ8qZ[7d[^8q^p7dqr7drs8qst+Ptw7dwx8qx!]7d!]!^9f!^!a8q!a#S7d#S#T8q#T;'S7d;'S;=`:]<%lO7d!R8tVOp8qqs8qt!]8q!]!^9Z!^;'S8q;'S;=`9`<%lO8q!R9`O_!R!R9cP;=`<%l8q!Z9mYiW_!ROX+PZ[+P^p+Pqr+Psw+Px!^+P!a#S+P#T;'S+P;'S;=`+t<%lO+P!Z:`P;=`<%l7d!_:jjfSiWOX7dXZ8qZ[7d[^8q^p7dqr:crs8qst/^tw:cwx8qx!P:c!P!Q7d!Q!]:c!]!^<[!^!_=p!_!a8q!a#S:c#S#T=p#T#s:c#s$f7d$f;'S:c;'S;=`?}<%l?Ah:c?Ah?BY7d?BY?Mn:c?MnO7d!_{let l=o.type.id;if(l==fC)return ac(o,a,t);if(l==dC)return ac(o,a,i);if(l==pC)return ac(o,a,r);if(s&&l==zb){let h=o.node,c;if(c=h.firstChild){let u=s[a.read(c.from,c.to)];if(u)for(let f of u){if(f.tagName){if(!tagName){let g=h.parent.getChild(cC);tagName=g?a.read(g.from,g.to):" "}if(attrTagName!=tagName)continue}let p=h.lastChild;if(p.type.id==Xu)return{parser:f.parser,overlay:[{from:p.from+1,to:p.to-1}]};if(p.type.id==_b)return{parser:f.parser,overlay:[{from:p.from,to:p.to}]}}}}return null})}const EC=94,nm=1,DC=95,NC=96,rm=2,eS=[9,10,11,12,13,32,133,160,5760,8192,8193,8194,8195,8196,8197,8198,8199,8200,8201,8202,8232,8233,8239,8287,12288],BC=58,qC=40,tS=95,MC=91,Ya=45,VC=46,XC=35,LC=37;function Gl(n){return n>=65&&n<=90||n>=97&&n<=122||n>=161}function UC(n){return n>=48&&n<=57}const ZC=new ii((n,e)=>{for(let t=!1,i=0,r=0;;r++){let{next:s}=n;if(Gl(s)||s==Ya||s==tS||t&&UC(s))!t&&(s!=Ya||r>0)&&(t=!0),i===r&&s==Ya&&i++,n.advance();else{t&&n.acceptToken(s==qC?DC:i==2&&e.canShift(rm)?rm:NC);break}}}),WC=new ii(n=>{if(eS.includes(n.peek(-1))){let{next:e}=n;(Gl(e)||e==tS||e==XC||e==VC||e==MC||e==BC||e==Ya)&&n.acceptToken(EC)}}),jC=new ii(n=>{if(!eS.includes(n.peek(-1))){let{next:e}=n;if(e==LC&&(n.advance(),n.acceptToken(nm)),Gl(e)){do n.advance();while(Gl(n.next));n.acceptToken(nm)}}}),FC=$s({"AtKeyword import charset namespace keyframes media supports":b.definitionKeyword,"from to selector":b.keyword,NamespaceName:b.namespace,KeyframeName:b.labelName,TagName:b.tagName,ClassName:b.className,PseudoClassName:b.constant(b.className),IdName:b.labelName,"FeatureName PropertyName":b.propertyName,AttributeName:b.attributeName,NumberLiteral:b.number,KeywordQuery:b.keyword,UnaryQueryOp:b.operatorKeyword,"CallTag ValueName":b.atom,VariableName:b.variableName,Callee:b.operatorKeyword,Unit:b.unit,"UniversalSelector NestingSelector":b.definitionOperator,MatchOp:b.compareOperator,"ChildOp SiblingOp, LogicOp":b.logicOperator,BinOp:b.arithmeticOperator,Important:b.modifier,Comment:b.blockComment,ParenthesizedContent:b.special(b.name),ColorLiteral:b.color,StringLiteral:b.string,":":b.punctuation,"PseudoOp #":b.derefOperator,"; ,":b.separator,"( )":b.paren,"[ ]":b.squareBracket,"{ }":b.brace}),zC={__proto__:null,lang:32,"nth-child":32,"nth-last-child":32,"nth-of-type":32,"nth-last-of-type":32,dir:32,"host-context":32,url:60,"url-prefix":60,domain:60,regexp:60,selector:134},_C={__proto__:null,"@import":114,"@media":138,"@charset":142,"@namespace":146,"@keyframes":152,"@supports":164},GC={__proto__:null,not:128,only:128,from:158,to:160},JC=Qs.deserialize({version:14,states:"7WQYQ[OOO#_Q[OOOOQP'#Cd'#CdOOQP'#Cc'#CcO#fQ[O'#CfO$YQXO'#CaO$aQ[O'#ChO$lQ[O'#DPO$qQ[O'#DTOOQP'#Ed'#EdO$vQdO'#DeO%bQ[O'#DrO$vQdO'#DtO%sQ[O'#DvO&OQ[O'#DyO&TQ[O'#EPO&cQ[O'#EROOQS'#Ec'#EcOOQS'#ET'#ETQYQ[OOO&jQXO'#CdO'_QWO'#DaO'dQWO'#EjO'oQ[O'#EjQOQWOOOOQP'#Cg'#CgOOQP,59Q,59QO#fQ[O,59QO'yQ[O'#EWO(eQWO,58{O(mQ[O,59SO$lQ[O,59kO$qQ[O,59oO'yQ[O,59sO'yQ[O,59uO'yQ[O,59vO(xQ[O'#D`OOQS,58{,58{OOQP'#Ck'#CkOOQO'#C}'#C}OOQP,59S,59SO)PQWO,59SO)UQWO,59SOOQP'#DR'#DROOQP,59k,59kOOQO'#DV'#DVO)ZQ`O,59oOOQS'#Cp'#CpO$vQdO'#CqO)cQvO'#CsO*pQtO,5:POOQO'#Cx'#CxO)UQWO'#CwO+UQWO'#CyOOQS'#Eg'#EgOOQO'#Dh'#DhO+ZQ[O'#DoO+iQWO'#EkO&TQ[O'#DmO+wQWO'#DpOOQO'#El'#ElO(hQWO,5:^O+|QpO,5:`OOQS'#Dx'#DxO,UQWO,5:bO,ZQ[O,5:bOOQO'#D{'#D{O,cQWO,5:eO,hQWO,5:kO,pQWO,5:mOOQS-E8R-E8RO$vQdO,59{O,xQ[O'#EYO-VQWO,5;UO-VQWO,5;UOOQP1G.l1G.lO-|QXO,5:rOOQO-E8U-E8UOOQS1G.g1G.gOOQP1G.n1G.nO)PQWO1G.nO)UQWO1G.nOOQP1G/V1G/VO.ZQ`O1G/ZO.tQXO1G/_O/[QXO1G/aO/rQXO1G/bO0YQWO,59zO0_Q[O'#DOO0fQdO'#CoOOQP1G/Z1G/ZO$vQdO1G/ZO0mQpO,59]OOQS,59_,59_O$vQdO,59aO0uQWO1G/kOOQS,59c,59cO0zQ!bO,59eO1SQWO'#DhO1_QWO,5:TO1dQWO,5:ZO&TQ[O,5:VO&TQ[O'#EZO1lQWO,5;VO1wQWO,5:XO'yQ[O,5:[OOQS1G/x1G/xOOQS1G/z1G/zOOQS1G/|1G/|O2YQWO1G/|O2_QdO'#D|OOQS1G0P1G0POOQS1G0V1G0VOOQS1G0X1G0XO2mQtO1G/gOOQO,5:t,5:tO3TQ[O,5:tOOQO-E8W-E8WO3bQWO1G0pOOQP7+$Y7+$YOOQP7+$u7+$uO$vQdO7+$uOOQS1G/f1G/fO3mQXO'#EiO3tQWO,59jO3yQtO'#EUO4nQdO'#EfO4xQWO,59ZO4}QpO7+$uOOQS1G.w1G.wOOQS1G.{1G.{OOQS7+%V7+%VO5VQWO1G/PO$vQdO1G/oOOQO1G/u1G/uOOQO1G/q1G/qO5[QWO,5:uOOQO-E8X-E8XO5jQXO1G/vOOQS7+%h7+%hO5qQYO'#CsO(hQWO'#E[O5yQdO,5:hOOQS,5:h,5:hO6XQtO'#EXO$vQdO'#EXO7VQdO7+%ROOQO7+%R7+%ROOQO1G0`1G0`O7jQpO<T![;'S%^;'S;=`%o<%lO%^^;TUoWOy%^z!Q%^!Q![;g![;'S%^;'S;=`%o<%lO%^^;nYoW#[UOy%^z!Q%^!Q![;g![!g%^!g!h<^!h#X%^#X#Y<^#Y;'S%^;'S;=`%o<%lO%^^[[oW#[UOy%^z!O%^!O!P;g!P!Q%^!Q![>T![!g%^!g!h<^!h#X%^#X#Y<^#Y;'S%^;'S;=`%o<%lO%^_?VSpVOy%^z;'S%^;'S;=`%o<%lO%^^?hWjSOy%^z!O%^!O!P;O!P!Q%^!Q![>T![;'S%^;'S;=`%o<%lO%^_@VU#XPOy%^z!Q%^!Q![;g![;'S%^;'S;=`%o<%lO%^~@nTjSOy%^z{@}{;'S%^;'S;=`%o<%lO%^~ASUoWOy@}yzAfz{Bm{;'S@};'S;=`Co<%lO@}~AiTOzAfz{Ax{;'SAf;'S;=`Bg<%lOAf~A{VOzAfz{Ax{!PAf!P!QBb!Q;'SAf;'S;=`Bg<%lOAf~BgOR~~BjP;=`<%lAf~BrWoWOy@}yzAfz{Bm{!P@}!P!QC[!Q;'S@};'S;=`Co<%lO@}~CcSoWR~Oy%^z;'S%^;'S;=`%o<%lO%^~CrP;=`<%l@}^Cz[#[UOy%^z!O%^!O!P;g!P!Q%^!Q![>T![!g%^!g!h<^!h#X%^#X#Y<^#Y;'S%^;'S;=`%o<%lO%^XDuU]POy%^z![%^![!]EX!];'S%^;'S;=`%o<%lO%^XE`S^PoWOy%^z;'S%^;'S;=`%o<%lO%^_EqS!WVOy%^z;'S%^;'S;=`%o<%lO%^YFSSzQOy%^z;'S%^;'S;=`%o<%lO%^XFeU|POy%^z!`%^!`!aFw!a;'S%^;'S;=`%o<%lO%^XGOS|PoWOy%^z;'S%^;'S;=`%o<%lO%^XG_WOy%^z!c%^!c!}Gw!}#T%^#T#oGw#o;'S%^;'S;=`%o<%lO%^XHO[!YPoWOy%^z}%^}!OGw!O!Q%^!Q![Gw![!c%^!c!}Gw!}#T%^#T#oGw#o;'S%^;'S;=`%o<%lO%^XHySxPOy%^z;'S%^;'S;=`%o<%lO%^^I[SvUOy%^z;'S%^;'S;=`%o<%lO%^XIkUOy%^z#b%^#b#cI}#c;'S%^;'S;=`%o<%lO%^XJSUoWOy%^z#W%^#W#XJf#X;'S%^;'S;=`%o<%lO%^XJmS!`PoWOy%^z;'S%^;'S;=`%o<%lO%^XJ|UOy%^z#f%^#f#gJf#g;'S%^;'S;=`%o<%lO%^XKeS!RPOy%^z;'S%^;'S;=`%o<%lO%^_KvS!QVOy%^z;'S%^;'S;=`%o<%lO%^ZLXU!PPOy%^z!_%^!_!`6y!`;'S%^;'S;=`%o<%lO%^WLnP;=`<%l$}",tokenizers:[WC,jC,ZC,0,1,2,3],topRules:{StyleSheet:[0,4],Styles:[1,84]},specialized:[{term:95,get:n=>zC[n]||-1},{term:56,get:n=>_C[n]||-1},{term:96,get:n=>GC[n]||-1}],tokenPrec:1123});let lc=null;function hc(){if(!lc&&typeof document=="object"&&document.body){let n=[];for(let e in document.body.style)/[A-Z]|^-|^(item|length)$/.test(e)||n.push(e);lc=n.sort().map(e=>({type:"property",label:e}))}return lc||[]}const sm=["active","after","any-link","autofill","backdrop","before","checked","cue","default","defined","disabled","empty","enabled","file-selector-button","first","first-child","first-letter","first-line","first-of-type","focus","focus-visible","focus-within","fullscreen","has","host","host-context","hover","in-range","indeterminate","invalid","is","lang","last-child","last-of-type","left","link","marker","modal","not","nth-child","nth-last-child","nth-last-of-type","nth-of-type","only-child","only-of-type","optional","out-of-range","part","placeholder","placeholder-shown","read-only","read-write","required","right","root","scope","selection","slotted","target","target-text","valid","visited","where"].map(n=>({type:"class",label:n})),om=["above","absolute","activeborder","additive","activecaption","after-white-space","ahead","alias","all","all-scroll","alphabetic","alternate","always","antialiased","appworkspace","asterisks","attr","auto","auto-flow","avoid","avoid-column","avoid-page","avoid-region","axis-pan","background","backwards","baseline","below","bidi-override","blink","block","block-axis","bold","bolder","border","border-box","both","bottom","break","break-all","break-word","bullets","button","button-bevel","buttonface","buttonhighlight","buttonshadow","buttontext","calc","capitalize","caps-lock-indicator","caption","captiontext","caret","cell","center","checkbox","circle","cjk-decimal","clear","clip","close-quote","col-resize","collapse","color","color-burn","color-dodge","column","column-reverse","compact","condensed","contain","content","contents","content-box","context-menu","continuous","copy","counter","counters","cover","crop","cross","crosshair","currentcolor","cursive","cyclic","darken","dashed","decimal","decimal-leading-zero","default","default-button","dense","destination-atop","destination-in","destination-out","destination-over","difference","disc","discard","disclosure-closed","disclosure-open","document","dot-dash","dot-dot-dash","dotted","double","down","e-resize","ease","ease-in","ease-in-out","ease-out","element","ellipse","ellipsis","embed","end","ethiopic-abegede-gez","ethiopic-halehame-aa-er","ethiopic-halehame-gez","ew-resize","exclusion","expanded","extends","extra-condensed","extra-expanded","fantasy","fast","fill","fill-box","fixed","flat","flex","flex-end","flex-start","footnotes","forwards","from","geometricPrecision","graytext","grid","groove","hand","hard-light","help","hidden","hide","higher","highlight","highlighttext","horizontal","hsl","hsla","hue","icon","ignore","inactiveborder","inactivecaption","inactivecaptiontext","infinite","infobackground","infotext","inherit","initial","inline","inline-axis","inline-block","inline-flex","inline-grid","inline-table","inset","inside","intrinsic","invert","italic","justify","keep-all","landscape","large","larger","left","level","lighter","lighten","line-through","linear","linear-gradient","lines","list-item","listbox","listitem","local","logical","loud","lower","lower-hexadecimal","lower-latin","lower-norwegian","lowercase","ltr","luminosity","manipulation","match","matrix","matrix3d","medium","menu","menutext","message-box","middle","min-intrinsic","mix","monospace","move","multiple","multiple_mask_images","multiply","n-resize","narrower","ne-resize","nesw-resize","no-close-quote","no-drop","no-open-quote","no-repeat","none","normal","not-allowed","nowrap","ns-resize","numbers","numeric","nw-resize","nwse-resize","oblique","opacity","open-quote","optimizeLegibility","optimizeSpeed","outset","outside","outside-shape","overlay","overline","padding","padding-box","painted","page","paused","perspective","pinch-zoom","plus-darker","plus-lighter","pointer","polygon","portrait","pre","pre-line","pre-wrap","preserve-3d","progress","push-button","radial-gradient","radio","read-only","read-write","read-write-plaintext-only","rectangle","region","relative","repeat","repeating-linear-gradient","repeating-radial-gradient","repeat-x","repeat-y","reset","reverse","rgb","rgba","ridge","right","rotate","rotate3d","rotateX","rotateY","rotateZ","round","row","row-resize","row-reverse","rtl","run-in","running","s-resize","sans-serif","saturation","scale","scale3d","scaleX","scaleY","scaleZ","screen","scroll","scrollbar","scroll-position","se-resize","self-start","self-end","semi-condensed","semi-expanded","separate","serif","show","single","skew","skewX","skewY","skip-white-space","slide","slider-horizontal","slider-vertical","sliderthumb-horizontal","sliderthumb-vertical","slow","small","small-caps","small-caption","smaller","soft-light","solid","source-atop","source-in","source-out","source-over","space","space-around","space-between","space-evenly","spell-out","square","start","static","status-bar","stretch","stroke","stroke-box","sub","subpixel-antialiased","svg_masks","super","sw-resize","symbolic","symbols","system-ui","table","table-caption","table-cell","table-column","table-column-group","table-footer-group","table-header-group","table-row","table-row-group","text","text-bottom","text-top","textarea","textfield","thick","thin","threeddarkshadow","threedface","threedhighlight","threedlightshadow","threedshadow","to","top","transform","translate","translate3d","translateX","translateY","translateZ","transparent","ultra-condensed","ultra-expanded","underline","unidirectional-pan","unset","up","upper-latin","uppercase","url","var","vertical","vertical-text","view-box","visible","visibleFill","visiblePainted","visibleStroke","visual","w-resize","wait","wave","wider","window","windowframe","windowtext","words","wrap","wrap-reverse","x-large","x-small","xor","xx-large","xx-small"].map(n=>({type:"keyword",label:n})).concat(["aliceblue","antiquewhite","aqua","aquamarine","azure","beige","bisque","black","blanchedalmond","blue","blueviolet","brown","burlywood","cadetblue","chartreuse","chocolate","coral","cornflowerblue","cornsilk","crimson","cyan","darkblue","darkcyan","darkgoldenrod","darkgray","darkgreen","darkkhaki","darkmagenta","darkolivegreen","darkorange","darkorchid","darkred","darksalmon","darkseagreen","darkslateblue","darkslategray","darkturquoise","darkviolet","deeppink","deepskyblue","dimgray","dodgerblue","firebrick","floralwhite","forestgreen","fuchsia","gainsboro","ghostwhite","gold","goldenrod","gray","grey","green","greenyellow","honeydew","hotpink","indianred","indigo","ivory","khaki","lavender","lavenderblush","lawngreen","lemonchiffon","lightblue","lightcoral","lightcyan","lightgoldenrodyellow","lightgray","lightgreen","lightpink","lightsalmon","lightseagreen","lightskyblue","lightslategray","lightsteelblue","lightyellow","lime","limegreen","linen","magenta","maroon","mediumaquamarine","mediumblue","mediumorchid","mediumpurple","mediumseagreen","mediumslateblue","mediumspringgreen","mediumturquoise","mediumvioletred","midnightblue","mintcream","mistyrose","moccasin","navajowhite","navy","oldlace","olive","olivedrab","orange","orangered","orchid","palegoldenrod","palegreen","paleturquoise","palevioletred","papayawhip","peachpuff","peru","pink","plum","powderblue","purple","rebeccapurple","red","rosybrown","royalblue","saddlebrown","salmon","sandybrown","seagreen","seashell","sienna","silver","skyblue","slateblue","slategray","snow","springgreen","steelblue","tan","teal","thistle","tomato","turquoise","violet","wheat","white","whitesmoke","yellow","yellowgreen"].map(n=>({type:"constant",label:n}))),YC=["a","abbr","address","article","aside","b","bdi","bdo","blockquote","body","br","button","canvas","caption","cite","code","col","colgroup","dd","del","details","dfn","dialog","div","dl","dt","em","figcaption","figure","footer","form","header","hgroup","h1","h2","h3","h4","h5","h6","hr","html","i","iframe","img","input","ins","kbd","label","legend","li","main","meter","nav","ol","output","p","pre","ruby","section","select","small","source","span","strong","sub","summary","sup","table","tbody","td","template","textarea","tfoot","th","thead","tr","u","ul"].map(n=>({type:"type",label:n})),zn=/^[\w-]*/,HC=n=>{let{state:e,pos:t}=n,i=de(e).resolveInner(t,-1);if(i.name=="PropertyName")return{from:i.from,options:hc(),validFor:zn};if(i.name=="ValueName")return{from:i.from,options:om,validFor:zn};if(i.name=="PseudoClassName")return{from:i.from,options:sm,validFor:zn};if(i.name=="TagName"){for(let{parent:o}=i;o;o=o.parent)if(o.name=="Block")return{from:i.from,options:hc(),validFor:zn};return{from:i.from,options:YC,validFor:zn}}if(!n.explicit)return null;let r=i.resolve(t),s=r.childBefore(t);return s&&s.name==":"&&r.name=="PseudoClassSelector"?{from:t,options:sm,validFor:zn}:s&&s.name==":"&&r.name=="Declaration"||r.name=="ArgList"?{from:t,options:om,validFor:zn}:r.name=="Block"?{from:t,options:hc(),validFor:zn}:null},Jl=ws.define({name:"css",parser:JC.configure({props:[zo.add({Declaration:_a()}),_o.add({Block:cy})]}),languageData:{commentTokens:{block:{open:"/*",close:"*/"}},indentOnInput:/^\s*\}$/,wordChars:"-"}});function KC(){return new Co(Jl,Jl.data.of({autocomplete:HC}))}const eI=1,am=294,lm=2,tI=3,Ca=295,iI=4,nI=296,hm=297,rI=299,sI=300,oI=5,aI=6,lI=1,hI=[9,10,11,12,13,32,133,160,5760,8192,8193,8194,8195,8196,8197,8198,8199,8200,8201,8202,8232,8233,8239,8287,12288],iS=125,cI=123,uI=59,cm=47,fI=42,dI=43,pI=45,gI=36,mI=96,OI=92,yI=new Ub({start:!1,shift(n,e){return e==oI||e==aI||e==rI?n:e==sI},strict:!1}),bI=new ii((n,e)=>{let{next:t}=n;(t==iS||t==-1||e.context)&&e.canShift(hm)&&n.acceptToken(hm)},{contextual:!0,fallback:!0}),SI=new ii((n,e)=>{let{next:t}=n,i;hI.indexOf(t)>-1||t==cm&&((i=n.peek(1))==cm||i==fI)||t!=iS&&t!=uI&&t!=-1&&!e.context&&e.canShift(am)&&n.acceptToken(am)},{contextual:!0}),wI=new ii((n,e)=>{let{next:t}=n;if((t==dI||t==pI)&&(n.advance(),t==n.next)){n.advance();let i=!e.context&&e.canShift(lm);n.acceptToken(i?lm:tI)}},{contextual:!0}),vI=new ii(n=>{for(let e=!1,t=0;;t++){let{next:i}=n;if(i<0){t&&n.acceptToken(Ca);break}else if(i==mI){t?n.acceptToken(Ca):n.acceptToken(nI,1);break}else if(i==cI&&e){t==1?n.acceptToken(iI,1):n.acceptToken(Ca,-1);break}else if(i==10&&t){n.advance(),n.acceptToken(Ca);break}else i==OI&&n.advance();e=i==gI,n.advance()}}),kI=new ii((n,e)=>{if(!(n.next!=101||!e.dialectEnabled(lI))){n.advance();for(let t=0;t<6;t++){if(n.next!="xtends".charCodeAt(t))return;n.advance()}n.next>=57&&n.next<=65||n.next>=48&&n.next<=90||n.next==95||n.next>=97&&n.next<=122||n.next>160||n.acceptToken(eI)}}),xI=$s({"get set async static":b.modifier,"for while do if else switch try catch finally return throw break continue default case":b.controlKeyword,"in of await yield void typeof delete instanceof":b.operatorKeyword,"let var const function class extends":b.definitionKeyword,"import export from":b.moduleKeyword,"with debugger as new":b.keyword,TemplateString:b.special(b.string),super:b.atom,BooleanLiteral:b.bool,this:b.self,null:b.null,Star:b.modifier,VariableName:b.variableName,"CallExpression/VariableName TaggedTemplateExpression/VariableName":b.function(b.variableName),VariableDefinition:b.definition(b.variableName),Label:b.labelName,PropertyName:b.propertyName,PrivatePropertyName:b.special(b.propertyName),"CallExpression/MemberExpression/PropertyName":b.function(b.propertyName),"FunctionDeclaration/VariableDefinition":b.function(b.definition(b.variableName)),"ClassDeclaration/VariableDefinition":b.definition(b.className),PropertyDefinition:b.definition(b.propertyName),PrivatePropertyDefinition:b.definition(b.special(b.propertyName)),UpdateOp:b.updateOperator,LineComment:b.lineComment,BlockComment:b.blockComment,Number:b.number,String:b.string,ArithOp:b.arithmeticOperator,LogicOp:b.logicOperator,BitOp:b.bitwiseOperator,CompareOp:b.compareOperator,RegExp:b.regexp,Equals:b.definitionOperator,Arrow:b.function(b.punctuation),": Spread":b.punctuation,"( )":b.paren,"[ ]":b.squareBracket,"{ }":b.brace,"InterpolationStart InterpolationEnd":b.special(b.brace),".":b.derefOperator,", ;":b.separator,"@":b.meta,TypeName:b.typeName,TypeDefinition:b.definition(b.typeName),"type enum interface implements namespace module declare":b.definitionKeyword,"abstract global Privacy readonly override":b.modifier,"is keyof unique infer":b.operatorKeyword,JSXAttributeValue:b.attributeValue,JSXText:b.content,"JSXStartTag JSXStartCloseTag JSXSelfCloseEndTag JSXEndTag":b.angleBracket,"JSXIdentifier JSXNameSpacedName":b.tagName,"JSXAttribute/JSXIdentifier JSXAttribute/JSXNameSpacedName":b.attributeName,"JSXBuiltin/JSXIdentifier":b.standard(b.tagName)}),TI={__proto__:null,export:18,as:23,from:29,default:32,async:37,function:38,this:50,true:58,false:58,null:68,void:72,typeof:76,super:92,new:126,await:143,yield:145,delete:146,class:156,extends:158,public:213,private:213,protected:213,readonly:215,instanceof:234,satisfies:237,in:238,const:240,import:272,keyof:327,unique:331,infer:337,is:373,abstract:393,implements:395,type:397,let:400,var:402,interface:409,enum:413,namespace:419,module:421,declare:425,global:429,for:450,of:459,while:462,with:466,do:470,if:474,else:476,switch:480,case:486,try:492,catch:496,finally:500,return:504,throw:508,break:512,continue:516,debugger:520},QI={__proto__:null,async:113,get:115,set:117,public:175,private:175,protected:175,static:177,abstract:179,override:181,readonly:187,accessor:189,new:377},PI={__proto__:null,"<":133},AI=Qs.deserialize({version:14,states:"$CWO`QdOOO$}QdOOO)WQ(C|O'#ChO)_OWO'#DYO+jQdO'#D_O+zQdO'#DjO$}QdO'#DtO.OQdO'#DzOOQ(C['#ET'#ETO.fQ`O'#EQOOQO'#IW'#IWO.nQ`O'#GgOOQO'#Ee'#EeO.yQ`O'#EdO/OQ`O'#EdO1QQ(C|O'#JQO3nQ(C|O'#JRO4_Q`O'#FSO4dQ!bO'#FkOOQ(C['#F['#F[O4oO#tO'#F[O4}Q&jO'#FrO6bQ`O'#FqOOQ(C['#JR'#JROOQ(CW'#JQ'#JQOOQS'#Jk'#JkO6gQ`O'#H{O6lQ(ChO'#H|OOQS'#Iu'#IuOOQS'#IO'#IOQ`QdOOO$}QdO'#DlO6tQ`O'#GgO6yQ&jO'#CmO7XQ`O'#EcO7dQ`O'#EnO7iQ&jO'#FZO8TQ`O'#GgO8YQ`O'#GkO8eQ`O'#GkO8sQ`O'#GnO8sQ`O'#GoO8sQ`O'#GqO6tQ`O'#GtO9dQ`O'#GwO:uQ`O'#CdO;VQ`O'#HUO;_Q`O'#H[O;_Q`O'#H^O`QdO'#H`O;_Q`O'#HbO;_Q`O'#HeO;dQ`O'#HkO;iQ(CjO'#HqO$}QdO'#HsO;tQ(CjO'#HuOWQpO'#FZO$}QdO'#DZOOOW'#IQ'#IQO>`OWO,59tOOQ(C[,59t,59tO>kQdO'#IRO?OQ`O'#JSOAQQtO'#JSO)jQdO'#JSOAXQ`O,59yOAoQ`O'#EeOA|Q`O'#J`OBXQ`O'#J_OBXQ`O'#J_OBaQ`O,5;ROBfQ`O'#J^OOQ(C[,5:U,5:UOBmQdO,5:UODnQ(C|O,5:`OE_Q`O,5:fOEdQ`O'#J[OF^Q(ChO'#J]O8YQ`O'#J[OFeQ`O'#J[OFmQ`O,5;QOFrQ`O'#J[OOQ(C]'#Ch'#ChO$}QdO'#DzOGfQpO,5:lOOQO'#JX'#JXOOQO-EgOOQS'#Ix'#IxOOQS,5>h,5>hOOQS-E;|-E;|O!.xQ(C|O,5:WOOQ(CX'#Cp'#CpO!/lQ&kO,5=ROOQO'#Cf'#CfO!/}Q(ChO'#IyO6bQ`O'#IyO;dQ`O,59XO!0`Q!bO,59XO!0hQ&jO,59XO6yQ&jO,59XO!0sQ`O,5;OO!0{Q`O'#HTO!1ZQ`O'#JoO$}QdO,5;sO!1cQ,UO,5;uO!1hQ`O,5=nO!1mQ`O,5=nO!1rQ`O,5=nO6lQ(ChO,5=nO!2QQ`O'#EgO!2wQ,UO'#EhOOQ(CW'#J^'#J^O!3OQ(ChO'#JlO6lQ(ChO,5=VO8sQ`O,5=]OOQP'#Cs'#CsO!3ZQ!bO,5=YO!3cQ!cO,5=ZO!3nQ`O,5=]O!3sQpO,5=`O;dQ`O'#GyO6tQ`O'#G{O!3{Q`O'#G{O6yQ&jO'#HOO!4QQ`O'#HOOOQS,5=c,5=cO!4VQ`O'#HPO!4_Q`O'#CmO!4dQ`O,59OO!4nQ`O,59OO!6sQdO,59OOOQS,59O,59OO!7QQ(ChO,59OO$}QdO,59OO!7]QdO'#HWOOQS'#HX'#HXOOQS'#HY'#HYO`QdO,5=pO!7mQ`O,5=pO`QdO,5=vO`QdO,5=xO!7rQ`O,5=zO`QdO,5=|O!7wQ`O,5>PO!7|QdO,5>VOOQS,5>],5>]O$}QdO,5>]O6lQ(ChO,5>_OOQS,5>a,5>aO!aOOQS,5>c,5>cO!cOOQS,5>e,5>eO!mO)jQdO,5>mOOQO,5>s,5>sO!CUQdO'#IROOQO-ExOOQ(CW-E<[-E<[O#5]Q(C}O1G0tOOQ(C[1G0t1G0tO#7hQ(C|O1G1YO#8[Q!bO,5;}O#8dQ!bO,5OQ,UO'#GXOOQ(C],5=Q,5=QOKhQ&jO,5?hOKhQ&jO,5?hO#>TQ`O'#IcO#>`Q`O,5?gO#>hQ`O,59^O#?XQ&kO,59mOOQ(C],59m,59mO#?zQ&kO,5<`O#@mQ&kO,5mO$)XQ`O1G5YO$)aQ`O1G5eO$)iQtO1G5fO8YQ`O,5>sO$)sQ`O1G5bO$)sQ`O1G5bO8YQ`O1G5bO$){Q(C|O1G5cO$}QdO1G5cO$*]Q(ChO1G5cO$*nQ`O,5>uO8YQ`O,5>uOOQO,5>u,5>uO$+SQ`O,5>uOOQO-Ez,5>zO$8rQ`O,5>zOOQ(C]1G2Z1G2ZP$8wQ`O'#I`POQ(C]-E<^-E<^O$9hQ&kO1G2gO$:ZQ&kO1G2iO$:eQqO1G2kOOQ(C]1G2S1G2SO$:lQ`O'#I_O$:zQ`O,5@SO$:zQ`O,5@SO$;SQ`O,5@SO$;_Q`O,5@SOOQO1G2U1G2UO$;mQ&kO1G2TOKhQ&jO1G2TO$;}QMhO'#IaO$<_Q`O,5@TOJRQ&jO,5@TO$|,5>|OOQO-E<`-E<`OOQ(C]1G2]1G2]O!)dQ,UO,5},5>}OOQO-EkQqO'#JjO$(iQ`O7+(XO$>uQ`O7+(XO$>}QqO7+(XO$?XQ(CyO'#ChO$?lQ(CyO,5ROOQS,5>R,5>RO$}QdO'#HhO$EoQ`O'#HjOOQS,5>X,5>XO8YQ`O,5>XOOQS,5>Z,5>ZOOQS7+)]7+)]OOQS7+)c7+)cOOQS7+)g7+)gOOQS7+)i7+)iO$EtQ!bO1G5[O$FYQ!LUO1G0oO$FdQ`O1G0oOOQO1G/k1G/kO$FoQ!LUO1G/kO$FyQ`O,5?pO;dQ`O1G/kOMqQdO'#DeOOQO,5>n,5>nOOQO-Et,5>tOOQO-EoOOQO-EpO$}QdO,5>pOOQO-ExOOOO7+'_7+'_OOOW1G/S1G/SOOQ(C]1G4f1G4fOKhQ&jO7+(VO%7}Q`O,5>yO6tQ`O,5>yOOQO-E<]-E<]O%8]Q`O1G5nO%8]Q`O1G5nO%8eQ`O1G5nO%8pQ&kO7+'oO%9QQqO,5>{O%9[Q`O,5>{OJRQ&jO,5>{OOQO-E<_-E<_O%9aQqO1G5oO%9kQ`O1G5oOOQ(CW1G2_1G2_O$VQdO'#JUO%>^Q,UO'#E[O%>tQ(ChO'#E[O$$sQ(DjO'#E[O$%hQ,UO'#G}OOQO'#Ih'#IhO%?YQ,UO,5=hOOQS,5=h,5=hO%?aQ,UO'#E[O%?rQ,UO'#E[O%@YQ,UO'#E[O%@vQ,UO'#G}O%AXQ`O7+(mO%A^Q`O7+(mO%AfQqO7+(mOOQS7+(m7+(mOJRQ&jO7+(mO$}QdO7+(mOJRQ&jO7+(mO%ApQaO7+(mOOQS7+(p7+(pO6lQ(ChO7+(pO#=PQ`O7+(pO6bQ`O7+(pO!0`Q!bO7+(pO%BOQ`O,5?TOOQO-ESOOQS,5>U,5>UO%CYQ`O1G3sO8YQ`O7+&ZOMqQdO7+&ZOOQ(CW1G5[1G5[OOQO7+%V7+%VO%C_Q!LUO1G5fO;dQ`O7+%VO;dQ`O1G0VOOQO1G0b1G0bO$}QdO1G0bO%CiQ(ChO1G0bO%CtQ(ChO1G0bO!0`Q!bO1G0VO$%_Q,UO1G0VO%DSQ,UO1G0VO%DaQ(DjO1G0bO%D{Q,UO1G0VO$%_Q,UO1G0bO%E]Q,UO1G0bO%EvQ(ChO1G0bOOQO1G0V1G0VO%F[Q(C|O1G0bOOQ(C[<VQdO,5iQ!LVO7+'qO&@_Q&kOG26wOOQO<wAN>wO;dQ`OAN>wO$}QdOAN?SO!0`Q!bOAN>wO&ATQ(ChOAN?SO$%_Q,UOAN>wO&A`Q(ChOAN?SOOQS!$(!P!$(!PO$(iQ`O!$(!PO&AnQ(C}OG26wOOQ(CWG26lG26lOOQO<SO!T+rO!U'wX~O!U+tO~O!_+kO#T+jO!T#]X!U#]X~O!T+uO!U(TX~O!U+wO~O]&VOl&VO{+nO'k$vO's)TO~O!Z+xO![+xO~P!AQO_+}O!U,PO!Y,QO!Z+|O![+|O!u;WO!y,UO!z,SO!{,TO!|,RO#P,VO#Q,VO'|+zO~P!AQOP,[O!V&cO!q,ZO~Oo,aO~O!Q&ua!T&ua~P!-RO!S,eO!Q&uX!T&uX~P$}O!T&rO!Q'va~O!Q'va~P?WO!T&yO!Q(Ra~O{%WO!S,iO!V%XO'j$tO!Q&{X!T&{X~O!T'WO!e(Oa~O{%WO!V%XO#_,lO'j$tO~O#T,nO!T(Pa!e(Pa_(Pa'e(Pa~O!_#UO~P!DvO{%WO!S,qO!V%XO!uXO#^,sO#_,qO'j$tO!T&}X!e&}X~Oy,wO!f#XO~OP,{O!V&cO!q,zO%],yO'n$bO~O_#Wi!T#Wi'e#Wi'a#Wi!Q#Wi!e#Wio#Wi!V#Wi%]#Wi!_#Wi~P!-ROP=mOx(mO{(nO(U(pO(V(rO~O#`#Sa!T#Sa!e#Sa#T#Sa!V#Sa_#Sa'e#Sa!Q#Sa~P!G[O!d#WOP'qXx'qX{'qX(U'qX(V'qXQ'qXZ'qXk'qXy'qX!T'qX!c'qX!f'qX!l'qX#c'qX#d'qX#e'qX#f'qX#g'qX#h'qX#i'qX#j'qX#k'qX#m'qX#o'qX#q'qX#r'qX'r'qX'}'qX~O#`'qX_'qX'e'qX!e'qX!Q'qX'a'qX!V'qX#T'qXo'qX%]'qX!_'qX~P!HZO!T-UOe'yX~P!&VOe-WO~O!T-XO!e'zX~P!-RO!e-[O~O!Q-^O~OQ#lOx#YOy#ZO{#[O!d#WO!f#XO!l#lO'rROZ#bi_#bik#bi!T#bi!c#bi#d#bi#e#bi#f#bi#g#bi#h#bi#i#bi#j#bi#k#bi#m#bi#o#bi#q#bi#r#bi'e#bi'}#bi(U#bi(V#bi'a#bi!Q#bi!e#bio#bi!V#bi%]#bi!_#bi~O#c#bi~P!KrO#c#_O~P!KrOQ#lOx#YOy#ZO{#[O!d#WO!f#XO!l#lO#c#_O#d#`O#e#`O#f#`O'rROZ#bi_#bi!T#bi!c#bi#g#bi#h#bi#i#bi#j#bi#k#bi#m#bi#o#bi#q#bi#r#bi'e#bi'}#bi(U#bi(V#bi'a#bi!Q#bi!e#bio#bi!V#bi%]#bi!_#bi~Ok#bi~P!NdOk#aO~P!NdOQ#lOk#aOx#YOy#ZO{#[O!d#WO!f#XO!l#lO#c#_O#d#`O#e#`O#f#`O#g#bO'rRO_#bi!T#bi#m#bi#o#bi#q#bi#r#bi'e#bi'}#bi(U#bi(V#bi'a#bi!Q#bi!e#bio#bi!V#bi%]#bi!_#bi~OZ#bi!c#bi#h#bi#i#bi#j#bi#k#bi~P##UOZ#sO!c#cO#h#cO#i#cO#j#rO#k#cO~P##UOQ#lOZ#sOk#aOx#YOy#ZO{#[O!c#cO!d#WO!f#XO!l#lO#c#_O#d#`O#e#`O#f#`O#g#bO#h#cO#i#cO#j#rO#k#cO#m#dO'rRO_#bi!T#bi#o#bi#q#bi#r#bi'e#bi'}#bi(V#bi'a#bi!Q#bi!e#bio#bi!V#bi%]#bi!_#bi~O(U#bi~P#&VO(U#]O~P#&VOQ#lOZ#sOk#aOx#YOy#ZO{#[O!c#cO!d#WO!f#XO!l#lO#c#_O#d#`O#e#`O#f#`O#g#bO#h#cO#i#cO#j#rO#k#cO#m#dO#o#fO'rRO(U#]O_#bi!T#bi#q#bi#r#bi'e#bi'}#bi'a#bi!Q#bi!e#bio#bi!V#bi%]#bi!_#bi~O(V#bi~P#(wO(V#^O~P#(wOQ#lOZ#sOk#aOx#YOy#ZO{#[O!c#cO!d#WO!f#XO!l#lO#c#_O#d#`O#e#`O#f#`O#g#bO#h#cO#i#cO#j#rO#k#cO#m#dO#o#fO#q#hO'rRO(U#]O(V#^O~O_#bi!T#bi#r#bi'e#bi'}#bi'a#bi!Q#bi!e#bio#bi!V#bi%]#bi!_#bi~P#+iOQ[XZ[Xk[Xx[Xy[X{[X!c[X!d[X!f[X!l[X#T[X#`dX#c[X#d[X#e[X#f[X#g[X#h[X#i[X#j[X#k[X#m[X#o[X#q[X#r[X#w[X'r[X'}[X(U[X(V[X!T[X!U[X~O#u[X~P#.SOQ#lOZ;mOk;aOx#YOy#ZO{#[O!c;cO!d#WO!f#XO!l#lO#c;_O#d;`O#e;`O#f;`O#g;bO#h;cO#i;cO#j;lO#k;cO#m;dO#o;fO#q;hO#r;iO'rRO'}#jO(U#]O(V#^O~O#u-`O~P#0aOQ'uXZ'uXk'uXx'uXy'uX{'uX!c'uX!d'uX!f'uX!l'uX#c'uX#d'uX#e'uX#f'uX#g'uX#h'uX#i'uX#j'uX#m'uX#o'uX#q'uX#r'uX'r'uX'}'uX(U'uX(V'uX!T'uX~O#T;nO#w;nO#k'uX#u'uX!U'uX~P#2_O_'Qa!T'Qa'e'Qa'a'Qa!e'Qao'Qa!Q'Qa!V'Qa%]'Qa!_'Qa~P!-ROQ#biZ#bi_#bik#biy#bi!T#bi!c#bi!d#bi!f#bi!l#bi#c#bi#d#bi#e#bi#f#bi#g#bi#h#bi#i#bi#j#bi#k#bi#m#bi#o#bi#q#bi#r#bi'e#bi'r#bi'}#bi'a#bi!Q#bi!e#bio#bi!V#bi%]#bi!_#bi~P!G[O_#vi!T#vi'e#vi'a#vi!Q#vi!e#vio#vi!V#vi%]#vi!_#vi~P!-RO$S-cO$U-cO~O$S-dO$U-dO~O!_(VO#T-eO!V$YX$P$YX$S$YX$U$YX$]$YX~O!S-fO~O!V(YO$P-hO$S(XO$U(XO$]-iO~O!T;jO!U'tX~P#0aO!U-jO~O$]-lO~OS(hO'c(iO'd-oO~O]-rOl-rO!Q-sO~O!TdX!_dX!edX!e$oX'}dX~P!$|O!e-yO~P!G[O!T-zO!_#UO'}'SO!e([X~O!e.PO~O!S(yO'j$tO!e([P~O#`.RO~O!Q$oX!T$oX!_$vX~P!$|O!T.SO!Q(]X~P!G[O!_.UO~O!Q.WO~Ok.[O!_#UO!f$mO'n$bO'}'SO~O'j.^O~O!_)yO~O_$pO!T.bO'e$pO~O!U.dO~P!(wO!Z.eO![.eO'k$vO's)TO~O{.gO's)TO~O#P.hO~O'j%^Oe'VX!T'VX~O!T)dOe'oa~Oe.mO~Ox.nOy.nO{.oOPua(Uua(Vua!Tua#Tua~Oeua#uua~P#>mOx(mO{(nOP$ha(U$ha(V$ha!T$ha#T$ha~Oe$ha#u$ha~P#?cOx(mO{(nOP$ja(U$ja(V$ja!T$ja#T$ja~Oe$ja#u$ja~P#@UO].pO~O#`.qO~Oe$xa!T$xa#T$xa#u$xa~P!&VO#`.tO~OP,{O!V&cO!q,zO%],yO~O]$SOk$TOl$SOm$SOr$dOt$eOv;oO{$[O!V$]O!a=`O!f$XO#_;xO#|$iO$i;rO$k;uO$n$jO'n$bO'r$UO~Oi.{O'j.zO~P#AvO!_)yO!V'ma_'ma!T'ma'e'ma~O#`/RO~OZ[X!TdX!UdX~O!T/SO!U(dX~O!U/UO~OZ/VO~O]/XO'j*RO~O!V%OO'j$tO^'_X!T'_X~O!T*WO^(ca~O!e/[O~P!-RO]/^O~OZ/_O~O^/`O~O!T*dO_(`a'e(`a~O#T/fO~OP/iO!V$]O~O's'lO!U(aP~OP/sO!V/oO!q/rO%]/qO'n$bO~OZ/}O!T/{O!U(bX~O!U0OO~O^0QO_$pO'e$pO~O]0RO~O]0SO'j!|O~O#k0TO%}0UO~P1nO#T#tO#k0TO%}0UO~O_0VO~P$}O_0XO~O&W0]OQ&UiR&UiX&Ui]&Ui_&Uib&Uic&Uii&Uik&Uil&Uim&Uir&Uit&Uiv&Ui{&Ui!O&Ui!P&Ui!V&Ui!a&Ui!f&Ui!i&Ui!j&Ui!k&Ui!l&Ui!m&Ui!p&Ui!u&Ui#l&Ui#|&Ui$Q&Ui%[&Ui%^&Ui%`&Ui%a&Ui%d&Ui%f&Ui%i&Ui%j&Ui%l&Ui%y&Ui&P&Ui&R&Ui&T&Ui&V&Ui&Y&Ui&`&Ui&f&Ui&h&Ui&j&Ui&l&Ui&n&Ui'a&Ui'j&Ui'r&Ui'|&Ui(Z&Ui!U&Ui`&Ui&]&Ui~O`0cO!U0aO&]0bO~P`O!VTO!f0eO~O&d+aOQ&_iR&_iX&_i]&_i_&_ib&_ic&_ii&_ik&_il&_im&_ir&_it&_iv&_i{&_i!O&_i!P&_i!V&_i!a&_i!f&_i!i&_i!j&_i!k&_i!l&_i!m&_i!p&_i!u&_i#l&_i#|&_i$Q&_i%[&_i%^&_i%`&_i%a&_i%d&_i%f&_i%i&_i%j&_i%l&_i%y&_i&P&_i&R&_i&T&_i&V&_i&Y&_i&`&_i&f&_i&h&_i&j&_i&l&_i&n&_i'a&_i'j&_i'r&_i'|&_i(Z&_i!U&_i&W&_i`&_i&]&_i~O!Q0kO~O!T!Xa!U!Xa~P#0aO!S0rO!Y&bO!Z&ZO![&ZO!T&vX!U&vX~P!AQO!T+rO!U'wa~O!T&|X!U&|X~P!2fO!T+uO!U(Ta~O!Y0{O!Z0zO![0zO!u;WO!y1OO!z0}O!{0}O!|0|O#P1PO#Q1PO'|+zO~P!AQO_$pO!_#UO!f$mO!l1UO#T1SO'e$pO'n$bO'}'SO~O]&VOl&VO{+nO's)TO'|+zO~O_+}O!U1XO!Y,QO!Z+|O![+|O!u;WO!y,UO!z,SO!{,TO!|,RO#P,VO#Q,VO'|+zO~P!AQO!Z0zO![0zO'|+zO~P!AQO!Y0{O!Z0zO![0zO'|+zO~P!AQO!VTO!Y0{O!Z0zO![0zO!|0|O#P1PO#Q1PO'|+zO~P!AQO!Y0{O!Z0zO![0zO!z0}O!{0}O!|0|O#P1PO#Q1PO'|+zO~P!AQO!V&cO~O!V&cO~P!G[O!T#pOo$ga~O!Q&ui!T&ui~P!-RO!T&rO!Q'vi~O!T&yO!Q(Ri~O!Q(Si!T(Si~P!-RO!T'WO!e(Oi~O!T(Pi!e(Pi_(Pi'e(Pi~P!-RO#T1eO!T(Pi!e(Pi_(Pi'e(Pi~O{%WO!V%XO!uXO#^1hO#_1gO'j$tO~O{%WO!V%XO#_1gO'j$tO~OP1pO!V&cO!q1oO%]1nO~OP1pO!V&cO!q1oO%]1nO'n$bO~O#`uaQuaZua_uakua!cua!dua!fua!lua#cua#dua#eua#fua#gua#hua#iua#jua#kua#mua#oua#qua#rua'eua'rua'}ua!eua!Qua'aua!Vuaoua%]ua!_ua~P#>mO#`$haQ$haZ$ha_$hak$hay$ha!c$ha!d$ha!f$ha!l$ha#c$ha#d$ha#e$ha#f$ha#g$ha#h$ha#i$ha#j$ha#k$ha#m$ha#o$ha#q$ha#r$ha'e$ha'r$ha'}$ha!e$ha!Q$ha'a$ha!V$hao$ha%]$ha!_$ha~P#?cO#`$jaQ$jaZ$ja_$jak$jay$ja!c$ja!d$ja!f$ja!l$ja#c$ja#d$ja#e$ja#f$ja#g$ja#h$ja#i$ja#j$ja#k$ja#m$ja#o$ja#q$ja#r$ja'e$ja'r$ja'}$ja!e$ja!Q$ja'a$ja!V$jao$ja%]$ja!_$ja~P#@UO#`$xaQ$xaZ$xa_$xak$xay$xa!T$xa!c$xa!d$xa!f$xa!l$xa#c$xa#d$xa#e$xa#f$xa#g$xa#h$xa#i$xa#j$xa#k$xa#m$xa#o$xa#q$xa#r$xa'e$xa'r$xa'}$xa!e$xa!Q$xa'a$xa!V$xa#T$xao$xa%]$xa!_$xa~P!G[O_#Wq!T#Wq'e#Wq'a#Wq!Q#Wq!e#Wqo#Wq!V#Wq%]#Wq!_#Wq~P!-ROe&wX!T&wX~PKhO!T-UOe'ya~O!S1xO!T&xX!e&xX~P$}O!T-XO!e'za~O!T-XO!e'za~P!-RO!Q1{O~O#u!ha!U!ha~PBtO#u!`a!T!`a!U!`a~P#0aO!V2^O$QbO$Z2_O~O!U2cO~Oo2dO~P!G[O_$dq!T$dq'e$dq'a$dq!Q$dq!e$dqo$dq!V$dq%]$dq!_$dq~P!-RO!Q2eO~O]-rOl-rO~Ox(mO{(nO(V(rOP%Ti(U%Ti!T%Ti#T%Ti~Oe%Ti#u%Ti~P$9POx(mO{(nOP%Vi(U%Vi(V%Vi!T%Vi#T%Vi~Oe%Vi#u%Vi~P$9rO'}#jO~P!G[O!S2hO'j$tO!T'RX!e'RX~O!T-zO!e([a~O!T-zO!_#UO!e([a~O!T-zO!_#UO'}'SO!e([a~Oe$qi!T$qi#T$qi#u$qi~P!&VO!S2pO'j)OO!Q'TX!T'TX~P!&tO!T.SO!Q(]a~O!T.SO!Q(]a~P!G[O!_#UO~O!_#UO#k2xO~Ok2{O!_#UO'}'SO~Oe'pi!T'pi~P!&VO#T3OOe'pi!T'pi~P!&VO!e3RO~O_$eq!T$eq'e$eq'a$eq!Q$eq!e$eqo$eq!V$eq%]$eq!_$eq~P!-RO!T3VO!V(^X~P!G[O!V&cO%]1nO~O!V&cO%]1nO~P!G[O!V$oX%Q[X_$oX!T$oX'e$oX~P!$|O%Q3XOPhXxhX{hX!VhX(UhX(VhX_hX!ThX'ehX~O%Q3XO~O]3_O%^3`O'j*RO!T'^X!U'^X~O!T/SO!U(da~OZ3dO~O^3eO~O]3hO~O!Q3iO~O_$pO'e$pO~P!G[O!V$]O~P!G[O!T3nO#T3pO!U(aX~O!U3qO~O]&VOl&VO{3sO!Y4OO!Z3wO![3wO!u;WO!y3}O!z3|O!{3|O#P3{O#Q,VO'k$vO's)TO'|+zO~O!U3zO~P$BTOP4VO!V/oO!q4UO%]4TO~OP4VO!V/oO!q4UO%]4TO'n$bO~O'j!|O!T']X!U']X~O!T/{O!U(ba~O]4aO's4`O~O]4bO~O^4dO~O!e4gO~P$}O_4iO~O_4iO~P$}O#k4kO%}4lO~PExO`0cO!U4pO&]0bO~P`O!_4rO~O!_4tO!T'xi!U'xi!_'xi!f'xi'n'xi~O!T#]i!U#]i~P#0aO#T4uO!T#]i!U#]i~O!T!Xi!U!Xi~P#0aO!Q4vO~O]!tal!ta!Y!ta!Z!ta![!ta!y!ta!z!ta!{!ta!|!ta#P!ta#Q!ta'k!ta's!ta'|!ta~PGQO_$pO!_#UO!f$mO!l5OO#T4|O'e$pO'n$bO'}'SO~O!Z5QO![5QO'|+zO~P!AQO!Y5RO!Z5QO![5QO'|+zO~P!AQO!Y5RO!Z5QO![5QO!|5TO#P5UO#Q5UO'|+zO~P!AQO!Y5RO!Z5QO![5QO!z5VO!{5VO!|5TO#P5UO#Q5UO'|+zO~P!AQO_$pO#T4|O'e$pO~O_$pO!_#UO#T4|O'e$pO~O_$pO!_#UO!l5OO#T4|O'e$pO'}'SO~O!T'WO!e(Oq~O!T(Pq!e(Pq_(Pq'e(Pq~P!-RO{%WO!V%XO#_5aO'j$tO~O!V&cO%]5cO~O!V&cO%]5cO~P!G[OP5hO!V&cO!q5gO%]5cO~O#`%TiQ%TiZ%Ti_%Tik%Tiy%Ti!c%Ti!d%Ti!f%Ti!l%Ti#c%Ti#d%Ti#e%Ti#f%Ti#g%Ti#h%Ti#i%Ti#j%Ti#k%Ti#m%Ti#o%Ti#q%Ti#r%Ti'e%Ti'r%Ti'}%Ti!e%Ti!Q%Ti'a%Ti!V%Tio%Ti%]%Ti!_%Ti~P$9PO#`%ViQ%ViZ%Vi_%Vik%Viy%Vi!c%Vi!d%Vi!f%Vi!l%Vi#c%Vi#d%Vi#e%Vi#f%Vi#g%Vi#h%Vi#i%Vi#j%Vi#k%Vi#m%Vi#o%Vi#q%Vi#r%Vi'e%Vi'r%Vi'}%Vi!e%Vi!Q%Vi'a%Vi!V%Vio%Vi%]%Vi!_%Vi~P$9rO#`$qiQ$qiZ$qi_$qik$qiy$qi!T$qi!c$qi!d$qi!f$qi!l$qi#c$qi#d$qi#e$qi#f$qi#g$qi#h$qi#i$qi#j$qi#k$qi#m$qi#o$qi#q$qi#r$qi'e$qi'r$qi'}$qi!e$qi!Q$qi'a$qi!V$qi#T$qio$qi%]$qi!_$qi~P!G[Oe&wa!T&wa~P!&VO!T&xa!e&xa~P!-RO!T-XO!e'zi~O#u#Wi!T#Wi!U#Wi~P#0aOQ#lOx#YOy#ZO{#[O!d#WO!f#XO!l#lO'rROZ#bik#bi!c#bi#d#bi#e#bi#f#bi#g#bi#h#bi#i#bi#j#bi#k#bi#m#bi#o#bi#q#bi#r#bi#u#bi'}#bi(U#bi(V#bi!T#bi!U#bi~O#c#bi~P%&nO#c;_O~P%&nOQ#lOx#YOy#ZO{#[O!d#WO!f#XO!l#lO#c;_O#d;`O#e;`O#f;`O'rROZ#bi!c#bi#g#bi#h#bi#i#bi#j#bi#k#bi#m#bi#o#bi#q#bi#r#bi#u#bi'}#bi(U#bi(V#bi!T#bi!U#bi~Ok#bi~P%(yOk;aO~P%(yOQ#lOk;aOx#YOy#ZO{#[O!d#WO!f#XO!l#lO#c;_O#d;`O#e;`O#f;`O#g;bO'rRO#m#bi#o#bi#q#bi#r#bi#u#bi'}#bi(U#bi(V#bi!T#bi!U#bi~OZ#bi!c#bi#h#bi#i#bi#j#bi#k#bi~P%+UOZ;mO!c;cO#h;cO#i;cO#j;lO#k;cO~P%+UOQ#lOZ;mOk;aOx#YOy#ZO{#[O!c;cO!d#WO!f#XO!l#lO#c;_O#d;`O#e;`O#f;`O#g;bO#h;cO#i;cO#j;lO#k;cO#m;dO'rRO#o#bi#q#bi#r#bi#u#bi'}#bi(V#bi!T#bi!U#bi~O(U#bi~P%-pO(U#]O~P%-pOQ#lOZ;mOk;aOx#YOy#ZO{#[O!c;cO!d#WO!f#XO!l#lO#c;_O#d;`O#e;`O#f;`O#g;bO#h;cO#i;cO#j;lO#k;cO#m;dO#o;fO'rRO(U#]O#q#bi#r#bi#u#bi'}#bi!T#bi!U#bi~O(V#bi~P%/{O(V#^O~P%/{OQ#lOZ;mOk;aOx#YOy#ZO{#[O!c;cO!d#WO!f#XO!l#lO#c;_O#d;`O#e;`O#f;`O#g;bO#h;cO#i;cO#j;lO#k;cO#m;dO#o;fO#q;hO'rRO(U#]O(V#^O~O#r#bi#u#bi'}#bi!T#bi!U#bi~P%2WO_#sy!T#sy'e#sy'a#sy!Q#sy!e#syo#sy!V#sy%]#sy!_#sy~P!-ROP=oOx(mO{(nO(U(pO(V(rO~OQ#biZ#bik#biy#bi!c#bi!d#bi!f#bi!l#bi#c#bi#d#bi#e#bi#f#bi#g#bi#h#bi#i#bi#j#bi#k#bi#m#bi#o#bi#q#bi#r#bi#u#bi'r#bi'}#bi!T#bi!U#bi~P%5OO#u'qX!U'qX~P!HZO#u#vi!T#vi!U#vi~P#0aO!U5tO~O!T'Qa!U'Qa~P#0aO!_#UO'}'SO!T'Ra!e'Ra~O!T-zO!e([i~O!T-zO!_#UO!e([i~Oe$qq!T$qq#T$qq#u$qq~P!&VO!Q'Ta!T'Ta~P!G[O!_5{O~O!T.SO!Q(]i~P!G[O!T.SO!Q(]i~O!Q6PO~O!_#UO#k6UO~Ok6VO!_#UO'}'SO~O!Q6XO~Oe$sq!T$sq#T$sq#u$sq~P!&VO_$ey!T$ey'e$ey'a$ey!Q$ey!e$eyo$ey!V$ey%]$ey!_$ey~P!-RO!T3VO!V(^a~O_#Wy!T#Wy'e#Wy'a#Wy!Q#Wy!e#Wyo#Wy!V#Wy%]#Wy!_#Wy~P!-ROZ6^O~O]6`O'j*RO~O!T/SO!U(di~O]6cO~O^6dO~O!_4tO~O's'lO!T'YX!U'YX~O!T3nO!U(aa~O!f$mO'n$bO_'xX!_'xX!l'xX#T'xX'e'xX'}'xX~O'j6mO~P,RO!u;WO!y6oO!z6nO!{6nO#P1PO#Q1PO~P$%_O_$pO!_#UO!l1UO#T1SO'e$pO'}'SO~O!U6rO~P$BTO]&VOl&VO{6sO's)TO'|+zO~O!Y6wO!Z6vO![6vO#P1PO#Q1PO'|+zO~P!AQO!Y6wO!Z6vO![6vO!z6xO!{6xO#P1PO#Q1PO'|+zO~P!AQO!Z6vO![6vO'k$vO's)TO'|+zO~O!V/oO~O!V/oO%]6zO~O!V/oO%]6zO~P!G[OP7PO!V/oO!q7OO%]6zO~OZ7UO!T']a!U']a~O!T/{O!U(bi~O]7XO~O!e7YO~O!e7ZO~O!e7[O~O!e7[O~P$}O_7^O~O!_7aO~O!e7bO~O!T(Si!U(Si~P#0aO_$pO#T7iO'e$pO~O_$pO!_#UO#T7iO'e$pO~O!Z7mO![7mO'|+zO~P!AQO_$pO!_#UO!f$mO!l7nO#T7iO'e$pO'n$bO'}'SO~O!Y7oO!Z7mO![7mO'|+zO~P!AQO!Y7oO!Z7mO![7mO!|7rO#P7sO#Q7sO'|+zO~P!AQO_$pO!_#UO!l7nO#T7iO'e$pO'}'SO~O_$pO'e$pO~P!-RO!T'WO!e(Oy~O!T(Py!e(Py_(Py'e(Py~P!-RO!V&cO%]7xO~O!V&cO%]7xO~P!G[O#`$qqQ$qqZ$qq_$qqk$qqy$qq!T$qq!c$qq!d$qq!f$qq!l$qq#c$qq#d$qq#e$qq#f$qq#g$qq#h$qq#i$qq#j$qq#k$qq#m$qq#o$qq#q$qq#r$qq'e$qq'r$qq'}$qq!e$qq!Q$qq'a$qq!V$qq#T$qqo$qq%]$qq!_$qq~P!G[O#`$sqQ$sqZ$sq_$sqk$sqy$sq!T$sq!c$sq!d$sq!f$sq!l$sq#c$sq#d$sq#e$sq#f$sq#g$sq#h$sq#i$sq#j$sq#k$sq#m$sq#o$sq#q$sq#r$sq'e$sq'r$sq'}$sq!e$sq!Q$sq'a$sq!V$sq#T$sqo$sq%]$sq!_$sq~P!G[O!T&xi!e&xi~P!-RO#u#Wq!T#Wq!U#Wq~P#0aOx.nOy.nO{.oOPua(Uua(Vua!Uua~OQuaZuakua!cua!dua!fua!lua#cua#dua#eua#fua#gua#hua#iua#jua#kua#mua#oua#qua#rua#uua'rua'}ua!Tua~P%LmOx(mO{(nOP$ha(U$ha(V$ha!U$ha~OQ$haZ$hak$hay$ha!c$ha!d$ha!f$ha!l$ha#c$ha#d$ha#e$ha#f$ha#g$ha#h$ha#i$ha#j$ha#k$ha#m$ha#o$ha#q$ha#r$ha#u$ha'r$ha'}$ha!T$ha~P%NtOx(mO{(nOP$ja(U$ja(V$ja!U$ja~OQ$jaZ$jak$jay$ja!c$ja!d$ja!f$ja!l$ja#c$ja#d$ja#e$ja#f$ja#g$ja#h$ja#i$ja#j$ja#k$ja#m$ja#o$ja#q$ja#r$ja#u$ja'r$ja'}$ja!T$ja~P&!{OQ$xaZ$xak$xay$xa!c$xa!d$xa!f$xa!l$xa#c$xa#d$xa#e$xa#f$xa#g$xa#h$xa#i$xa#j$xa#k$xa#m$xa#o$xa#q$xa#r$xa#u$xa'r$xa'}$xa!T$xa!U$xa~P%5OO#u$dq!T$dq!U$dq~P#0aO#u$eq!T$eq!U$eq~P#0aO!U8RO~O#u8SO~P!&VO!_#UO!T'Ri!e'Ri~O!_#UO'}'SO!T'Ri!e'Ri~O!T-zO!e([q~O!Q'Ti!T'Ti~P!G[O!T.SO!Q(]q~O!Q8YO~P!G[O!Q8YO~Oe'py!T'py~P!&VO!T'Wa!V'Wa~P!G[O!V%Pq_%Pq!T%Pq'e%Pq~P!G[OZ8_O~O!T/SO!U(dq~O]8bO~O#T8cO!T'Ya!U'Ya~O!T3nO!U(ai~P#0aOQ[XZ[Xk[Xx[Xy[X{[X!Q[X!T[X!c[X!d[X!f[X!l[X#T[X#`dX#c[X#d[X#e[X#f[X#g[X#h[X#i[X#j[X#k[X#m[X#o[X#q[X#r[X#w[X'r[X'}[X(U[X(V[X~O!_$}X#k$}X~P&*pO#P5UO#Q5UO~P$%_O!z8gO!{8gO#P5UO#Q5UO~P$%_O!Z8jO![8jO'k$vO's)TO'|+zO~O!Y8mO!Z8jO![8jO#P5UO#Q5UO'|+zO~P!AQO!V/oO%]8pO~O!V/oO%]8pO~P!G[O]8wO's8vO~O!T/{O!U(bq~O!e8yO~O!e8yO~P$}O!e8{O~O!e8|O~O#T9OO!T#]y!U#]y~O!T#]y!U#]y~P#0aO_$pO#T9RO'e$pO~O_$pO!_#UO#T9RO'e$pO~O!Z9WO![9WO'|+zO~P!AQO_$pO!_#UO!l9XO#T9RO'e$pO'}'SO~O!f$mO'n$bO~P&0|O!Y9YO!Z9WO![9WO'|+zO~P!AQO!V&cO%]9^O~O!V&cO%]9^O~P!G[O#u#sy!T#sy!U#sy~P#0aOQ$qiZ$qik$qiy$qi!c$qi!d$qi!f$qi!l$qi#c$qi#d$qi#e$qi#f$qi#g$qi#h$qi#i$qi#j$qi#k$qi#m$qi#o$qi#q$qi#r$qi#u$qi'r$qi'}$qi!T$qi!U$qi~P%5OOx(mO{(nO(V(rOP%Ti(U%Ti!U%Ti~OQ%TiZ%Tik%Tiy%Ti!c%Ti!d%Ti!f%Ti!l%Ti#c%Ti#d%Ti#e%Ti#f%Ti#g%Ti#h%Ti#i%Ti#j%Ti#k%Ti#m%Ti#o%Ti#q%Ti#r%Ti#u%Ti'r%Ti'}%Ti!T%Ti~P&4cOx(mO{(nOP%Vi(U%Vi(V%Vi!U%Vi~OQ%ViZ%Vik%Viy%Vi!c%Vi!d%Vi!f%Vi!l%Vi#c%Vi#d%Vi#e%Vi#f%Vi#g%Vi#h%Vi#i%Vi#j%Vi#k%Vi#m%Vi#o%Vi#q%Vi#r%Vi#u%Vi'r%Vi'}%Vi!T%Vi~P&6jO#u$ey!T$ey!U$ey~P#0aO#u#Wy!T#Wy!U#Wy~P#0aO!_#UO!T'Rq!e'Rq~O!T-zO!e([y~O!Q'Tq!T'Tq~P!G[O!Q9dO~P!G[O!T/SO!U(dy~O!T3nO!U(aq~O#P7sO#Q7sO~P$%_O!Z9nO![9nO'k$vO's)TO'|+zO~O!V/oO%]9qO~O!V/oO%]9qO~P!G[O!e9tO~O_$pO#T9zO'e$pO~O_$pO!_#UO#T9zO'e$pO~O!Z9}O![9}O'|+zO~P!AQO_$pO!_#UO!l:OO#T9zO'e$pO'}'SO~OQ$qqZ$qqk$qqy$qq!c$qq!d$qq!f$qq!l$qq#c$qq#d$qq#e$qq#f$qq#g$qq#h$qq#i$qq#j$qq#k$qq#m$qq#o$qq#q$qq#r$qq#u$qq'r$qq'}$qq!T$qq!U$qq~P%5OOQ$sqZ$sqk$sqy$sq!c$sq!d$sq!f$sq!l$sq#c$sq#d$sq#e$sq#f$sq#g$sq#h$sq#i$sq#j$sq#k$sq#m$sq#o$sq#q$sq#r$sq#u$sq'r$sq'}$sq!T$sq!U$sq~P%5OOe%X!Z!T%X!Z#T%X!Z#u%X!Z~P!&VO!T'Yq!U'Yq~P#0aO!T#]!Z!U#]!Z~P#0aO_$pO#T:aO'e$pO~O_$pO!_#UO#T:aO'e$pO~O#`%X!ZQ%X!ZZ%X!Z_%X!Zk%X!Zy%X!Z!T%X!Z!c%X!Z!d%X!Z!f%X!Z!l%X!Z#c%X!Z#d%X!Z#e%X!Z#f%X!Z#g%X!Z#h%X!Z#i%X!Z#j%X!Z#k%X!Z#m%X!Z#o%X!Z#q%X!Z#r%X!Z'e%X!Z'r%X!Z'}%X!Z!e%X!Z!Q%X!Z'a%X!Z!V%X!Z#T%X!Zo%X!Z%]%X!Z!_%X!Z~P!G[O_$pO#T:oO'e$pO~OP=nOx(mO{(nO(U(pO(V(rO~O]#Sal#Sa!U#Sa!Y#Sa!Z#Sa![#Sa!u#Sa!y#Sa!z#Sa!{#Sa#P#Sa#Q#Sa'k#Sa's#Sa'|#Sa~P&D[OQ%X!ZZ%X!Zk%X!Zy%X!Z!c%X!Z!d%X!Z!f%X!Z!l%X!Z#c%X!Z#d%X!Z#e%X!Z#f%X!Z#g%X!Z#h%X!Z#i%X!Z#j%X!Z#k%X!Z#m%X!Z#o%X!Z#q%X!Z#r%X!Z#u%X!Z'r%X!Z'}%X!Z!T%X!Z!U%X!Z~P%5OO]ualua!Yua!Zua![ua!uua!yua!zua!{ua#Pua#Qua'kua'sua'|ua~P%LmO]$hal$ha!Y$ha!Z$ha![$ha!u$ha!y$ha!z$ha!{$ha#P$ha#Q$ha'k$ha's$ha'|$ha~P%NtO]$jal$ja!Y$ja!Z$ja![$ja!u$ja!y$ja!z$ja!{$ja#P$ja#Q$ja'k$ja's$ja'|$ja~P&!{O]$xal$xa!U$xa!Y$xa!Z$xa![$xa!u$xa!y$xa!z$xa!{$xa#P$xa#Q$xa'k$xa's$xa'|$xa~P&D[O]%Til%Ti!Y%Ti!Z%Ti![%Ti!u%Ti!y%Ti!z%Ti!{%Ti#P%Ti#Q%Ti'k%Ti's%Ti'|%Ti~P&4cO]%Vil%Vi!Y%Vi!Z%Vi![%Vi!u%Vi!y%Vi!z%Vi!{%Vi#P%Vi#Q%Vi'k%Vi's%Vi'|%Vi~P&6jO]$qil$qi!U$qi!Y$qi!Z$qi![$qi!u$qi!y$qi!z$qi!{$qi#P$qi#Q$qi'k$qi's$qi'|$qi~P&D[O]$qql$qq!U$qq!Y$qq!Z$qq![$qq!u$qq!y$qq!z$qq!{$qq#P$qq#Q$qq'k$qq's$qq'|$qq~P&D[O]$sql$sq!U$sq!Y$sq!Z$sq![$sq!u$sq!y$sq!z$sq!{$sq#P$sq#Q$sq'k$sq's$sq'|$sq~P&D[O]%X!Zl%X!Z!U%X!Z!Y%X!Z!Z%X!Z![%X!Z!u%X!Z!y%X!Z!z%X!Z!{%X!Z#P%X!Z#Q%X!Z'k%X!Z's%X!Z'|%X!Z~P&D[Oo'tX~P/WO!QdX!TdX#TdX~P&*pOQ[XZ[Xk[Xx[Xy[X{[X!T[X!TdX!c[X!d[X!f[X!l[X#T[X#TdX#`dX#c[X#d[X#e[X#f[X#g[X#h[X#i[X#j[X#k[X#m[X#o[X#q[X#r[X#w[X'r[X'}[X(U[X(V[X~O!_dX!e[X!edX'}dX~P'$ZOQ;VOR;VO]gOb=ZOc!`OigOk;VOlgOmgOrgOt;VOv;VO{SO!OgO!PgO!VTO!a;YO!fVO!i;VO!j;VO!k;VO!l;VO!m;VO!p!_O#|!bO$QbO'j'|O'rRO'|WO(Z=XO~O]$SOi$cOk$TOl$SOm$SOr$dOt$eOv;pO{$[O!V$]O!a=aO!f$XO#_;yO#|$iO$i;sO$k;vO$n$jO'j'dO'n$bO'r$UO~O!T;jO!U$ga~O]$SOi$cOk$TOl$SOm$SOr$dOt$eOv;qO{$[O!V$]O!a=bO!f$XO#_;zO#|$iO$i;tO$k;wO$n$jO'j'dO'n$bO'r$UO~O#l(TO~P'*^O!U[X!UdX~P'$ZO!_;^O~O#`;]O~O!_#UO#`;]O~O#T;nO~O#k;cO~O#T;{O!T(SX!U(SX~O#T;nO!T(QX!U(QX~O#`;|O~Oe TypeParamList TypeDefinition ThisType this LiteralType ArithOp Number BooleanLiteral TemplateType InterpolationEnd Interpolation NullType null VoidType void TypeofType typeof MemberExpression . ?. PropertyName [ TemplateString Interpolation super RegExp ] ArrayExpression Spread , } { ObjectExpression Property async get set PropertyDefinition Block : NewExpression new TypeArgList CompareOp < ) ( ArgList UnaryExpression await yield delete LogicOp BitOp ParenthesizedExpression ClassExpression class extends ClassBody MethodDeclaration Decorator @ MemberExpression PrivatePropertyName CallExpression Privacy static abstract override PrivatePropertyDefinition PropertyDeclaration readonly accessor Optional TypeAnnotation Equals StaticBlock FunctionExpression ArrowFunction ParamList ParamList ArrayPattern ObjectPattern PatternProperty Privacy readonly Arrow MemberExpression BinaryExpression ArithOp ArithOp ArithOp ArithOp BitOp CompareOp instanceof satisfies in const CompareOp BitOp BitOp BitOp LogicOp LogicOp ConditionalExpression LogicOp LogicOp AssignmentExpression UpdateOp PostfixExpression CallExpression TaggedTemplateExpression DynamicImport import ImportMeta JSXElement JSXSelfCloseEndTag JSXStartTag JSXSelfClosingTag JSXIdentifier JSXBuiltin JSXIdentifier JSXNamespacedName JSXMemberExpression JSXSpreadAttribute JSXAttribute JSXAttributeValue JSXEscape JSXEndTag JSXOpenTag JSXFragmentTag JSXText JSXEscape JSXStartCloseTag JSXCloseTag PrefixCast ArrowFunction TypeParamList SequenceExpression KeyofType keyof UniqueType unique ImportType InferredType infer TypeName ParenthesizedType FunctionSignature ParamList NewSignature IndexedType TupleType Label ArrayType ReadonlyType ObjectType MethodType PropertyType IndexSignature PropertyDefinition CallSignature TypePredicate is NewSignature new UnionType LogicOp IntersectionType LogicOp ConditionalType ParameterizedType ClassDeclaration abstract implements type VariableDeclaration let var TypeAliasDeclaration InterfaceDeclaration interface EnumDeclaration enum EnumBody NamespaceDeclaration namespace module AmbientDeclaration declare GlobalDeclaration global ClassDeclaration ClassBody MethodDeclaration AmbientFunctionDeclaration ExportGroup VariableName VariableName ImportDeclaration ImportGroup ForStatement for ForSpec ForInSpec ForOfSpec of WhileStatement while WithStatement with DoStatement do IfStatement if else SwitchStatement switch SwitchBody CaseLabel case DefaultLabel TryStatement try CatchClause catch FinallyClause finally ReturnStatement return ThrowStatement throw BreakStatement break ContinueStatement continue DebuggerStatement debugger LabeledStatement ExpressionStatement SingleExpression",maxTerm:345,context:yI,nodeProps:[["closedBy",4,"InterpolationEnd",43,"]",53,"}",68,")",140,"JSXSelfCloseEndTag JSXEndTag",156,"JSXEndTag"],["group",-26,8,15,17,60,195,199,202,203,205,208,211,222,224,230,232,234,236,239,245,251,253,255,257,259,261,262,"Statement",-30,12,13,25,28,29,34,44,46,47,49,54,62,70,76,77,99,100,109,110,127,130,132,133,134,135,137,138,158,159,161,"Expression",-23,24,26,30,33,35,37,162,164,166,167,169,170,171,173,174,175,177,178,179,189,191,193,194,"Type",-3,81,92,98,"ClassItem"],["openedBy",31,"InterpolationStart",48,"[",52,"{",67,"(",139,"JSXStartTag",151,"JSXStartTag JSXStartCloseTag"]],propSources:[xI],skippedNodes:[0,5,6],repeatNodeCount:29,tokenData:"#2k~R!bOX%ZXY%uYZ'kZ[%u[]%Z]^'k^p%Zpq%uqr(Rrs)mst7]tu9guvlxyJcyzJyz{Ka{|Lm|}MW}!OLm!O!PMn!P!Q!$v!Q!R!Er!R![!G_![!]!Nc!]!^!N{!^!_# c!_!`#!`!`!a##d!a!b#%s!b!c#'h!c!}9g!}#O#(O#O#P%Z#P#Q#(f#Q#R#(|#R#S9g#S#T#)g#T#o#)}#o#p#,w#p#q#,|#q#r#-j#r#s#.S#s$f%Z$f$g%u$g#BY9g#BY#BZ#.j#BZ$IS9g$IS$I_#.j$I_$I|9g$I|$I}#1X$I}$JO#1X$JO$JT9g$JT$JU#.j$JU$KV9g$KV$KW#.j$KW&FU9g&FU&FV#.j&FV;'S9g;'S;=`Rw!^%Z!_!`YU$`W#q&lO!^%Z!_!`s]$`W]&ZOY>lYZ?lZw>lwx,jx!^>l!^!_@|!_#O>l#O#PE_#P#o>l#o#p@|#p;'S>l;'S;=`J]<%lO>l,^?qX$`WOw?lwx+_x!^?l!^!_@^!_#o?l#o#p@^#p;'S?l;'S;=`@v<%lO?l,U@aTOw@^wx,Xx;'S@^;'S;=`@p<%lO@^,U@sP;=`<%l@^,^@yP;=`<%l?l1aARX]&ZOY@|YZ@^Zw@|wx-tx#O@|#O#PAn#P;'S@|;'S;=`EX<%lO@|1aAqUOw@|wxBTx;'S@|;'S;=`Dg;=`<%lBt<%lO@|1aB[W$Z,U]&ZOYBtZwBtwx/px#OBt#O#PCc#P;'SBt;'S;=`Da<%lOBt&ZByW]&ZOYBtZwBtwx/px#OBt#O#PCc#P;'SBt;'S;=`Da<%lOBt&ZCfRO;'SBt;'S;=`Co;=`OBt&ZCtX]&ZOYBtZwBtwx/px#OBt#O#PCc#P;'SBt;'S;=`Da;=`<%lBt<%lOBt&ZDdP;=`<%lBt1aDlX]&ZOYBtZwBtwx/px#OBt#O#PCc#P;'SBt;'S;=`Da;=`<%l@|<%lOBt1aE[P;=`<%l@|1iEdY$`WOw>lwxFSx!^>l!^!_@|!_#o>l#o#p@|#p;'S>l;'S;=`Ik;=`<%lBt<%lO>l1iF]]$Z,U$`W]&ZOYGUYZ%ZZwGUwx4hx!^GU!^!_Bt!_#OGU#O#PHU#P#oGU#o#pBt#p;'SGU;'S;=`Ie<%lOGU&cG]]$`W]&ZOYGUYZ%ZZwGUwx4hx!^GU!^!_Bt!_#OGU#O#PHU#P#oGU#o#pBt#p;'SGU;'S;=`Ie<%lOGU&cHZW$`WO!^GU!^!_Bt!_#oGU#o#pBt#p;'SGU;'S;=`Hs;=`<%lBt<%lOGU&cHxX]&ZOYBtZwBtwx/px#OBt#O#PCc#P;'SBt;'S;=`Da;=`<%lGU<%lOBt&cIhP;=`<%lGU1iIpX]&ZOYBtZwBtwx/px#OBt#O#PCc#P;'SBt;'S;=`Da;=`<%l>l<%lOBt1iJ`P;=`<%l>l,TJjT!f+{$`WO!^%Z!_#o%Z#p;'S%Z;'S;=`%o<%lO%Z$PKQT!e#w$`WO!^%Z!_#o%Z#p;'S%Z;'S;=`%o<%lO%Z)ZKjW$`W'k#e#f&lOz%Zz{LS{!^%Z!_!`q#P#Q!-n#Q#o!;l#o#p!6|#p;'S!;l;'S;=`!?i<%lO!;l7Z!q#P#Q!-n#Q#o!;l#o#p!6|#p;'S!;l;'S;=`!?i<%lO!;l7Z!={[$`WU7ROY!+TYZ%ZZ!^!+T!^!_!)o!_#O!+T#O#P!,O#P#Q!&V#Q#o!+T#o#p!)o#p;'S!+T;'S;=`!,p<%lO!+T7Z!>vZ$`WOY!;lYZ!.wZz!;lz{!TI[n]||-1},{term:311,get:n=>QI[n]||-1},{term:65,get:n=>PI[n]||-1}],tokenPrec:13429}),$I=[Ut("function ${name}(${params}) {\n ${}\n}",{label:"function",detail:"definition",type:"keyword"}),Ut("for (let ${index} = 0; ${index} < ${bound}; ${index}++) {\n ${}\n}",{label:"for",detail:"loop",type:"keyword"}),Ut("for (let ${name} of ${collection}) {\n ${}\n}",{label:"for",detail:"of loop",type:"keyword"}),Ut("do {\n ${}\n} while (${})",{label:"do",detail:"loop",type:"keyword"}),Ut("while (${}) {\n ${}\n}",{label:"while",detail:"loop",type:"keyword"}),Ut(`try { +`);i=r<0?t:t.slice(0,r)}return e+i.length>this.to?i.slice(0,this.to-e):i}prevLineEnd(){return this.atEnd?this.lineStart:this.lineStart-1}startContext(e,t,i=0){this.block=jl.create(e,i,this.lineStart+t,this.block.hash,this.lineStart+this.line.text.length),this.stack.push(this.block)}startComposite(e,t,i=0){this.startContext(this.parser.getNodeType(e),t,i)}addNode(e,t,i){typeof e=="number"&&(e=new ne(this.parser.nodeSet.types[e],Ts,Ts,(i??this.prevLineEnd())-t)),this.block.addChild(e,t-this.block.from)}addElement(e){this.block.addChild(e.toTree(this.parser.nodeSet),e.from-this.block.from)}addLeafElement(e,t){this.addNode(this.buffer.writeElements(Vu(t.children,e.marks),-t.from).finish(t.type,t.to-t.from),t.from)}finishContext(){let e=this.stack.pop(),t=this.stack[this.stack.length-1];t.addChild(e.toTree(this.parser.nodeSet),e.from-t.from),this.block=t}finish(){for(;this.stack.length>1;)this.finishContext();return this.addGaps(this.block.toTree(this.parser.nodeSet,this.lineStart))}addGaps(e){return this.ranges.length>1?Ib(this.ranges,0,e.topNode,this.ranges[0].from,this.dontInject):e}finishLeaf(e){for(let i of e.parsers)if(i.finish(this,e))return;let t=Vu(this.parser.parseInline(e.content,e.start),e.marks);this.addNode(this.buffer.writeElements(t,-e.start).finish(I.Paragraph,e.content.length),e.start)}elt(e,t,i,r){return typeof e=="string"?te(this.parser.getNodeType(e),t,i,r):new Db(e,t)}get buffer(){return new Eb(this.parser.nodeSet)}}function Ib(n,e,t,i,r){if(r.has(t.tree))return t.tree;let s=n[e].to,o=[],a=[],l=t.from+i;function h(c,u){for(;u?c>=s:c>s;){let f=n[e+1].from-s;i+=f,c+=f,e++,s=n[e].to}}for(let c=t.firstChild;c;c=c.nextSibling){h(c.from+i,!0);let u=c.from+i,f;c.to+i>s?(f=Ib(n,e,c,i,r),h(c.to+i,!1)):f=c.toTree(),o.push(f),a.push(u-l)}return h(t.to+i,!1),new ne(t.type,o,a,t.to+i-l,t.tree?t.tree.propValues:void 0)}class wh extends Qf{constructor(e,t,i,r,s,o,a,l,h){super(),this.nodeSet=e,this.blockParsers=t,this.leafBlockParsers=i,this.blockNames=r,this.endLeafBlock=s,this.skipContextMarkup=o,this.inlineParsers=a,this.inlineNames=l,this.wrappers=h,this.nodeTypes=Object.create(null);for(let c of e.types)this.nodeTypes[c.name]=c.id}createParse(e,t,i){let r=new P$(this,e,t,i);for(let s of this.wrappers)r=s(r,e,t,i);return r}configure(e){let t=Mu(e);if(!t)return this;let{nodeSet:i,skipContextMarkup:r}=this,s=this.blockParsers.slice(),o=this.leafBlockParsers.slice(),a=this.blockNames.slice(),l=this.inlineParsers.slice(),h=this.inlineNames.slice(),c=this.endLeafBlock.slice(),u=this.wrappers;if(Xs(t.defineNodes)){r=Object.assign({},r);let f=i.types.slice(),p;for(let g of t.defineNodes){let{name:O,block:y,composite:S,style:k}=typeof g=="string"?{name:g}:g;if(f.some(Q=>Q.name==O))continue;S&&(r[f.length]=(Q,A,R)=>S(A,R,Q.value));let $=f.length,x=S?["Block","BlockContext"]:y?$>=I.ATXHeading1&&$<=I.SetextHeading2?["Block","LeafBlock","Heading"]:["Block","LeafBlock"]:void 0;f.push(Ie.define({id:$,name:O,props:x&&[[_.group,x]]})),k&&(p||(p={}),Array.isArray(k)||k instanceof jt?p[O]=k:Object.assign(p,k))}i=new Fo(f),p&&(i=i.extend($s(p)))}if(Xs(t.props)&&(i=i.extend(...t.props)),Xs(t.remove))for(let f of t.remove){let p=this.blockNames.indexOf(f),g=this.inlineNames.indexOf(f);p>-1&&(s[p]=o[p]=void 0),g>-1&&(l[g]=void 0)}if(Xs(t.parseBlock))for(let f of t.parseBlock){let p=a.indexOf(f.name);if(p>-1)s[p]=f.parse,o[p]=f.leaf;else{let g=f.before?Aa(a,f.before):f.after?Aa(a,f.after)+1:a.length-1;s.splice(g,0,f.parse),o.splice(g,0,f.leaf),a.splice(g,0,f.name)}f.endLeaf&&c.push(f.endLeaf)}if(Xs(t.parseInline))for(let f of t.parseInline){let p=h.indexOf(f.name);if(p>-1)l[p]=f.parse;else{let g=f.before?Aa(h,f.before):f.after?Aa(h,f.after)+1:h.length-1;l.splice(g,0,f.parse),h.splice(g,0,f.name)}}return t.wrap&&(u=u.concat(t.wrap)),new wh(i,s,o,a,c,r,l,h,u)}getNodeType(e){let t=this.nodeTypes[e];if(t==null)throw new RangeError(`Unknown node type '${e}'`);return t}parseInline(e,t){let i=new $$(this,e,t);e:for(let r=t;r=0){r=a;continue e}}r++}return i.resolveMarkers(0)}}function Xs(n){return n!=null&&n.length>0}function Mu(n){if(!Array.isArray(n))return n;if(n.length==0)return null;let e=Mu(n[0]);if(n.length==1)return e;let t=Mu(n.slice(1));if(!t||!e)return e||t;let i=(o,a)=>(o||Ts).concat(a||Ts),r=e.wrap,s=t.wrap;return{props:i(e.props,t.props),defineNodes:i(e.defineNodes,t.defineNodes),parseBlock:i(e.parseBlock,t.parseBlock),parseInline:i(e.parseInline,t.parseInline),remove:i(e.remove,t.remove),wrap:r?s?(o,a,l,h)=>r(s(o,a,l,h),a,l,h):r:s}}function Aa(n,e){let t=n.indexOf(e);if(t<0)throw new RangeError(`Position specified relative to unknown parser ${e}`);return t}let Rb=[Ie.none];for(let n=1,e;e=I[n];n++)Rb[n]=Ie.define({id:n,name:e,props:n>=I.Escape?[]:[[_.group,n in vb?["Block","BlockContext"]:["Block","LeafBlock"]]]});const Ts=[];class Eb{constructor(e){this.nodeSet=e,this.content=[],this.nodes=[]}write(e,t,i,r=0){return this.content.push(e,t,i,4+r*4),this}writeElements(e,t=0){for(let i of e)i.writeTo(this,t);return this}finish(e,t){return ne.build({buffer:this.content,nodeSet:this.nodeSet,reused:this.nodes,topID:e,length:t})}}let No=class{constructor(e,t,i,r=Ts){this.type=e,this.from=t,this.to=i,this.children=r}writeTo(e,t){let i=e.content.length;e.writeElements(this.children,t),e.content.push(this.type,this.from+t,this.to+t,e.content.length+4-i)}toTree(e){return new Eb(e).writeElements(this.children,-this.from).finish(this.type,this.to-this.from)}};class Db{constructor(e,t){this.tree=e,this.from=t}get to(){return this.from+this.tree.length}get type(){return this.tree.type.id}get children(){return Ts}writeTo(e,t){e.nodes.push(this.tree),e.content.push(e.nodes.length-1,this.from+t,this.to+t,-1)}toTree(){return this.tree}}function te(n,e,t,i){return new No(n,e,t,i)}const Nb={resolve:"Emphasis",mark:"EmphasisMark"},Bb={resolve:"Emphasis",mark:"EmphasisMark"},Ls={},qg={};class Ft{constructor(e,t,i,r){this.type=e,this.from=t,this.to=i,this.side=r}}const Mg="!\"#$%&'()*+,-./:;<=>?@[\\]^_`{|}~";let Bo=/[!"#$%&'()*+,\-.\/:;<=>?@\[\\\]^_`{|}~\xA1\u2010-\u2027]/;try{Bo=new RegExp("[\\p{Pc}|\\p{Pd}|\\p{Pe}|\\p{Pf}|\\p{Pi}|\\p{Po}|\\p{Ps}]","u")}catch{}const nc={Escape(n,e,t){if(e!=92||t==n.end-1)return-1;let i=n.char(t+1);for(let r=0;r]+|[a-z\d.!#$%&'*+/=?^_`{|}~-]+@[a-z\d](?:[a-z\d-]{0,61}[a-z\d])?(?:\.[a-z\d](?:[a-z\d-]{0,61}[a-z\d])?)*)>/i.exec(i);if(r)return n.append(te(I.URL,t,t+1+r[0].length));let s=/^!--[^>](?:-[^-]|[^-])*?-->/i.exec(i);if(s)return n.append(te(I.Comment,t,t+1+s[0].length));let o=/^\?[^]*?\?>/.exec(i);if(o)return n.append(te(I.ProcessingInstruction,t,t+1+o[0].length));let a=/^(?:![A-Z][^]*?>|!\[CDATA\[[^]*?\]\]>|\/\s*[a-zA-Z][\w-]*\s*>|\s*[a-zA-Z][\w-]*(\s+[a-zA-Z:_][\w-.:]*(?:\s*=\s*(?:[^\s"'=<>`]+|'[^']*'|"[^"]*"))?)*\s*(\/\s*)?>)/.exec(i);return a?n.append(te(I.HTMLTag,t,t+1+a[0].length)):-1},Emphasis(n,e,t){if(e!=95&&e!=42)return-1;let i=t+1;for(;n.char(i)==e;)i++;let r=n.slice(t-1,t),s=n.slice(i,i+1),o=Bo.test(r),a=Bo.test(s),l=/\s|^$/.test(r),h=/\s|^$/.test(s),c=!h&&(!a||l||o),u=!l&&(!o||h||a),f=c&&(e==42||!u||o),p=u&&(e==42||!c||a);return n.append(new Ft(e==95?Nb:Bb,t,i,(f?1:0)|(p?2:0)))},HardBreak(n,e,t){if(e==92&&n.char(t+1)==10)return n.append(te(I.HardBreak,t,t+2));if(e==32){let i=t+1;for(;n.char(i)==32;)i++;if(n.char(i)==10&&i>=t+2)return n.append(te(I.HardBreak,t,i+1))}return-1},Link(n,e,t){return e==91?n.append(new Ft(Ls,t,t+1,1)):-1},Image(n,e,t){return e==33&&n.char(t+1)==91?n.append(new Ft(qg,t,t+2,1)):-1},LinkEnd(n,e,t){if(e!=93)return-1;for(let i=n.parts.length-1;i>=0;i--){let r=n.parts[i];if(r instanceof Ft&&(r.type==Ls||r.type==qg)){if(!r.side||n.skipSpace(r.to)==t&&!/[(\[]/.test(n.slice(t+1,t+2)))return n.parts[i]=null,-1;let s=n.takeContent(i),o=n.parts[i]=A$(n,s,r.type==Ls?I.Link:I.Image,r.from,t+1);if(r.type==Ls)for(let a=0;ae?te(I.URL,e+t,s+t):s==n.length?null:!1}}function Mb(n,e,t){let i=n.charCodeAt(e);if(i!=39&&i!=34&&i!=40)return!1;let r=i==40?41:i;for(let s=e+1,o=!1;s=this.end?-1:this.text.charCodeAt(e-this.offset)}get end(){return this.offset+this.text.length}slice(e,t){return this.text.slice(e-this.offset,t-this.offset)}append(e){return this.parts.push(e),e.to}addDelimiter(e,t,i,r,s){return this.append(new Ft(e,t,i,(r?1:0)|(s?2:0)))}addElement(e){return this.append(e)}resolveMarkers(e){for(let i=e;i=e;l--){let O=this.parts[l];if(O instanceof Ft&&O.side&1&&O.type==r.type&&!(s&&(r.side&1||O.side&2)&&(O.to-O.from+o)%3==0&&((O.to-O.from)%3||o%3))){a=O;break}}if(!a)continue;let h=r.type.resolve,c=[],u=a.from,f=r.to;if(s){let O=Math.min(2,a.to-a.from,o);u=a.to-O,f=r.from+O,h=O==1?"Emphasis":"StrongEmphasis"}a.type.mark&&c.push(this.elt(a.type.mark,u,a.to));for(let O=l+1;O=0;t--){let i=this.parts[t];if(i instanceof Ft&&i.type==e)return t}return null}takeContent(e){let t=this.resolveMarkers(e);return this.parts.length=e,t}skipSpace(e){return oo(this.text,e-this.offset)+this.offset}elt(e,t,i,r){return typeof e=="string"?te(this.parser.getNodeType(e),t,i,r):new Db(e,t)}}function Vu(n,e){if(!e.length)return n;if(!n.length)return e;let t=n.slice(),i=0;for(let r of e){for(;i(e?e-1:0))return!1;if(this.fragmentEnd<0){let s=this.fragment.to;for(;s>0&&this.input.read(s-1,s)!=` +`;)s--;this.fragmentEnd=s?s-1:0}let i=this.cursor;i||(i=this.cursor=this.fragment.tree.cursor(),i.firstChild());let r=e+this.fragment.offset;for(;i.to<=r;)if(!i.parent())return!1;for(;;){if(i.from>=r)return this.fragment.from<=t;if(!i.childAfter(r))return!1}}matches(e){let t=this.cursor.tree;return t&&t.prop(_.contextHash)==e}takeNodes(e){let t=this.cursor,i=this.fragment.offset,r=this.fragmentEnd-(this.fragment.openEnd?1:0),s=e.absoluteLineStart,o=s,a=e.block.children.length,l=o,h=a;for(;;){if(t.to-i>r){if(t.type.isAnonymous&&t.firstChild())continue;break}if(e.dontInject.add(t.tree),e.addNode(t.tree,t.from-i),t.type.is("Block")&&(C$.indexOf(t.type.id)<0?(o=t.to-i,a=e.block.children.length):(o=l,a=h,l=t.to-i,h=e.block.children.length)),!t.nextSibling())break}for(;e.block.children.length>a;)e.block.children.pop(),e.block.positions.pop();return o-s}};const R$=$s({"Blockquote/...":b.quote,HorizontalRule:b.contentSeparator,"ATXHeading1/... SetextHeading1/...":b.heading1,"ATXHeading2/... SetextHeading2/...":b.heading2,"ATXHeading3/...":b.heading3,"ATXHeading4/...":b.heading4,"ATXHeading5/...":b.heading5,"ATXHeading6/...":b.heading6,"Comment CommentBlock":b.comment,Escape:b.escape,Entity:b.character,"Emphasis/...":b.emphasis,"StrongEmphasis/...":b.strong,"Link/... Image/...":b.link,"OrderedList/... BulletList/...":b.list,"BlockQuote/...":b.quote,"InlineCode CodeText":b.monospace,URL:b.url,"HeaderMark HardBreak QuoteMark ListMark LinkMark EmphasisMark CodeMark":b.processingInstruction,"CodeInfo LinkLabel":b.labelName,LinkTitle:b.string,Paragraph:b.content}),E$=new wh(new Fo(Rb).extend(R$),Object.keys(Pa).map(n=>Pa[n]),Object.keys(Pa).map(n=>x$[n]),Object.keys(Pa),T$,vb,Object.keys(nc).map(n=>nc[n]),Object.keys(nc),[]);function D$(n,e,t){let i=[];for(let r=n.firstChild,s=e;;r=r.nextSibling){let o=r?r.from:t;if(o>s&&i.push({from:s,to:o}),!r)break;s=r.to}return i}function N$(n){let{codeParser:e,htmlParser:t}=n;return{wrap:ny((r,s)=>{let o=r.type.id;if(e&&(o==I.CodeBlock||o==I.FencedCode)){let a="";if(o==I.FencedCode){let h=r.node.getChild(I.CodeInfo);h&&(a=s.read(h.from,h.to))}let l=e(a);if(l)return{parser:l,overlay:h=>h.type.id==I.CodeText}}else if(t&&(o==I.HTMLBlock||o==I.HTMLTag))return{parser:t,overlay:D$(r.node,r.from,r.to)};return null})}}const B$={resolve:"Strikethrough",mark:"StrikethroughMark"},q$={defineNodes:[{name:"Strikethrough",style:{"Strikethrough/...":b.strikethrough}},{name:"StrikethroughMark",style:b.processingInstruction}],parseInline:[{name:"Strikethrough",parse(n,e,t){if(e!=126||n.char(t+1)!=126||n.char(t+2)==126)return-1;let i=n.slice(t-1,t),r=n.slice(t+2,t+3),s=/\s|^$/.test(i),o=/\s|^$/.test(r),a=Bo.test(i),l=Bo.test(r);return n.addDelimiter(B$,t,t+2,!o&&(!l||s||a),!s&&(!a||o||l))},after:"Emphasis"}]};function ao(n,e,t=0,i,r=0){let s=0,o=!0,a=-1,l=-1,h=!1,c=()=>{i.push(n.elt("TableCell",r+a,r+l,n.parser.parseInline(e.slice(a,l),r+a)))};for(let u=t;u-1)&&s++,o=!1,i&&(a>-1&&c(),i.push(n.elt("TableDelimiter",u+r,u+r+1))),a=l=-1):(h||f!=32&&f!=9)&&(a<0&&(a=u),l=u+1),h=!h&&f==92}return a>-1&&(s++,i&&c()),s}function Vg(n,e){for(let t=e;tr instanceof Xg)||!Vg(e.text,e.basePos))return!1;let i=n.scanLine(n.absoluteLineEnd+1).text;return Xb.test(i)&&ao(n,e.text,e.basePos)==ao(n,i,e.basePos)},before:"SetextHeading"}]};class V${nextLine(){return!1}finish(e,t){return e.addLeafElement(t,e.elt("Task",t.start,t.start+t.content.length,[e.elt("TaskMarker",t.start,t.start+3),...e.parser.parseInline(t.content.slice(3),t.start+3)])),!0}}const X$={defineNodes:[{name:"Task",block:!0,style:b.list},{name:"TaskMarker",style:b.atom}],parseBlock:[{name:"TaskList",leaf(n,e){return/^\[[ xX]\]/.test(e.content)&&n.parentType().name=="ListItem"?new V$:null},after:"SetextHeading"}]},L$=[M$,X$,q$];function Lb(n,e,t){return(i,r,s)=>{if(r!=n||i.char(s+1)==n)return-1;let o=[i.elt(t,s,s+1)];for(let a=s+1;at%3==0).concat(this.state)}]@${this.pos}${this.score?"!"+this.score:""}`}static start(e,t,i=0){let r=e.parser.context;return new Fl(e,[],t,i,i,0,[],0,r?new Ug(r,r.start):null,0,null)}get context(){return this.curContext?this.curContext.context:null}pushState(e,t){this.stack.push(this.state,t,this.bufferBase+this.buffer.length),this.state=e}reduce(e){let t=e>>19,i=e&65535,{parser:r}=this.p,s=r.dynamicPrecedence(i);if(s&&(this.score+=s),t==0){this.pushState(r.getGoto(this.state,i,!0),this.reducePos),io;)this.stack.pop();this.reduceContext(i,a)}storeNode(e,t,i,r=4,s=!1){if(e==0&&(!this.stack.length||this.stack[this.stack.length-1]0&&o.buffer[a-4]==0&&o.buffer[a-1]>-1){if(t==i)return;if(o.buffer[a-2]>=t){o.buffer[a-2]=i;return}}}if(!s||this.pos==i)this.buffer.push(e,t,i,r);else{let o=this.buffer.length;if(o>0&&this.buffer[o-4]!=0)for(;o>0&&this.buffer[o-2]>i;)this.buffer[o]=this.buffer[o-4],this.buffer[o+1]=this.buffer[o-3],this.buffer[o+2]=this.buffer[o-2],this.buffer[o+3]=this.buffer[o-1],o-=4,r>4&&(r-=4);this.buffer[o]=e,this.buffer[o+1]=t,this.buffer[o+2]=i,this.buffer[o+3]=r}}shift(e,t,i){let r=this.pos;if(e&131072)this.pushState(e&65535,this.pos);else if(e&262144)this.pos=i,this.shiftContext(t,r),t<=this.p.parser.maxNode&&this.buffer.push(t,r,i,4);else{let s=e,{parser:o}=this.p;(i>this.pos||t<=o.maxNode)&&(this.pos=i,o.stateFlag(s,1)||(this.reducePos=i)),this.pushState(s,r),this.shiftContext(t,r),t<=o.maxNode&&this.buffer.push(t,r,i,4)}}apply(e,t,i){e&65536?this.reduce(e):this.shift(e,t,i)}useNode(e,t){let i=this.p.reused.length-1;(i<0||this.p.reused[i]!=e)&&(this.p.reused.push(e),i++);let r=this.pos;this.reducePos=this.pos=r+e.length,this.pushState(t,r),this.buffer.push(i,r,this.reducePos,-1),this.curContext&&this.updateContext(this.curContext.tracker.reuse(this.curContext.context,e,this,this.p.stream.reset(this.pos-e.length)))}split(){let e=this,t=e.buffer.length;for(;t>0&&e.buffer[t-2]>e.reducePos;)t-=4;let i=e.buffer.slice(t),r=e.bufferBase+t;for(;e&&r==e.bufferBase;)e=e.parent;return new Fl(this.p,this.stack.slice(),this.state,this.reducePos,this.pos,this.score,i,r,this.curContext,this.lookAhead,e)}recoverByDelete(e,t){let i=e<=this.p.parser.maxNode;i&&this.storeNode(e,this.pos,t,4),this.storeNode(0,this.pos,t,i?8:4),this.pos=this.reducePos=t,this.score-=190}canShift(e){for(let t=new j$(this);;){let i=this.p.parser.stateSlot(t.state,4)||this.p.parser.hasAction(t.state,e);if(i==0)return!1;if(!(i&65536))return!0;t.reduce(i)}}recoverByInsert(e){if(this.stack.length>=300)return[];let t=this.p.parser.nextStates(this.state);if(t.length>8||this.stack.length>=120){let r=[];for(let s=0,o;sl&1&&a==o)||r.push(t[s],o)}t=r}let i=[];for(let r=0;r>19,r=e&65535,s=this.stack.length-i*3;if(s<0||t.getGoto(this.stack[s],r,!1)<0)return!1;this.storeNode(0,this.reducePos,this.reducePos,4,!0),this.score-=100}return this.reducePos=this.pos,this.reduce(e),!0}forceAll(){for(;!this.p.parser.stateFlag(this.state,2);)if(!this.forceReduce()){this.storeNode(0,this.pos,this.pos,4,!0);break}return this}get deadEnd(){if(this.stack.length!=3)return!1;let{parser:e}=this.p;return e.data[e.stateSlot(this.state,1)]==65535&&!e.stateSlot(this.state,4)}restart(){this.state=this.stack[0],this.stack.length=0}sameState(e){if(this.state!=e.state||this.stack.length!=e.stack.length)return!1;for(let t=0;tthis.lookAhead&&(this.emitLookAhead(),this.lookAhead=e)}close(){this.curContext&&this.curContext.tracker.strict&&this.emitContext(),this.lookAhead>0&&this.emitLookAhead()}}class Ug{constructor(e,t){this.tracker=e,this.context=t,this.hash=e.strict?e.hash(t):0}}var Zg;(function(n){n[n.Insert=200]="Insert",n[n.Delete=190]="Delete",n[n.Reduce=100]="Reduce",n[n.MaxNext=4]="MaxNext",n[n.MaxInsertStackDepth=300]="MaxInsertStackDepth",n[n.DampenInsertStackDepth=120]="DampenInsertStackDepth"})(Zg||(Zg={}));class j${constructor(e){this.start=e,this.state=e.state,this.stack=e.stack,this.base=this.stack.length}reduce(e){let t=e&65535,i=e>>19;i==0?(this.stack==this.start.stack&&(this.stack=this.stack.slice()),this.stack.push(this.state,0,0),this.base+=3):this.base-=(i-1)*3;let r=this.start.p.parser.getGoto(this.stack[this.base-3],t,!0);this.state=r}}class zl{constructor(e,t,i){this.stack=e,this.pos=t,this.index=i,this.buffer=e.buffer,this.index==0&&this.maybeNext()}static create(e,t=e.bufferBase+e.buffer.length){return new zl(e,t,t-e.bufferBase)}maybeNext(){let e=this.stack.parent;e!=null&&(this.index=this.stack.bufferBase-e.bufferBase,this.stack=e,this.buffer=e.buffer)}get id(){return this.buffer[this.index-4]}get start(){return this.buffer[this.index-3]}get end(){return this.buffer[this.index-2]}get size(){return this.buffer[this.index-1]}next(){this.index-=4,this.pos-=4,this.index==0&&this.maybeNext()}fork(){return new zl(this.stack,this.pos,this.index)}}class Ga{constructor(){this.start=-1,this.value=-1,this.end=-1,this.extended=-1,this.lookAhead=0,this.mask=0,this.context=0}}const Wg=new Ga;class F${constructor(e,t){this.input=e,this.ranges=t,this.chunk="",this.chunkOff=0,this.chunk2="",this.chunk2Pos=0,this.next=-1,this.token=Wg,this.rangeIndex=0,this.pos=this.chunkPos=t[0].from,this.range=t[0],this.end=t[t.length-1].to,this.readNext()}resolveOffset(e,t){let i=this.range,r=this.rangeIndex,s=this.pos+e;for(;si.to:s>=i.to;){if(r==this.ranges.length-1)return null;let o=this.ranges[++r];s+=o.from-i.to,i=o}return s}clipPos(e){if(e>=this.range.from&&ee)return Math.max(e,t.from);return this.end}peek(e){let t=this.chunkOff+e,i,r;if(t>=0&&t=this.chunk2Pos&&ia.to&&(this.chunk2=this.chunk2.slice(0,a.to-i)),r=this.chunk2.charCodeAt(0)}}return i>=this.token.lookAhead&&(this.token.lookAhead=i+1),r}acceptToken(e,t=0){let i=t?this.resolveOffset(t,-1):this.pos;if(i==null||i=this.chunk2Pos&&this.posthis.range.to?e.slice(0,this.range.to-this.pos):e,this.chunkPos=this.pos,this.chunkOff=0}}readNext(){return this.chunkOff>=this.chunk.length&&(this.getChunk(),this.chunkOff==this.chunk.length)?this.next=-1:this.next=this.chunk.charCodeAt(this.chunkOff)}advance(e=1){for(this.chunkOff+=e;this.pos+e>=this.range.to;){if(this.rangeIndex==this.ranges.length-1)return this.setDone();e-=this.range.to-this.pos,this.range=this.ranges[++this.rangeIndex],this.pos=this.range.from}return this.pos+=e,this.pos>=this.token.lookAhead&&(this.token.lookAhead=this.pos+1),this.readNext()}setDone(){return this.pos=this.chunkPos=this.end,this.range=this.ranges[this.rangeIndex=this.ranges.length-1],this.chunk="",this.next=-1}reset(e,t){if(t?(this.token=t,t.start=e,t.lookAhead=e+1,t.value=t.extended=-1):this.token=Wg,this.pos!=e){if(this.pos=e,e==this.end)return this.setDone(),this;for(;e=this.range.to;)this.range=this.ranges[++this.rangeIndex];e>=this.chunkPos&&e=this.chunkPos&&t<=this.chunkPos+this.chunk.length)return this.chunk.slice(e-this.chunkPos,t-this.chunkPos);if(e>=this.chunk2Pos&&t<=this.chunk2Pos+this.chunk2.length)return this.chunk2.slice(e-this.chunk2Pos,t-this.chunk2Pos);if(e>=this.range.from&&t<=this.range.to)return this.input.read(e,t);let i="";for(let r of this.ranges){if(r.from>=t)break;r.to>e&&(i+=this.input.read(Math.max(r.from,e),Math.min(r.to,t)))}return i}}class Ja{constructor(e,t){this.data=e,this.id=t}token(e,t){z$(this.data,e,t,this.id)}}Ja.prototype.contextual=Ja.prototype.fallback=Ja.prototype.extend=!1;class ii{constructor(e,t={}){this.token=e,this.contextual=!!t.contextual,this.fallback=!!t.fallback,this.extend=!!t.extend}}function z$(n,e,t,i){let r=0,s=1<0){let p=n[f];if(a.allows(p)&&(e.token.value==-1||e.token.value==p||o.overrides(p,e.token.value))){e.acceptToken(p);break}}let h=e.next,c=0,u=n[r+2];if(e.next<0&&u>c&&n[l+u*3-3]==65535&&n[l+u*3-3]==65535){r=n[l+u*3-1];continue e}for(;c>1,p=l+f+(f<<1),g=n[p],O=n[p+1]||65536;if(h=O)c=f+1;else{r=n[p+2],e.advance();continue e}}break}}function $a(n,e=Uint16Array){if(typeof n!="string")return n;let t=null;for(let i=0,r=0;i=92&&o--,o>=34&&o--;let l=o-32;if(l>=46&&(l-=46,a=!0),s+=l,a)break;s*=46}t?t[r++]=s:t=new e(s)}return t}const Zt=typeof process<"u"&&Lg&&/\bparse\b/.test(Lg.LOG);let rc=null;var jg;(function(n){n[n.Margin=25]="Margin"})(jg||(jg={}));function Fg(n,e,t){let i=n.cursor(ce.IncludeAnonymous);for(i.moveTo(e);;)if(!(t<0?i.childBefore(e):i.childAfter(e)))for(;;){if((t<0?i.toe)&&!i.type.isError)return t<0?Math.max(0,Math.min(i.to-1,e-25)):Math.min(n.length,Math.max(i.from+1,e+25));if(t<0?i.prevSibling():i.nextSibling())break;if(!i.parent())return t<0?0:n.length}}class _${constructor(e,t){this.fragments=e,this.nodeSet=t,this.i=0,this.fragment=null,this.safeFrom=-1,this.safeTo=-1,this.trees=[],this.start=[],this.index=[],this.nextFragment()}nextFragment(){let e=this.fragment=this.i==this.fragments.length?null:this.fragments[this.i++];if(e){for(this.safeFrom=e.openStart?Fg(e.tree,e.from+e.offset,1)-e.offset:e.from,this.safeTo=e.openEnd?Fg(e.tree,e.to+e.offset,-1)-e.offset:e.to;this.trees.length;)this.trees.pop(),this.start.pop(),this.index.pop();this.trees.push(e.tree),this.start.push(-e.offset),this.index.push(0),this.nextStart=this.safeFrom}else this.nextStart=1e9}nodeAt(e){if(ee)return this.nextStart=o,null;if(s instanceof ne){if(o==e){if(o=Math.max(this.safeFrom,e)&&(this.trees.push(s),this.start.push(o),this.index.push(0))}else this.index[t]++,this.nextStart=o+s.length}}}class G${constructor(e,t){this.stream=t,this.tokens=[],this.mainToken=null,this.actions=[],this.tokens=e.tokenizers.map(i=>new Ga)}getActions(e){let t=0,i=null,{parser:r}=e.p,{tokenizers:s}=r,o=r.stateSlot(e.state,3),a=e.curContext?e.curContext.hash:0,l=0;for(let h=0;hu.end+25&&(l=Math.max(u.lookAhead,l)),u.value!=0)){let f=t;if(u.extended>-1&&(t=this.addActions(e,u.extended,u.end,t)),t=this.addActions(e,u.value,u.end,t),!c.extend&&(i=u,t>f))break}}for(;this.actions.length>t;)this.actions.pop();return l&&e.setLookAhead(l),!i&&e.pos==this.stream.end&&(i=new Ga,i.value=e.p.parser.eofTerm,i.start=i.end=e.pos,t=this.addActions(e,i.value,i.end,t)),this.mainToken=i,this.actions}getMainToken(e){if(this.mainToken)return this.mainToken;let t=new Ga,{pos:i,p:r}=e;return t.start=i,t.end=Math.min(i+1,r.stream.end),t.value=i==r.stream.end?r.parser.eofTerm:0,t}updateCachedToken(e,t,i){let r=this.stream.clipPos(i.pos);if(t.token(this.stream.reset(r,e),i),e.value>-1){let{parser:s}=i.p;for(let o=0;o=0&&i.p.parser.dialect.allows(a>>1)){a&1?e.extended=a>>1:e.value=a>>1;break}}}else e.value=0,e.end=this.stream.clipPos(r+1)}putAction(e,t,i,r){for(let s=0;se.bufferLength*4?new _$(i,e.nodeSet):null}get parsedPos(){return this.minStackPos}advance(){let e=this.stacks,t=this.minStackPos,i=this.stacks=[],r,s;for(let o=0;ot)i.push(a);else{if(this.advanceStack(a,i,e))continue;{r||(r=[],s=[]),r.push(a);let l=this.tokens.getMainToken(a);s.push(l.value,l.end)}}break}}if(!i.length){let o=r&&H$(r);if(o)return this.stackToTree(o);if(this.parser.strict)throw Zt&&r&&console.log("Stuck with token "+(this.tokens.mainToken?this.parser.getName(this.tokens.mainToken.value):"none")),new SyntaxError("No parse at "+t);this.recovering||(this.recovering=5)}if(this.recovering&&r){let o=this.stoppedAt!=null&&r[0].pos>this.stoppedAt?r[0]:this.runRecovery(r,s,i);if(o)return this.stackToTree(o.forceAll())}if(this.recovering){let o=this.recovering==1?1:this.recovering*3;if(i.length>o)for(i.sort((a,l)=>l.score-a.score);i.length>o;)i.pop();i.some(a=>a.reducePos>t)&&this.recovering--}else if(i.length>1)e:for(let o=0;o500&&h.buffer.length>500)if((a.score-h.score||a.buffer.length-h.buffer.length)>0)i.splice(l--,1);else{i.splice(o--,1);continue e}}}this.minStackPos=i[0].pos;for(let o=1;o ":"";if(this.stoppedAt!=null&&r>this.stoppedAt)return e.forceReduce()?e:null;if(this.fragments){let h=e.curContext&&e.curContext.tracker.strict,c=h?e.curContext.hash:0;for(let u=this.fragments.nodeAt(r);u;){let f=this.parser.nodeSet.types[u.type.id]==u.type?s.getGoto(e.state,u.type.id):-1;if(f>-1&&u.length&&(!h||(u.prop(_.contextHash)||0)==c))return e.useNode(u,f),Zt&&console.log(o+this.stackID(e)+` (via reuse of ${s.getName(u.type.id)})`),!0;if(!(u instanceof ne)||u.children.length==0||u.positions[0]>0)break;let p=u.children[0];if(p instanceof ne&&u.positions[0]==0)u=p;else break}}let a=s.stateSlot(e.state,4);if(a>0)return e.reduce(a),Zt&&console.log(o+this.stackID(e)+` (via always-reduce ${s.getName(a&65535)})`),!0;if(e.stack.length>=15e3)for(;e.stack.length>9e3&&e.forceReduce(););let l=this.tokens.getActions(e);for(let h=0;hr?t.push(g):i.push(g)}return!1}advanceFully(e,t){let i=e.pos;for(;;){if(!this.advanceStack(e,null,null))return!1;if(e.pos>i)return _g(e,t),!0}}runRecovery(e,t,i){let r=null,s=!1;for(let o=0;o ":"";if(a.deadEnd&&(s||(s=!0,a.restart(),Zt&&console.log(c+this.stackID(a)+" (restarted)"),this.advanceFully(a,i))))continue;let u=a.split(),f=c;for(let p=0;u.forceReduce()&&p<10&&(Zt&&console.log(f+this.stackID(u)+" (via force-reduce)"),!this.advanceFully(u,i));p++)Zt&&(f=this.stackID(u)+" -> ");for(let p of a.recoverByInsert(l))Zt&&console.log(c+this.stackID(p)+" (via recover-insert)"),this.advanceFully(p,i);this.stream.end>a.pos?(h==a.pos&&(h++,l=0),a.recoverByDelete(l,h),Zt&&console.log(c+this.stackID(a)+` (via recover-delete ${this.parser.getName(l)})`),_g(a,i)):(!r||r.scoren;class Ub{constructor(e){this.start=e.start,this.shift=e.shift||sc,this.reduce=e.reduce||sc,this.reuse=e.reuse||sc,this.hash=e.hash||(()=>0),this.strict=e.strict!==!1}}class Qs extends Qf{constructor(e){if(super(),this.wrappers=[],e.version!=14)throw new RangeError(`Parser version (${e.version}) doesn't match runtime version (14)`);let t=e.nodeNames.split(" ");this.minRepeatTerm=t.length;for(let a=0;ae.topRules[a][1]),r=[];for(let a=0;a=0)s(c,l,a[h++]);else{let u=a[h+-c];for(let f=-c;f>0;f--)s(a[h++],l,u);h++}}}this.nodeSet=new Fo(t.map((a,l)=>Ie.define({name:l>=this.minRepeatTerm?void 0:a,id:l,props:r[l],top:i.indexOf(l)>-1,error:l==0,skipped:e.skippedNodes&&e.skippedNodes.indexOf(l)>-1}))),e.propSources&&(this.nodeSet=this.nodeSet.extend(...e.propSources)),this.strict=!1,this.bufferLength=ey;let o=$a(e.tokenData);this.context=e.context,this.specializerSpecs=e.specialized||[],this.specialized=new Uint16Array(this.specializerSpecs.length);for(let a=0;atypeof a=="number"?new Ja(o,a):a),this.topRules=e.topRules,this.dialects=e.dialects||{},this.dynamicPrecedences=e.dynamicPrecedences||null,this.tokenPrecTable=e.tokenPrec,this.termNames=e.termNames||null,this.maxNode=this.nodeSet.types.length-1,this.dialect=this.parseDialect(),this.top=this.topRules[Object.keys(this.topRules)[0]]}createParse(e,t,i){let r=new J$(this,e,t,i);for(let s of this.wrappers)r=s(r,e,t,i);return r}getGoto(e,t,i=!1){let r=this.goto;if(t>=r[0])return-1;for(let s=r[t+1];;){let o=r[s++],a=o&1,l=r[s++];if(a&&i)return l;for(let h=s+(o>>1);s0}validAction(e,t){if(t==this.stateSlot(e,4))return!0;for(let i=this.stateSlot(e,1);;i+=3){if(this.data[i]==65535)if(this.data[i+1]==1)i=$n(this.data,i+2);else return!1;if(t==$n(this.data,i+1))return!0}}nextStates(e){let t=[];for(let i=this.stateSlot(e,1);;i+=3){if(this.data[i]==65535)if(this.data[i+1]==1)i=$n(this.data,i+2);else break;if(!(this.data[i+2]&1)){let r=this.data[i+1];t.some((s,o)=>o&1&&s==r)||t.push(this.data[i],r)}}return t}overrides(e,t){let i=Gg(this.data,this.tokenPrecTable,t);return i<0||Gg(this.data,this.tokenPrecTable,e){let r=e.tokenizers.find(s=>s.from==i);return r?r.to:i})),e.specializers&&(t.specializers=this.specializers.slice(),t.specializerSpecs=this.specializerSpecs.map((i,r)=>{let s=e.specializers.find(a=>a.from==i.external);if(!s)return i;let o=Object.assign(Object.assign({},i),{external:s.to});return t.specializers[r]=Jg(o),o})),e.contextTracker&&(t.context=e.contextTracker),e.dialect&&(t.dialect=this.parseDialect(e.dialect)),e.strict!=null&&(t.strict=e.strict),e.wrap&&(t.wrappers=t.wrappers.concat(e.wrap)),e.bufferLength!=null&&(t.bufferLength=e.bufferLength),t}hasWrappers(){return this.wrappers.length>0}getName(e){return this.termNames?this.termNames[e]:String(e<=this.maxNode&&this.nodeSet.types[e].name||e)}get eofTerm(){return this.maxNode+1}get topNode(){return this.nodeSet.types[this.top[1]]}dynamicPrecedence(e){let t=this.dynamicPrecedences;return t==null?0:t[e]||0}parseDialect(e){let t=Object.keys(this.dialects),i=t.map(()=>!1);if(e)for(let s of e.split(" ")){let o=t.indexOf(s);o>=0&&(i[o]=!0)}let r=null;for(let s=0;si)&&t.p.parser.stateFlag(t.state,2)&&(!e||e.scoren.external(t,i)<<1|e}return n.get}const K$=54,eC=1,tC=55,iC=2,nC=56,rC=3,_l=4,Zb=5,Wb=6,jb=7,Fb=8,sC=9,oC=10,aC=11,oc=57,lC=12,Yg=58,hC=18,cC=20,zb=21,uC=22,Xu=24,_b=25,fC=27,dC=30,pC=33,gC=35,mC=0,OC={area:!0,base:!0,br:!0,col:!0,command:!0,embed:!0,frame:!0,hr:!0,img:!0,input:!0,keygen:!0,link:!0,meta:!0,param:!0,source:!0,track:!0,wbr:!0,menuitem:!0},yC={dd:!0,li:!0,optgroup:!0,option:!0,p:!0,rp:!0,rt:!0,tbody:!0,td:!0,tfoot:!0,th:!0,tr:!0},Hg={dd:{dd:!0,dt:!0},dt:{dd:!0,dt:!0},li:{li:!0},option:{option:!0,optgroup:!0},optgroup:{optgroup:!0},p:{address:!0,article:!0,aside:!0,blockquote:!0,dir:!0,div:!0,dl:!0,fieldset:!0,footer:!0,form:!0,h1:!0,h2:!0,h3:!0,h4:!0,h5:!0,h6:!0,header:!0,hgroup:!0,hr:!0,menu:!0,nav:!0,ol:!0,p:!0,pre:!0,section:!0,table:!0,ul:!0},rp:{rp:!0,rt:!0},rt:{rp:!0,rt:!0},tbody:{tbody:!0,tfoot:!0},td:{td:!0,th:!0},tfoot:{tbody:!0},th:{td:!0,th:!0},thead:{tbody:!0,tfoot:!0},tr:{tr:!0}};function bC(n){return n==45||n==46||n==58||n>=65&&n<=90||n==95||n>=97&&n<=122||n>=161}function Gb(n){return n==9||n==10||n==13||n==32}let Kg=null,em=null,tm=0;function Lu(n,e){let t=n.pos+e;if(tm==t&&em==n)return Kg;let i=n.peek(e);for(;Gb(i);)i=n.peek(++e);let r="";for(;bC(i);)r+=String.fromCharCode(i),i=n.peek(++e);return em=n,tm=t,Kg=r?r.toLowerCase():i==SC||i==wC?void 0:null}const Jb=60,Yb=62,Hb=47,SC=63,wC=33,vC=45;function im(n,e){this.name=n,this.parent=e,this.hash=e?e.hash:0;for(let t=0;t-1?new im(Lu(i,1)||"",n):n},reduce(n,e){return e==hC&&n?n.parent:n},reuse(n,e,t,i){let r=e.type.id;return r==_l||r==gC?new im(Lu(i,1)||"",n):n},hash(n){return n?n.hash:0},strict:!1}),TC=new ii((n,e)=>{if(n.next!=Jb){n.next<0&&e.context&&n.acceptToken(oc);return}n.advance();let t=n.next==Hb;t&&n.advance();let i=Lu(n,0);if(i===void 0)return;if(!i)return n.acceptToken(t?lC:_l);let r=e.context?e.context.name:null;if(t){if(i==r)return n.acceptToken(sC);if(r&&yC[r])return n.acceptToken(oc,-2);if(e.dialectEnabled(mC))return n.acceptToken(oC);for(let s=e.context;s;s=s.parent)if(s.name==i)return;n.acceptToken(aC)}else{if(i=="script")return n.acceptToken(Zb);if(i=="style")return n.acceptToken(Wb);if(i=="textarea")return n.acceptToken(jb);if(OC.hasOwnProperty(i))return n.acceptToken(Fb);r&&Hg[r]&&Hg[r][i]?n.acceptToken(oc,-1):n.acceptToken(_l)}},{contextual:!0}),QC=new ii(n=>{for(let e=0,t=0;;t++){if(n.next<0){t&&n.acceptToken(Yg);break}if(n.next==vC)e++;else if(n.next==Yb&&e>=2){t>3&&n.acceptToken(Yg,-2);break}else e=0;n.advance()}});function _f(n,e,t){let i=2+n.length;return new ii(r=>{for(let s=0,o=0,a=0;;a++){if(r.next<0){a&&r.acceptToken(e);break}if(s==0&&r.next==Jb||s==1&&r.next==Hb||s>=2&&so?r.acceptToken(e,-o):r.acceptToken(t,-(o-2));break}else if((r.next==10||r.next==13)&&a){r.acceptToken(e,1);break}else s=o=0;r.advance()}})}const PC=_f("script",K$,eC),AC=_f("style",tC,iC),$C=_f("textarea",nC,rC),CC=$s({"Text RawText":b.content,"StartTag StartCloseTag SelfClosingEndTag EndTag":b.angleBracket,TagName:b.tagName,"MismatchedCloseTag/TagName":[b.tagName,b.invalid],AttributeName:b.attributeName,"AttributeValue UnquotedAttributeValue":b.attributeValue,Is:b.definitionOperator,"EntityReference CharacterReference":b.character,Comment:b.blockComment,ProcessingInst:b.processingInstruction,DoctypeDecl:b.documentMeta}),IC=Qs.deserialize({version:14,states:",xOVOxOOO!WQ!bO'#CoO!]Q!bO'#CyO!bQ!bO'#C|O!gQ!bO'#DPO!lQ!bO'#DRO!qOXO'#CnO!|OYO'#CnO#XO[O'#CnO$eOxO'#CnOOOW'#Cn'#CnO$lO!rO'#DTO$tQ!bO'#DVO$yQ!bO'#DWOOOW'#Dk'#DkOOOW'#DY'#DYQVOxOOO%OQ#tO,59ZO%WQ#tO,59eO%`Q#tO,59hO%hQ#tO,59kO%sQ#tO,59mOOOX'#D^'#D^O%{OXO'#CwO&WOXO,59YOOOY'#D_'#D_O&`OYO'#CzO&kOYO,59YOOO['#D`'#D`O&sO[O'#C}O'OO[O,59YOOOW'#Da'#DaO'WOxO,59YO'_Q!bO'#DQOOOW,59Y,59YOOO`'#Db'#DbO'dO!rO,59oOOOW,59o,59oO'lQ!bO,59qO'qQ!bO,59rOOOW-E7W-E7WO'vQ#tO'#CqOOQO'#DZ'#DZO(UQ#tO1G.uOOOX1G.u1G.uO(^Q#tO1G/POOOY1G/P1G/PO(fQ#tO1G/SOOO[1G/S1G/SO(nQ#tO1G/VOOOW1G/V1G/VOOOW1G/X1G/XO(yQ#tO1G/XOOOX-E7[-E7[O)RQ!bO'#CxOOOW1G.t1G.tOOOY-E7]-E7]O)WQ!bO'#C{OOO[-E7^-E7^O)]Q!bO'#DOOOOW-E7_-E7_O)bQ!bO,59lOOO`-E7`-E7`OOOW1G/Z1G/ZOOOW1G/]1G/]OOOW1G/^1G/^O)gQ&jO,59]OOQO-E7X-E7XOOOX7+$a7+$aOOOY7+$k7+$kOOO[7+$n7+$nOOOW7+$q7+$qOOOW7+$s7+$sO)rQ!bO,59dO)wQ!bO,59gO)|Q!bO,59jOOOW1G/W1G/WO*RO,UO'#CtO*dO7[O'#CtOOQO1G.w1G.wOOOW1G/O1G/OOOOW1G/R1G/ROOOW1G/U1G/UOOOO'#D['#D[O*uO,UO,59`OOQO,59`,59`OOOO'#D]'#D]O+WO7[O,59`OOOO-E7Y-E7YOOQO1G.z1G.zOOOO-E7Z-E7Z",stateData:"+u~O!^OS~OSSOTPOUQOVROWTOY]OZ[O[^O^^O_^O`^Oa^Ox^O{_O!dZO~OdaO~OdbO~OdcO~OddO~OdeO~O!WfOPkP!ZkP~O!XiOQnP!ZnP~O!YlORqP!ZqP~OSSOTPOUQOVROWTOXqOY]OZ[O[^O^^O_^O`^Oa^Ox^O!dZO~O!ZrO~P#dO![sO!euO~OdvO~OdwO~OfyOj|O~OfyOj!OO~OfyOj!QO~OfyOj!SOv!TO~OfyOj!TO~O!WfOPkX!ZkX~OP!WO!Z!XO~O!XiOQnX!ZnX~OQ!ZO!Z!XO~O!YlORqX!ZqX~OR!]O!Z!XO~O!Z!XO~P#dOd!_O~O![sO!e!aO~Oj!bO~Oj!cO~Og!dOfeXjeXveX~OfyOj!fO~OfyOj!gO~OfyOj!hO~OfyOj!iOv!jO~OfyOj!jO~Od!kO~Od!lO~Od!mO~Oj!nO~Oi!qO!`!oO!b!pO~Oj!rO~Oj!sO~Oj!tO~O_!uO`!uOa!uO!`!wO!a!uO~O_!xO`!xOa!xO!b!wO!c!xO~O_!uO`!uOa!uO!`!{O!a!uO~O_!xO`!xOa!xO!b!{O!c!xO~Ov~vj`!dx{_a_~",goto:"%p!`PPPPPPPPPPPPPPPPPP!a!gP!mPP!yPP!|#P#S#Y#]#`#f#i#l#r#xP!aP!a!aP$O$U$l$r$x%O%U%[%bPPPPPPPP%hX^OX`pXUOX`pezabcde{}!P!R!UR!q!dRhUR!XhXVOX`pRkVR!XkXWOX`pRnWR!XnXXOX`pQrXR!XpXYOX`pQ`ORx`Q{aQ}bQ!PcQ!RdQ!UeZ!e{}!P!R!UQ!v!oR!z!vQ!y!pR!|!yQgUR!VgQjVR!YjQmWR![mQpXR!^pQtZR!`tS_O`ToXp",nodeNames:"⚠ StartCloseTag StartCloseTag StartCloseTag StartTag StartTag StartTag StartTag StartTag StartCloseTag StartCloseTag StartCloseTag IncompleteCloseTag Document Text EntityReference CharacterReference InvalidEntity Element OpenTag TagName Attribute AttributeName Is AttributeValue UnquotedAttributeValue EndTag ScriptText CloseTag OpenTag StyleText CloseTag OpenTag TextareaText CloseTag OpenTag CloseTag SelfClosingTag SelfClosingEndTag Comment ProcessingInst MismatchedCloseTag CloseTag DoctypeDecl",maxTerm:67,context:xC,nodeProps:[["closedBy",-10,1,2,3,5,6,7,8,9,10,11,"EndTag",4,"EndTag SelfClosingEndTag",-4,19,29,32,35,"CloseTag"],["group",-9,12,15,16,17,18,39,40,41,42,"Entity",14,"Entity TextContent",-3,27,30,33,"TextContent Entity"],["openedBy",26,"StartTag StartCloseTag",-4,28,31,34,36,"OpenTag",38,"StartTag"]],propSources:[CC],skippedNodes:[0],repeatNodeCount:9,tokenData:"#(r!aR!YOX$qXY,QYZ,QZ[$q[]&X]^,Q^p$qpq,Qqr-_rs4ysv-_vw5iwxJ^x}-_}!OKP!O!P-_!P!Q!!O!Q![-_![!]!$c!]!^-_!^!_!(k!_!`#'S!`!a#'z!a!c-_!c!}!$c!}#R-_#R#S!$c#S#T3V#T#o!$c#o#s-_#s$f$q$f%W-_%W%o!$c%o%p-_%p&a!$c&a&b-_&b1p!$c1p4U-_4U4d!$c4d4e-_4e$IS!$c$IS$I`-_$I`$Ib!$c$Ib$Kh-_$Kh%#t!$c%#t&/x-_&/x&Et!$c&Et&FV-_&FV;'S!$c;'S;:j!(e;:j;=`4s<%l?&r-_?&r?Ah!$c?Ah?BY$q?BY?Mn!$c?MnO$q!Z$|c^PiW!a`!cpOX$qXZ&XZ[$q[^&X^p$qpq&Xqr$qrs&}sv$qvw+Pwx(tx!^$q!^!_*V!_!a&X!a#S$q#S#T&X#T;'S$q;'S;=`+z<%lO$q!R&bX^P!a`!cpOr&Xrs&}sv&Xwx(tx!^&X!^!_*V!_;'S&X;'S;=`*y<%lO&Xq'UV^P!cpOv&}wx'kx!^&}!^!_(V!_;'S&};'S;=`(n<%lO&}P'pT^POv'kw!^'k!_;'S'k;'S;=`(P<%lO'kP(SP;=`<%l'kp([S!cpOv(Vx;'S(V;'S;=`(h<%lO(Vp(kP;=`<%l(Vq(qP;=`<%l&}a({W^P!a`Or(trs'ksv(tw!^(t!^!_)e!_;'S(t;'S;=`*P<%lO(t`)jT!a`Or)esv)ew;'S)e;'S;=`)y<%lO)e`)|P;=`<%l)ea*SP;=`<%l(t!Q*^V!a`!cpOr*Vrs(Vsv*Vwx)ex;'S*V;'S;=`*s<%lO*V!Q*vP;=`<%l*V!R*|P;=`<%l&XW+UYiWOX+PZ[+P^p+Pqr+Psw+Px!^+P!a#S+P#T;'S+P;'S;=`+t<%lO+PW+wP;=`<%l+P!Z+}P;=`<%l$q!a,]`^P!a`!cp!^^OX&XXY,QYZ,QZ]&X]^,Q^p&Xpq,Qqr&Xrs&}sv&Xwx(tx!^&X!^!_*V!_;'S&X;'S;=`*y<%lO&X!_-ljfS^PiW!a`!cpOX$qXZ&XZ[$q[^&X^p$qpq&Xqr-_rs&}sv-_vw/^wx(tx!P-_!P!Q$q!Q!^-_!^!_1n!_!a&X!a#S-_#S#T3V#T#s-_#s$f$q$f;'S-_;'S;=`4s<%l?Ah-_?Ah?BY$q?BY?Mn-_?MnO$q[/ecfSiWOX+PZ[+P^p+Pqr/^sw/^x!P/^!P!Q+P!Q!^/^!^!_0p!a#S/^#S#T0p#T#s/^#s$f+P$f;'S/^;'S;=`1h<%l?Ah/^?Ah?BY+P?BY?Mn/^?MnO+PS0uXfSqr0psw0px!P0p!Q!_0p!a#s0p$f;'S0p;'S;=`1b<%l?Ah0p?BY?Mn0pS1eP;=`<%l0p[1kP;=`<%l/^!U1wbfS!a`!cpOq*Vqr1nrs(Vsv1nvw0pwx)ex!P1n!P!Q*V!Q!_1n!_!a*V!a#s1n#s$f*V$f;'S1n;'S;=`3P<%l?Ah1n?Ah?BY*V?BY?Mn1n?MnO*V!U3SP;=`<%l1n!V3bcfS^P!a`!cpOq&Xqr3Vrs&}sv3Vvw0pwx(tx!P3V!P!Q&X!Q!^3V!^!_1n!_!a&X!a#s3V#s$f&X$f;'S3V;'S;=`4m<%l?Ah3V?Ah?BY&X?BY?Mn3V?MnO&X!V4pP;=`<%l3V!_4vP;=`<%l-_!Z5SV!`h^P!cpOv&}wx'kx!^&}!^!_(V!_;'S&};'S;=`(n<%lO&}!_5rjfSiWa!ROX7dXZ8qZ[7d[^8q^p7dqr:crs8qst@Ttw:cwx8qx!P:c!P!Q7d!Q!]:c!]!^/^!^!_=p!_!a8q!a#S:c#S#T=p#T#s:c#s$f7d$f;'S:c;'S;=`?}<%l?Ah:c?Ah?BY7d?BY?Mn:c?MnO7d!Z7ibiWOX7dXZ8qZ[7d[^8q^p7dqr7drs8qst+Ptw7dwx8qx!]7d!]!^9f!^!a8q!a#S7d#S#T8q#T;'S7d;'S;=`:]<%lO7d!R8tVOp8qqs8qt!]8q!]!^9Z!^;'S8q;'S;=`9`<%lO8q!R9`O_!R!R9cP;=`<%l8q!Z9mYiW_!ROX+PZ[+P^p+Pqr+Psw+Px!^+P!a#S+P#T;'S+P;'S;=`+t<%lO+P!Z:`P;=`<%l7d!_:jjfSiWOX7dXZ8qZ[7d[^8q^p7dqr:crs8qst/^tw:cwx8qx!P:c!P!Q7d!Q!]:c!]!^<[!^!_=p!_!a8q!a#S:c#S#T=p#T#s:c#s$f7d$f;'S:c;'S;=`?}<%l?Ah:c?Ah?BY7d?BY?Mn:c?MnO7d!_{let l=o.type.id;if(l==fC)return ac(o,a,t);if(l==dC)return ac(o,a,i);if(l==pC)return ac(o,a,r);if(s&&l==zb){let h=o.node,c;if(c=h.firstChild){let u=s[a.read(c.from,c.to)];if(u)for(let f of u){if(f.tagName){if(!tagName){let g=h.parent.getChild(cC);tagName=g?a.read(g.from,g.to):" "}if(attrTagName!=tagName)continue}let p=h.lastChild;if(p.type.id==Xu)return{parser:f.parser,overlay:[{from:p.from+1,to:p.to-1}]};if(p.type.id==_b)return{parser:f.parser,overlay:[{from:p.from,to:p.to}]}}}}return null})}const EC=94,nm=1,DC=95,NC=96,rm=2,eS=[9,10,11,12,13,32,133,160,5760,8192,8193,8194,8195,8196,8197,8198,8199,8200,8201,8202,8232,8233,8239,8287,12288],BC=58,qC=40,tS=95,MC=91,Ya=45,VC=46,XC=35,LC=37;function Gl(n){return n>=65&&n<=90||n>=97&&n<=122||n>=161}function UC(n){return n>=48&&n<=57}const ZC=new ii((n,e)=>{for(let t=!1,i=0,r=0;;r++){let{next:s}=n;if(Gl(s)||s==Ya||s==tS||t&&UC(s))!t&&(s!=Ya||r>0)&&(t=!0),i===r&&s==Ya&&i++,n.advance();else{t&&n.acceptToken(s==qC?DC:i==2&&e.canShift(rm)?rm:NC);break}}}),WC=new ii(n=>{if(eS.includes(n.peek(-1))){let{next:e}=n;(Gl(e)||e==tS||e==XC||e==VC||e==MC||e==BC||e==Ya)&&n.acceptToken(EC)}}),jC=new ii(n=>{if(!eS.includes(n.peek(-1))){let{next:e}=n;if(e==LC&&(n.advance(),n.acceptToken(nm)),Gl(e)){do n.advance();while(Gl(n.next));n.acceptToken(nm)}}}),FC=$s({"AtKeyword import charset namespace keyframes media supports":b.definitionKeyword,"from to selector":b.keyword,NamespaceName:b.namespace,KeyframeName:b.labelName,TagName:b.tagName,ClassName:b.className,PseudoClassName:b.constant(b.className),IdName:b.labelName,"FeatureName PropertyName":b.propertyName,AttributeName:b.attributeName,NumberLiteral:b.number,KeywordQuery:b.keyword,UnaryQueryOp:b.operatorKeyword,"CallTag ValueName":b.atom,VariableName:b.variableName,Callee:b.operatorKeyword,Unit:b.unit,"UniversalSelector NestingSelector":b.definitionOperator,MatchOp:b.compareOperator,"ChildOp SiblingOp, LogicOp":b.logicOperator,BinOp:b.arithmeticOperator,Important:b.modifier,Comment:b.blockComment,ParenthesizedContent:b.special(b.name),ColorLiteral:b.color,StringLiteral:b.string,":":b.punctuation,"PseudoOp #":b.derefOperator,"; ,":b.separator,"( )":b.paren,"[ ]":b.squareBracket,"{ }":b.brace}),zC={__proto__:null,lang:32,"nth-child":32,"nth-last-child":32,"nth-of-type":32,"nth-last-of-type":32,dir:32,"host-context":32,url:60,"url-prefix":60,domain:60,regexp:60,selector:134},_C={__proto__:null,"@import":114,"@media":138,"@charset":142,"@namespace":146,"@keyframes":152,"@supports":164},GC={__proto__:null,not:128,only:128,from:158,to:160},JC=Qs.deserialize({version:14,states:"7WQYQ[OOO#_Q[OOOOQP'#Cd'#CdOOQP'#Cc'#CcO#fQ[O'#CfO$YQXO'#CaO$aQ[O'#ChO$lQ[O'#DPO$qQ[O'#DTOOQP'#Ed'#EdO$vQdO'#DeO%bQ[O'#DrO$vQdO'#DtO%sQ[O'#DvO&OQ[O'#DyO&TQ[O'#EPO&cQ[O'#EROOQS'#Ec'#EcOOQS'#ET'#ETQYQ[OOO&jQXO'#CdO'_QWO'#DaO'dQWO'#EjO'oQ[O'#EjQOQWOOOOQP'#Cg'#CgOOQP,59Q,59QO#fQ[O,59QO'yQ[O'#EWO(eQWO,58{O(mQ[O,59SO$lQ[O,59kO$qQ[O,59oO'yQ[O,59sO'yQ[O,59uO'yQ[O,59vO(xQ[O'#D`OOQS,58{,58{OOQP'#Ck'#CkOOQO'#C}'#C}OOQP,59S,59SO)PQWO,59SO)UQWO,59SOOQP'#DR'#DROOQP,59k,59kOOQO'#DV'#DVO)ZQ`O,59oOOQS'#Cp'#CpO$vQdO'#CqO)cQvO'#CsO*pQtO,5:POOQO'#Cx'#CxO)UQWO'#CwO+UQWO'#CyOOQS'#Eg'#EgOOQO'#Dh'#DhO+ZQ[O'#DoO+iQWO'#EkO&TQ[O'#DmO+wQWO'#DpOOQO'#El'#ElO(hQWO,5:^O+|QpO,5:`OOQS'#Dx'#DxO,UQWO,5:bO,ZQ[O,5:bOOQO'#D{'#D{O,cQWO,5:eO,hQWO,5:kO,pQWO,5:mOOQS-E8R-E8RO$vQdO,59{O,xQ[O'#EYO-VQWO,5;UO-VQWO,5;UOOQP1G.l1G.lO-|QXO,5:rOOQO-E8U-E8UOOQS1G.g1G.gOOQP1G.n1G.nO)PQWO1G.nO)UQWO1G.nOOQP1G/V1G/VO.ZQ`O1G/ZO.tQXO1G/_O/[QXO1G/aO/rQXO1G/bO0YQWO,59zO0_Q[O'#DOO0fQdO'#CoOOQP1G/Z1G/ZO$vQdO1G/ZO0mQpO,59]OOQS,59_,59_O$vQdO,59aO0uQWO1G/kOOQS,59c,59cO0zQ!bO,59eO1SQWO'#DhO1_QWO,5:TO1dQWO,5:ZO&TQ[O,5:VO&TQ[O'#EZO1lQWO,5;VO1wQWO,5:XO'yQ[O,5:[OOQS1G/x1G/xOOQS1G/z1G/zOOQS1G/|1G/|O2YQWO1G/|O2_QdO'#D|OOQS1G0P1G0POOQS1G0V1G0VOOQS1G0X1G0XO2mQtO1G/gOOQO,5:t,5:tO3TQ[O,5:tOOQO-E8W-E8WO3bQWO1G0pOOQP7+$Y7+$YOOQP7+$u7+$uO$vQdO7+$uOOQS1G/f1G/fO3mQXO'#EiO3tQWO,59jO3yQtO'#EUO4nQdO'#EfO4xQWO,59ZO4}QpO7+$uOOQS1G.w1G.wOOQS1G.{1G.{OOQS7+%V7+%VO5VQWO1G/PO$vQdO1G/oOOQO1G/u1G/uOOQO1G/q1G/qO5[QWO,5:uOOQO-E8X-E8XO5jQXO1G/vOOQS7+%h7+%hO5qQYO'#CsO(hQWO'#E[O5yQdO,5:hOOQS,5:h,5:hO6XQtO'#EXO$vQdO'#EXO7VQdO7+%ROOQO7+%R7+%ROOQO1G0`1G0`O7jQpO<T![;'S%^;'S;=`%o<%lO%^^;TUoWOy%^z!Q%^!Q![;g![;'S%^;'S;=`%o<%lO%^^;nYoW#[UOy%^z!Q%^!Q![;g![!g%^!g!h<^!h#X%^#X#Y<^#Y;'S%^;'S;=`%o<%lO%^^[[oW#[UOy%^z!O%^!O!P;g!P!Q%^!Q![>T![!g%^!g!h<^!h#X%^#X#Y<^#Y;'S%^;'S;=`%o<%lO%^_?VSpVOy%^z;'S%^;'S;=`%o<%lO%^^?hWjSOy%^z!O%^!O!P;O!P!Q%^!Q![>T![;'S%^;'S;=`%o<%lO%^_@VU#XPOy%^z!Q%^!Q![;g![;'S%^;'S;=`%o<%lO%^~@nTjSOy%^z{@}{;'S%^;'S;=`%o<%lO%^~ASUoWOy@}yzAfz{Bm{;'S@};'S;=`Co<%lO@}~AiTOzAfz{Ax{;'SAf;'S;=`Bg<%lOAf~A{VOzAfz{Ax{!PAf!P!QBb!Q;'SAf;'S;=`Bg<%lOAf~BgOR~~BjP;=`<%lAf~BrWoWOy@}yzAfz{Bm{!P@}!P!QC[!Q;'S@};'S;=`Co<%lO@}~CcSoWR~Oy%^z;'S%^;'S;=`%o<%lO%^~CrP;=`<%l@}^Cz[#[UOy%^z!O%^!O!P;g!P!Q%^!Q![>T![!g%^!g!h<^!h#X%^#X#Y<^#Y;'S%^;'S;=`%o<%lO%^XDuU]POy%^z![%^![!]EX!];'S%^;'S;=`%o<%lO%^XE`S^PoWOy%^z;'S%^;'S;=`%o<%lO%^_EqS!WVOy%^z;'S%^;'S;=`%o<%lO%^YFSSzQOy%^z;'S%^;'S;=`%o<%lO%^XFeU|POy%^z!`%^!`!aFw!a;'S%^;'S;=`%o<%lO%^XGOS|PoWOy%^z;'S%^;'S;=`%o<%lO%^XG_WOy%^z!c%^!c!}Gw!}#T%^#T#oGw#o;'S%^;'S;=`%o<%lO%^XHO[!YPoWOy%^z}%^}!OGw!O!Q%^!Q![Gw![!c%^!c!}Gw!}#T%^#T#oGw#o;'S%^;'S;=`%o<%lO%^XHySxPOy%^z;'S%^;'S;=`%o<%lO%^^I[SvUOy%^z;'S%^;'S;=`%o<%lO%^XIkUOy%^z#b%^#b#cI}#c;'S%^;'S;=`%o<%lO%^XJSUoWOy%^z#W%^#W#XJf#X;'S%^;'S;=`%o<%lO%^XJmS!`PoWOy%^z;'S%^;'S;=`%o<%lO%^XJ|UOy%^z#f%^#f#gJf#g;'S%^;'S;=`%o<%lO%^XKeS!RPOy%^z;'S%^;'S;=`%o<%lO%^_KvS!QVOy%^z;'S%^;'S;=`%o<%lO%^ZLXU!PPOy%^z!_%^!_!`6y!`;'S%^;'S;=`%o<%lO%^WLnP;=`<%l$}",tokenizers:[WC,jC,ZC,0,1,2,3],topRules:{StyleSheet:[0,4],Styles:[1,84]},specialized:[{term:95,get:n=>zC[n]||-1},{term:56,get:n=>_C[n]||-1},{term:96,get:n=>GC[n]||-1}],tokenPrec:1123});let lc=null;function hc(){if(!lc&&typeof document=="object"&&document.body){let n=[];for(let e in document.body.style)/[A-Z]|^-|^(item|length)$/.test(e)||n.push(e);lc=n.sort().map(e=>({type:"property",label:e}))}return lc||[]}const sm=["active","after","any-link","autofill","backdrop","before","checked","cue","default","defined","disabled","empty","enabled","file-selector-button","first","first-child","first-letter","first-line","first-of-type","focus","focus-visible","focus-within","fullscreen","has","host","host-context","hover","in-range","indeterminate","invalid","is","lang","last-child","last-of-type","left","link","marker","modal","not","nth-child","nth-last-child","nth-last-of-type","nth-of-type","only-child","only-of-type","optional","out-of-range","part","placeholder","placeholder-shown","read-only","read-write","required","right","root","scope","selection","slotted","target","target-text","valid","visited","where"].map(n=>({type:"class",label:n})),om=["above","absolute","activeborder","additive","activecaption","after-white-space","ahead","alias","all","all-scroll","alphabetic","alternate","always","antialiased","appworkspace","asterisks","attr","auto","auto-flow","avoid","avoid-column","avoid-page","avoid-region","axis-pan","background","backwards","baseline","below","bidi-override","blink","block","block-axis","bold","bolder","border","border-box","both","bottom","break","break-all","break-word","bullets","button","button-bevel","buttonface","buttonhighlight","buttonshadow","buttontext","calc","capitalize","caps-lock-indicator","caption","captiontext","caret","cell","center","checkbox","circle","cjk-decimal","clear","clip","close-quote","col-resize","collapse","color","color-burn","color-dodge","column","column-reverse","compact","condensed","contain","content","contents","content-box","context-menu","continuous","copy","counter","counters","cover","crop","cross","crosshair","currentcolor","cursive","cyclic","darken","dashed","decimal","decimal-leading-zero","default","default-button","dense","destination-atop","destination-in","destination-out","destination-over","difference","disc","discard","disclosure-closed","disclosure-open","document","dot-dash","dot-dot-dash","dotted","double","down","e-resize","ease","ease-in","ease-in-out","ease-out","element","ellipse","ellipsis","embed","end","ethiopic-abegede-gez","ethiopic-halehame-aa-er","ethiopic-halehame-gez","ew-resize","exclusion","expanded","extends","extra-condensed","extra-expanded","fantasy","fast","fill","fill-box","fixed","flat","flex","flex-end","flex-start","footnotes","forwards","from","geometricPrecision","graytext","grid","groove","hand","hard-light","help","hidden","hide","higher","highlight","highlighttext","horizontal","hsl","hsla","hue","icon","ignore","inactiveborder","inactivecaption","inactivecaptiontext","infinite","infobackground","infotext","inherit","initial","inline","inline-axis","inline-block","inline-flex","inline-grid","inline-table","inset","inside","intrinsic","invert","italic","justify","keep-all","landscape","large","larger","left","level","lighter","lighten","line-through","linear","linear-gradient","lines","list-item","listbox","listitem","local","logical","loud","lower","lower-hexadecimal","lower-latin","lower-norwegian","lowercase","ltr","luminosity","manipulation","match","matrix","matrix3d","medium","menu","menutext","message-box","middle","min-intrinsic","mix","monospace","move","multiple","multiple_mask_images","multiply","n-resize","narrower","ne-resize","nesw-resize","no-close-quote","no-drop","no-open-quote","no-repeat","none","normal","not-allowed","nowrap","ns-resize","numbers","numeric","nw-resize","nwse-resize","oblique","opacity","open-quote","optimizeLegibility","optimizeSpeed","outset","outside","outside-shape","overlay","overline","padding","padding-box","painted","page","paused","perspective","pinch-zoom","plus-darker","plus-lighter","pointer","polygon","portrait","pre","pre-line","pre-wrap","preserve-3d","progress","push-button","radial-gradient","radio","read-only","read-write","read-write-plaintext-only","rectangle","region","relative","repeat","repeating-linear-gradient","repeating-radial-gradient","repeat-x","repeat-y","reset","reverse","rgb","rgba","ridge","right","rotate","rotate3d","rotateX","rotateY","rotateZ","round","row","row-resize","row-reverse","rtl","run-in","running","s-resize","sans-serif","saturation","scale","scale3d","scaleX","scaleY","scaleZ","screen","scroll","scrollbar","scroll-position","se-resize","self-start","self-end","semi-condensed","semi-expanded","separate","serif","show","single","skew","skewX","skewY","skip-white-space","slide","slider-horizontal","slider-vertical","sliderthumb-horizontal","sliderthumb-vertical","slow","small","small-caps","small-caption","smaller","soft-light","solid","source-atop","source-in","source-out","source-over","space","space-around","space-between","space-evenly","spell-out","square","start","static","status-bar","stretch","stroke","stroke-box","sub","subpixel-antialiased","svg_masks","super","sw-resize","symbolic","symbols","system-ui","table","table-caption","table-cell","table-column","table-column-group","table-footer-group","table-header-group","table-row","table-row-group","text","text-bottom","text-top","textarea","textfield","thick","thin","threeddarkshadow","threedface","threedhighlight","threedlightshadow","threedshadow","to","top","transform","translate","translate3d","translateX","translateY","translateZ","transparent","ultra-condensed","ultra-expanded","underline","unidirectional-pan","unset","up","upper-latin","uppercase","url","var","vertical","vertical-text","view-box","visible","visibleFill","visiblePainted","visibleStroke","visual","w-resize","wait","wave","wider","window","windowframe","windowtext","words","wrap","wrap-reverse","x-large","x-small","xor","xx-large","xx-small"].map(n=>({type:"keyword",label:n})).concat(["aliceblue","antiquewhite","aqua","aquamarine","azure","beige","bisque","black","blanchedalmond","blue","blueviolet","brown","burlywood","cadetblue","chartreuse","chocolate","coral","cornflowerblue","cornsilk","crimson","cyan","darkblue","darkcyan","darkgoldenrod","darkgray","darkgreen","darkkhaki","darkmagenta","darkolivegreen","darkorange","darkorchid","darkred","darksalmon","darkseagreen","darkslateblue","darkslategray","darkturquoise","darkviolet","deeppink","deepskyblue","dimgray","dodgerblue","firebrick","floralwhite","forestgreen","fuchsia","gainsboro","ghostwhite","gold","goldenrod","gray","grey","green","greenyellow","honeydew","hotpink","indianred","indigo","ivory","khaki","lavender","lavenderblush","lawngreen","lemonchiffon","lightblue","lightcoral","lightcyan","lightgoldenrodyellow","lightgray","lightgreen","lightpink","lightsalmon","lightseagreen","lightskyblue","lightslategray","lightsteelblue","lightyellow","lime","limegreen","linen","magenta","maroon","mediumaquamarine","mediumblue","mediumorchid","mediumpurple","mediumseagreen","mediumslateblue","mediumspringgreen","mediumturquoise","mediumvioletred","midnightblue","mintcream","mistyrose","moccasin","navajowhite","navy","oldlace","olive","olivedrab","orange","orangered","orchid","palegoldenrod","palegreen","paleturquoise","palevioletred","papayawhip","peachpuff","peru","pink","plum","powderblue","purple","rebeccapurple","red","rosybrown","royalblue","saddlebrown","salmon","sandybrown","seagreen","seashell","sienna","silver","skyblue","slateblue","slategray","snow","springgreen","steelblue","tan","teal","thistle","tomato","turquoise","violet","wheat","white","whitesmoke","yellow","yellowgreen"].map(n=>({type:"constant",label:n}))),YC=["a","abbr","address","article","aside","b","bdi","bdo","blockquote","body","br","button","canvas","caption","cite","code","col","colgroup","dd","del","details","dfn","dialog","div","dl","dt","em","figcaption","figure","footer","form","header","hgroup","h1","h2","h3","h4","h5","h6","hr","html","i","iframe","img","input","ins","kbd","label","legend","li","main","meter","nav","ol","output","p","pre","ruby","section","select","small","source","span","strong","sub","summary","sup","table","tbody","td","template","textarea","tfoot","th","thead","tr","u","ul"].map(n=>({type:"type",label:n})),zn=/^[\w-]*/,HC=n=>{let{state:e,pos:t}=n,i=de(e).resolveInner(t,-1);if(i.name=="PropertyName")return{from:i.from,options:hc(),validFor:zn};if(i.name=="ValueName")return{from:i.from,options:om,validFor:zn};if(i.name=="PseudoClassName")return{from:i.from,options:sm,validFor:zn};if(i.name=="TagName"){for(let{parent:o}=i;o;o=o.parent)if(o.name=="Block")return{from:i.from,options:hc(),validFor:zn};return{from:i.from,options:YC,validFor:zn}}if(!n.explicit)return null;let r=i.resolve(t),s=r.childBefore(t);return s&&s.name==":"&&r.name=="PseudoClassSelector"?{from:t,options:sm,validFor:zn}:s&&s.name==":"&&r.name=="Declaration"||r.name=="ArgList"?{from:t,options:om,validFor:zn}:r.name=="Block"?{from:t,options:hc(),validFor:zn}:null},Jl=ws.define({name:"css",parser:JC.configure({props:[zo.add({Declaration:_a()}),_o.add({Block:cy})]}),languageData:{commentTokens:{block:{open:"/*",close:"*/"}},indentOnInput:/^\s*\}$/,wordChars:"-"}});function KC(){return new Co(Jl,Jl.data.of({autocomplete:HC}))}const eI=1,am=294,lm=2,tI=3,Ca=295,iI=4,nI=296,hm=297,rI=299,sI=300,oI=5,aI=6,lI=1,hI=[9,10,11,12,13,32,133,160,5760,8192,8193,8194,8195,8196,8197,8198,8199,8200,8201,8202,8232,8233,8239,8287,12288],iS=125,cI=123,uI=59,cm=47,fI=42,dI=43,pI=45,gI=36,mI=96,OI=92,yI=new Ub({start:!1,shift(n,e){return e==oI||e==aI||e==rI?n:e==sI},strict:!1}),bI=new ii((n,e)=>{let{next:t}=n;(t==iS||t==-1||e.context)&&e.canShift(hm)&&n.acceptToken(hm)},{contextual:!0,fallback:!0}),SI=new ii((n,e)=>{let{next:t}=n,i;hI.indexOf(t)>-1||t==cm&&((i=n.peek(1))==cm||i==fI)||t!=iS&&t!=uI&&t!=-1&&!e.context&&e.canShift(am)&&n.acceptToken(am)},{contextual:!0}),wI=new ii((n,e)=>{let{next:t}=n;if((t==dI||t==pI)&&(n.advance(),t==n.next)){n.advance();let i=!e.context&&e.canShift(lm);n.acceptToken(i?lm:tI)}},{contextual:!0}),vI=new ii(n=>{for(let e=!1,t=0;;t++){let{next:i}=n;if(i<0){t&&n.acceptToken(Ca);break}else if(i==mI){t?n.acceptToken(Ca):n.acceptToken(nI,1);break}else if(i==cI&&e){t==1?n.acceptToken(iI,1):n.acceptToken(Ca,-1);break}else if(i==10&&t){n.advance(),n.acceptToken(Ca);break}else i==OI&&n.advance();e=i==gI,n.advance()}}),kI=new ii((n,e)=>{if(!(n.next!=101||!e.dialectEnabled(lI))){n.advance();for(let t=0;t<6;t++){if(n.next!="xtends".charCodeAt(t))return;n.advance()}n.next>=57&&n.next<=65||n.next>=48&&n.next<=90||n.next==95||n.next>=97&&n.next<=122||n.next>160||n.acceptToken(eI)}}),xI=$s({"get set async static":b.modifier,"for while do if else switch try catch finally return throw break continue default case":b.controlKeyword,"in of await yield void typeof delete instanceof":b.operatorKeyword,"let var const function class extends":b.definitionKeyword,"import export from":b.moduleKeyword,"with debugger as new":b.keyword,TemplateString:b.special(b.string),super:b.atom,BooleanLiteral:b.bool,this:b.self,null:b.null,Star:b.modifier,VariableName:b.variableName,"CallExpression/VariableName TaggedTemplateExpression/VariableName":b.function(b.variableName),VariableDefinition:b.definition(b.variableName),Label:b.labelName,PropertyName:b.propertyName,PrivatePropertyName:b.special(b.propertyName),"CallExpression/MemberExpression/PropertyName":b.function(b.propertyName),"FunctionDeclaration/VariableDefinition":b.function(b.definition(b.variableName)),"ClassDeclaration/VariableDefinition":b.definition(b.className),PropertyDefinition:b.definition(b.propertyName),PrivatePropertyDefinition:b.definition(b.special(b.propertyName)),UpdateOp:b.updateOperator,LineComment:b.lineComment,BlockComment:b.blockComment,Number:b.number,String:b.string,ArithOp:b.arithmeticOperator,LogicOp:b.logicOperator,BitOp:b.bitwiseOperator,CompareOp:b.compareOperator,RegExp:b.regexp,Equals:b.definitionOperator,Arrow:b.function(b.punctuation),": Spread":b.punctuation,"( )":b.paren,"[ ]":b.squareBracket,"{ }":b.brace,"InterpolationStart InterpolationEnd":b.special(b.brace),".":b.derefOperator,", ;":b.separator,"@":b.meta,TypeName:b.typeName,TypeDefinition:b.definition(b.typeName),"type enum interface implements namespace module declare":b.definitionKeyword,"abstract global Privacy readonly override":b.modifier,"is keyof unique infer":b.operatorKeyword,JSXAttributeValue:b.attributeValue,JSXText:b.content,"JSXStartTag JSXStartCloseTag JSXSelfCloseEndTag JSXEndTag":b.angleBracket,"JSXIdentifier JSXNameSpacedName":b.tagName,"JSXAttribute/JSXIdentifier JSXAttribute/JSXNameSpacedName":b.attributeName,"JSXBuiltin/JSXIdentifier":b.standard(b.tagName)}),TI={__proto__:null,export:18,as:23,from:29,default:32,async:37,function:38,this:50,true:58,false:58,null:68,void:72,typeof:76,super:92,new:126,await:143,yield:145,delete:146,class:156,extends:158,public:213,private:213,protected:213,readonly:215,instanceof:234,satisfies:237,in:238,const:240,import:272,keyof:327,unique:331,infer:337,is:373,abstract:393,implements:395,type:397,let:400,var:402,interface:409,enum:413,namespace:419,module:421,declare:425,global:429,for:450,of:459,while:462,with:466,do:470,if:474,else:476,switch:480,case:486,try:492,catch:496,finally:500,return:504,throw:508,break:512,continue:516,debugger:520},QI={__proto__:null,async:113,get:115,set:117,public:175,private:175,protected:175,static:177,abstract:179,override:181,readonly:187,accessor:189,new:377},PI={__proto__:null,"<":133},AI=Qs.deserialize({version:14,states:"$CWO`QdOOO$}QdOOO)WQ(C|O'#ChO)_OWO'#DYO+jQdO'#D_O+zQdO'#DjO$}QdO'#DtO.OQdO'#DzOOQ(C['#ET'#ETO.fQ`O'#EQOOQO'#IW'#IWO.nQ`O'#GgOOQO'#Ee'#EeO.yQ`O'#EdO/OQ`O'#EdO1QQ(C|O'#JQO3nQ(C|O'#JRO4_Q`O'#FSO4dQ!bO'#FkOOQ(C['#F['#F[O4oO#tO'#F[O4}Q&jO'#FrO6bQ`O'#FqOOQ(C['#JR'#JROOQ(CW'#JQ'#JQOOQS'#Jk'#JkO6gQ`O'#H{O6lQ(ChO'#H|OOQS'#Iu'#IuOOQS'#IO'#IOQ`QdOOO$}QdO'#DlO6tQ`O'#GgO6yQ&jO'#CmO7XQ`O'#EcO7dQ`O'#EnO7iQ&jO'#FZO8TQ`O'#GgO8YQ`O'#GkO8eQ`O'#GkO8sQ`O'#GnO8sQ`O'#GoO8sQ`O'#GqO6tQ`O'#GtO9dQ`O'#GwO:uQ`O'#CdO;VQ`O'#HUO;_Q`O'#H[O;_Q`O'#H^O`QdO'#H`O;_Q`O'#HbO;_Q`O'#HeO;dQ`O'#HkO;iQ(CjO'#HqO$}QdO'#HsO;tQ(CjO'#HuOWQpO'#FZO$}QdO'#DZOOOW'#IQ'#IQO>`OWO,59tOOQ(C[,59t,59tO>kQdO'#IRO?OQ`O'#JSOAQQtO'#JSO)jQdO'#JSOAXQ`O,59yOAoQ`O'#EeOA|Q`O'#J`OBXQ`O'#J_OBXQ`O'#J_OBaQ`O,5;ROBfQ`O'#J^OOQ(C[,5:U,5:UOBmQdO,5:UODnQ(C|O,5:`OE_Q`O,5:fOEdQ`O'#J[OF^Q(ChO'#J]O8YQ`O'#J[OFeQ`O'#J[OFmQ`O,5;QOFrQ`O'#J[OOQ(C]'#Ch'#ChO$}QdO'#DzOGfQpO,5:lOOQO'#JX'#JXOOQO-EgOOQS'#Ix'#IxOOQS,5>h,5>hOOQS-E;|-E;|O!.xQ(C|O,5:WOOQ(CX'#Cp'#CpO!/lQ&kO,5=ROOQO'#Cf'#CfO!/}Q(ChO'#IyO6bQ`O'#IyO;dQ`O,59XO!0`Q!bO,59XO!0hQ&jO,59XO6yQ&jO,59XO!0sQ`O,5;OO!0{Q`O'#HTO!1ZQ`O'#JoO$}QdO,5;sO!1cQ,UO,5;uO!1hQ`O,5=nO!1mQ`O,5=nO!1rQ`O,5=nO6lQ(ChO,5=nO!2QQ`O'#EgO!2wQ,UO'#EhOOQ(CW'#J^'#J^O!3OQ(ChO'#JlO6lQ(ChO,5=VO8sQ`O,5=]OOQP'#Cs'#CsO!3ZQ!bO,5=YO!3cQ!cO,5=ZO!3nQ`O,5=]O!3sQpO,5=`O;dQ`O'#GyO6tQ`O'#G{O!3{Q`O'#G{O6yQ&jO'#HOO!4QQ`O'#HOOOQS,5=c,5=cO!4VQ`O'#HPO!4_Q`O'#CmO!4dQ`O,59OO!4nQ`O,59OO!6sQdO,59OOOQS,59O,59OO!7QQ(ChO,59OO$}QdO,59OO!7]QdO'#HWOOQS'#HX'#HXOOQS'#HY'#HYO`QdO,5=pO!7mQ`O,5=pO`QdO,5=vO`QdO,5=xO!7rQ`O,5=zO`QdO,5=|O!7wQ`O,5>PO!7|QdO,5>VOOQS,5>],5>]O$}QdO,5>]O6lQ(ChO,5>_OOQS,5>a,5>aO!aOOQS,5>c,5>cO!cOOQS,5>e,5>eO!mO)jQdO,5>mOOQO,5>s,5>sO!CUQdO'#IROOQO-ExOOQ(CW-E<[-E<[O#5]Q(C}O1G0tOOQ(C[1G0t1G0tO#7hQ(C|O1G1YO#8[Q!bO,5;}O#8dQ!bO,5OQ,UO'#GXOOQ(C],5=Q,5=QOKhQ&jO,5?hOKhQ&jO,5?hO#>TQ`O'#IcO#>`Q`O,5?gO#>hQ`O,59^O#?XQ&kO,59mOOQ(C],59m,59mO#?zQ&kO,5<`O#@mQ&kO,5mO$)XQ`O1G5YO$)aQ`O1G5eO$)iQtO1G5fO8YQ`O,5>sO$)sQ`O1G5bO$)sQ`O1G5bO8YQ`O1G5bO$){Q(C|O1G5cO$}QdO1G5cO$*]Q(ChO1G5cO$*nQ`O,5>uO8YQ`O,5>uOOQO,5>u,5>uO$+SQ`O,5>uOOQO-Ez,5>zO$8rQ`O,5>zOOQ(C]1G2Z1G2ZP$8wQ`O'#I`POQ(C]-E<^-E<^O$9hQ&kO1G2gO$:ZQ&kO1G2iO$:eQqO1G2kOOQ(C]1G2S1G2SO$:lQ`O'#I_O$:zQ`O,5@SO$:zQ`O,5@SO$;SQ`O,5@SO$;_Q`O,5@SOOQO1G2U1G2UO$;mQ&kO1G2TOKhQ&jO1G2TO$;}QMhO'#IaO$<_Q`O,5@TOJRQ&jO,5@TO$|,5>|OOQO-E<`-E<`OOQ(C]1G2]1G2]O!)dQ,UO,5},5>}OOQO-EkQqO'#JjO$(iQ`O7+(XO$>uQ`O7+(XO$>}QqO7+(XO$?XQ(CyO'#ChO$?lQ(CyO,5ROOQS,5>R,5>RO$}QdO'#HhO$EoQ`O'#HjOOQS,5>X,5>XO8YQ`O,5>XOOQS,5>Z,5>ZOOQS7+)]7+)]OOQS7+)c7+)cOOQS7+)g7+)gOOQS7+)i7+)iO$EtQ!bO1G5[O$FYQ!LUO1G0oO$FdQ`O1G0oOOQO1G/k1G/kO$FoQ!LUO1G/kO$FyQ`O,5?pO;dQ`O1G/kOMqQdO'#DeOOQO,5>n,5>nOOQO-Et,5>tOOQO-EoOOQO-EpO$}QdO,5>pOOQO-ExOOOO7+'_7+'_OOOW1G/S1G/SOOQ(C]1G4f1G4fOKhQ&jO7+(VO%7}Q`O,5>yO6tQ`O,5>yOOQO-E<]-E<]O%8]Q`O1G5nO%8]Q`O1G5nO%8eQ`O1G5nO%8pQ&kO7+'oO%9QQqO,5>{O%9[Q`O,5>{OJRQ&jO,5>{OOQO-E<_-E<_O%9aQqO1G5oO%9kQ`O1G5oOOQ(CW1G2_1G2_O$VQdO'#JUO%>^Q,UO'#E[O%>tQ(ChO'#E[O$$sQ(DjO'#E[O$%hQ,UO'#G}OOQO'#Ih'#IhO%?YQ,UO,5=hOOQS,5=h,5=hO%?aQ,UO'#E[O%?rQ,UO'#E[O%@YQ,UO'#E[O%@vQ,UO'#G}O%AXQ`O7+(mO%A^Q`O7+(mO%AfQqO7+(mOOQS7+(m7+(mOJRQ&jO7+(mO$}QdO7+(mOJRQ&jO7+(mO%ApQaO7+(mOOQS7+(p7+(pO6lQ(ChO7+(pO#=PQ`O7+(pO6bQ`O7+(pO!0`Q!bO7+(pO%BOQ`O,5?TOOQO-ESOOQS,5>U,5>UO%CYQ`O1G3sO8YQ`O7+&ZOMqQdO7+&ZOOQ(CW1G5[1G5[OOQO7+%V7+%VO%C_Q!LUO1G5fO;dQ`O7+%VO;dQ`O1G0VOOQO1G0b1G0bO$}QdO1G0bO%CiQ(ChO1G0bO%CtQ(ChO1G0bO!0`Q!bO1G0VO$%_Q,UO1G0VO%DSQ,UO1G0VO%DaQ(DjO1G0bO%D{Q,UO1G0VO$%_Q,UO1G0bO%E]Q,UO1G0bO%EvQ(ChO1G0bOOQO1G0V1G0VO%F[Q(C|O1G0bOOQ(C[<VQdO,5iQ!LVO7+'qO&@_Q&kOG26wOOQO<wAN>wO;dQ`OAN>wO$}QdOAN?SO!0`Q!bOAN>wO&ATQ(ChOAN?SO$%_Q,UOAN>wO&A`Q(ChOAN?SOOQS!$(!P!$(!PO$(iQ`O!$(!PO&AnQ(C}OG26wOOQ(CWG26lG26lOOQO<SO!T+rO!U'wX~O!U+tO~O!_+kO#T+jO!T#]X!U#]X~O!T+uO!U(TX~O!U+wO~O]&VOl&VO{+nO'k$vO's)TO~O!Z+xO![+xO~P!AQO_+}O!U,PO!Y,QO!Z+|O![+|O!u;WO!y,UO!z,SO!{,TO!|,RO#P,VO#Q,VO'|+zO~P!AQOP,[O!V&cO!q,ZO~Oo,aO~O!Q&ua!T&ua~P!-RO!S,eO!Q&uX!T&uX~P$}O!T&rO!Q'va~O!Q'va~P?WO!T&yO!Q(Ra~O{%WO!S,iO!V%XO'j$tO!Q&{X!T&{X~O!T'WO!e(Oa~O{%WO!V%XO#_,lO'j$tO~O#T,nO!T(Pa!e(Pa_(Pa'e(Pa~O!_#UO~P!DvO{%WO!S,qO!V%XO!uXO#^,sO#_,qO'j$tO!T&}X!e&}X~Oy,wO!f#XO~OP,{O!V&cO!q,zO%],yO'n$bO~O_#Wi!T#Wi'e#Wi'a#Wi!Q#Wi!e#Wio#Wi!V#Wi%]#Wi!_#Wi~P!-ROP=mOx(mO{(nO(U(pO(V(rO~O#`#Sa!T#Sa!e#Sa#T#Sa!V#Sa_#Sa'e#Sa!Q#Sa~P!G[O!d#WOP'qXx'qX{'qX(U'qX(V'qXQ'qXZ'qXk'qXy'qX!T'qX!c'qX!f'qX!l'qX#c'qX#d'qX#e'qX#f'qX#g'qX#h'qX#i'qX#j'qX#k'qX#m'qX#o'qX#q'qX#r'qX'r'qX'}'qX~O#`'qX_'qX'e'qX!e'qX!Q'qX'a'qX!V'qX#T'qXo'qX%]'qX!_'qX~P!HZO!T-UOe'yX~P!&VOe-WO~O!T-XO!e'zX~P!-RO!e-[O~O!Q-^O~OQ#lOx#YOy#ZO{#[O!d#WO!f#XO!l#lO'rROZ#bi_#bik#bi!T#bi!c#bi#d#bi#e#bi#f#bi#g#bi#h#bi#i#bi#j#bi#k#bi#m#bi#o#bi#q#bi#r#bi'e#bi'}#bi(U#bi(V#bi'a#bi!Q#bi!e#bio#bi!V#bi%]#bi!_#bi~O#c#bi~P!KrO#c#_O~P!KrOQ#lOx#YOy#ZO{#[O!d#WO!f#XO!l#lO#c#_O#d#`O#e#`O#f#`O'rROZ#bi_#bi!T#bi!c#bi#g#bi#h#bi#i#bi#j#bi#k#bi#m#bi#o#bi#q#bi#r#bi'e#bi'}#bi(U#bi(V#bi'a#bi!Q#bi!e#bio#bi!V#bi%]#bi!_#bi~Ok#bi~P!NdOk#aO~P!NdOQ#lOk#aOx#YOy#ZO{#[O!d#WO!f#XO!l#lO#c#_O#d#`O#e#`O#f#`O#g#bO'rRO_#bi!T#bi#m#bi#o#bi#q#bi#r#bi'e#bi'}#bi(U#bi(V#bi'a#bi!Q#bi!e#bio#bi!V#bi%]#bi!_#bi~OZ#bi!c#bi#h#bi#i#bi#j#bi#k#bi~P##UOZ#sO!c#cO#h#cO#i#cO#j#rO#k#cO~P##UOQ#lOZ#sOk#aOx#YOy#ZO{#[O!c#cO!d#WO!f#XO!l#lO#c#_O#d#`O#e#`O#f#`O#g#bO#h#cO#i#cO#j#rO#k#cO#m#dO'rRO_#bi!T#bi#o#bi#q#bi#r#bi'e#bi'}#bi(V#bi'a#bi!Q#bi!e#bio#bi!V#bi%]#bi!_#bi~O(U#bi~P#&VO(U#]O~P#&VOQ#lOZ#sOk#aOx#YOy#ZO{#[O!c#cO!d#WO!f#XO!l#lO#c#_O#d#`O#e#`O#f#`O#g#bO#h#cO#i#cO#j#rO#k#cO#m#dO#o#fO'rRO(U#]O_#bi!T#bi#q#bi#r#bi'e#bi'}#bi'a#bi!Q#bi!e#bio#bi!V#bi%]#bi!_#bi~O(V#bi~P#(wO(V#^O~P#(wOQ#lOZ#sOk#aOx#YOy#ZO{#[O!c#cO!d#WO!f#XO!l#lO#c#_O#d#`O#e#`O#f#`O#g#bO#h#cO#i#cO#j#rO#k#cO#m#dO#o#fO#q#hO'rRO(U#]O(V#^O~O_#bi!T#bi#r#bi'e#bi'}#bi'a#bi!Q#bi!e#bio#bi!V#bi%]#bi!_#bi~P#+iOQ[XZ[Xk[Xx[Xy[X{[X!c[X!d[X!f[X!l[X#T[X#`dX#c[X#d[X#e[X#f[X#g[X#h[X#i[X#j[X#k[X#m[X#o[X#q[X#r[X#w[X'r[X'}[X(U[X(V[X!T[X!U[X~O#u[X~P#.SOQ#lOZ;mOk;aOx#YOy#ZO{#[O!c;cO!d#WO!f#XO!l#lO#c;_O#d;`O#e;`O#f;`O#g;bO#h;cO#i;cO#j;lO#k;cO#m;dO#o;fO#q;hO#r;iO'rRO'}#jO(U#]O(V#^O~O#u-`O~P#0aOQ'uXZ'uXk'uXx'uXy'uX{'uX!c'uX!d'uX!f'uX!l'uX#c'uX#d'uX#e'uX#f'uX#g'uX#h'uX#i'uX#j'uX#m'uX#o'uX#q'uX#r'uX'r'uX'}'uX(U'uX(V'uX!T'uX~O#T;nO#w;nO#k'uX#u'uX!U'uX~P#2_O_'Qa!T'Qa'e'Qa'a'Qa!e'Qao'Qa!Q'Qa!V'Qa%]'Qa!_'Qa~P!-ROQ#biZ#bi_#bik#biy#bi!T#bi!c#bi!d#bi!f#bi!l#bi#c#bi#d#bi#e#bi#f#bi#g#bi#h#bi#i#bi#j#bi#k#bi#m#bi#o#bi#q#bi#r#bi'e#bi'r#bi'}#bi'a#bi!Q#bi!e#bio#bi!V#bi%]#bi!_#bi~P!G[O_#vi!T#vi'e#vi'a#vi!Q#vi!e#vio#vi!V#vi%]#vi!_#vi~P!-RO$S-cO$U-cO~O$S-dO$U-dO~O!_(VO#T-eO!V$YX$P$YX$S$YX$U$YX$]$YX~O!S-fO~O!V(YO$P-hO$S(XO$U(XO$]-iO~O!T;jO!U'tX~P#0aO!U-jO~O$]-lO~OS(hO'c(iO'd-oO~O]-rOl-rO!Q-sO~O!TdX!_dX!edX!e$oX'}dX~P!$|O!e-yO~P!G[O!T-zO!_#UO'}'SO!e([X~O!e.PO~O!S(yO'j$tO!e([P~O#`.RO~O!Q$oX!T$oX!_$vX~P!$|O!T.SO!Q(]X~P!G[O!_.UO~O!Q.WO~Ok.[O!_#UO!f$mO'n$bO'}'SO~O'j.^O~O!_)yO~O_$pO!T.bO'e$pO~O!U.dO~P!(wO!Z.eO![.eO'k$vO's)TO~O{.gO's)TO~O#P.hO~O'j%^Oe'VX!T'VX~O!T)dOe'oa~Oe.mO~Ox.nOy.nO{.oOPua(Uua(Vua!Tua#Tua~Oeua#uua~P#>mOx(mO{(nOP$ha(U$ha(V$ha!T$ha#T$ha~Oe$ha#u$ha~P#?cOx(mO{(nOP$ja(U$ja(V$ja!T$ja#T$ja~Oe$ja#u$ja~P#@UO].pO~O#`.qO~Oe$xa!T$xa#T$xa#u$xa~P!&VO#`.tO~OP,{O!V&cO!q,zO%],yO~O]$SOk$TOl$SOm$SOr$dOt$eOv;oO{$[O!V$]O!a=`O!f$XO#_;xO#|$iO$i;rO$k;uO$n$jO'n$bO'r$UO~Oi.{O'j.zO~P#AvO!_)yO!V'ma_'ma!T'ma'e'ma~O#`/RO~OZ[X!TdX!UdX~O!T/SO!U(dX~O!U/UO~OZ/VO~O]/XO'j*RO~O!V%OO'j$tO^'_X!T'_X~O!T*WO^(ca~O!e/[O~P!-RO]/^O~OZ/_O~O^/`O~O!T*dO_(`a'e(`a~O#T/fO~OP/iO!V$]O~O's'lO!U(aP~OP/sO!V/oO!q/rO%]/qO'n$bO~OZ/}O!T/{O!U(bX~O!U0OO~O^0QO_$pO'e$pO~O]0RO~O]0SO'j!|O~O#k0TO%}0UO~P1nO#T#tO#k0TO%}0UO~O_0VO~P$}O_0XO~O&W0]OQ&UiR&UiX&Ui]&Ui_&Uib&Uic&Uii&Uik&Uil&Uim&Uir&Uit&Uiv&Ui{&Ui!O&Ui!P&Ui!V&Ui!a&Ui!f&Ui!i&Ui!j&Ui!k&Ui!l&Ui!m&Ui!p&Ui!u&Ui#l&Ui#|&Ui$Q&Ui%[&Ui%^&Ui%`&Ui%a&Ui%d&Ui%f&Ui%i&Ui%j&Ui%l&Ui%y&Ui&P&Ui&R&Ui&T&Ui&V&Ui&Y&Ui&`&Ui&f&Ui&h&Ui&j&Ui&l&Ui&n&Ui'a&Ui'j&Ui'r&Ui'|&Ui(Z&Ui!U&Ui`&Ui&]&Ui~O`0cO!U0aO&]0bO~P`O!VTO!f0eO~O&d+aOQ&_iR&_iX&_i]&_i_&_ib&_ic&_ii&_ik&_il&_im&_ir&_it&_iv&_i{&_i!O&_i!P&_i!V&_i!a&_i!f&_i!i&_i!j&_i!k&_i!l&_i!m&_i!p&_i!u&_i#l&_i#|&_i$Q&_i%[&_i%^&_i%`&_i%a&_i%d&_i%f&_i%i&_i%j&_i%l&_i%y&_i&P&_i&R&_i&T&_i&V&_i&Y&_i&`&_i&f&_i&h&_i&j&_i&l&_i&n&_i'a&_i'j&_i'r&_i'|&_i(Z&_i!U&_i&W&_i`&_i&]&_i~O!Q0kO~O!T!Xa!U!Xa~P#0aO!S0rO!Y&bO!Z&ZO![&ZO!T&vX!U&vX~P!AQO!T+rO!U'wa~O!T&|X!U&|X~P!2fO!T+uO!U(Ta~O!Y0{O!Z0zO![0zO!u;WO!y1OO!z0}O!{0}O!|0|O#P1PO#Q1PO'|+zO~P!AQO_$pO!_#UO!f$mO!l1UO#T1SO'e$pO'n$bO'}'SO~O]&VOl&VO{+nO's)TO'|+zO~O_+}O!U1XO!Y,QO!Z+|O![+|O!u;WO!y,UO!z,SO!{,TO!|,RO#P,VO#Q,VO'|+zO~P!AQO!Z0zO![0zO'|+zO~P!AQO!Y0{O!Z0zO![0zO'|+zO~P!AQO!VTO!Y0{O!Z0zO![0zO!|0|O#P1PO#Q1PO'|+zO~P!AQO!Y0{O!Z0zO![0zO!z0}O!{0}O!|0|O#P1PO#Q1PO'|+zO~P!AQO!V&cO~O!V&cO~P!G[O!T#pOo$ga~O!Q&ui!T&ui~P!-RO!T&rO!Q'vi~O!T&yO!Q(Ri~O!Q(Si!T(Si~P!-RO!T'WO!e(Oi~O!T(Pi!e(Pi_(Pi'e(Pi~P!-RO#T1eO!T(Pi!e(Pi_(Pi'e(Pi~O{%WO!V%XO!uXO#^1hO#_1gO'j$tO~O{%WO!V%XO#_1gO'j$tO~OP1pO!V&cO!q1oO%]1nO~OP1pO!V&cO!q1oO%]1nO'n$bO~O#`uaQuaZua_uakua!cua!dua!fua!lua#cua#dua#eua#fua#gua#hua#iua#jua#kua#mua#oua#qua#rua'eua'rua'}ua!eua!Qua'aua!Vuaoua%]ua!_ua~P#>mO#`$haQ$haZ$ha_$hak$hay$ha!c$ha!d$ha!f$ha!l$ha#c$ha#d$ha#e$ha#f$ha#g$ha#h$ha#i$ha#j$ha#k$ha#m$ha#o$ha#q$ha#r$ha'e$ha'r$ha'}$ha!e$ha!Q$ha'a$ha!V$hao$ha%]$ha!_$ha~P#?cO#`$jaQ$jaZ$ja_$jak$jay$ja!c$ja!d$ja!f$ja!l$ja#c$ja#d$ja#e$ja#f$ja#g$ja#h$ja#i$ja#j$ja#k$ja#m$ja#o$ja#q$ja#r$ja'e$ja'r$ja'}$ja!e$ja!Q$ja'a$ja!V$jao$ja%]$ja!_$ja~P#@UO#`$xaQ$xaZ$xa_$xak$xay$xa!T$xa!c$xa!d$xa!f$xa!l$xa#c$xa#d$xa#e$xa#f$xa#g$xa#h$xa#i$xa#j$xa#k$xa#m$xa#o$xa#q$xa#r$xa'e$xa'r$xa'}$xa!e$xa!Q$xa'a$xa!V$xa#T$xao$xa%]$xa!_$xa~P!G[O_#Wq!T#Wq'e#Wq'a#Wq!Q#Wq!e#Wqo#Wq!V#Wq%]#Wq!_#Wq~P!-ROe&wX!T&wX~PKhO!T-UOe'ya~O!S1xO!T&xX!e&xX~P$}O!T-XO!e'za~O!T-XO!e'za~P!-RO!Q1{O~O#u!ha!U!ha~PBtO#u!`a!T!`a!U!`a~P#0aO!V2^O$QbO$Z2_O~O!U2cO~Oo2dO~P!G[O_$dq!T$dq'e$dq'a$dq!Q$dq!e$dqo$dq!V$dq%]$dq!_$dq~P!-RO!Q2eO~O]-rOl-rO~Ox(mO{(nO(V(rOP%Ti(U%Ti!T%Ti#T%Ti~Oe%Ti#u%Ti~P$9POx(mO{(nOP%Vi(U%Vi(V%Vi!T%Vi#T%Vi~Oe%Vi#u%Vi~P$9rO'}#jO~P!G[O!S2hO'j$tO!T'RX!e'RX~O!T-zO!e([a~O!T-zO!_#UO!e([a~O!T-zO!_#UO'}'SO!e([a~Oe$qi!T$qi#T$qi#u$qi~P!&VO!S2pO'j)OO!Q'TX!T'TX~P!&tO!T.SO!Q(]a~O!T.SO!Q(]a~P!G[O!_#UO~O!_#UO#k2xO~Ok2{O!_#UO'}'SO~Oe'pi!T'pi~P!&VO#T3OOe'pi!T'pi~P!&VO!e3RO~O_$eq!T$eq'e$eq'a$eq!Q$eq!e$eqo$eq!V$eq%]$eq!_$eq~P!-RO!T3VO!V(^X~P!G[O!V&cO%]1nO~O!V&cO%]1nO~P!G[O!V$oX%Q[X_$oX!T$oX'e$oX~P!$|O%Q3XOPhXxhX{hX!VhX(UhX(VhX_hX!ThX'ehX~O%Q3XO~O]3_O%^3`O'j*RO!T'^X!U'^X~O!T/SO!U(da~OZ3dO~O^3eO~O]3hO~O!Q3iO~O_$pO'e$pO~P!G[O!V$]O~P!G[O!T3nO#T3pO!U(aX~O!U3qO~O]&VOl&VO{3sO!Y4OO!Z3wO![3wO!u;WO!y3}O!z3|O!{3|O#P3{O#Q,VO'k$vO's)TO'|+zO~O!U3zO~P$BTOP4VO!V/oO!q4UO%]4TO~OP4VO!V/oO!q4UO%]4TO'n$bO~O'j!|O!T']X!U']X~O!T/{O!U(ba~O]4aO's4`O~O]4bO~O^4dO~O!e4gO~P$}O_4iO~O_4iO~P$}O#k4kO%}4lO~PExO`0cO!U4pO&]0bO~P`O!_4rO~O!_4tO!T'xi!U'xi!_'xi!f'xi'n'xi~O!T#]i!U#]i~P#0aO#T4uO!T#]i!U#]i~O!T!Xi!U!Xi~P#0aO!Q4vO~O]!tal!ta!Y!ta!Z!ta![!ta!y!ta!z!ta!{!ta!|!ta#P!ta#Q!ta'k!ta's!ta'|!ta~PGQO_$pO!_#UO!f$mO!l5OO#T4|O'e$pO'n$bO'}'SO~O!Z5QO![5QO'|+zO~P!AQO!Y5RO!Z5QO![5QO'|+zO~P!AQO!Y5RO!Z5QO![5QO!|5TO#P5UO#Q5UO'|+zO~P!AQO!Y5RO!Z5QO![5QO!z5VO!{5VO!|5TO#P5UO#Q5UO'|+zO~P!AQO_$pO#T4|O'e$pO~O_$pO!_#UO#T4|O'e$pO~O_$pO!_#UO!l5OO#T4|O'e$pO'}'SO~O!T'WO!e(Oq~O!T(Pq!e(Pq_(Pq'e(Pq~P!-RO{%WO!V%XO#_5aO'j$tO~O!V&cO%]5cO~O!V&cO%]5cO~P!G[OP5hO!V&cO!q5gO%]5cO~O#`%TiQ%TiZ%Ti_%Tik%Tiy%Ti!c%Ti!d%Ti!f%Ti!l%Ti#c%Ti#d%Ti#e%Ti#f%Ti#g%Ti#h%Ti#i%Ti#j%Ti#k%Ti#m%Ti#o%Ti#q%Ti#r%Ti'e%Ti'r%Ti'}%Ti!e%Ti!Q%Ti'a%Ti!V%Tio%Ti%]%Ti!_%Ti~P$9PO#`%ViQ%ViZ%Vi_%Vik%Viy%Vi!c%Vi!d%Vi!f%Vi!l%Vi#c%Vi#d%Vi#e%Vi#f%Vi#g%Vi#h%Vi#i%Vi#j%Vi#k%Vi#m%Vi#o%Vi#q%Vi#r%Vi'e%Vi'r%Vi'}%Vi!e%Vi!Q%Vi'a%Vi!V%Vio%Vi%]%Vi!_%Vi~P$9rO#`$qiQ$qiZ$qi_$qik$qiy$qi!T$qi!c$qi!d$qi!f$qi!l$qi#c$qi#d$qi#e$qi#f$qi#g$qi#h$qi#i$qi#j$qi#k$qi#m$qi#o$qi#q$qi#r$qi'e$qi'r$qi'}$qi!e$qi!Q$qi'a$qi!V$qi#T$qio$qi%]$qi!_$qi~P!G[Oe&wa!T&wa~P!&VO!T&xa!e&xa~P!-RO!T-XO!e'zi~O#u#Wi!T#Wi!U#Wi~P#0aOQ#lOx#YOy#ZO{#[O!d#WO!f#XO!l#lO'rROZ#bik#bi!c#bi#d#bi#e#bi#f#bi#g#bi#h#bi#i#bi#j#bi#k#bi#m#bi#o#bi#q#bi#r#bi#u#bi'}#bi(U#bi(V#bi!T#bi!U#bi~O#c#bi~P%&nO#c;_O~P%&nOQ#lOx#YOy#ZO{#[O!d#WO!f#XO!l#lO#c;_O#d;`O#e;`O#f;`O'rROZ#bi!c#bi#g#bi#h#bi#i#bi#j#bi#k#bi#m#bi#o#bi#q#bi#r#bi#u#bi'}#bi(U#bi(V#bi!T#bi!U#bi~Ok#bi~P%(yOk;aO~P%(yOQ#lOk;aOx#YOy#ZO{#[O!d#WO!f#XO!l#lO#c;_O#d;`O#e;`O#f;`O#g;bO'rRO#m#bi#o#bi#q#bi#r#bi#u#bi'}#bi(U#bi(V#bi!T#bi!U#bi~OZ#bi!c#bi#h#bi#i#bi#j#bi#k#bi~P%+UOZ;mO!c;cO#h;cO#i;cO#j;lO#k;cO~P%+UOQ#lOZ;mOk;aOx#YOy#ZO{#[O!c;cO!d#WO!f#XO!l#lO#c;_O#d;`O#e;`O#f;`O#g;bO#h;cO#i;cO#j;lO#k;cO#m;dO'rRO#o#bi#q#bi#r#bi#u#bi'}#bi(V#bi!T#bi!U#bi~O(U#bi~P%-pO(U#]O~P%-pOQ#lOZ;mOk;aOx#YOy#ZO{#[O!c;cO!d#WO!f#XO!l#lO#c;_O#d;`O#e;`O#f;`O#g;bO#h;cO#i;cO#j;lO#k;cO#m;dO#o;fO'rRO(U#]O#q#bi#r#bi#u#bi'}#bi!T#bi!U#bi~O(V#bi~P%/{O(V#^O~P%/{OQ#lOZ;mOk;aOx#YOy#ZO{#[O!c;cO!d#WO!f#XO!l#lO#c;_O#d;`O#e;`O#f;`O#g;bO#h;cO#i;cO#j;lO#k;cO#m;dO#o;fO#q;hO'rRO(U#]O(V#^O~O#r#bi#u#bi'}#bi!T#bi!U#bi~P%2WO_#sy!T#sy'e#sy'a#sy!Q#sy!e#syo#sy!V#sy%]#sy!_#sy~P!-ROP=oOx(mO{(nO(U(pO(V(rO~OQ#biZ#bik#biy#bi!c#bi!d#bi!f#bi!l#bi#c#bi#d#bi#e#bi#f#bi#g#bi#h#bi#i#bi#j#bi#k#bi#m#bi#o#bi#q#bi#r#bi#u#bi'r#bi'}#bi!T#bi!U#bi~P%5OO#u'qX!U'qX~P!HZO#u#vi!T#vi!U#vi~P#0aO!U5tO~O!T'Qa!U'Qa~P#0aO!_#UO'}'SO!T'Ra!e'Ra~O!T-zO!e([i~O!T-zO!_#UO!e([i~Oe$qq!T$qq#T$qq#u$qq~P!&VO!Q'Ta!T'Ta~P!G[O!_5{O~O!T.SO!Q(]i~P!G[O!T.SO!Q(]i~O!Q6PO~O!_#UO#k6UO~Ok6VO!_#UO'}'SO~O!Q6XO~Oe$sq!T$sq#T$sq#u$sq~P!&VO_$ey!T$ey'e$ey'a$ey!Q$ey!e$eyo$ey!V$ey%]$ey!_$ey~P!-RO!T3VO!V(^a~O_#Wy!T#Wy'e#Wy'a#Wy!Q#Wy!e#Wyo#Wy!V#Wy%]#Wy!_#Wy~P!-ROZ6^O~O]6`O'j*RO~O!T/SO!U(di~O]6cO~O^6dO~O!_4tO~O's'lO!T'YX!U'YX~O!T3nO!U(aa~O!f$mO'n$bO_'xX!_'xX!l'xX#T'xX'e'xX'}'xX~O'j6mO~P,RO!u;WO!y6oO!z6nO!{6nO#P1PO#Q1PO~P$%_O_$pO!_#UO!l1UO#T1SO'e$pO'}'SO~O!U6rO~P$BTO]&VOl&VO{6sO's)TO'|+zO~O!Y6wO!Z6vO![6vO#P1PO#Q1PO'|+zO~P!AQO!Y6wO!Z6vO![6vO!z6xO!{6xO#P1PO#Q1PO'|+zO~P!AQO!Z6vO![6vO'k$vO's)TO'|+zO~O!V/oO~O!V/oO%]6zO~O!V/oO%]6zO~P!G[OP7PO!V/oO!q7OO%]6zO~OZ7UO!T']a!U']a~O!T/{O!U(bi~O]7XO~O!e7YO~O!e7ZO~O!e7[O~O!e7[O~P$}O_7^O~O!_7aO~O!e7bO~O!T(Si!U(Si~P#0aO_$pO#T7iO'e$pO~O_$pO!_#UO#T7iO'e$pO~O!Z7mO![7mO'|+zO~P!AQO_$pO!_#UO!f$mO!l7nO#T7iO'e$pO'n$bO'}'SO~O!Y7oO!Z7mO![7mO'|+zO~P!AQO!Y7oO!Z7mO![7mO!|7rO#P7sO#Q7sO'|+zO~P!AQO_$pO!_#UO!l7nO#T7iO'e$pO'}'SO~O_$pO'e$pO~P!-RO!T'WO!e(Oy~O!T(Py!e(Py_(Py'e(Py~P!-RO!V&cO%]7xO~O!V&cO%]7xO~P!G[O#`$qqQ$qqZ$qq_$qqk$qqy$qq!T$qq!c$qq!d$qq!f$qq!l$qq#c$qq#d$qq#e$qq#f$qq#g$qq#h$qq#i$qq#j$qq#k$qq#m$qq#o$qq#q$qq#r$qq'e$qq'r$qq'}$qq!e$qq!Q$qq'a$qq!V$qq#T$qqo$qq%]$qq!_$qq~P!G[O#`$sqQ$sqZ$sq_$sqk$sqy$sq!T$sq!c$sq!d$sq!f$sq!l$sq#c$sq#d$sq#e$sq#f$sq#g$sq#h$sq#i$sq#j$sq#k$sq#m$sq#o$sq#q$sq#r$sq'e$sq'r$sq'}$sq!e$sq!Q$sq'a$sq!V$sq#T$sqo$sq%]$sq!_$sq~P!G[O!T&xi!e&xi~P!-RO#u#Wq!T#Wq!U#Wq~P#0aOx.nOy.nO{.oOPua(Uua(Vua!Uua~OQuaZuakua!cua!dua!fua!lua#cua#dua#eua#fua#gua#hua#iua#jua#kua#mua#oua#qua#rua#uua'rua'}ua!Tua~P%LmOx(mO{(nOP$ha(U$ha(V$ha!U$ha~OQ$haZ$hak$hay$ha!c$ha!d$ha!f$ha!l$ha#c$ha#d$ha#e$ha#f$ha#g$ha#h$ha#i$ha#j$ha#k$ha#m$ha#o$ha#q$ha#r$ha#u$ha'r$ha'}$ha!T$ha~P%NtOx(mO{(nOP$ja(U$ja(V$ja!U$ja~OQ$jaZ$jak$jay$ja!c$ja!d$ja!f$ja!l$ja#c$ja#d$ja#e$ja#f$ja#g$ja#h$ja#i$ja#j$ja#k$ja#m$ja#o$ja#q$ja#r$ja#u$ja'r$ja'}$ja!T$ja~P&!{OQ$xaZ$xak$xay$xa!c$xa!d$xa!f$xa!l$xa#c$xa#d$xa#e$xa#f$xa#g$xa#h$xa#i$xa#j$xa#k$xa#m$xa#o$xa#q$xa#r$xa#u$xa'r$xa'}$xa!T$xa!U$xa~P%5OO#u$dq!T$dq!U$dq~P#0aO#u$eq!T$eq!U$eq~P#0aO!U8RO~O#u8SO~P!&VO!_#UO!T'Ri!e'Ri~O!_#UO'}'SO!T'Ri!e'Ri~O!T-zO!e([q~O!Q'Ti!T'Ti~P!G[O!T.SO!Q(]q~O!Q8YO~P!G[O!Q8YO~Oe'py!T'py~P!&VO!T'Wa!V'Wa~P!G[O!V%Pq_%Pq!T%Pq'e%Pq~P!G[OZ8_O~O!T/SO!U(dq~O]8bO~O#T8cO!T'Ya!U'Ya~O!T3nO!U(ai~P#0aOQ[XZ[Xk[Xx[Xy[X{[X!Q[X!T[X!c[X!d[X!f[X!l[X#T[X#`dX#c[X#d[X#e[X#f[X#g[X#h[X#i[X#j[X#k[X#m[X#o[X#q[X#r[X#w[X'r[X'}[X(U[X(V[X~O!_$}X#k$}X~P&*pO#P5UO#Q5UO~P$%_O!z8gO!{8gO#P5UO#Q5UO~P$%_O!Z8jO![8jO'k$vO's)TO'|+zO~O!Y8mO!Z8jO![8jO#P5UO#Q5UO'|+zO~P!AQO!V/oO%]8pO~O!V/oO%]8pO~P!G[O]8wO's8vO~O!T/{O!U(bq~O!e8yO~O!e8yO~P$}O!e8{O~O!e8|O~O#T9OO!T#]y!U#]y~O!T#]y!U#]y~P#0aO_$pO#T9RO'e$pO~O_$pO!_#UO#T9RO'e$pO~O!Z9WO![9WO'|+zO~P!AQO_$pO!_#UO!l9XO#T9RO'e$pO'}'SO~O!f$mO'n$bO~P&0|O!Y9YO!Z9WO![9WO'|+zO~P!AQO!V&cO%]9^O~O!V&cO%]9^O~P!G[O#u#sy!T#sy!U#sy~P#0aOQ$qiZ$qik$qiy$qi!c$qi!d$qi!f$qi!l$qi#c$qi#d$qi#e$qi#f$qi#g$qi#h$qi#i$qi#j$qi#k$qi#m$qi#o$qi#q$qi#r$qi#u$qi'r$qi'}$qi!T$qi!U$qi~P%5OOx(mO{(nO(V(rOP%Ti(U%Ti!U%Ti~OQ%TiZ%Tik%Tiy%Ti!c%Ti!d%Ti!f%Ti!l%Ti#c%Ti#d%Ti#e%Ti#f%Ti#g%Ti#h%Ti#i%Ti#j%Ti#k%Ti#m%Ti#o%Ti#q%Ti#r%Ti#u%Ti'r%Ti'}%Ti!T%Ti~P&4cOx(mO{(nOP%Vi(U%Vi(V%Vi!U%Vi~OQ%ViZ%Vik%Viy%Vi!c%Vi!d%Vi!f%Vi!l%Vi#c%Vi#d%Vi#e%Vi#f%Vi#g%Vi#h%Vi#i%Vi#j%Vi#k%Vi#m%Vi#o%Vi#q%Vi#r%Vi#u%Vi'r%Vi'}%Vi!T%Vi~P&6jO#u$ey!T$ey!U$ey~P#0aO#u#Wy!T#Wy!U#Wy~P#0aO!_#UO!T'Rq!e'Rq~O!T-zO!e([y~O!Q'Tq!T'Tq~P!G[O!Q9dO~P!G[O!T/SO!U(dy~O!T3nO!U(aq~O#P7sO#Q7sO~P$%_O!Z9nO![9nO'k$vO's)TO'|+zO~O!V/oO%]9qO~O!V/oO%]9qO~P!G[O!e9tO~O_$pO#T9zO'e$pO~O_$pO!_#UO#T9zO'e$pO~O!Z9}O![9}O'|+zO~P!AQO_$pO!_#UO!l:OO#T9zO'e$pO'}'SO~OQ$qqZ$qqk$qqy$qq!c$qq!d$qq!f$qq!l$qq#c$qq#d$qq#e$qq#f$qq#g$qq#h$qq#i$qq#j$qq#k$qq#m$qq#o$qq#q$qq#r$qq#u$qq'r$qq'}$qq!T$qq!U$qq~P%5OOQ$sqZ$sqk$sqy$sq!c$sq!d$sq!f$sq!l$sq#c$sq#d$sq#e$sq#f$sq#g$sq#h$sq#i$sq#j$sq#k$sq#m$sq#o$sq#q$sq#r$sq#u$sq'r$sq'}$sq!T$sq!U$sq~P%5OOe%X!Z!T%X!Z#T%X!Z#u%X!Z~P!&VO!T'Yq!U'Yq~P#0aO!T#]!Z!U#]!Z~P#0aO_$pO#T:aO'e$pO~O_$pO!_#UO#T:aO'e$pO~O#`%X!ZQ%X!ZZ%X!Z_%X!Zk%X!Zy%X!Z!T%X!Z!c%X!Z!d%X!Z!f%X!Z!l%X!Z#c%X!Z#d%X!Z#e%X!Z#f%X!Z#g%X!Z#h%X!Z#i%X!Z#j%X!Z#k%X!Z#m%X!Z#o%X!Z#q%X!Z#r%X!Z'e%X!Z'r%X!Z'}%X!Z!e%X!Z!Q%X!Z'a%X!Z!V%X!Z#T%X!Zo%X!Z%]%X!Z!_%X!Z~P!G[O_$pO#T:oO'e$pO~OP=nOx(mO{(nO(U(pO(V(rO~O]#Sal#Sa!U#Sa!Y#Sa!Z#Sa![#Sa!u#Sa!y#Sa!z#Sa!{#Sa#P#Sa#Q#Sa'k#Sa's#Sa'|#Sa~P&D[OQ%X!ZZ%X!Zk%X!Zy%X!Z!c%X!Z!d%X!Z!f%X!Z!l%X!Z#c%X!Z#d%X!Z#e%X!Z#f%X!Z#g%X!Z#h%X!Z#i%X!Z#j%X!Z#k%X!Z#m%X!Z#o%X!Z#q%X!Z#r%X!Z#u%X!Z'r%X!Z'}%X!Z!T%X!Z!U%X!Z~P%5OO]ualua!Yua!Zua![ua!uua!yua!zua!{ua#Pua#Qua'kua'sua'|ua~P%LmO]$hal$ha!Y$ha!Z$ha![$ha!u$ha!y$ha!z$ha!{$ha#P$ha#Q$ha'k$ha's$ha'|$ha~P%NtO]$jal$ja!Y$ja!Z$ja![$ja!u$ja!y$ja!z$ja!{$ja#P$ja#Q$ja'k$ja's$ja'|$ja~P&!{O]$xal$xa!U$xa!Y$xa!Z$xa![$xa!u$xa!y$xa!z$xa!{$xa#P$xa#Q$xa'k$xa's$xa'|$xa~P&D[O]%Til%Ti!Y%Ti!Z%Ti![%Ti!u%Ti!y%Ti!z%Ti!{%Ti#P%Ti#Q%Ti'k%Ti's%Ti'|%Ti~P&4cO]%Vil%Vi!Y%Vi!Z%Vi![%Vi!u%Vi!y%Vi!z%Vi!{%Vi#P%Vi#Q%Vi'k%Vi's%Vi'|%Vi~P&6jO]$qil$qi!U$qi!Y$qi!Z$qi![$qi!u$qi!y$qi!z$qi!{$qi#P$qi#Q$qi'k$qi's$qi'|$qi~P&D[O]$qql$qq!U$qq!Y$qq!Z$qq![$qq!u$qq!y$qq!z$qq!{$qq#P$qq#Q$qq'k$qq's$qq'|$qq~P&D[O]$sql$sq!U$sq!Y$sq!Z$sq![$sq!u$sq!y$sq!z$sq!{$sq#P$sq#Q$sq'k$sq's$sq'|$sq~P&D[O]%X!Zl%X!Z!U%X!Z!Y%X!Z!Z%X!Z![%X!Z!u%X!Z!y%X!Z!z%X!Z!{%X!Z#P%X!Z#Q%X!Z'k%X!Z's%X!Z'|%X!Z~P&D[Oo'tX~P/WO!QdX!TdX#TdX~P&*pOQ[XZ[Xk[Xx[Xy[X{[X!T[X!TdX!c[X!d[X!f[X!l[X#T[X#TdX#`dX#c[X#d[X#e[X#f[X#g[X#h[X#i[X#j[X#k[X#m[X#o[X#q[X#r[X#w[X'r[X'}[X(U[X(V[X~O!_dX!e[X!edX'}dX~P'$ZOQ;VOR;VO]gOb=ZOc!`OigOk;VOlgOmgOrgOt;VOv;VO{SO!OgO!PgO!VTO!a;YO!fVO!i;VO!j;VO!k;VO!l;VO!m;VO!p!_O#|!bO$QbO'j'|O'rRO'|WO(Z=XO~O]$SOi$cOk$TOl$SOm$SOr$dOt$eOv;pO{$[O!V$]O!a=aO!f$XO#_;yO#|$iO$i;sO$k;vO$n$jO'j'dO'n$bO'r$UO~O!T;jO!U$ga~O]$SOi$cOk$TOl$SOm$SOr$dOt$eOv;qO{$[O!V$]O!a=bO!f$XO#_;zO#|$iO$i;tO$k;wO$n$jO'j'dO'n$bO'r$UO~O#l(TO~P'*^O!U[X!UdX~P'$ZO!_;^O~O#`;]O~O!_#UO#`;]O~O#T;nO~O#k;cO~O#T;{O!T(SX!U(SX~O#T;nO!T(QX!U(QX~O#`;|O~Oe TypeParamList TypeDefinition ThisType this LiteralType ArithOp Number BooleanLiteral TemplateType InterpolationEnd Interpolation NullType null VoidType void TypeofType typeof MemberExpression . ?. PropertyName [ TemplateString Interpolation super RegExp ] ArrayExpression Spread , } { ObjectExpression Property async get set PropertyDefinition Block : NewExpression new TypeArgList CompareOp < ) ( ArgList UnaryExpression await yield delete LogicOp BitOp ParenthesizedExpression ClassExpression class extends ClassBody MethodDeclaration Decorator @ MemberExpression PrivatePropertyName CallExpression Privacy static abstract override PrivatePropertyDefinition PropertyDeclaration readonly accessor Optional TypeAnnotation Equals StaticBlock FunctionExpression ArrowFunction ParamList ParamList ArrayPattern ObjectPattern PatternProperty Privacy readonly Arrow MemberExpression BinaryExpression ArithOp ArithOp ArithOp ArithOp BitOp CompareOp instanceof satisfies in const CompareOp BitOp BitOp BitOp LogicOp LogicOp ConditionalExpression LogicOp LogicOp AssignmentExpression UpdateOp PostfixExpression CallExpression TaggedTemplateExpression DynamicImport import ImportMeta JSXElement JSXSelfCloseEndTag JSXStartTag JSXSelfClosingTag JSXIdentifier JSXBuiltin JSXIdentifier JSXNamespacedName JSXMemberExpression JSXSpreadAttribute JSXAttribute JSXAttributeValue JSXEscape JSXEndTag JSXOpenTag JSXFragmentTag JSXText JSXEscape JSXStartCloseTag JSXCloseTag PrefixCast ArrowFunction TypeParamList SequenceExpression KeyofType keyof UniqueType unique ImportType InferredType infer TypeName ParenthesizedType FunctionSignature ParamList NewSignature IndexedType TupleType Label ArrayType ReadonlyType ObjectType MethodType PropertyType IndexSignature PropertyDefinition CallSignature TypePredicate is NewSignature new UnionType LogicOp IntersectionType LogicOp ConditionalType ParameterizedType ClassDeclaration abstract implements type VariableDeclaration let var TypeAliasDeclaration InterfaceDeclaration interface EnumDeclaration enum EnumBody NamespaceDeclaration namespace module AmbientDeclaration declare GlobalDeclaration global ClassDeclaration ClassBody MethodDeclaration AmbientFunctionDeclaration ExportGroup VariableName VariableName ImportDeclaration ImportGroup ForStatement for ForSpec ForInSpec ForOfSpec of WhileStatement while WithStatement with DoStatement do IfStatement if else SwitchStatement switch SwitchBody CaseLabel case DefaultLabel TryStatement try CatchClause catch FinallyClause finally ReturnStatement return ThrowStatement throw BreakStatement break ContinueStatement continue DebuggerStatement debugger LabeledStatement ExpressionStatement SingleExpression",maxTerm:345,context:yI,nodeProps:[["closedBy",4,"InterpolationEnd",43,"]",53,"}",68,")",140,"JSXSelfCloseEndTag JSXEndTag",156,"JSXEndTag"],["group",-26,8,15,17,60,195,199,202,203,205,208,211,222,224,230,232,234,236,239,245,251,253,255,257,259,261,262,"Statement",-30,12,13,25,28,29,34,44,46,47,49,54,62,70,76,77,99,100,109,110,127,130,132,133,134,135,137,138,158,159,161,"Expression",-23,24,26,30,33,35,37,162,164,166,167,169,170,171,173,174,175,177,178,179,189,191,193,194,"Type",-3,81,92,98,"ClassItem"],["openedBy",31,"InterpolationStart",48,"[",52,"{",67,"(",139,"JSXStartTag",151,"JSXStartTag JSXStartCloseTag"]],propSources:[xI],skippedNodes:[0,5,6],repeatNodeCount:29,tokenData:"#2k~R!bOX%ZXY%uYZ'kZ[%u[]%Z]^'k^p%Zpq%uqr(Rrs)mst7]tu9guvlxyJcyzJyz{Ka{|Lm|}MW}!OLm!O!PMn!P!Q!$v!Q!R!Er!R![!G_![!]!Nc!]!^!N{!^!_# c!_!`#!`!`!a##d!a!b#%s!b!c#'h!c!}9g!}#O#(O#O#P%Z#P#Q#(f#Q#R#(|#R#S9g#S#T#)g#T#o#)}#o#p#,w#p#q#,|#q#r#-j#r#s#.S#s$f%Z$f$g%u$g#BY9g#BY#BZ#.j#BZ$IS9g$IS$I_#.j$I_$I|9g$I|$I}#1X$I}$JO#1X$JO$JT9g$JT$JU#.j$JU$KV9g$KV$KW#.j$KW&FU9g&FU&FV#.j&FV;'S9g;'S;=`Rw!^%Z!_!`YU$`W#q&lO!^%Z!_!`s]$`W]&ZOY>lYZ?lZw>lwx,jx!^>l!^!_@|!_#O>l#O#PE_#P#o>l#o#p@|#p;'S>l;'S;=`J]<%lO>l,^?qX$`WOw?lwx+_x!^?l!^!_@^!_#o?l#o#p@^#p;'S?l;'S;=`@v<%lO?l,U@aTOw@^wx,Xx;'S@^;'S;=`@p<%lO@^,U@sP;=`<%l@^,^@yP;=`<%l?l1aARX]&ZOY@|YZ@^Zw@|wx-tx#O@|#O#PAn#P;'S@|;'S;=`EX<%lO@|1aAqUOw@|wxBTx;'S@|;'S;=`Dg;=`<%lBt<%lO@|1aB[W$Z,U]&ZOYBtZwBtwx/px#OBt#O#PCc#P;'SBt;'S;=`Da<%lOBt&ZByW]&ZOYBtZwBtwx/px#OBt#O#PCc#P;'SBt;'S;=`Da<%lOBt&ZCfRO;'SBt;'S;=`Co;=`OBt&ZCtX]&ZOYBtZwBtwx/px#OBt#O#PCc#P;'SBt;'S;=`Da;=`<%lBt<%lOBt&ZDdP;=`<%lBt1aDlX]&ZOYBtZwBtwx/px#OBt#O#PCc#P;'SBt;'S;=`Da;=`<%l@|<%lOBt1aE[P;=`<%l@|1iEdY$`WOw>lwxFSx!^>l!^!_@|!_#o>l#o#p@|#p;'S>l;'S;=`Ik;=`<%lBt<%lO>l1iF]]$Z,U$`W]&ZOYGUYZ%ZZwGUwx4hx!^GU!^!_Bt!_#OGU#O#PHU#P#oGU#o#pBt#p;'SGU;'S;=`Ie<%lOGU&cG]]$`W]&ZOYGUYZ%ZZwGUwx4hx!^GU!^!_Bt!_#OGU#O#PHU#P#oGU#o#pBt#p;'SGU;'S;=`Ie<%lOGU&cHZW$`WO!^GU!^!_Bt!_#oGU#o#pBt#p;'SGU;'S;=`Hs;=`<%lBt<%lOGU&cHxX]&ZOYBtZwBtwx/px#OBt#O#PCc#P;'SBt;'S;=`Da;=`<%lGU<%lOBt&cIhP;=`<%lGU1iIpX]&ZOYBtZwBtwx/px#OBt#O#PCc#P;'SBt;'S;=`Da;=`<%l>l<%lOBt1iJ`P;=`<%l>l,TJjT!f+{$`WO!^%Z!_#o%Z#p;'S%Z;'S;=`%o<%lO%Z$PKQT!e#w$`WO!^%Z!_#o%Z#p;'S%Z;'S;=`%o<%lO%Z)ZKjW$`W'k#e#f&lOz%Zz{LS{!^%Z!_!`q#P#Q!-n#Q#o!;l#o#p!6|#p;'S!;l;'S;=`!?i<%lO!;l7Z!q#P#Q!-n#Q#o!;l#o#p!6|#p;'S!;l;'S;=`!?i<%lO!;l7Z!={[$`WU7ROY!+TYZ%ZZ!^!+T!^!_!)o!_#O!+T#O#P!,O#P#Q!&V#Q#o!+T#o#p!)o#p;'S!+T;'S;=`!,p<%lO!+T7Z!>vZ$`WOY!;lYZ!.wZz!;lz{!TI[n]||-1},{term:311,get:n=>QI[n]||-1},{term:65,get:n=>PI[n]||-1}],tokenPrec:13429}),$I=[Ut("function ${name}(${params}) {\n ${}\n}",{label:"function",detail:"definition",type:"keyword"}),Ut("for (let ${index} = 0; ${index} < ${bound}; ${index}++) {\n ${}\n}",{label:"for",detail:"loop",type:"keyword"}),Ut("for (let ${name} of ${collection}) {\n ${}\n}",{label:"for",detail:"of loop",type:"keyword"}),Ut("do {\n ${}\n} while (${})",{label:"do",detail:"loop",type:"keyword"}),Ut("while (${}) {\n ${}\n}",{label:"while",detail:"loop",type:"keyword"}),Ut(`try { \${} } catch (\${error}) { \${} @@ -49,5 +49,5 @@ var yS=Object.defineProperty;var bS=(n,e,t)=>e in n?yS(n,e,{enumerable:!0,config constructor(\${params}) { \${} } -}`,{label:"class",detail:"definition",type:"keyword"}),Ut('import {${names}} from "${module}"\n${}',{label:"import",detail:"named",type:"keyword"}),Ut('import ${name} from "${module}"\n${}',{label:"import",detail:"default",type:"keyword"})],um=new vT,nS=new Set(["Script","Block","FunctionExpression","FunctionDeclaration","ArrowFunction","MethodDeclaration","ForStatement"]);function Us(n){return(e,t)=>{let i=e.node.getChild("VariableDefinition");return i&&t(i,n),!0}}const CI=["FunctionDeclaration"],II={FunctionDeclaration:Us("function"),ClassDeclaration:Us("class"),ClassExpression:()=>!0,EnumDeclaration:Us("constant"),TypeAliasDeclaration:Us("type"),NamespaceDeclaration:Us("namespace"),VariableDefinition(n,e){n.matchContext(CI)||e(n,"variable")},TypeDefinition(n,e){e(n,"type")},__proto__:null};function rS(n,e){let t=um.get(e);if(t)return t;let i=[],r=!0;function s(o,a){let l=n.sliceString(o.from,o.to);i.push({label:l,type:a})}return e.cursor(ce.IncludeAnonymous).iterate(o=>{if(r)r=!1;else if(o.name){let a=II[o.name];if(a&&a(o,s)||nS.has(o.name))return!1}else if(o.to-o.from>8192){for(let a of rS(n,o.node))i.push(a);return!1}}),um.set(e,i),i}const fm=/^[\w$\xa1-\uffff][\w$\d\xa1-\uffff]*$/,sS=["TemplateString","String","RegExp","LineComment","BlockComment","VariableDefinition","TypeDefinition","Label","PropertyDefinition","PropertyName","PrivatePropertyDefinition","PrivatePropertyName"];function RI(n){let e=de(n.state).resolveInner(n.pos,-1);if(sS.indexOf(e.name)>-1)return null;let t=e.name=="VariableName"||e.to-e.from<20&&fm.test(n.state.sliceDoc(e.from,e.to));if(!t&&!n.explicit)return null;let i=[];for(let r=e;r;r=r.parent)nS.has(r.name)&&(i=i.concat(rS(n.state.doc,r)));return{options:i,from:t?e.from:n.pos,validFor:fm}}const qn=ws.define({name:"javascript",parser:AI.configure({props:[zo.add({IfStatement:_a({except:/^\s*({|else\b)/}),TryStatement:_a({except:/^\s*({|catch\b|finally\b)/}),LabeledStatement:GT,SwitchBody:n=>{let e=n.textAfter,t=/^\s*\}/.test(e),i=/^\s*(case|default)\b/.test(e);return n.baseIndent+(t?0:i?1:2)*n.unit},Block:_T({closing:"}"}),ArrowFunction:n=>n.baseIndent+n.unit,"TemplateString BlockComment":()=>null,"Statement Property":_a({except:/^{/}),JSXElement(n){let e=/^\s*<\//.test(n.textAfter);return n.lineIndent(n.node.from)+(e?0:n.unit)},JSXEscape(n){let e=/\s*\}/.test(n.textAfter);return n.lineIndent(n.node.from)+(e?0:n.unit)},"JSXOpenTag JSXSelfClosingTag"(n){return n.column(n.node.from)+n.unit}}),_o.add({"Block ClassBody SwitchBody EnumBody ObjectExpression ArrayExpression":cy,BlockComment(n){return{from:n.from+2,to:n.to-2}}})]}),languageData:{closeBrackets:{brackets:["(","[","{","'",'"',"`"]},commentTokens:{line:"//",block:{open:"/*",close:"*/"}},indentOnInput:/^\s*(?:case |default:|\{|\}|<\/)$/,wordChars:"$"}}),oS=qn.configure({dialect:"ts"},"typescript"),aS=qn.configure({dialect:"jsx"}),lS=qn.configure({dialect:"jsx ts"},"typescript"),EI="break case const continue default delete export extends false finally in instanceof let new return static super switch this throw true typeof var yield".split(" ").map(n=>({label:n,type:"keyword"}));function DI(n={}){let e=n.jsx?n.typescript?lS:aS:n.typescript?oS:qn;return new Co(e,[qn.data.of({autocomplete:pA(sS,ob($I.concat(EI)))}),qn.data.of({autocomplete:RI}),n.jsx?qI:[]])}function NI(n){for(;;){if(n.name=="JSXOpenTag"||n.name=="JSXSelfClosingTag"||n.name=="JSXFragmentTag")return n;if(!n.parent)return null;n=n.parent}}function dm(n,e,t=n.length){for(let i=e==null?void 0:e.firstChild;i;i=i.nextSibling)if(i.name=="JSXIdentifier"||i.name=="JSXBuiltin"||i.name=="JSXNamespacedName"||i.name=="JSXMemberExpression")return n.sliceString(i.from,Math.min(i.to,t));return""}const BI=typeof navigator=="object"&&/Android\b/.test(navigator.userAgent),qI=N.inputHandler.of((n,e,t,i)=>{if((BI?n.composing:n.compositionStarted)||n.state.readOnly||e!=t||i!=">"&&i!="/"||!qn.isActiveAt(n.state,e,-1))return!1;let{state:r}=n,s=r.changeByRange(o=>{var a,l;let{head:h}=o,c=de(r).resolveInner(h,-1),u;if(c.name=="JSXStartTag"&&(c=c.parent),i==">"&&c.name=="JSXFragmentTag")return{range:P.cursor(h+1),changes:{from:h,insert:"><>"}};if(i=="/"&&c.name=="JSXFragmentTag"){let f=c.parent,p=f==null?void 0:f.parent;if(f.from==h-1&&((a=p.lastChild)===null||a===void 0?void 0:a.name)!="JSXEndTag"&&(u=dm(r.doc,p==null?void 0:p.firstChild,h))){let g=`/${u}>`;return{range:P.cursor(h+g.length),changes:{from:h,insert:g}}}}else if(i==">"){let f=NI(c);if(f&&((l=f.lastChild)===null||l===void 0?void 0:l.name)!="JSXEndTag"&&r.sliceDoc(h,h+2)!="`}}}return{range:o}});return s.changes.empty?!1:(n.dispatch(s,{userEvent:"input.type",scrollIntoView:!0}),!0)}),Zs=["_blank","_self","_top","_parent"],cc=["ascii","utf-8","utf-16","latin1","latin1"],uc=["get","post","put","delete"],fc=["application/x-www-form-urlencoded","multipart/form-data","text/plain"],ot=["true","false"],V={},MI={a:{attrs:{href:null,ping:null,type:null,media:null,target:Zs,hreflang:null}},abbr:V,address:V,area:{attrs:{alt:null,coords:null,href:null,target:null,ping:null,media:null,hreflang:null,type:null,shape:["default","rect","circle","poly"]}},article:V,aside:V,audio:{attrs:{src:null,mediagroup:null,crossorigin:["anonymous","use-credentials"],preload:["none","metadata","auto"],autoplay:["autoplay"],loop:["loop"],controls:["controls"]}},b:V,base:{attrs:{href:null,target:Zs}},bdi:V,bdo:V,blockquote:{attrs:{cite:null}},body:V,br:V,button:{attrs:{form:null,formaction:null,name:null,value:null,autofocus:["autofocus"],disabled:["autofocus"],formenctype:fc,formmethod:uc,formnovalidate:["novalidate"],formtarget:Zs,type:["submit","reset","button"]}},canvas:{attrs:{width:null,height:null}},caption:V,center:V,cite:V,code:V,col:{attrs:{span:null}},colgroup:{attrs:{span:null}},command:{attrs:{type:["command","checkbox","radio"],label:null,icon:null,radiogroup:null,command:null,title:null,disabled:["disabled"],checked:["checked"]}},data:{attrs:{value:null}},datagrid:{attrs:{disabled:["disabled"],multiple:["multiple"]}},datalist:{attrs:{data:null}},dd:V,del:{attrs:{cite:null,datetime:null}},details:{attrs:{open:["open"]}},dfn:V,div:V,dl:V,dt:V,em:V,embed:{attrs:{src:null,type:null,width:null,height:null}},eventsource:{attrs:{src:null}},fieldset:{attrs:{disabled:["disabled"],form:null,name:null}},figcaption:V,figure:V,footer:V,form:{attrs:{action:null,name:null,"accept-charset":cc,autocomplete:["on","off"],enctype:fc,method:uc,novalidate:["novalidate"],target:Zs}},h1:V,h2:V,h3:V,h4:V,h5:V,h6:V,head:{children:["title","base","link","style","meta","script","noscript","command"]},header:V,hgroup:V,hr:V,html:{attrs:{manifest:null}},i:V,iframe:{attrs:{src:null,srcdoc:null,name:null,width:null,height:null,sandbox:["allow-top-navigation","allow-same-origin","allow-forms","allow-scripts"],seamless:["seamless"]}},img:{attrs:{alt:null,src:null,ismap:null,usemap:null,width:null,height:null,crossorigin:["anonymous","use-credentials"]}},input:{attrs:{alt:null,dirname:null,form:null,formaction:null,height:null,list:null,max:null,maxlength:null,min:null,name:null,pattern:null,placeholder:null,size:null,src:null,step:null,value:null,width:null,accept:["audio/*","video/*","image/*"],autocomplete:["on","off"],autofocus:["autofocus"],checked:["checked"],disabled:["disabled"],formenctype:fc,formmethod:uc,formnovalidate:["novalidate"],formtarget:Zs,multiple:["multiple"],readonly:["readonly"],required:["required"],type:["hidden","text","search","tel","url","email","password","datetime","date","month","week","time","datetime-local","number","range","color","checkbox","radio","file","submit","image","reset","button"]}},ins:{attrs:{cite:null,datetime:null}},kbd:V,keygen:{attrs:{challenge:null,form:null,name:null,autofocus:["autofocus"],disabled:["disabled"],keytype:["RSA"]}},label:{attrs:{for:null,form:null}},legend:V,li:{attrs:{value:null}},link:{attrs:{href:null,type:null,hreflang:null,media:null,sizes:["all","16x16","16x16 32x32","16x16 32x32 64x64"]}},map:{attrs:{name:null}},mark:V,menu:{attrs:{label:null,type:["list","context","toolbar"]}},meta:{attrs:{content:null,charset:cc,name:["viewport","application-name","author","description","generator","keywords"],"http-equiv":["content-language","content-type","default-style","refresh"]}},meter:{attrs:{value:null,min:null,low:null,high:null,max:null,optimum:null}},nav:V,noscript:V,object:{attrs:{data:null,type:null,name:null,usemap:null,form:null,width:null,height:null,typemustmatch:["typemustmatch"]}},ol:{attrs:{reversed:["reversed"],start:null,type:["1","a","A","i","I"]},children:["li","script","template","ul","ol"]},optgroup:{attrs:{disabled:["disabled"],label:null}},option:{attrs:{disabled:["disabled"],label:null,selected:["selected"],value:null}},output:{attrs:{for:null,form:null,name:null}},p:V,param:{attrs:{name:null,value:null}},pre:V,progress:{attrs:{value:null,max:null}},q:{attrs:{cite:null}},rp:V,rt:V,ruby:V,samp:V,script:{attrs:{type:["text/javascript"],src:null,async:["async"],defer:["defer"],charset:cc}},section:V,select:{attrs:{form:null,name:null,size:null,autofocus:["autofocus"],disabled:["disabled"],multiple:["multiple"]}},slot:{attrs:{name:null}},small:V,source:{attrs:{src:null,type:null,media:null}},span:V,strong:V,style:{attrs:{type:["text/css"],media:null,scoped:null}},sub:V,summary:V,sup:V,table:V,tbody:V,td:{attrs:{colspan:null,rowspan:null,headers:null}},template:V,textarea:{attrs:{dirname:null,form:null,maxlength:null,name:null,placeholder:null,rows:null,cols:null,autofocus:["autofocus"],disabled:["disabled"],readonly:["readonly"],required:["required"],wrap:["soft","hard"]}},tfoot:V,th:{attrs:{colspan:null,rowspan:null,headers:null,scope:["row","col","rowgroup","colgroup"]}},thead:V,time:{attrs:{datetime:null}},title:V,tr:V,track:{attrs:{src:null,label:null,default:null,kind:["subtitles","captions","descriptions","chapters","metadata"],srclang:null}},ul:{children:["li","script","template","ul","ol"]},var:V,video:{attrs:{src:null,poster:null,width:null,height:null,crossorigin:["anonymous","use-credentials"],preload:["auto","metadata","none"],autoplay:["autoplay"],mediagroup:["movie"],muted:["muted"],controls:["controls"]}},wbr:V},VI={accesskey:null,class:null,contenteditable:ot,contextmenu:null,dir:["ltr","rtl","auto"],draggable:["true","false","auto"],dropzone:["copy","move","link","string:","file:"],hidden:["hidden"],id:null,inert:["inert"],itemid:null,itemprop:null,itemref:null,itemscope:["itemscope"],itemtype:null,lang:["ar","bn","de","en-GB","en-US","es","fr","hi","id","ja","pa","pt","ru","tr","zh"],spellcheck:ot,autocorrect:ot,autocapitalize:ot,style:null,tabindex:null,title:null,translate:["yes","no"],onclick:null,rel:["stylesheet","alternate","author","bookmark","help","license","next","nofollow","noreferrer","prefetch","prev","search","tag"],role:"alert application article banner button cell checkbox complementary contentinfo dialog document feed figure form grid gridcell heading img list listbox listitem main navigation region row rowgroup search switch tab table tabpanel textbox timer".split(" "),"aria-activedescendant":null,"aria-atomic":ot,"aria-autocomplete":["inline","list","both","none"],"aria-busy":ot,"aria-checked":["true","false","mixed","undefined"],"aria-controls":null,"aria-describedby":null,"aria-disabled":ot,"aria-dropeffect":null,"aria-expanded":["true","false","undefined"],"aria-flowto":null,"aria-grabbed":["true","false","undefined"],"aria-haspopup":ot,"aria-hidden":ot,"aria-invalid":["true","false","grammar","spelling"],"aria-label":null,"aria-labelledby":null,"aria-level":null,"aria-live":["off","polite","assertive"],"aria-multiline":ot,"aria-multiselectable":ot,"aria-owns":null,"aria-posinset":null,"aria-pressed":["true","false","mixed","undefined"],"aria-readonly":ot,"aria-relevant":null,"aria-required":ot,"aria-selected":["true","false","undefined"],"aria-setsize":null,"aria-sort":["ascending","descending","none","other"],"aria-valuemax":null,"aria-valuemin":null,"aria-valuenow":null,"aria-valuetext":null};class Yl{constructor(e,t){this.tags=Object.assign(Object.assign({},MI),e),this.globalAttrs=Object.assign(Object.assign({},VI),t),this.allTags=Object.keys(this.tags),this.globalAttrNames=Object.keys(this.globalAttrs)}}Yl.default=new Yl;function Ps(n,e,t=n.length){if(!e)return"";let i=e.firstChild,r=i&&i.getChild("TagName");return r?n.sliceString(r.from,Math.min(r.to,t)):""}function vh(n,e=!1){for(let t=n.parent;t;t=t.parent)if(t.name=="Element")if(e)e=!1;else return t;return null}function hS(n,e,t){let i=t.tags[Ps(n,vh(e,!0))];return(i==null?void 0:i.children)||t.allTags}function Gf(n,e){let t=[];for(let i=e;i=vh(i);){let r=Ps(n,i);if(r&&i.lastChild.name=="CloseTag")break;r&&t.indexOf(r)<0&&(e.name=="EndTag"||e.from>=i.firstChild.to)&&t.push(r)}return t}const cS=/^[:\-\.\w\u00b7-\uffff]*$/;function pm(n,e,t,i,r){let s=/\s*>/.test(n.sliceDoc(r,r+5))?"":">";return{from:i,to:r,options:hS(n.doc,t,e).map(o=>({label:o,type:"type"})).concat(Gf(n.doc,t).map((o,a)=>({label:"/"+o,apply:"/"+o+s,type:"type",boost:99-a}))),validFor:/^\/?[:\-\.\w\u00b7-\uffff]*$/}}function gm(n,e,t,i){let r=/\s*>/.test(n.sliceDoc(i,i+5))?"":">";return{from:t,to:i,options:Gf(n.doc,e).map((s,o)=>({label:s,apply:s+r,type:"type",boost:99-o})),validFor:cS}}function XI(n,e,t,i){let r=[],s=0;for(let o of hS(n.doc,t,e))r.push({label:"<"+o,type:"type"});for(let o of Gf(n.doc,t))r.push({label:"",type:"type",boost:99-s++});return{from:i,to:i,options:r,validFor:/^<\/?[:\-\.\w\u00b7-\uffff]*$/}}function LI(n,e,t,i,r){let s=vh(t),o=s?e.tags[Ps(n.doc,s)]:null,a=o&&o.attrs?Object.keys(o.attrs):[],l=o&&o.globalAttrs===!1?a:a.length?a.concat(e.globalAttrNames):e.globalAttrNames;return{from:i,to:r,options:l.map(h=>({label:h,type:"property"})),validFor:cS}}function UI(n,e,t,i,r){var s;let o=(s=t.parent)===null||s===void 0?void 0:s.getChild("AttributeName"),a=[],l;if(o){let h=n.sliceDoc(o.from,o.to),c=e.globalAttrs[h];if(!c){let u=vh(t),f=u?e.tags[Ps(n.doc,u)]:null;c=(f==null?void 0:f.attrs)&&f.attrs[h]}if(c){let u=n.sliceDoc(i,r).toLowerCase(),f='"',p='"';/^['"]/.test(u)?(l=u[0]=='"'?/^[^"]*$/:/^[^']*$/,f="",p=n.sliceDoc(r,r+1)==u[0]?"":u[0],u=u.slice(1),i++):l=/^[^\s<>='"]*$/;for(let g of c)a.push({label:g,apply:f+g+p,type:"constant"})}}return{from:i,to:r,options:a,validFor:l}}function ZI(n,e){let{state:t,pos:i}=e,r=de(t).resolveInner(i),s=r.resolve(i,-1);for(let o=i,a;r==s&&(a=s.childBefore(o));){let l=a.lastChild;if(!l||!l.type.isError||l.fromZI(i,r)}const uS=[{tag:"script",attrs:n=>n.type=="text/typescript"||n.lang=="ts",parser:oS.parser},{tag:"script",attrs:n=>n.type=="text/babel"||n.type=="text/jsx",parser:aS.parser},{tag:"script",attrs:n=>n.type=="text/typescript-jsx",parser:lS.parser},{tag:"script",attrs(n){return!n.type||/^(?:text|application)\/(?:x-)?(?:java|ecma)script$|^module$|^$/i.test(n.type)},parser:qn.parser},{tag:"style",attrs(n){return(!n.lang||n.lang=="css")&&(!n.type||/^(text\/)?(x-)?(stylesheet|css)$/i.test(n.type))},parser:Jl.parser}],fS=[{name:"style",parser:Jl.parser.configure({top:"Styles"})}].concat("beforeunload copy cut dragstart dragover dragleave dragenter dragend drag paste focus blur change click load mousedown mouseenter mouseleave mouseup keydown keyup resize scroll unload".split(" ").map(n=>({name:"on"+n,parser:qn.parser}))),Ha=ws.define({name:"html",parser:IC.configure({props:[zo.add({Element(n){let e=/^(\s*)(<\/)?/.exec(n.textAfter);return n.node.to<=n.pos+e[0].length?n.continue():n.lineIndent(n.node.from)+(e[2]?0:n.unit)},"OpenTag CloseTag SelfClosingTag"(n){return n.column(n.node.from)+n.unit},Document(n){if(n.pos+/\s*/.exec(n.textAfter)[0].length"}},indentOnInput:/^\s*<\/\w+\W$/,wordChars:"-._"}});function jI(n={}){let e="",t;n.matchClosingTags===!1&&(e="noMatch"),n.selfClosingTags===!0&&(e=(e?e+" ":"")+"selfClosing"),(n.nestedLanguages&&n.nestedLanguages.length||n.nestedAttributes&&n.nestedAttributes.length)&&(t=Kb((n.nestedLanguages||[]).concat(uS),(n.nestedAttributes||[]).concat(fS)));let i=t||e?Ha.configure({dialect:e,wrap:t}):Ha;return new Co(i,[Ha.data.of({autocomplete:WI(n)}),n.autoCloseTags!==!1?FI:[],DI().support,KC().support])}const FI=N.inputHandler.of((n,e,t,i)=>{if(n.composing||n.state.readOnly||e!=t||i!=">"&&i!="/"||!Ha.isActiveAt(n.state,e,-1))return!1;let{state:r}=n,s=r.changeByRange(o=>{var a,l,h;let{head:c}=o,u=de(r).resolveInner(c,-1),f;if((u.name=="TagName"||u.name=="StartTag")&&(u=u.parent),i==">"&&u.name=="OpenTag"){if(((l=(a=u.parent)===null||a===void 0?void 0:a.lastChild)===null||l===void 0?void 0:l.name)!="CloseTag"&&(f=Ps(r.doc,u.parent,c))){let p=n.state.doc.sliceString(c,c+1)===">",g=`${p?"":">"}`;return{range:P.cursor(c+1),changes:{from:c+(p?1:0),insert:g}}}}else if(i=="/"&&u.name=="OpenTag"){let p=u.parent,g=p==null?void 0:p.parent;if(p.from==c-1&&((h=g.lastChild)===null||h===void 0?void 0:h.name)!="CloseTag"&&(f=Ps(r.doc,g,c))){let y=n.state.doc.sliceString(c,c+1)===">",O=`/${f}${y?"":">"}`,S=c+O.length+(y?1:0);return{range:P.cursor(S),changes:{from:c,insert:O}}}}return{range:o}});return s.changes.empty?!1:(n.dispatch(s,{userEvent:"input.type",scrollIntoView:!0}),!0)}),dS=oy({block:{open:""}}),pS=E$.configure({props:[_o.add(n=>{if(!(!n.is("Block")||n.is("Document")))return(e,t)=>({from:t.doc.lineAt(e.from).to,to:e.to})}),zo.add({Document:()=>null}),Ss.add({Document:dS})]});function Jf(n){return new Et(dS,n,[],"markdown")}const zI=Jf(pS),_I=pS.configure([L$,Z$,U$,W$]),Yf=Jf(_I);function GI(n,e){return t=>{if(t&&n){let i=null;if(t=/\S*/.exec(t)[0],typeof n=="function"?i=n(t):i=Rl.matchLanguageName(n,t,!0),i instanceof Rl)return i.support?i.support.language.parser:$o.getSkippingParser(i.load());if(i)return i.parser}return e?e.parser:null}}class Ia{constructor(e,t,i,r,s,o,a){this.node=e,this.from=t,this.to=i,this.spaceBefore=r,this.spaceAfter=s,this.type=o,this.item=a}blank(e,t=!0){let i=this.spaceBefore+(this.node.name=="Blockquote"?">":"");if(e!=null){for(;i.length0;r--)i+=" ";return i+(t?this.spaceAfter:"")}}marker(e,t){let i=this.node.name=="OrderedList"?String(+mS(this.item,e)[2]+t):"";return this.spaceBefore+i+this.type+this.spaceAfter}}function gS(n,e){let t=[];for(let r=n;r&&r.name!="Document";r=r.parent)(r.name=="ListItem"||r.name=="Blockquote"||r.name=="FencedCode")&&t.push(r);let i=[];for(let r=t.length-1;r>=0;r--){let s=t[r],o,a=e.lineAt(s.from),l=s.from-a.from;if(s.name=="FencedCode")i.push(new Ia(s,l,l,"","","",null));else if(s.name=="Blockquote"&&(o=/^[ \t]*>( ?)/.exec(a.text.slice(l))))i.push(new Ia(s,l,l+o[0].length,"",o[1],">",null));else if(s.name=="ListItem"&&s.parent.name=="OrderedList"&&(o=/^([ \t]*)\d+([.)])([ \t]*)/.exec(a.text.slice(l)))){let h=o[3],c=o[0].length;h.length>=4&&(h=h.slice(0,h.length-4),c-=4),i.push(new Ia(s.parent,l,l+c,o[1],h,o[2],s))}else if(s.name=="ListItem"&&s.parent.name=="BulletList"&&(o=/^([ \t]*)([-+*])([ \t]{1,4}\[[ xX]\])?([ \t]+)/.exec(a.text.slice(l)))){let h=o[4],c=o[0].length;h.length>4&&(h=h.slice(0,h.length-4),c-=4);let u=o[2];o[3]&&(u+=o[3].replace(/[xX]/," ")),i.push(new Ia(s.parent,l,l+c,o[1],h,u,s))}}return i}function mS(n,e){return/^(\s*)(\d+)(?=[.)])/.exec(e.sliceString(n.from,n.from+10))}function dc(n,e,t,i=0){for(let r=-1,s=n;;){if(s.name=="ListItem"){let a=mS(s,e),l=+a[2];if(r>=0){if(l!=r+1)return;t.push({from:s.from+a[1].length,to:s.from+a[0].length,insert:String(r+2+i)})}r=l}let o=s.nextSibling;if(!o)break;s=o}}const JI=({state:n,dispatch:e})=>{let t=de(n),{doc:i}=n,r=null,s=n.changeByRange(o=>{if(!o.empty||!Yf.isActiveAt(n,o.from))return r={range:o};let a=o.from,l=i.lineAt(a),h=gS(t.resolveInner(a,-1),i);for(;h.length&&h[h.length-1].from>a-l.from;)h.pop();if(!h.length)return r={range:o};let c=h[h.length-1];if(c.to-c.spaceAfter.length>a-l.from)return r={range:o};let u=a>=c.to-c.spaceAfter.length&&!/\S/.test(l.text.slice(c.to));if(c.item&&u)if(c.node.firstChild.to>=a||l.from>0&&!/[^\s>]/.test(i.lineAt(l.from-1).text)){let O=h.length>1?h[h.length-2]:null,S,k="";O&&O.item?(S=l.from+O.from,k=O.marker(i,1)):S=l.from+(O?O.to:0);let $=[{from:S,to:a,insert:k}];return c.node.name=="OrderedList"&&dc(c.item,i,$,-2),O&&O.node.name=="OrderedList"&&dc(O.item,i,$),{range:P.cursor(S+k.length),changes:$}}else{let O="";for(let S=0,k=h.length-2;S<=k;S++)O+=h[S].blank(S\s*$/.exec(O.text);if(S&&S.index==c.from){let k=n.changes([{from:O.from+S.index,to:O.to},{from:l.from+c.from,to:l.to}]);return{range:o.map(k),changes:k}}}let f=[];c.node.name=="OrderedList"&&dc(c.item,i,f);let p=c.item&&c.item.from]*/.exec(l.text)[0].length>=c.to)for(let O=0,S=h.length-1;O<=S;O++)g+=O==S&&!p?h[O].marker(i,1):h[O].blank(Ol.from&&/\s/.test(l.text.charAt(y-l.from-1));)y--;return g=n.lineBreak+g,f.push({from:y,to:a,insert:g}),{range:P.cursor(y+g.length),changes:f}});return r?!1:(e(n.update(s,{scrollIntoView:!0,userEvent:"input"})),!0)};function mm(n){return n.name=="QuoteMark"||n.name=="ListMark"}function YI(n,e){let t=n.resolveInner(e,-1),i=e;mm(t)&&(i=t.from,t=t.parent);for(let r;r=t.childBefore(i);)if(mm(r))i=r.from;else if(r.name=="OrderedList"||r.name=="BulletList")t=r.lastChild,i=t.to;else break;return t}const HI=({state:n,dispatch:e})=>{let t=de(n),i=null,r=n.changeByRange(s=>{let o=s.from,{doc:a}=n;if(s.empty&&Yf.isActiveAt(n,s.from)){let l=a.lineAt(o),h=gS(YI(t,o),a);if(h.length){let c=h[h.length-1],u=c.to-c.spaceAfter.length+(c.spaceAfter?1:0);if(o-l.from>u&&!/\S/.test(l.text.slice(u,o-l.from)))return{range:P.cursor(l.from+u),changes:{from:l.from+u,to:o}};if(o-l.from==u){let f=l.from+c.from;if(c.item&&c.node.from{xr.isOnline=!1,n.innerHTML=' '},showOnline:n=>{xr.isOnline=!0,n.innerHTML=' '},statusListener:n=>e=>{xr.isOnline&&e.value==yo.Disconnected?xr.showOffline(n):!xr.isOnline&&e.value==yo.Connected&&xr.showOnline(n)}};function eR(n,e,t){const i=[];for(const{clientID:r}of e)i.push(t===r?`${r}`:r);n.innerHTML=JSON.stringify(i)}function ym(n,e,t){n.innerText=t.toJSON(),e.innerText=t.getRoot().content.toTestString()}const tR=document.getElementById("editor"),iR=document.getElementById("peers"),bm=document.getElementById("document"),Sm=document.getElementById("document-text"),nR=document.getElementById("network-status");async function rR(){const n=new Rh.Client("https://api.yorkie.dev",{apiKey:"cedaovjuioqlk4pjqn6g"});await n.activate();const e=new Rh.Document(`codemirror6-${new Date().toISOString().substring(0,10).replace(/-/g,"")}`,{enableDevtools:!0});e.subscribe("connection",a=>{xr.statusListener(nR)(a)}),e.subscribe("presence",a=>{a.type!==_e.PresenceChanged&&eR(iR,e.getPresences(),n.getID())}),await n.attach(e),e.update(a=>{a.content||(a.content=new Rh.Text)},"create content if not exists");const t=()=>{const a=e.getRoot().content;r.dispatch({changes:{from:0,to:r.state.doc.length,insert:a.toString()},annotations:[ye.remote.of(!0)]})};e.subscribe(a=>{a.type==="snapshot"&&t(),ym(bm,Sm,e)}),e.subscribe("$.content",a=>{if(a.type==="remote-change"){const{operations:l}=a.value;s(l)}}),await n.sync();const i=N.updateListener.of(a=>{if(a.docChanged)for(const l of a.transactions){if(!["select","input","delete","move","undo","redo"].map(u=>l.isUserEvent(u)).some(Boolean)||l.annotation(ye.remote))continue;let c=0;l.changes.iterChanges((u,f,p,g,y)=>{const O=y.toJSON().join(` -`);e.update(S=>{S.content.edit(u+c,f+c,O)},`update content byA ${n.getID()}`),c+=O.length-(f-u)})}}),r=new N({doc:"",extensions:[b$,KI({base:Yf}),As.of(OS),i],parent:tR});function s(a){for(const l of a)l.type==="edit"&&o(l)}function o(a){const l=[{from:Math.max(0,a.from),to:Math.max(0,a.to),insert:a.value.content}];r.dispatch({changes:l,annotations:[ye.remote.of(!0)]})}t(),ym(bm,Sm,e)}rR(); +}`,{label:"class",detail:"definition",type:"keyword"}),Ut('import {${names}} from "${module}"\n${}',{label:"import",detail:"named",type:"keyword"}),Ut('import ${name} from "${module}"\n${}',{label:"import",detail:"default",type:"keyword"})],um=new vT,nS=new Set(["Script","Block","FunctionExpression","FunctionDeclaration","ArrowFunction","MethodDeclaration","ForStatement"]);function Us(n){return(e,t)=>{let i=e.node.getChild("VariableDefinition");return i&&t(i,n),!0}}const CI=["FunctionDeclaration"],II={FunctionDeclaration:Us("function"),ClassDeclaration:Us("class"),ClassExpression:()=>!0,EnumDeclaration:Us("constant"),TypeAliasDeclaration:Us("type"),NamespaceDeclaration:Us("namespace"),VariableDefinition(n,e){n.matchContext(CI)||e(n,"variable")},TypeDefinition(n,e){e(n,"type")},__proto__:null};function rS(n,e){let t=um.get(e);if(t)return t;let i=[],r=!0;function s(o,a){let l=n.sliceString(o.from,o.to);i.push({label:l,type:a})}return e.cursor(ce.IncludeAnonymous).iterate(o=>{if(r)r=!1;else if(o.name){let a=II[o.name];if(a&&a(o,s)||nS.has(o.name))return!1}else if(o.to-o.from>8192){for(let a of rS(n,o.node))i.push(a);return!1}}),um.set(e,i),i}const fm=/^[\w$\xa1-\uffff][\w$\d\xa1-\uffff]*$/,sS=["TemplateString","String","RegExp","LineComment","BlockComment","VariableDefinition","TypeDefinition","Label","PropertyDefinition","PropertyName","PrivatePropertyDefinition","PrivatePropertyName"];function RI(n){let e=de(n.state).resolveInner(n.pos,-1);if(sS.indexOf(e.name)>-1)return null;let t=e.name=="VariableName"||e.to-e.from<20&&fm.test(n.state.sliceDoc(e.from,e.to));if(!t&&!n.explicit)return null;let i=[];for(let r=e;r;r=r.parent)nS.has(r.name)&&(i=i.concat(rS(n.state.doc,r)));return{options:i,from:t?e.from:n.pos,validFor:fm}}const qn=ws.define({name:"javascript",parser:AI.configure({props:[zo.add({IfStatement:_a({except:/^\s*({|else\b)/}),TryStatement:_a({except:/^\s*({|catch\b|finally\b)/}),LabeledStatement:GT,SwitchBody:n=>{let e=n.textAfter,t=/^\s*\}/.test(e),i=/^\s*(case|default)\b/.test(e);return n.baseIndent+(t?0:i?1:2)*n.unit},Block:_T({closing:"}"}),ArrowFunction:n=>n.baseIndent+n.unit,"TemplateString BlockComment":()=>null,"Statement Property":_a({except:/^{/}),JSXElement(n){let e=/^\s*<\//.test(n.textAfter);return n.lineIndent(n.node.from)+(e?0:n.unit)},JSXEscape(n){let e=/\s*\}/.test(n.textAfter);return n.lineIndent(n.node.from)+(e?0:n.unit)},"JSXOpenTag JSXSelfClosingTag"(n){return n.column(n.node.from)+n.unit}}),_o.add({"Block ClassBody SwitchBody EnumBody ObjectExpression ArrayExpression":cy,BlockComment(n){return{from:n.from+2,to:n.to-2}}})]}),languageData:{closeBrackets:{brackets:["(","[","{","'",'"',"`"]},commentTokens:{line:"//",block:{open:"/*",close:"*/"}},indentOnInput:/^\s*(?:case |default:|\{|\}|<\/)$/,wordChars:"$"}}),oS=qn.configure({dialect:"ts"},"typescript"),aS=qn.configure({dialect:"jsx"}),lS=qn.configure({dialect:"jsx ts"},"typescript"),EI="break case const continue default delete export extends false finally in instanceof let new return static super switch this throw true typeof var yield".split(" ").map(n=>({label:n,type:"keyword"}));function DI(n={}){let e=n.jsx?n.typescript?lS:aS:n.typescript?oS:qn;return new Co(e,[qn.data.of({autocomplete:pA(sS,ob($I.concat(EI)))}),qn.data.of({autocomplete:RI}),n.jsx?qI:[]])}function NI(n){for(;;){if(n.name=="JSXOpenTag"||n.name=="JSXSelfClosingTag"||n.name=="JSXFragmentTag")return n;if(!n.parent)return null;n=n.parent}}function dm(n,e,t=n.length){for(let i=e==null?void 0:e.firstChild;i;i=i.nextSibling)if(i.name=="JSXIdentifier"||i.name=="JSXBuiltin"||i.name=="JSXNamespacedName"||i.name=="JSXMemberExpression")return n.sliceString(i.from,Math.min(i.to,t));return""}const BI=typeof navigator=="object"&&/Android\b/.test(navigator.userAgent),qI=N.inputHandler.of((n,e,t,i)=>{if((BI?n.composing:n.compositionStarted)||n.state.readOnly||e!=t||i!=">"&&i!="/"||!qn.isActiveAt(n.state,e,-1))return!1;let{state:r}=n,s=r.changeByRange(o=>{var a,l;let{head:h}=o,c=de(r).resolveInner(h,-1),u;if(c.name=="JSXStartTag"&&(c=c.parent),i==">"&&c.name=="JSXFragmentTag")return{range:P.cursor(h+1),changes:{from:h,insert:"><>"}};if(i=="/"&&c.name=="JSXFragmentTag"){let f=c.parent,p=f==null?void 0:f.parent;if(f.from==h-1&&((a=p.lastChild)===null||a===void 0?void 0:a.name)!="JSXEndTag"&&(u=dm(r.doc,p==null?void 0:p.firstChild,h))){let g=`/${u}>`;return{range:P.cursor(h+g.length),changes:{from:h,insert:g}}}}else if(i==">"){let f=NI(c);if(f&&((l=f.lastChild)===null||l===void 0?void 0:l.name)!="JSXEndTag"&&r.sliceDoc(h,h+2)!="`}}}return{range:o}});return s.changes.empty?!1:(n.dispatch(s,{userEvent:"input.type",scrollIntoView:!0}),!0)}),Zs=["_blank","_self","_top","_parent"],cc=["ascii","utf-8","utf-16","latin1","latin1"],uc=["get","post","put","delete"],fc=["application/x-www-form-urlencoded","multipart/form-data","text/plain"],ot=["true","false"],V={},MI={a:{attrs:{href:null,ping:null,type:null,media:null,target:Zs,hreflang:null}},abbr:V,address:V,area:{attrs:{alt:null,coords:null,href:null,target:null,ping:null,media:null,hreflang:null,type:null,shape:["default","rect","circle","poly"]}},article:V,aside:V,audio:{attrs:{src:null,mediagroup:null,crossorigin:["anonymous","use-credentials"],preload:["none","metadata","auto"],autoplay:["autoplay"],loop:["loop"],controls:["controls"]}},b:V,base:{attrs:{href:null,target:Zs}},bdi:V,bdo:V,blockquote:{attrs:{cite:null}},body:V,br:V,button:{attrs:{form:null,formaction:null,name:null,value:null,autofocus:["autofocus"],disabled:["autofocus"],formenctype:fc,formmethod:uc,formnovalidate:["novalidate"],formtarget:Zs,type:["submit","reset","button"]}},canvas:{attrs:{width:null,height:null}},caption:V,center:V,cite:V,code:V,col:{attrs:{span:null}},colgroup:{attrs:{span:null}},command:{attrs:{type:["command","checkbox","radio"],label:null,icon:null,radiogroup:null,command:null,title:null,disabled:["disabled"],checked:["checked"]}},data:{attrs:{value:null}},datagrid:{attrs:{disabled:["disabled"],multiple:["multiple"]}},datalist:{attrs:{data:null}},dd:V,del:{attrs:{cite:null,datetime:null}},details:{attrs:{open:["open"]}},dfn:V,div:V,dl:V,dt:V,em:V,embed:{attrs:{src:null,type:null,width:null,height:null}},eventsource:{attrs:{src:null}},fieldset:{attrs:{disabled:["disabled"],form:null,name:null}},figcaption:V,figure:V,footer:V,form:{attrs:{action:null,name:null,"accept-charset":cc,autocomplete:["on","off"],enctype:fc,method:uc,novalidate:["novalidate"],target:Zs}},h1:V,h2:V,h3:V,h4:V,h5:V,h6:V,head:{children:["title","base","link","style","meta","script","noscript","command"]},header:V,hgroup:V,hr:V,html:{attrs:{manifest:null}},i:V,iframe:{attrs:{src:null,srcdoc:null,name:null,width:null,height:null,sandbox:["allow-top-navigation","allow-same-origin","allow-forms","allow-scripts"],seamless:["seamless"]}},img:{attrs:{alt:null,src:null,ismap:null,usemap:null,width:null,height:null,crossorigin:["anonymous","use-credentials"]}},input:{attrs:{alt:null,dirname:null,form:null,formaction:null,height:null,list:null,max:null,maxlength:null,min:null,name:null,pattern:null,placeholder:null,size:null,src:null,step:null,value:null,width:null,accept:["audio/*","video/*","image/*"],autocomplete:["on","off"],autofocus:["autofocus"],checked:["checked"],disabled:["disabled"],formenctype:fc,formmethod:uc,formnovalidate:["novalidate"],formtarget:Zs,multiple:["multiple"],readonly:["readonly"],required:["required"],type:["hidden","text","search","tel","url","email","password","datetime","date","month","week","time","datetime-local","number","range","color","checkbox","radio","file","submit","image","reset","button"]}},ins:{attrs:{cite:null,datetime:null}},kbd:V,keygen:{attrs:{challenge:null,form:null,name:null,autofocus:["autofocus"],disabled:["disabled"],keytype:["RSA"]}},label:{attrs:{for:null,form:null}},legend:V,li:{attrs:{value:null}},link:{attrs:{href:null,type:null,hreflang:null,media:null,sizes:["all","16x16","16x16 32x32","16x16 32x32 64x64"]}},map:{attrs:{name:null}},mark:V,menu:{attrs:{label:null,type:["list","context","toolbar"]}},meta:{attrs:{content:null,charset:cc,name:["viewport","application-name","author","description","generator","keywords"],"http-equiv":["content-language","content-type","default-style","refresh"]}},meter:{attrs:{value:null,min:null,low:null,high:null,max:null,optimum:null}},nav:V,noscript:V,object:{attrs:{data:null,type:null,name:null,usemap:null,form:null,width:null,height:null,typemustmatch:["typemustmatch"]}},ol:{attrs:{reversed:["reversed"],start:null,type:["1","a","A","i","I"]},children:["li","script","template","ul","ol"]},optgroup:{attrs:{disabled:["disabled"],label:null}},option:{attrs:{disabled:["disabled"],label:null,selected:["selected"],value:null}},output:{attrs:{for:null,form:null,name:null}},p:V,param:{attrs:{name:null,value:null}},pre:V,progress:{attrs:{value:null,max:null}},q:{attrs:{cite:null}},rp:V,rt:V,ruby:V,samp:V,script:{attrs:{type:["text/javascript"],src:null,async:["async"],defer:["defer"],charset:cc}},section:V,select:{attrs:{form:null,name:null,size:null,autofocus:["autofocus"],disabled:["disabled"],multiple:["multiple"]}},slot:{attrs:{name:null}},small:V,source:{attrs:{src:null,type:null,media:null}},span:V,strong:V,style:{attrs:{type:["text/css"],media:null,scoped:null}},sub:V,summary:V,sup:V,table:V,tbody:V,td:{attrs:{colspan:null,rowspan:null,headers:null}},template:V,textarea:{attrs:{dirname:null,form:null,maxlength:null,name:null,placeholder:null,rows:null,cols:null,autofocus:["autofocus"],disabled:["disabled"],readonly:["readonly"],required:["required"],wrap:["soft","hard"]}},tfoot:V,th:{attrs:{colspan:null,rowspan:null,headers:null,scope:["row","col","rowgroup","colgroup"]}},thead:V,time:{attrs:{datetime:null}},title:V,tr:V,track:{attrs:{src:null,label:null,default:null,kind:["subtitles","captions","descriptions","chapters","metadata"],srclang:null}},ul:{children:["li","script","template","ul","ol"]},var:V,video:{attrs:{src:null,poster:null,width:null,height:null,crossorigin:["anonymous","use-credentials"],preload:["auto","metadata","none"],autoplay:["autoplay"],mediagroup:["movie"],muted:["muted"],controls:["controls"]}},wbr:V},VI={accesskey:null,class:null,contenteditable:ot,contextmenu:null,dir:["ltr","rtl","auto"],draggable:["true","false","auto"],dropzone:["copy","move","link","string:","file:"],hidden:["hidden"],id:null,inert:["inert"],itemid:null,itemprop:null,itemref:null,itemscope:["itemscope"],itemtype:null,lang:["ar","bn","de","en-GB","en-US","es","fr","hi","id","ja","pa","pt","ru","tr","zh"],spellcheck:ot,autocorrect:ot,autocapitalize:ot,style:null,tabindex:null,title:null,translate:["yes","no"],onclick:null,rel:["stylesheet","alternate","author","bookmark","help","license","next","nofollow","noreferrer","prefetch","prev","search","tag"],role:"alert application article banner button cell checkbox complementary contentinfo dialog document feed figure form grid gridcell heading img list listbox listitem main navigation region row rowgroup search switch tab table tabpanel textbox timer".split(" "),"aria-activedescendant":null,"aria-atomic":ot,"aria-autocomplete":["inline","list","both","none"],"aria-busy":ot,"aria-checked":["true","false","mixed","undefined"],"aria-controls":null,"aria-describedby":null,"aria-disabled":ot,"aria-dropeffect":null,"aria-expanded":["true","false","undefined"],"aria-flowto":null,"aria-grabbed":["true","false","undefined"],"aria-haspopup":ot,"aria-hidden":ot,"aria-invalid":["true","false","grammar","spelling"],"aria-label":null,"aria-labelledby":null,"aria-level":null,"aria-live":["off","polite","assertive"],"aria-multiline":ot,"aria-multiselectable":ot,"aria-owns":null,"aria-posinset":null,"aria-pressed":["true","false","mixed","undefined"],"aria-readonly":ot,"aria-relevant":null,"aria-required":ot,"aria-selected":["true","false","undefined"],"aria-setsize":null,"aria-sort":["ascending","descending","none","other"],"aria-valuemax":null,"aria-valuemin":null,"aria-valuenow":null,"aria-valuetext":null};class Yl{constructor(e,t){this.tags=Object.assign(Object.assign({},MI),e),this.globalAttrs=Object.assign(Object.assign({},VI),t),this.allTags=Object.keys(this.tags),this.globalAttrNames=Object.keys(this.globalAttrs)}}Yl.default=new Yl;function Ps(n,e,t=n.length){if(!e)return"";let i=e.firstChild,r=i&&i.getChild("TagName");return r?n.sliceString(r.from,Math.min(r.to,t)):""}function vh(n,e=!1){for(let t=n.parent;t;t=t.parent)if(t.name=="Element")if(e)e=!1;else return t;return null}function hS(n,e,t){let i=t.tags[Ps(n,vh(e,!0))];return(i==null?void 0:i.children)||t.allTags}function Gf(n,e){let t=[];for(let i=e;i=vh(i);){let r=Ps(n,i);if(r&&i.lastChild.name=="CloseTag")break;r&&t.indexOf(r)<0&&(e.name=="EndTag"||e.from>=i.firstChild.to)&&t.push(r)}return t}const cS=/^[:\-\.\w\u00b7-\uffff]*$/;function pm(n,e,t,i,r){let s=/\s*>/.test(n.sliceDoc(r,r+5))?"":">";return{from:i,to:r,options:hS(n.doc,t,e).map(o=>({label:o,type:"type"})).concat(Gf(n.doc,t).map((o,a)=>({label:"/"+o,apply:"/"+o+s,type:"type",boost:99-a}))),validFor:/^\/?[:\-\.\w\u00b7-\uffff]*$/}}function gm(n,e,t,i){let r=/\s*>/.test(n.sliceDoc(i,i+5))?"":">";return{from:t,to:i,options:Gf(n.doc,e).map((s,o)=>({label:s,apply:s+r,type:"type",boost:99-o})),validFor:cS}}function XI(n,e,t,i){let r=[],s=0;for(let o of hS(n.doc,t,e))r.push({label:"<"+o,type:"type"});for(let o of Gf(n.doc,t))r.push({label:"",type:"type",boost:99-s++});return{from:i,to:i,options:r,validFor:/^<\/?[:\-\.\w\u00b7-\uffff]*$/}}function LI(n,e,t,i,r){let s=vh(t),o=s?e.tags[Ps(n.doc,s)]:null,a=o&&o.attrs?Object.keys(o.attrs):[],l=o&&o.globalAttrs===!1?a:a.length?a.concat(e.globalAttrNames):e.globalAttrNames;return{from:i,to:r,options:l.map(h=>({label:h,type:"property"})),validFor:cS}}function UI(n,e,t,i,r){var s;let o=(s=t.parent)===null||s===void 0?void 0:s.getChild("AttributeName"),a=[],l;if(o){let h=n.sliceDoc(o.from,o.to),c=e.globalAttrs[h];if(!c){let u=vh(t),f=u?e.tags[Ps(n.doc,u)]:null;c=(f==null?void 0:f.attrs)&&f.attrs[h]}if(c){let u=n.sliceDoc(i,r).toLowerCase(),f='"',p='"';/^['"]/.test(u)?(l=u[0]=='"'?/^[^"]*$/:/^[^']*$/,f="",p=n.sliceDoc(r,r+1)==u[0]?"":u[0],u=u.slice(1),i++):l=/^[^\s<>='"]*$/;for(let g of c)a.push({label:g,apply:f+g+p,type:"constant"})}}return{from:i,to:r,options:a,validFor:l}}function ZI(n,e){let{state:t,pos:i}=e,r=de(t).resolveInner(i),s=r.resolve(i,-1);for(let o=i,a;r==s&&(a=s.childBefore(o));){let l=a.lastChild;if(!l||!l.type.isError||l.fromZI(i,r)}const uS=[{tag:"script",attrs:n=>n.type=="text/typescript"||n.lang=="ts",parser:oS.parser},{tag:"script",attrs:n=>n.type=="text/babel"||n.type=="text/jsx",parser:aS.parser},{tag:"script",attrs:n=>n.type=="text/typescript-jsx",parser:lS.parser},{tag:"script",attrs(n){return!n.type||/^(?:text|application)\/(?:x-)?(?:java|ecma)script$|^module$|^$/i.test(n.type)},parser:qn.parser},{tag:"style",attrs(n){return(!n.lang||n.lang=="css")&&(!n.type||/^(text\/)?(x-)?(stylesheet|css)$/i.test(n.type))},parser:Jl.parser}],fS=[{name:"style",parser:Jl.parser.configure({top:"Styles"})}].concat("beforeunload copy cut dragstart dragover dragleave dragenter dragend drag paste focus blur change click load mousedown mouseenter mouseleave mouseup keydown keyup resize scroll unload".split(" ").map(n=>({name:"on"+n,parser:qn.parser}))),Ha=ws.define({name:"html",parser:IC.configure({props:[zo.add({Element(n){let e=/^(\s*)(<\/)?/.exec(n.textAfter);return n.node.to<=n.pos+e[0].length?n.continue():n.lineIndent(n.node.from)+(e[2]?0:n.unit)},"OpenTag CloseTag SelfClosingTag"(n){return n.column(n.node.from)+n.unit},Document(n){if(n.pos+/\s*/.exec(n.textAfter)[0].length"}},indentOnInput:/^\s*<\/\w+\W$/,wordChars:"-._"}});function jI(n={}){let e="",t;n.matchClosingTags===!1&&(e="noMatch"),n.selfClosingTags===!0&&(e=(e?e+" ":"")+"selfClosing"),(n.nestedLanguages&&n.nestedLanguages.length||n.nestedAttributes&&n.nestedAttributes.length)&&(t=Kb((n.nestedLanguages||[]).concat(uS),(n.nestedAttributes||[]).concat(fS)));let i=t||e?Ha.configure({dialect:e,wrap:t}):Ha;return new Co(i,[Ha.data.of({autocomplete:WI(n)}),n.autoCloseTags!==!1?FI:[],DI().support,KC().support])}const FI=N.inputHandler.of((n,e,t,i)=>{if(n.composing||n.state.readOnly||e!=t||i!=">"&&i!="/"||!Ha.isActiveAt(n.state,e,-1))return!1;let{state:r}=n,s=r.changeByRange(o=>{var a,l,h;let{head:c}=o,u=de(r).resolveInner(c,-1),f;if((u.name=="TagName"||u.name=="StartTag")&&(u=u.parent),i==">"&&u.name=="OpenTag"){if(((l=(a=u.parent)===null||a===void 0?void 0:a.lastChild)===null||l===void 0?void 0:l.name)!="CloseTag"&&(f=Ps(r.doc,u.parent,c))){let p=n.state.doc.sliceString(c,c+1)===">",g=`${p?"":">"}`;return{range:P.cursor(c+1),changes:{from:c+(p?1:0),insert:g}}}}else if(i=="/"&&u.name=="OpenTag"){let p=u.parent,g=p==null?void 0:p.parent;if(p.from==c-1&&((h=g.lastChild)===null||h===void 0?void 0:h.name)!="CloseTag"&&(f=Ps(r.doc,g,c))){let O=n.state.doc.sliceString(c,c+1)===">",y=`/${f}${O?"":">"}`,S=c+y.length+(O?1:0);return{range:P.cursor(S),changes:{from:c,insert:y}}}}return{range:o}});return s.changes.empty?!1:(n.dispatch(s,{userEvent:"input.type",scrollIntoView:!0}),!0)}),dS=oy({block:{open:""}}),pS=E$.configure({props:[_o.add(n=>{if(!(!n.is("Block")||n.is("Document")))return(e,t)=>({from:t.doc.lineAt(e.from).to,to:e.to})}),zo.add({Document:()=>null}),Ss.add({Document:dS})]});function Jf(n){return new Et(dS,n,[],"markdown")}const zI=Jf(pS),_I=pS.configure([L$,Z$,U$,W$]),Yf=Jf(_I);function GI(n,e){return t=>{if(t&&n){let i=null;if(t=/\S*/.exec(t)[0],typeof n=="function"?i=n(t):i=Rl.matchLanguageName(n,t,!0),i instanceof Rl)return i.support?i.support.language.parser:$o.getSkippingParser(i.load());if(i)return i.parser}return e?e.parser:null}}class Ia{constructor(e,t,i,r,s,o,a){this.node=e,this.from=t,this.to=i,this.spaceBefore=r,this.spaceAfter=s,this.type=o,this.item=a}blank(e,t=!0){let i=this.spaceBefore+(this.node.name=="Blockquote"?">":"");if(e!=null){for(;i.length0;r--)i+=" ";return i+(t?this.spaceAfter:"")}}marker(e,t){let i=this.node.name=="OrderedList"?String(+mS(this.item,e)[2]+t):"";return this.spaceBefore+i+this.type+this.spaceAfter}}function gS(n,e){let t=[];for(let r=n;r&&r.name!="Document";r=r.parent)(r.name=="ListItem"||r.name=="Blockquote"||r.name=="FencedCode")&&t.push(r);let i=[];for(let r=t.length-1;r>=0;r--){let s=t[r],o,a=e.lineAt(s.from),l=s.from-a.from;if(s.name=="FencedCode")i.push(new Ia(s,l,l,"","","",null));else if(s.name=="Blockquote"&&(o=/^[ \t]*>( ?)/.exec(a.text.slice(l))))i.push(new Ia(s,l,l+o[0].length,"",o[1],">",null));else if(s.name=="ListItem"&&s.parent.name=="OrderedList"&&(o=/^([ \t]*)\d+([.)])([ \t]*)/.exec(a.text.slice(l)))){let h=o[3],c=o[0].length;h.length>=4&&(h=h.slice(0,h.length-4),c-=4),i.push(new Ia(s.parent,l,l+c,o[1],h,o[2],s))}else if(s.name=="ListItem"&&s.parent.name=="BulletList"&&(o=/^([ \t]*)([-+*])([ \t]{1,4}\[[ xX]\])?([ \t]+)/.exec(a.text.slice(l)))){let h=o[4],c=o[0].length;h.length>4&&(h=h.slice(0,h.length-4),c-=4);let u=o[2];o[3]&&(u+=o[3].replace(/[xX]/," ")),i.push(new Ia(s.parent,l,l+c,o[1],h,u,s))}}return i}function mS(n,e){return/^(\s*)(\d+)(?=[.)])/.exec(e.sliceString(n.from,n.from+10))}function dc(n,e,t,i=0){for(let r=-1,s=n;;){if(s.name=="ListItem"){let a=mS(s,e),l=+a[2];if(r>=0){if(l!=r+1)return;t.push({from:s.from+a[1].length,to:s.from+a[0].length,insert:String(r+2+i)})}r=l}let o=s.nextSibling;if(!o)break;s=o}}const JI=({state:n,dispatch:e})=>{let t=de(n),{doc:i}=n,r=null,s=n.changeByRange(o=>{if(!o.empty||!Yf.isActiveAt(n,o.from))return r={range:o};let a=o.from,l=i.lineAt(a),h=gS(t.resolveInner(a,-1),i);for(;h.length&&h[h.length-1].from>a-l.from;)h.pop();if(!h.length)return r={range:o};let c=h[h.length-1];if(c.to-c.spaceAfter.length>a-l.from)return r={range:o};let u=a>=c.to-c.spaceAfter.length&&!/\S/.test(l.text.slice(c.to));if(c.item&&u)if(c.node.firstChild.to>=a||l.from>0&&!/[^\s>]/.test(i.lineAt(l.from-1).text)){let y=h.length>1?h[h.length-2]:null,S,k="";y&&y.item?(S=l.from+y.from,k=y.marker(i,1)):S=l.from+(y?y.to:0);let $=[{from:S,to:a,insert:k}];return c.node.name=="OrderedList"&&dc(c.item,i,$,-2),y&&y.node.name=="OrderedList"&&dc(y.item,i,$),{range:P.cursor(S+k.length),changes:$}}else{let y="";for(let S=0,k=h.length-2;S<=k;S++)y+=h[S].blank(S\s*$/.exec(y.text);if(S&&S.index==c.from){let k=n.changes([{from:y.from+S.index,to:y.to},{from:l.from+c.from,to:l.to}]);return{range:o.map(k),changes:k}}}let f=[];c.node.name=="OrderedList"&&dc(c.item,i,f);let p=c.item&&c.item.from]*/.exec(l.text)[0].length>=c.to)for(let y=0,S=h.length-1;y<=S;y++)g+=y==S&&!p?h[y].marker(i,1):h[y].blank(yl.from&&/\s/.test(l.text.charAt(O-l.from-1));)O--;return g=n.lineBreak+g,f.push({from:O,to:a,insert:g}),{range:P.cursor(O+g.length),changes:f}});return r?!1:(e(n.update(s,{scrollIntoView:!0,userEvent:"input"})),!0)};function mm(n){return n.name=="QuoteMark"||n.name=="ListMark"}function YI(n,e){let t=n.resolveInner(e,-1),i=e;mm(t)&&(i=t.from,t=t.parent);for(let r;r=t.childBefore(i);)if(mm(r))i=r.from;else if(r.name=="OrderedList"||r.name=="BulletList")t=r.lastChild,i=t.to;else break;return t}const HI=({state:n,dispatch:e})=>{let t=de(n),i=null,r=n.changeByRange(s=>{let o=s.from,{doc:a}=n;if(s.empty&&Yf.isActiveAt(n,s.from)){let l=a.lineAt(o),h=gS(YI(t,o),a);if(h.length){let c=h[h.length-1],u=c.to-c.spaceAfter.length+(c.spaceAfter?1:0);if(o-l.from>u&&!/\S/.test(l.text.slice(u,o-l.from)))return{range:P.cursor(l.from+u),changes:{from:l.from+u,to:o}};if(o-l.from==u){let f=l.from+c.from;if(c.item&&c.node.from{xr.isOnline=!1,n.innerHTML=' '},showOnline:n=>{xr.isOnline=!0,n.innerHTML=' '},statusListener:n=>e=>{xr.isOnline&&e.value==yo.Disconnected?xr.showOffline(n):!xr.isOnline&&e.value==yo.Connected&&xr.showOnline(n)}};function eR(n,e,t){const i=[];for(const{clientID:r}of e)i.push(t===r?`${r}`:r);n.innerHTML=JSON.stringify(i)}function ym(n,e,t){n.innerText=t.toJSON(),e.innerText=t.getRoot().content.toTestString()}const tR=document.getElementById("editor"),iR=document.getElementById("peers"),bm=document.getElementById("document"),Sm=document.getElementById("document-text"),nR=document.getElementById("network-status");async function rR(){const n=new Rh.Client("https://api.yorkie.dev",{apiKey:"cedaovjuioqlk4pjqn6g"});await n.activate();const e=new Rh.Document(`codemirror6-${new Date().toISOString().substring(0,10).replace(/-/g,"")}`,{enableDevtools:!0});e.subscribe("connection",a=>{xr.statusListener(nR)(a)}),e.subscribe("presence",a=>{a.type!==_e.PresenceChanged&&eR(iR,e.getPresences(),n.getID())}),await n.attach(e),e.update(a=>{a.content||(a.content=new Rh.Text)},"create content if not exists");const t=()=>{const a=e.getRoot().content,l=e.getMyPresence().selection,h={changes:{from:0,to:r.state.doc.length,insert:a.toString()},annotations:[ye.remote.of(!0)]};if(l){const c=a.posRangeToIndexRange(l);h.selection={anchor:c[0],head:c[1]}}r.dispatch(h)};e.subscribe(a=>{a.type==="snapshot"&&t(),ym(bm,Sm,e)}),e.subscribe("$.content",a=>{if(a.type==="remote-change"){const{operations:l}=a.value;s(l)}}),await n.sync();const i=N.updateListener.of(a=>{if(a.docChanged)for(const c of a.transactions){if(!["select","input","delete","move","undo","redo"].map(p=>c.isUserEvent(p)).some(Boolean)||c.annotation(ye.remote))continue;let f=0;c.changes.iterChanges((p,g,O,y,S)=>{const k=S.toJSON().join(` +`);e.update($=>{$.content.edit(p+f,g+f,k)},`update content byA ${n.getID()}`),f+=k.length-(g-p)})}const h=a.view.hasFocus&&a.view.dom.ownerDocument.hasFocus()?a.state.selection.main:null;e.update((c,u)=>{if(h&&c.content){const f=c.content.indexRangeToPosRange([h.anchor,h.head]);JSON.stringify(f)!==JSON.stringify(u.get("selection"))&&u.set({selection:f})}else u.get("selection")&&u.set({selection:void 0})})}),r=new N({doc:"",extensions:[b$,KI({base:Yf}),As.of(OS),i],parent:tR});function s(a){for(const l of a)l.type==="edit"&&o(l)}function o(a){const l=[{from:Math.max(0,a.from),to:Math.max(0,a.to),insert:a.value.content}];r.dispatch({changes:l,annotations:[ye.remote.of(!0)]})}t(),ym(bm,Sm,e)}rR(); diff --git a/examples/vanilla-codemirror6/index.html b/examples/vanilla-codemirror6/index.html index cad1fe515..44c77d7b2 100644 --- a/examples/vanilla-codemirror6/index.html +++ b/examples/vanilla-codemirror6/index.html @@ -4,7 +4,7 @@ Yorkie + CodeMirror 6 Example - + diff --git a/examples/vanilla-quill/assets/index-CXKQfVgS.js b/examples/vanilla-quill/assets/index-VO1uos3h.js similarity index 99% rename from examples/vanilla-quill/assets/index-CXKQfVgS.js rename to examples/vanilla-quill/assets/index-VO1uos3h.js index da36550c8..9cfe8722c 100644 --- a/examples/vanilla-quill/assets/index-CXKQfVgS.js +++ b/examples/vanilla-quill/assets/index-VO1uos3h.js @@ -19,7 +19,7 @@ var Vu=Object.defineProperty;var Ku=(i,t,e)=>t in i?Vu(i,t,{enumerable:!0,config * limitations under the License. * * SPDX-License-Identifier: Apache-2.0 - */var Ht=null;try{Ht=new WebAssembly.Instance(new WebAssembly.Module(new Uint8Array([0,97,115,109,1,0,0,0,1,13,2,96,0,1,127,96,4,127,127,127,127,1,127,3,7,6,0,1,1,1,1,1,6,6,1,127,1,65,0,11,7,50,6,3,109,117,108,0,1,5,100,105,118,95,115,0,2,5,100,105,118,95,117,0,3,5,114,101,109,95,115,0,4,5,114,101,109,95,117,0,5,8,103,101,116,95,104,105,103,104,0,0,10,191,1,6,4,0,35,0,11,36,1,1,126,32,0,173,32,1,173,66,32,134,132,32,2,173,32,3,173,66,32,134,132,126,34,4,66,32,135,167,36,0,32,4,167,11,36,1,1,126,32,0,173,32,1,173,66,32,134,132,32,2,173,32,3,173,66,32,134,132,127,34,4,66,32,135,167,36,0,32,4,167,11,36,1,1,126,32,0,173,32,1,173,66,32,134,132,32,2,173,32,3,173,66,32,134,132,128,34,4,66,32,135,167,36,0,32,4,167,11,36,1,1,126,32,0,173,32,1,173,66,32,134,132,32,2,173,32,3,173,66,32,134,132,129,34,4,66,32,135,167,36,0,32,4,167,11,36,1,1,126,32,0,173,32,1,173,66,32,134,132,32,2,173,32,3,173,66,32,134,132,130,34,4,66,32,135,167,36,0,32,4,167,11])),{}).exports}catch{}function Ve(i,t,e){this.low=i|0,this.high=t|0,this.unsigned=!!e}Ve.prototype.__isLong__;Object.defineProperty(Ve.prototype,"__isLong__",{value:!0});function yt(i){return(i&&i.__isLong__)===!0}function ml(i){var t=Math.clz32(i&-i);return i?31-t:t}Ve.isLong=yt;var yl={},vl={};function Pi(i,t){var e,n,r;return t?(i>>>=0,(r=0<=i&&i<256)&&(n=vl[i],n)?n:(e=Ke(i,0,!0),r&&(vl[i]=e),e)):(i|=0,(r=-128<=i&&i<128)&&(n=yl[i],n)?n:(e=Ke(i,i<0?-1:0,!1),r&&(yl[i]=e),e))}Ve.fromInt=Pi;function Wt(i,t){if(isNaN(i))return t?Wr:an;if(t){if(i<0)return Wr;if(i>=fu)return gu}else{if(i<=-wl)return Et;if(i+1>=wl)return du}return i<0?Wt(-i,t).neg():Ke(i%Yi|0,i/Yi|0,t)}Ve.fromNumber=Wt;function Ke(i,t,e){return new Ve(i,t,e)}Ve.fromBits=Ke;var bs=Math.pow;function Sa(i,t,e){if(i.length===0)throw Error("empty string");if(typeof t=="number"?(e=t,t=!1):t=!!t,i==="NaN"||i==="Infinity"||i==="+Infinity"||i==="-Infinity")return t?Wr:an;if(e=e||10,e<2||360)throw Error("interior hyphen");if(n===0)return Sa(i.substring(1),t,e).neg();for(var r=Wt(bs(e,8)),o=an,s=0;s>>0:this.low};he.toNumber=function(){return this.unsigned?(this.high>>>0)*Yi+(this.low>>>0):this.high*Yi+(this.low>>>0)};he.toString=function(t){if(t=t||10,t<2||36>>0,y=m.toString(t);if(s=c,s.isZero())return y+u;for(;y.length<6;)y="0"+y;u=""+y+u}};he.getHighBits=function(){return this.high};he.getHighBitsUnsigned=function(){return this.high>>>0};he.getLowBits=function(){return this.low};he.getLowBitsUnsigned=function(){return this.low>>>0};he.getNumBitsAbs=function(){if(this.isNegative())return this.eq(Et)?64:this.neg().getNumBitsAbs();for(var t=this.high!=0?this.high:this.low,e=31;e>0&&!(t&1<=0};he.isOdd=function(){return(this.low&1)===1};he.isEven=function(){return(this.low&1)===0};he.equals=function(t){return yt(t)||(t=hn(t)),this.unsigned!==t.unsigned&&this.high>>>31===1&&t.high>>>31===1?!1:this.high===t.high&&this.low===t.low};he.eq=he.equals;he.notEquals=function(t){return!this.eq(t)};he.neq=he.notEquals;he.ne=he.notEquals;he.lessThan=function(t){return this.comp(t)<0};he.lt=he.lessThan;he.lessThanOrEqual=function(t){return this.comp(t)<=0};he.lte=he.lessThanOrEqual;he.le=he.lessThanOrEqual;he.greaterThan=function(t){return this.comp(t)>0};he.gt=he.greaterThan;he.greaterThanOrEqual=function(t){return this.comp(t)>=0};he.gte=he.greaterThanOrEqual;he.ge=he.greaterThanOrEqual;he.compare=function(t){if(yt(t)||(t=hn(t)),this.eq(t))return 0;var e=this.isNegative(),n=t.isNegative();return e&&!n?-1:!e&&n?1:this.unsigned?t.high>>>0>this.high>>>0||t.high===this.high&&t.low>>>0>this.low>>>0?-1:1:this.sub(t).isNegative()?-1:1};he.comp=he.compare;he.negate=function(){return!this.unsigned&&this.eq(Et)?Et:this.not().add(Ui)};he.neg=he.negate;he.add=function(t){yt(t)||(t=hn(t));var e=this.high>>>16,n=this.high&65535,r=this.low>>>16,o=this.low&65535,s=t.high>>>16,u=t.high&65535,c=t.low>>>16,m=t.low&65535,y=0,d=0,l=0,a=0;return a+=o+m,l+=a>>>16,a&=65535,l+=r+c,d+=l>>>16,l&=65535,d+=n+u,y+=d>>>16,d&=65535,y+=e+s,y&=65535,Ke(l<<16|a,y<<16|d,this.unsigned)};he.subtract=function(t){return yt(t)||(t=hn(t)),this.add(t.neg())};he.sub=he.subtract;he.multiply=function(t){if(this.isZero())return this;if(yt(t)||(t=hn(t)),Ht){var e=Ht.mul(this.low,this.high,t.low,t.high);return Ke(e,Ht.get_high(),this.unsigned)}if(t.isZero())return this.unsigned?Wr:an;if(this.eq(Et))return t.isOdd()?Et:an;if(t.eq(Et))return this.isOdd()?Et:an;if(this.isNegative())return t.isNegative()?this.neg().mul(t.neg()):this.neg().mul(t).neg();if(t.isNegative())return this.mul(t.neg()).neg();if(this.lt(Al)&&t.lt(Al))return Wt(this.toNumber()*t.toNumber(),this.unsigned);var n=this.high>>>16,r=this.high&65535,o=this.low>>>16,s=this.low&65535,u=t.high>>>16,c=t.high&65535,m=t.low>>>16,y=t.low&65535,d=0,l=0,a=0,p=0;return p+=s*y,a+=p>>>16,p&=65535,a+=o*y,l+=a>>>16,a&=65535,a+=s*m,l+=a>>>16,a&=65535,l+=r*y,d+=l>>>16,l&=65535,l+=o*m,d+=l>>>16,l&=65535,l+=s*c,d+=l>>>16,l&=65535,d+=n*y+r*m+o*c+s*u,d&=65535,Ke(a<<16|p,d<<16|l,this.unsigned)};he.mul=he.multiply;he.divide=function(t){if(yt(t)||(t=hn(t)),t.isZero())throw Error("division by zero");if(Ht){if(!this.unsigned&&this.high===-2147483648&&t.low===-1&&t.high===-1)return this;var e=(this.unsigned?Ht.div_u:Ht.div_s)(this.low,this.high,t.low,t.high);return Ke(e,Ht.get_high(),this.unsigned)}if(this.isZero())return this.unsigned?Wr:an;var n,r,o;if(this.unsigned){if(t.unsigned||(t=t.toUnsigned()),t.gt(this))return Wr;if(t.gt(this.shru(1)))return hu;o=Wr}else{if(this.eq(Et)){if(t.eq(Ui)||t.eq(da))return Et;if(t.eq(Et))return Ui;var s=this.shr(1);return n=s.div(t).shl(1),n.eq(an)?t.isNegative()?Ui:da:(r=this.sub(t.mul(n)),o=n.add(r.div(t)),o)}else if(t.eq(Et))return this.unsigned?Wr:an;if(this.isNegative())return t.isNegative()?this.neg().div(t.neg()):this.neg().div(t).neg();if(t.isNegative())return this.div(t.neg()).neg();o=an}for(r=this;r.gte(t);){n=Math.max(1,Math.floor(r.toNumber()/t.toNumber()));for(var u=Math.ceil(Math.log(n)/Math.LN2),c=u<=48?1:bs(2,u-48),m=Wt(n),y=m.mul(t);y.isNegative()||y.gt(r);)n-=c,m=Wt(n,this.unsigned),y=m.mul(t);m.isZero()&&(m=Ui),o=o.add(m),r=r.sub(y)}return o};he.div=he.divide;he.modulo=function(t){if(yt(t)||(t=hn(t)),Ht){var e=(this.unsigned?Ht.rem_u:Ht.rem_s)(this.low,this.high,t.low,t.high);return Ke(e,Ht.get_high(),this.unsigned)}return this.sub(this.div(t).mul(t))};he.mod=he.modulo;he.rem=he.modulo;he.not=function(){return Ke(~this.low,~this.high,this.unsigned)};he.countLeadingZeros=function(){return this.high?Math.clz32(this.high):Math.clz32(this.low)+32};he.clz=he.countLeadingZeros;he.countTrailingZeros=function(){return this.low?ml(this.low):ml(this.high)+32};he.ctz=he.countTrailingZeros;he.and=function(t){return yt(t)||(t=hn(t)),Ke(this.low&t.low,this.high&t.high,this.unsigned)};he.or=function(t){return yt(t)||(t=hn(t)),Ke(this.low|t.low,this.high|t.high,this.unsigned)};he.xor=function(t){return yt(t)||(t=hn(t)),Ke(this.low^t.low,this.high^t.high,this.unsigned)};he.shiftLeft=function(t){return yt(t)&&(t=t.toInt()),(t&=63)===0?this:t<32?Ke(this.low<>>32-t,this.unsigned):Ke(0,this.low<>>t|this.high<<32-t,this.high>>t,this.unsigned):Ke(this.high>>t-32,this.high>=0?0:-1,this.unsigned)};he.shr=he.shiftRight;he.shiftRightUnsigned=function(t){return yt(t)&&(t=t.toInt()),(t&=63)===0?this:t<32?Ke(this.low>>>t|this.high<<32-t,this.high>>>t,this.unsigned):t===32?Ke(this.high,0,this.unsigned):Ke(this.high>>>t-32,0,this.unsigned)};he.shru=he.shiftRightUnsigned;he.shr_u=he.shiftRightUnsigned;he.rotateLeft=function(t){var e;return yt(t)&&(t=t.toInt()),(t&=63)===0?this:t===32?Ke(this.high,this.low,this.unsigned):t<32?(e=32-t,Ke(this.low<>>e,this.high<>>e,this.unsigned)):(t-=32,e=32-t,Ke(this.high<>>e,this.low<>>e,this.unsigned))};he.rotl=he.rotateLeft;he.rotateRight=function(t){var e;return yt(t)&&(t=t.toInt()),(t&=63)===0?this:t===32?Ke(this.high,this.low,this.unsigned):t<32?(e=32-t,Ke(this.high<>>t,this.low<>>t,this.unsigned)):(t-=32,e=32-t,Ke(this.low<>>t,this.high<>>t,this.unsigned))};he.rotr=he.rotateRight;he.toSigned=function(){return this.unsigned?Ke(this.low,this.high,!1):this};he.toUnsigned=function(){return this.unsigned?this:Ke(this.low,this.high,!0)};he.toBytes=function(t){return t?this.toBytesLE():this.toBytesBE()};he.toBytesLE=function(){var t=this.high,e=this.low;return[e&255,e>>>8&255,e>>>16&255,e>>>24,t&255,t>>>8&255,t>>>16&255,t>>>24]};he.toBytesBE=function(){var t=this.high,e=this.low;return[t>>>24,t>>>16&255,t>>>8&255,t&255,e>>>24,e>>>16&255,e>>>8&255,e&255]};Ve.fromBytes=function(t,e,n){return n?Ve.fromBytesLE(t,e):Ve.fromBytesBE(t,e)};Ve.fromBytesLE=function(t,e){return new Ve(t[0]|t[1]<<8|t[2]<<16|t[3]<<24,t[4]|t[5]<<8|t[6]<<16|t[7]<<24,e)};Ve.fromBytesBE=function(t,e){return new Ve(t[4]<<24|t[5]<<16|t[6]<<8|t[7],t[0]<<24|t[1]<<16|t[2]<<8|t[3],e)};var ft=(i=>(i[i.Null=0]="Null",i[i.Boolean=1]="Boolean",i[i.Integer=2]="Integer",i[i.Long=3]="Long",i[i.Double=4]="Double",i[i.String=5]="String",i[i.Bytes=6]="Bytes",i[i.Date=7]="Date",i))(ft||{});class et extends Eo{constructor(e,n){super(n);T(this,"valueType");T(this,"value");this.valueType=et.getPrimitiveType(e),this.value=e===void 0?null:e}static of(e,n){return new et(e,n)}static valueFromBytes(e,n){switch(e){case 0:return null;case 1:return!!n[0];case 2:return n[0]|n[1]<<8|n[2]<<16|n[3]<<24;case 4:{const r=new DataView(n.buffer);return n.forEach(function(o,s){r.setUint8(s,o)}),r.getFloat64(0,!0)}case 5:return new TextDecoder("utf-8").decode(n);case 3:return Ve.fromBytesLE(Array.from(n));case 6:return n;case 7:return new Date(Ve.fromBytesLE(Array.from(n),!0).toNumber());default:throw new ne(te.ErrUnimplemented,`unimplemented type: ${e}`)}}toJSON(){return this.valueType===5?`"${Fn(this.value)}"`:`${this.value}`}toSortedJSON(){return this.toJSON()}toJSForTest(){return{createdAt:this.getCreatedAt().toTestString(),value:this.value,type:"YORKIE_PRIMITIVE"}}deepcopy(){const e=et.of(this.value,this.getCreatedAt());return e.setMovedAt(this.getMovedAt()),e.setRemovedAt(this.getRemovedAt()),e}getType(){return this.valueType}static getPrimitiveType(e){switch(typeof e){case"undefined":return 0;case"boolean":return 1;case"number":return this.isInteger(e)?2:4;case"string":return 5;case"object":if(e===null)return 0;if(e instanceof Ve)return 3;if(e instanceof Uint8Array)return 6;if(e instanceof Date)return 7}}static isSupport(e){return et.getPrimitiveType(e)!==void 0}static isInteger(e){return e%1===0}isNumericType(){const e=this.valueType;return e===2||e===3||e===4}getValue(){return this.value}toBytes(){switch(this.valueType){case 0:return new Uint8Array;case 1:return this.value?new Uint8Array([1]):new Uint8Array([0]);case 2:{const e=this.value;return new Uint8Array([e&255,e>>8&255,e>>16&255,e>>24&255])}case 4:{const e=this.value,n=new Uint8Array(8);return new DataView(n.buffer).setFloat64(0,e,!0),n}case 5:return new TextEncoder().encode(this.value);case 3:{const n=this.value.toBytesLE();return Uint8Array.from(n)}case 6:return this.value;case 7:{const e=this.value,n=Ve.fromNumber(e.getTime(),!0).toBytesLE();return Uint8Array.from(n)}default:throw new ne(te.ErrUnimplemented,`unimplemented type: ${this.valueType}`)}}}class ws extends cu{constructor(e){super(e);T(this,"prev");T(this,"next");this.value=e}static createAfter(e,n){const r=new ws(n),o=e.next;return e.next=r,r.prev=e,r.next=o,o&&(o.prev=r),r}remove(e){return this.value.remove(e)}getCreatedAt(){return this.value.getCreatedAt()}getPositionedAt(){return this.value.getPositionedAt()}release(){this.prev&&(this.prev.next=this.next),this.next&&(this.next.prev=this.prev),this.prev=void 0,this.next=void 0}getLength(){return this.value.isRemoved()?0:1}getPrev(){return this.prev}getNext(){return this.next}getValue(){return this.value}isRemoved(){return this.value.isRemoved()}}class bo{constructor(){T(this,"dummyHead");T(this,"last");T(this,"nodeMapByIndex");T(this,"nodeMapByCreatedAt");const t=et.of(0,un);t.setRemovedAt(un),this.dummyHead=new ws(t),this.last=this.dummyHead,this.nodeMapByIndex=new vo,this.nodeMapByCreatedAt=new Map,this.nodeMapByIndex.insert(this.dummyHead),this.nodeMapByCreatedAt.set(this.dummyHead.getCreatedAt().toIDString(),this.dummyHead)}static create(){return new bo}get length(){return this.nodeMapByIndex.length}findNextBeforeExecutedAt(t,e){let n=this.nodeMapByCreatedAt.get(t.toIDString());if(!n)throw new ne(te.ErrInvalidArgument,`cant find the given node: ${t.toIDString()}`);for(;n.getNext()&&n.getNext().getPositionedAt().after(e);)n=n.getNext();return n}release(t){this.last===t&&(this.last=t.getPrev()),t.release(),this.nodeMapByIndex.delete(t),this.nodeMapByCreatedAt.delete(t.getValue().getCreatedAt().toIDString())}insertAfter(t,e,n=e.getCreatedAt()){const r=this.findNextBeforeExecutedAt(t,n),o=ws.createAfter(r,e);r===this.last&&(this.last=o),this.nodeMapByIndex.insertAfter(r,o),this.nodeMapByCreatedAt.set(o.getCreatedAt().toIDString(),o)}moveAfter(t,e,n){const r=this.nodeMapByCreatedAt.get(t.toIDString());if(!r)throw new ne(te.ErrInvalidArgument,`cant find the given node: ${t.toIDString()}`);const o=this.nodeMapByCreatedAt.get(e.toIDString());if(!o)throw new ne(te.ErrInvalidArgument,`cant find the given node: ${e.toIDString()}`);r!==o&&(!o.getValue().getMovedAt()||n.after(o.getValue().getMovedAt()))&&(this.release(o),this.insertAfter(r.getCreatedAt(),o.getValue(),n),o.getValue().setMovedAt(n))}insert(t){this.insertAfter(this.last.getCreatedAt(),t)}getByID(t){return this.nodeMapByCreatedAt.get(t.toIDString())}subPathOf(t){const e=this.nodeMapByCreatedAt.get(t.toIDString());if(e)return String(this.nodeMapByIndex.indexOf(e))}purge(t){const e=this.nodeMapByCreatedAt.get(t.getCreatedAt().toIDString());if(!e)throw new ne(te.ErrInvalidArgument,`fail to find the given createdAt: ${t.getCreatedAt().toIDString()}`);this.release(e)}getByIndex(t){if(t>=this.length)return;const[e,n]=this.nodeMapByIndex.find(t);let r=e;if(t===0&&e===this.dummyHead||n>0)do r&&(r=r.getNext());while(r&&r.isRemoved());return r}getPrevCreatedAt(t){let e=this.nodeMapByCreatedAt.get(t.toIDString());do e=e.getPrev();while(this.dummyHead!==e&&e.isRemoved());return e.getValue().getCreatedAt()}delete(t,e){const n=this.nodeMapByCreatedAt.get(t.toIDString()),r=n.isRemoved();return n.remove(e)&&!r&&this.nodeMapByIndex.splayNode(n),n.getValue()}deleteByIndex(t,e){const n=this.getByIndex(t);if(n)return n.remove(e)&&this.nodeMapByIndex.splayNode(n),n.getValue()}getHead(){return this.dummyHead.getValue()}getLast(){return this.last.getValue()}getLastCreatedAt(){return this.last.getCreatedAt()}toTestString(){const t=[];for(const e of this){const n=`${e.getCreatedAt().toIDString()}:${e.getValue().toJSON()}`;e.isRemoved()?t.push(`{${n}}`):t.push(`[${n}]`)}return t.join("")}*[Symbol.iterator](){let t=this.dummyHead.getNext();for(;t;)yield t,t=t.getNext()}}class Rt extends hi{constructor(e,n){super(e);T(this,"elements");this.elements=n}static create(e,n){if(!n)return new Rt(e,bo.create());const r=bo.create();for(const o of n)r.insertAfter(r.getLastCreatedAt(),o.deepcopy());return new Rt(e,r)}subPathOf(e){return this.elements.subPathOf(e)}purge(e){this.elements.purge(e)}insertAfter(e,n){this.elements.insertAfter(e,n)}moveAfter(e,n,r){this.elements.moveAfter(e,n,r)}get(e){const n=this.elements.getByIndex(e);return n==null?void 0:n.getValue()}getByID(e){const n=this.elements.getByID(e);return n==null?void 0:n.getValue()}getHead(){return this.elements.getHead()}getLast(){return this.elements.getLast()}getPrevCreatedAt(e){return this.elements.getPrevCreatedAt(e)}delete(e,n){return this.elements.delete(e,n)}deleteByIndex(e,n){return this.elements.deleteByIndex(e,n)}getLastCreatedAt(){return this.elements.getLastCreatedAt()}get length(){return this.elements.length}*[Symbol.iterator](){for(const e of this.elements)e.isRemoved()||(yield e.getValue())}toTestString(){return this.elements.toTestString()}getDescendants(e){for(const n of this.elements){const r=n.getValue();if(e(r,this))return;r instanceof hi&&r.getDescendants(e)}}toJSON(){const e=[];for(const n of this)e.push(n.toJSON());return`[${e.join(",")}]`}toJS(){return JSON.parse(this.toJSON())}toJSForTest(){const e={};for(let n=0;n({...a,value:a.value?{attributes:$i(a.value.getAttributes()),content:a.value.getContent()}:{attributes:void 0,content:""},type:"content"}));return[m,l,y,[c,c]]}setStyle(e,n,r,o){const[,s]=this.rgaTreeSplit.findNodeWithSplit(e[1],r),[,u]=this.rgaTreeSplit.findNodeWithSplit(e[0],r),c=[],m=this.rgaTreeSplit.findBetween(u,s),y=new Map,d=[];for(const a of m){const p=a.getCreatedAt().getActorID(),b=o!=null&&o.size?o.has(p)?o.get(p):un:uo;if(a.canStyle(r,b)){const w=y.get(p),v=a.getCreatedAt();(!w||v.after(w))&&y.set(p,v),d.push(a)}}const l=[];for(const a of d){if(a.isRemoved())continue;const[p,b]=this.rgaTreeSplit.findIndexesFromRange(a.createPosRange());c.push({type:"style",actor:r.getActorID(),from:p,to:b,value:{attributes:$i(n)}});for(const[w,v]of Object.entries(n)){const[h]=a.getValue().setAttr(w,v,r);h!==void 0&&l.push({parent:a.getValue(),child:h})}}return[y,l,c]}indexRangeToPosRange(e,n){const r=this.rgaTreeSplit.indexToPos(e);return e===n?[r,r]:[r,this.rgaTreeSplit.indexToPos(n)]}get length(){return this.rgaTreeSplit.length}getTreeByIndex(){return this.rgaTreeSplit.getTreeByIndex()}getTreeByID(){return this.rgaTreeSplit.getTreeByID()}toJSON(){const e=[];for(const n of this.rgaTreeSplit)n.isRemoved()||e.push(n.getValue().toJSON());return`[${e.join(",")}]`}toSortedJSON(){return this.toJSON()}toJSForTest(){return{createdAt:this.getCreatedAt().toTestString(),value:JSON.parse(this.toJSON()),type:"YORKIE_TEXT"}}toString(){return this.rgaTreeSplit.toString()}values(){const e=[];for(const n of this.rgaTreeSplit)if(!n.isRemoved()){const r=n.getValue();e.push({attributes:$i(r.getAttributes()),content:r.getContent()})}return e}getRGATreeSplit(){return this.rgaTreeSplit}toTestString(){return this.rgaTreeSplit.toTestString()}deepcopy(){const e=new Gt(this.rgaTreeSplit.deepcopy(),this.getCreatedAt());return e.remove(this.getRemovedAt()),e}findIndexesFromRange(e){return this.rgaTreeSplit.findIndexesFromRange(e)}getGCPairs(){const e=[];for(const n of this.rgaTreeSplit){n.getRemovedAt()&&e.push({parent:this.rgaTreeSplit,child:n});for(const r of n.getValue().getGCPairs())e.push(r)}return e}}class ko extends fn{constructor(e,n,r,o,s,u,c){super(e,c);T(this,"fromPos");T(this,"toPos");T(this,"maxCreatedAtMapByActor");T(this,"content");T(this,"attributes");this.fromPos=n,this.toPos=r,this.maxCreatedAtMapByActor=o,this.content=s,this.attributes=u}static create(e,n,r,o,s,u,c){return new ko(e,n,r,o,s,u,c)}execute(e){const n=e.findByCreatedAt(this.getParentCreatedAt());if(!n)throw new ne(te.ErrInvalidArgument,`fail to find ${this.getParentCreatedAt()}`);if(!(n instanceof Gt))throw new ne(te.ErrInvalidArgument,"fail to execute, only Text can execute edit");const r=n,[,o,s]=r.edit([this.fromPos,this.toPos],this.content,this.getExecutedAt(),Object.fromEntries(this.attributes),this.maxCreatedAtMapByActor);for(const u of s)e.registerGCPair(u);return{opInfos:o.map(({from:u,to:c,value:m})=>({type:"edit",from:u,to:c,value:m,path:e.createPath(this.getParentCreatedAt())}))}}getEffectedCreatedAt(){return this.getParentCreatedAt()}toTestString(){const e=this.getParentCreatedAt().toTestString(),n=this.fromPos.toTestString(),r=this.toPos.toTestString(),o=this.content;return`${e}.EDIT(${n},${r},${o})`}getFromPos(){return this.fromPos}getToPos(){return this.toPos}getContent(){return this.content}getAttributes(){return this.attributes||new Map}getMaxCreatedAtMapByActor(){return this.maxCreatedAtMapByActor}}class Oo extends fn{constructor(e,n,r,o,s,u){super(e,u);T(this,"fromPos");T(this,"toPos");T(this,"maxCreatedAtMapByActor");T(this,"attributes");this.fromPos=n,this.toPos=r,this.maxCreatedAtMapByActor=o,this.attributes=s}static create(e,n,r,o,s,u){return new Oo(e,n,r,o,s,u)}execute(e){const n=e.findByCreatedAt(this.getParentCreatedAt());if(!n)throw new ne(te.ErrInvalidArgument,`fail to find ${this.getParentCreatedAt()}`);if(!(n instanceof Gt))throw new ne(te.ErrInvalidArgument,"fail to execute, only Text can execute edit");const r=n,[,o,s]=r.setStyle([this.fromPos,this.toPos],this.attributes?Object.fromEntries(this.attributes):{},this.getExecutedAt(),this.maxCreatedAtMapByActor);for(const u of o)e.registerGCPair(u);return{opInfos:s.map(({from:u,to:c,value:m})=>({type:"style",from:u,to:c,value:m,path:e.createPath(this.getParentCreatedAt())}))}}getEffectedCreatedAt(){return this.getParentCreatedAt()}toTestString(){const e=this.getParentCreatedAt().toTestString(),n=this.fromPos.toTestString(),r=this.toPos.toTestString(),o=this.attributes;return`${e}.STYL(${n},${r},${JSON.stringify(o)})`}getFromPos(){return this.fromPos}getToPos(){return this.toPos}getAttributes(){return this.attributes}getMaxCreatedAtMapByActor(){return this.maxCreatedAtMapByActor}}const xf=2,kf="root",Gr="text";function oo(i,t){let e=0;const n=i.children;for(let r=0;r0)throw new ne(te.ErrRefused,"Text node cannot have children")}updateAncestorsSize(){let t=this.parent;const e=this.isRemoved?-1:1;for(;t&&(t.size+=this.paddedSize*e,!t.isRemoved);)t=t.parent}updateDescendantsSize(){let t=0;for(const e of this._children){const n=e.updateDescendantsSize();e.isRemoved||(t+=n)}return this.size+=t,this.paddedSize}get isText(){return this.type===Gr}get paddedSize(){return this.size+(this.isText?0:xf)}isAncestorOf(t){return If(this,t)}get nextSibling(){const t=this.parent.findOffset(this),e=this.parent.children[t+1];if(e)return e}get prevSibling(){const t=this.parent.findOffset(this),e=this.parent.children[t-1];if(e)return e}splitText(t,e){if(t===0||t===this.size)return;const n=this.value.slice(0,t),r=this.value.slice(t);if(!r.length)return;this.value=n;const o=this.cloneText(t+e);return o.value=r,this.parent.insertAfterInternal(o,this),o}get children(){return this._children.filter(t=>!t.isRemoved)}get allChildren(){return[...this._children]}hasTextChild(){return this.children.length>0&&this.children.every(t=>t.isText)}append(...t){if(this.isText)throw new ne(te.ErrRefused,"Text node cannot have children");this._children.push(...t);for(const e of t)e.parent=this,e.updateAncestorsSize()}prepend(...t){if(this.isText)throw new ne(te.ErrRefused,"Text node cannot have children");this._children.unshift(...t);for(const e of t)e.parent=this}insertBefore(t,e){if(this.isText)throw new ne(te.ErrRefused,"Text node cannot have children");const n=this._children.indexOf(e);if(n===-1)throw new ne(te.ErrInvalidArgument,"child not found");this.insertAtInternal(t,n),t.updateAncestorsSize()}insertAfter(t,e){if(this.isText)throw new ne(te.ErrRefused,"Text node cannot have children");const n=this._children.indexOf(e);if(n===-1)throw new ne(te.ErrInvalidArgument,"child not found");this.insertAtInternal(t,n+1),t.updateAncestorsSize()}insertAt(t,e){if(this.isText)throw new ne(te.ErrRefused,"Text node cannot have children");this.insertAtInternal(t,e),t.updateAncestorsSize()}removeChild(t){if(this.isText)throw new ne(te.ErrRefused,"Text node cannot have children");const e=this._children.indexOf(t);if(e===-1)throw new ne(te.ErrInvalidArgument,"child not found");this._children.splice(e,1),t.parent=void 0}splitElement(t,e){const n=this.cloneElement(e);this.parent.insertAfterInternal(n,this),n.updateAncestorsSize();const r=this.children.slice(0,t),o=this.children.slice(t);this._children=r,n._children=o,this.size=this._children.reduce((s,u)=>s+u.paddedSize,0),n.size=n._children.reduce((s,u)=>s+u.paddedSize,0);for(const s of n._children)s.parent=n;return n}insertAfterInternal(t,e){if(this.isText)throw new ne(te.ErrRefused,"Text node cannot have children");const n=this._children.indexOf(e);if(n===-1)throw new ne(te.ErrInvalidArgument,"child not found");this.insertAtInternal(t,n+1)}insertAtInternal(t,e){if(this.isText)throw new ne(te.ErrRefused,"Text node cannot have children");this._children.splice(e,0,t),t.parent=this}findOffset(t){if(this.isText)throw new ne(te.ErrRefused,"Text node cannot have children");if(t.isRemoved){const e=this._children.indexOf(t);return this.allChildren.splice(0,e).filter(r=>!r.isRemoved).length}return this.children.indexOf(t)}findBranchOffset(t){if(this.isText)throw new ne(te.ErrRefused,"Text node cannot have children");let e=t;for(;e;){const n=this._children.indexOf(e);if(n!==-1)return n;e=e.parent}return-1}}function If(i,t){if(i===t)return!1;for(;t.parent;){if(t.parent===i)return!0;t=t.parent}return!1}var ut=(i=>(i.Start="Start",i.End="End",i.Text="Text",i))(ut||{});function pu(i,t,e,n){if(t>e)throw new ne(te.ErrInvalidArgument,`from is greater than to: ${t} > ${e}`);if(t>i.size)throw new ne(te.ErrInvalidArgument,`from is out of range: ${t} > ${i.size}`);if(e>i.size)throw new ne(te.ErrInvalidArgument,`to is out of range: ${e} > ${i.size}`);if(t===e)return;let r=0;for(const o of i.children){if(t-o.paddedSizeo.size;(o.isText||c)&&n([o,o.isText?"Text":"Start"],m),pu(o,Math.max(0,s),Math.min(u,o.size),n),m&&n([o,"End"],m)}r+=o.paddedSize}}function mu(i,t,e=0){for(const n of i.children)mu(n,t,e+1);t(i,e)}function ks(i,t,e=0){for(const n of i._children)ks(n,t,e+1);t(i,e)}function ga(i,t,e=!0){if(t>i.size)throw new ne(te.ErrInvalidArgument,`index is out of range: ${t} > ${i.size}`);if(i.isText)return{node:i,offset:t};let n=0,r=0;for(const o of i.children){if(e&&o.isText&&o.size>=t-r)return ga(o,t-r,e);if(t===r)return{node:i,offset:n};if(!e&&o.paddedSize===t-r)return{node:i,offset:n+1};if(o.paddedSize>t-r)return ga(o,t-r-1,e);r+=o.paddedSize,n+=1}return{node:i,offset:n}}function yu(i){return i.isText||i.children.length===0?i:yu(i.children[0])}function Nf(i,t){if(i.sizei===t?0:i0)if(e.right)e.right.parent=e,e=e.right;else return e;else if(n<0)if(e.left)e.left.parent=e,e=e.left;else{let r=e.parent,o=e;for(;r&&o===r.left;)o=r,r=r.parent;return r}else return e}}lastEntry(){if(!this.root)return this.root;let t=this.root;for(;t.right;)t=t.right;return t}size(){return this.counter}isEmpty(){return this.counter===0}getInternal(t,e){for(;e;){const n=this.comparator(t,e.key);if(n===0)return e;n<0?e=e.left:n>0&&(e=e.right)}}putInternal(t,e,n){if(!n)return this.counter+=1,new Cf(t,e,!0);const r=this.comparator(t,n.key);return r<0?n.left=this.putInternal(t,e,n.left):r>0?n.right=this.putInternal(t,e,n.right):n.value=e,this.isRed(n.right)&&!this.isRed(n.left)&&(n=this.rotateLeft(n)),this.isRed(n.left)&&this.isRed(n.left.left)&&(n=this.rotateRight(n)),this.isRed(n.left)&&this.isRed(n.right)&&this.flipColors(n),n}removeInternal(t,e){if(this.comparator(e,t.key)<0)!this.isRed(t.left)&&!this.isRed(t.left.left)&&(t=this.moveRedLeft(t)),t.left=this.removeInternal(t.left,e);else{if(this.isRed(t.left)&&(t=this.rotateRight(t)),this.comparator(e,t.key)===0&&!t.right){this.counter-=1;return}if(!this.isRed(t.right)&&!this.isRed(t.right.left)&&(t=this.moveRedRight(t)),this.comparator(e,t.key)===0){this.counter-=1;const n=this.min(t.right);t.value=n.value,t.key=n.key,t.right=this.removeMin(t.right)}else t.right=this.removeInternal(t.right,e)}return this.fixUp(t)}min(t){return t.left?this.min(t.left):t}removeMin(t){if(t.left)return!this.isRed(t.left)&&!this.isRed(t.left.left)&&(t=this.moveRedLeft(t)),t.left=this.removeMin(t.left),this.fixUp(t)}fixUp(t){return this.isRed(t.right)&&(t=this.rotateLeft(t)),this.isRed(t.left)&&this.isRed(t.left.left)&&(t=this.rotateRight(t)),this.isRed(t.left)&&this.isRed(t.right)&&this.flipColors(t),t}moveRedLeft(t){return this.flipColors(t),this.isRed(t.right.left)&&(t.right=this.rotateRight(t.right),t=this.rotateLeft(t),this.flipColors(t)),t}moveRedRight(t){return this.flipColors(t),this.isRed(t.left.left)&&(t=this.rotateRight(t),this.flipColors(t)),t}isRed(t){return t&&t.isRed}rotateLeft(t){const e=t.right;return t.right=e.left,e.left=t,e.isRed=e.left.isRed,e.left.isRed=!0,e}rotateRight(t){const e=t.left;return t.left=e.right,e.right=t,e.isRed=e.right.isRed,e.right.isRed=!0,e}flipColors(t){t.isRed=!t.isRed,t.left.isRed=!t.left.isRed,t.right.isRed=!t.right.isRed}}class ln{constructor(t,e){T(this,"parentID");T(this,"leftSiblingID");this.parentID=t,this.leftSiblingID=e}static of(t,e){return new ln(t,e)}static fromTreePos(t){const{offset:e}=t;let{node:n}=t,r;return n.isText?(n.parent.children[0]===n&&e===0?r=n.parent:r=n,n=n.parent):e===0?r=n:r=n.children[e-1],ln.of(n.id,pt.of(r.getCreatedAt(),r.getOffset()+e))}getParentID(){return this.parentID}static fromStruct(t){return ln.of(pt.of(Lt.fromStruct(t.parentID.createdAt),t.parentID.offset),pt.of(Lt.fromStruct(t.leftSiblingID.createdAt),t.leftSiblingID.offset))}toStruct(){return{parentID:{createdAt:this.getParentID().getCreatedAt().toStruct(),offset:this.getParentID().getOffset()},leftSiblingID:{createdAt:this.getLeftSiblingID().getCreatedAt().toStruct(),offset:this.getLeftSiblingID().getOffset()}}}toTreeNodePair(t){const e=this.getParentID(),n=this.getLeftSiblingID(),r=t.findFloorNode(e);let o=t.findFloorNode(n);if(!r||!o)throw new ne(te.ErrRefused,`cannot find node of CRDTTreePos(${e.toTestString()}, ${n.toTestString()})`);return!n.equals(e)&&n.getOffset()>0&&n.getOffset()===o.id.getOffset()&&o.insPrevID&&(o=t.findFloorNode(o.insPrevID)),[r,o]}getLeftSiblingID(){return this.leftSiblingID}equals(t){return this.getParentID().getCreatedAt().equals(t.getParentID().getCreatedAt())&&this.getParentID().getOffset()===t.getParentID().getOffset()&&this.getLeftSiblingID().getCreatedAt().equals(t.getLeftSiblingID().getCreatedAt())&&this.getLeftSiblingID().getOffset()===t.getLeftSiblingID().getOffset()}}class pt{constructor(t,e){T(this,"createdAt");T(this,"offset");this.createdAt=t,this.offset=e}static of(t,e){return new pt(t,e)}static fromStruct(t){return pt.of(Lt.fromStruct(t.createdAt),t.offset)}static createComparator(){return(t,e)=>{const n=t.getCreatedAt().compare(e.getCreatedAt());return n!==0?n:t.getOffset()>e.getOffset()?1:t.getOffset(){const o=r.deepcopy();return o.parent=e,o}),e.insPrevID=this.insPrevID,e.insNextID=this.insNextID,e}get value(){if(!this.isText)throw new ne(te.ErrInvalidType,`cannot get value of element node: ${this.type}`);return this._value}set value(e){if(!this.isText)throw new ne(te.ErrInvalidType,`cannot set value of element node: ${this.type}`);this._value=e,this.size=e.length}get isRemoved(){return!!this.removedAt}remove(e){const n=!this.removedAt;(!this.removedAt||this.removedAt.compare(e)>0)&&(this.removedAt=e),n&&this.updateAncestorsSize()}cloneText(e){return new Ct(pt.of(this.id.getCreatedAt(),e),this.type,void 0,void 0,this.removedAt)}cloneElement(e){return new Ct(pt.of(e(),0),this.type,void 0,void 0,this.removedAt)}split(e,n,r){const o=this.isText?this.splitText(n,this.id.getOffset()):this.splitElement(n,r);if(o){if(o.insPrevID=this.id,this.insNextID){const s=e.findFloorNode(this.insNextID);s.insPrevID=o.id,o.insNextID=this.insNextID}this.insNextID=o.id,e.registerNode(o)}return o}getCreatedAt(){return this.id.getCreatedAt()}getOffset(){return this.id.getOffset()}canDelete(e,n){return!this.getCreatedAt().after(n)&&(!this.removedAt||e.after(this.removedAt))}canStyle(e,n){return this.isText?!1:!this.getCreatedAt().after(n)&&(!this.removedAt||e.after(this.removedAt))}setAttrs(e,n){this.attrs||(this.attrs=new Xr);const r=new Array;for(const[o,s]of Object.entries(e))r.push(this.attrs.set(o,s,n));return r}purge(e){this.attrs&&this.attrs.purge(e)}getGCPairs(){const e=[];if(!this.attrs)return e;for(const n of this.attrs)n.getRemovedAt()&&e.push({parent:this,child:n});return e}}function pa(i){var e;if(i.isText){const n=i;return{type:n.type,value:n.value}}const t={type:i.type,children:i.children.map(pa)};return i.attrs&&(t.attributes=$i((e=i.attrs)==null?void 0:e.toObject())),t}function Ea(i){if(i.isText)return i.value;let t="";return i.attrs&&i.attrs.size()&&(t=" "+Array.from(i.attrs).filter(e=>!e.isRemoved()).sort((e,n)=>e.getKey().localeCompare(n.getKey())).map(e=>{const n=JSON.parse(e.getValue());return typeof n=="string"?`${e.getKey()}="${n}"`:`${e.getKey()}="${Fn(e.getValue())}"`}).join(" ")),`<${i.type}${t}>${i.children.map(e=>Ea(e)).join("")}`}function bu(i){if(i.isText){const t=i;return{type:t.type,value:t.value,size:t.size,isRemoved:t.isRemoved}}return{type:i.type,children:i.children.map(bu),size:i.size,isRemoved:i.isRemoved}}class Yt extends Eo{constructor(e,n){super(n);T(this,"indexTree");T(this,"nodeMapByID");this.indexTree=new _f(e),this.nodeMapByID=new vu(pt.createComparator()),this.indexTree.traverseAll(r=>{this.nodeMapByID.put(r.id,r)})}static create(e,n){return new Yt(e,n)}findFloorNode(e){const n=this.nodeMapByID.floorEntry(e);if(!(!n||!n.key.getCreatedAt().equals(e.getCreatedAt())))return n.value}registerNode(e){this.nodeMapByID.put(e.id,e)}findNodesAndSplitText(e,n){const[r,o]=e.toTreeNodePair(this);let s=o;const u=r===s,c=s.parent&&!u?s.parent:r;if(s.isText&&s.split(this,e.getLeftSiblingID().getOffset()-s.id.getOffset()),n){const m=c.allChildren,y=u?0:m.indexOf(s)+1;for(let d=y;d{const b=p.getCreatedAt().getActorID(),w=o?o.has(b)?o.get(b):un:uo;if(p.canStyle(r,w)&&n){const v=l.get(b),h=p.getCreatedAt();(!v||h.after(v))&&l.set(b,h);const g=p.setAttrs(n,r),f=g.reduce((E,[,O])=>(O&&(E[O.getKey()]=d[O.getKey()]),E),{}),A=p.parent,S=p.prevSibling||p.parent;Object.keys(f).length>0&&y.push({type:"style",from:this.toIndex(A,S),to:this.toIndex(p,p),fromPath:this.toPath(A,S),toPath:this.toPath(p,p),actor:r.getActorID(),value:f});for(const[E]of g)E&&a.push({parent:p,child:E})}}),[l,a,y]}removeStyle(e,n,r,o){const[s,u]=this.findNodesAndSplitText(e[0],r),[c,m]=this.findNodesAndSplitText(e[1],r),y=[],d=new Map,l=[];return this.traverseInPosRange(s,u,c,m,([a])=>{const p=a.getCreatedAt().getActorID(),b=o?o.has(p)?o.get(p):un:uo;if(a.canStyle(r,b)&&n){const w=d.get(p),v=a.getCreatedAt();(!w||v.after(w))&&d.set(p,v),a.attrs||(a.attrs=new Xr);for(const f of n){const A=a.attrs.remove(f,r);for(const S of A)l.push({parent:a,child:S})}const h=a.parent,g=a.prevSibling||a.parent;y.push({actor:r.getActorID(),type:"removeStyle",from:this.toIndex(h,g),to:this.toIndex(a,a),fromPath:this.toPath(h,g),toPath:this.toPath(a,a),value:n})}}),[d,l,y]}edit(e,n,r,o,s,u){const[c,m]=this.findNodesAndSplitText(e[0],o),[y,d]=this.findNodesAndSplitText(e[1],o),l=this.toIndex(c,m),a=this.toPath(c,m),p=[],b=[],w=[],v=new Map;this.traverseInPosRange(c,m,y,d,([f,A],S)=>{if(A===ut.Start&&!S)for(const P of f.children)w.push(P);const E=f.getCreatedAt().getActorID(),O=u?u.has(E)?u.get(E):un:uo;if(f.canDelete(o,O)||p.includes(f.parent)){const P=v.get(E),k=f.getCreatedAt();(!P||k.after(P))&&v.set(E,k),(A===ut.Text||A===ut.Start)&&p.push(f),b.push([f,A])}});const h=this.makeDeletionChanges(b,o),g=[];for(const f of p)f.remove(o),f.isRemoved&&g.push({parent:this,child:f});for(const f of w)f.removedAt||c.append(f);if(r>0){let f=0,A=c,S=m;for(;f{c.isRemoved&&(E.remove(o),g.push({parent:this,child:E})),this.nodeMapByID.put(E.id,E)}),S.isRemoved||f.push(S);if(f.length){const S=f.map(E=>pa(E));h.length&&h[h.length-1].from===l?h[h.length-1].value=S:h.push({type:"content",from:l,to:l,fromPath:a,toPath:a,actor:o.getActorID(),value:S})}}return[h,g,v]}editT(e,n,r,o,s){const u=this.findPos(e[0]),c=this.findPos(e[1]);this.edit([u,c],n,r,o,s)}move(e,n,r){throw new ne(te.ErrUnimplemented,`not implemented: ${e}, ${n}, ${r}`)}purge(e){var o;(o=e.parent)==null||o.removeChild(e),this.nodeMapByID.remove(e.id);const n=e.insPrevID,r=e.insNextID;if(n){const s=this.findFloorNode(n);s.insNextID=r}if(r){const s=this.findFloorNode(r);s.insPrevID=n}e.insPrevID=void 0,e.insNextID=void 0}getGCPairs(){const e=[];return this.indexTree.traverse(n=>{n.getRemovedAt()&&e.push({parent:this,child:n});for(const r of n.getGCPairs())e.push(r)}),e}findPos(e,n=!0){const r=this.indexTree.findTreePos(e,n);return ln.fromTreePos(r)}pathToPosRange(e){const n=this.pathToIndex(e);return[this.findPos(n),this.findPos(n+1)]}pathToPos(e){const n=this.indexTree.pathToIndex(e);return this.findPos(n)}getRoot(){return this.indexTree.getRoot()}getSize(){return this.indexTree.size}getNodeSize(){return this.nodeMapByID.size()}getIndexTree(){return this.indexTree}toXML(){return Ea(this.indexTree.getRoot())}toJSON(){return JSON.stringify(this.getRootTreeNode())}toJSForTest(){return{createdAt:this.getCreatedAt().toTestString(),value:JSON.parse(this.toJSON()),type:"YORKIE_TREE"}}toJSInfoForTest(){const e=this.indexTree.getRoot(),n=(r,o=void 0,s=void 0,u=0)=>{var a,p,b,w;let c,m,y;const d=r.isText?{node:r,offset:0}:o&&s?this.toTreePos(o,s):null;d&&(c=this.indexTree.indexOf(d),m=this.indexTree.treePosToPath(d),y=ln.fromTreePos(d).toStruct());const l={type:r.type,parent:o==null?void 0:o.id.toTestString(),size:r.size,id:r.id.toTestString(),removedAt:(a=r.removedAt)==null?void 0:a.toTestString(),insPrev:(p=r.insPrevID)==null?void 0:p.toTestString(),insNext:(b=r.insNextID)==null?void 0:b.toTestString(),value:r.isText?r.value:void 0,isRemoved:r.isRemoved,children:[],depth:u,attributes:r.attrs?$i((w=r.attrs)==null?void 0:w.toObject()):void 0,index:c,path:m,pos:y};for(let v=0;v0&&v===r[r.length-1].to?(r[r.length-1].to=h,r[r.length-1].toPath=this.toPath(w,a)):r.push({type:"content",from:v,to:h,fromPath:this.toPath(b,d),toPath:this.toPath(w,a),actor:n.getActorID()}))}return r.reverse()}findRightToken([e,n]){if(n===ut.Start){const c=e.allChildren;return c.length>0?[c[0],c[0].isText?ut.Text:ut.Start]:[e,ut.End]}const r=e.parent,o=r.allChildren,s=o.indexOf(e);if(r&&s===o.length-1)return[r,ut.End];const u=o[s+1];return[u,u.isText?ut.Text:ut.Start]}findLeftToken([e,n]){if(n===ut.End){const c=e.allChildren;if(c.length>0){const m=c[c.length-1];return[m,m.isText?ut.Text:ut.End]}return[e,ut.Start]}const r=e.parent,o=r.allChildren,s=o.indexOf(e);if(r&&s===0)return[r,ut.Start];const u=o[s-1];return[u,u.isText?ut.Text:ut.End]}}class Io extends fn{constructor(e,n,r,o,s,u,c){super(e,c);T(this,"fromPos");T(this,"toPos");T(this,"contents");T(this,"splitLevel");T(this,"maxCreatedAtMapByActor");this.fromPos=n,this.toPos=r,this.contents=o,this.splitLevel=s,this.maxCreatedAtMapByActor=u}static create(e,n,r,o,s,u,c){return new Io(e,n,r,o,s,u,c)}execute(e){var c;const n=e.findByCreatedAt(this.getParentCreatedAt());if(!n)throw new ne(te.ErrInvalidArgument,`fail to find ${this.getParentCreatedAt()}`);if(!(n instanceof Yt))throw new ne(te.ErrInvalidArgument,"fail to execute, only Tree can execute edit");const r=this.getExecutedAt(),o=n,[s,u]=o.edit([this.fromPos,this.toPos],(c=this.contents)==null?void 0:c.map(m=>m.deepcopy()),this.splitLevel,r,(()=>{let m=r.getDelimiter();return this.contents!==void 0&&(m+=this.contents.length),()=>Lt.of(r.getLamport(),++m,r.getActorID())})(),this.maxCreatedAtMapByActor);for(const m of u)e.registerGCPair(m);return{opInfos:s.map(({from:m,to:y,value:d,splitLevel:l,fromPath:a,toPath:p})=>({type:"tree-edit",path:e.createPath(this.getParentCreatedAt()),from:m,to:y,value:d,splitLevel:l,fromPath:a,toPath:p}))}}getEffectedCreatedAt(){return this.getParentCreatedAt()}toTestString(){const e=this.getParentCreatedAt().toTestString(),n=`${this.fromPos.getLeftSiblingID().getCreatedAt().toTestString()}/${this.fromPos.getLeftSiblingID().getOffset()}`,r=`${this.toPos.getLeftSiblingID().getCreatedAt().toTestString()}/${this.toPos.getLeftSiblingID().getOffset()}`,o=this.contents||[];return`${e}.EDIT(${n},${r},${o.map(s=>Ea(s)).join("")})`}getFromPos(){return this.fromPos}getToPos(){return this.toPos}getContents(){return this.contents}getSplitLevel(){return this.splitLevel}getMaxCreatedAtMapByActor(){return this.maxCreatedAtMapByActor}}class zi{constructor(t){T(this,"vector");this.vector=t||new Map}set(t,e){this.vector.set(t,e)}get(t){return this.vector.get(t)}maxLamport(){let t=BigInt(0);for(const[,e]of this)e>t&&(t=e);return t}max(t){const e=new Map;for(const[n,r]of t){const o=this.vector.get(n),s=o&&o>r?o:r;e.set(n,s)}for(const[n,r]of this){const o=t.get(n),s=o&&o>r?o:r;e.set(n,s)}return new zi(e)}afterOrEqual(t){const e=this.vector.get(t.getActorID());return e===void 0?!1:e>=t.getLamport()}deepcopy(){const t=new Map;for(const[e,n]of this.vector)t.set(e,n);return new zi(t)}filter(t){const e=new Map;for(const[n]of t){const r=this.vector.get(n);r!==void 0&&e.set(n,r)}return new zi(e)}size(){return this.vector.size}*[Symbol.iterator](){for(const[t,e]of this.vector)yield[t,e]}}const Rf=new zi(new Map);class zr{constructor(t,e,n,r,o){T(this,"clientSeq");T(this,"serverSeq");T(this,"lamport");T(this,"actor");T(this,"versionVector");this.clientSeq=t,this.serverSeq=o,this.lamport=e,this.versionVector=r,this.actor=n}static of(t,e,n,r,o){return new zr(t,e,n,r,o)}next(){const t=this.versionVector.deepcopy();return t.set(this.actor,this.lamport+1n),new zr(this.clientSeq+1,this.lamport+1n,this.actor,t)}syncClocks(t){const e=t.lamport>this.lamport?t.lamport+1n:this.lamport+1n,n=this.versionVector.max(t.versionVector),r=new zr(this.clientSeq,e,this.actor,n);return r.versionVector.set(this.actor,e),r}setClocks(t,e){const n=t>this.lamport?t:this.lamport+1n,r=this.versionVector.max(e);return r.set(this.actor,n),zr.of(this.clientSeq,n,this.actor,r)}createTimeTicket(t){return Lt.of(this.lamport,t,this.actor)}setActor(t){return new zr(this.clientSeq,this.lamport,t,this.versionVector,this.serverSeq)}setVersionVector(t){return new zr(this.clientSeq,this.lamport,this.actor,t,this.serverSeq)}getClientSeq(){return this.clientSeq}getServerSeq(){return this.serverSeq?this.serverSeq.toString():""}getLamport(){return this.lamport}getLamportAsString(){return this.lamport.toString()}getActorID(){return this.actor}getVersionVector(){return this.versionVector}toTestString(){return`${this.lamport.toString()}:${this.actor.slice(-2)}:${this.clientSeq}`}}const Df=new zr(0,0n,Aa,Rf);class Zi{constructor({id:t,operations:e,presenceChange:n,message:r}){T(this,"id");T(this,"operations");T(this,"presenceChange");T(this,"message");this.id=t,this.operations=e||[],this.presenceChange=n,this.message=r}static create({id:t,operations:e,presenceChange:n,message:r}){return new Zi({id:t,operations:e,presenceChange:n,message:r})}getID(){return this.id}getMessage(){return this.message}hasOperations(){return this.operations.length>0}getOperations(){return this.operations}setActor(t){for(const e of this.operations)e.setActor(t);this.id=this.id.setActor(t)}hasPresenceChange(){return this.presenceChange!==void 0}getPresenceChange(){return this.presenceChange}execute(t,e,n){const r=[],o=[];for(const s of this.operations){const u=s.execute(t,n);if(!u)continue;const{opInfos:c,reverseOp:m}=u;r.push(...c),m&&o.unshift(m)}return this.presenceChange&&(this.presenceChange.type===pi.Put?e.set(this.id.getActorID(),sn(this.presenceChange.presence)):e.delete(this.id.getActorID())),{opInfos:r,reverseOps:o}}toTestString(){return`${this.operations.map(t=>t.toTestString()).join(",")}`}toStruct(){return{changeID:at.bytesToHex(at.toChangeID(this.getID()).toBinary()),message:this.getMessage(),operations:this.getOperations().map(t=>at.bytesToHex(at.toOperation(t).toBinary())),presenceChange:this.getPresenceChange()}}static fromStruct(t){const{changeID:e,operations:n,presenceChange:r,message:o}=t;return Zi.create({id:at.bytesToChangeID(at.hexToBytes(e)),operations:n==null?void 0:n.map(s=>at.bytesToOperation(at.hexToBytes(s))),presenceChange:r,message:o})}}class Os{constructor(t,e,n,r,o,s,u){T(this,"documentKey");T(this,"checkpoint");T(this,"isRemoved");T(this,"changes");T(this,"snapshot");T(this,"minSyncedTicket");T(this,"versionVector");this.documentKey=t,this.checkpoint=e,this.isRemoved=n,this.changes=r,this.snapshot=s,this.minSyncedTicket=u,this.versionVector=o}static create(t,e,n,r,o,s,u){return new Os(t,e,n,r,o,s,u)}getDocumentKey(){return this.documentKey}getCheckpoint(){return this.checkpoint}getIsRemoved(){return this.isRemoved}getChanges(){return this.changes}hasChanges(){return this.changes.length>0}getChangeSize(){return this.changes.length}hasSnapshot(){return!!this.snapshot&&!!this.snapshot.length}getSnapshot(){return this.snapshot}getMinSyncedTicket(){return this.minSyncedTicket}getVersionVector(){return this.versionVector}}class Vi{constructor(t,e){T(this,"serverSeq");T(this,"clientSeq");this.serverSeq=t,this.clientSeq=e}static of(t,e){return new Vi(t,e)}increaseClientSeq(t){return t===0?this:new Vi(this.serverSeq,this.clientSeq+t)}forward(t){if(this.equals(t))return this;const e=this.serverSeq>t.serverSeq?this.serverSeq:t.serverSeq,n=Math.max(this.clientSeq,t.clientSeq);return Vi.of(e,n)}getServerSeqAsString(){return this.serverSeq.toString()}getClientSeq(){return this.clientSeq}getServerSeq(){return this.serverSeq}equals(t){return this.clientSeq===t.clientSeq&&this.serverSeq==t.serverSeq}toTestString(){return`serverSeq=${this.serverSeq}, clientSeq=${this.clientSeq}`}}const Bf=new Vi(0n,0);class jn{constructor(t,e){T(this,"createdAt");T(this,"offset");this.createdAt=t,this.offset=e}static of(t,e){return new jn(t,e)}static fromStruct(t){return jn.of(Lt.fromStruct(t.createdAt),t.offset)}getCreatedAt(){return this.createdAt}getOffset(){return this.offset}equals(t){return this.createdAt.compare(t.createdAt)===0&&this.offset===t.offset}hasSameCreatedAt(t){return this.createdAt.compare(t.createdAt)===0}split(t){return new jn(this.createdAt,this.offset+t)}toStruct(){return{createdAt:this.createdAt.toStruct(),offset:this.offset}}toTestString(){return`${this.createdAt.toTestString()}:${this.offset}`}toIDString(){return`${this.createdAt.toIDString()}:${this.offset}`}}const Mf=jn.of(un,0);class cn{constructor(t,e){T(this,"id");T(this,"relativeOffset");this.id=t,this.relativeOffset=e}static of(t,e){return new cn(t,e)}static fromStruct(t){const e=jn.fromStruct(t.id);return cn.of(e,t.relativeOffset)}getID(){return this.id}getRelativeOffset(){return this.relativeOffset}getAbsoluteID(){return jn.of(this.id.getCreatedAt(),this.id.getOffset()+this.relativeOffset)}toTestString(){return`${this.id.toTestString()}:${this.relativeOffset}`}toStruct(){return{id:this.id.toStruct(),relativeOffset:this.relativeOffset}}equals(t){return this.id.equals(t.id)?this.relativeOffset===t.relativeOffset:!1}}class di extends cu{constructor(e,n,r){super(n);T(this,"id");T(this,"removedAt");T(this,"prev");T(this,"next");T(this,"insPrev");T(this,"insNext");this.id=e,this.removedAt=r}static create(e,n){return new di(e,n)}static createComparator(){return(e,n)=>{const r=e.getCreatedAt().compare(n.getCreatedAt());return r!==0?r:e.getOffset()>n.getOffset()?1:e.getOffset()0&&e.getID().getOffset()==t.getOffset()){if(!e.hasInsPrev())return e;e=e.getInsPrev()}return e}findFloorNode(t){const e=this.treeByID.floorEntry(t);if(e&&!(!e.key.equals(t)&&!e.key.hasSameCreatedAt(t)))return e.value}findBetween(t,e){const n=[];let r=t;for(;r&&r!==e;)n.push(r),r=r.getNext();return n}splitNode(t,e){if(e>t.getContentLength())throw new ne(te.ErrInvalidArgument,"offset should be less than or equal to length");if(e===0)return t;if(e===t.getContentLength())return t.getNext();const n=t.split(e);this.treeByIndex.updateWeight(n),this.insertAfter(t,n);const r=t.getInsNext();return r&&r.setInsPrev(n),n.setInsPrev(t),n}deleteNodes(t,e,n){if(!t.length)return[[],new Map,new Map];const[r,o]=this.filterNodes(t,e,n),s=new Map,u=new Map,c=this.makeChanges(o,e);for(const m of r){const y=m.getCreatedAt().getActorID();(!s.has(y)||m.getID().getCreatedAt().after(s.get(y)))&&s.set(y,m.getID().getCreatedAt()),u.set(m.getID().toIDString(),m),m.remove(e)}return this.deleteIndexNodes(o),[c,s,u]}filterNodes(t,e,n){const r=!!n,o=[],s=[],[u,c]=this.findEdgesOfCandidates(t);s.push(u);for(const m of t){const y=m.getCreatedAt().getActorID(),d=r?n.has(y)?n.get(y):un:uo;m.canDelete(e,d)?o.push(m):s.push(m)}return s.push(c),[o,s]}findEdgesOfCandidates(t){return[t[0].getPrev(),t[t.length-1].getNext()]}makeChanges(t,e){const n=[];let r,o;for(let s=0;si<0?Math.ceil(i):Math.floor(i);var Un=(i=>(i[i.IntegerCnt=0]="IntegerCnt",i[i.LongCnt=1]="LongCnt",i))(Un||{});class Dt extends Eo{constructor(e,n,r){super(r);T(this,"valueType");T(this,"value");switch(this.valueType=e,e){case 0:typeof n=="number"?n>Math.pow(2,31)-1||n<-Math.pow(2,31)?this.value=Ve.fromNumber(n).toInt():this.value=Tl(n):this.value=n.toInt();break;case 1:typeof n=="number"?this.value=Ve.fromNumber(n):this.value=n;break;default:throw new ne(te.ErrUnimplemented,`unimplemented type: ${e}`)}}static create(e,n,r){return new Dt(e,n,r)}static valueFromBytes(e,n){switch(e){case 0:return n[0]|n[1]<<8|n[2]<<16|n[3]<<24;case 1:return Ve.fromBytesLE(Array.from(n));default:throw new ne(te.ErrUnimplemented,`unimplemented type: ${e}`)}}toJSON(){return`${this.value}`}toSortedJSON(){return this.toJSON()}toJSForTest(){return{createdAt:this.getCreatedAt().toTestString(),value:this.value,type:"YORKIE_COUNTER"}}deepcopy(){const e=Dt.create(this.valueType,this.value,this.getCreatedAt());return e.setMovedAt(this.getMovedAt()),e}getType(){return this.valueType}static getCounterType(e){switch(typeof e){case"object":return e instanceof Ve?1:void 0;case"number":return e>Math.pow(2,31)-1||e<-Math.pow(2,31)?1:0;default:return}}static isSupport(e){return!!Dt.getCounterType(e)}static isInteger(e){return e%1===0}isNumericType(){const e=this.valueType;return e===0||e===1}getValueType(){return this.valueType}getValue(){return this.value}toBytes(){switch(this.valueType){case 0:{const e=this.value;return new Uint8Array([e&255,e>>8&255,e>>16&255,e>>24&255])}case 1:{const n=this.value.toBytesLE();return Uint8Array.from(n)}default:throw new ne(te.ErrUnimplemented,`unimplemented type: ${this.valueType}`)}}increase(e){function n(r){if(!r.isNumericType())throw new TypeError(`Unsupported type of value: ${typeof r.getValue()}`)}return n(this),n(e),this.valueType===1?this.value=this.value.add(e.getValue()):e.getType()===ft.Long?this.value=this.value+e.getValue().toInt():this.value=Ve.fromNumber(this.value+Tl(e.getValue())).toInt(),this}}class Qi extends fn{constructor(e,n,r){super(e,r);T(this,"value");this.value=n}static create(e,n,r){return new Qi(e,n,r)}execute(e){const n=e.findByCreatedAt(this.getParentCreatedAt());if(!n)throw new ne(te.ErrInvalidArgument,`fail to find ${this.getParentCreatedAt()}`);if(!(n instanceof Dt))throw new ne(te.ErrInvalidArgument,"fail to execute, only Counter can execute increase");const r=n,o=this.value.deepcopy();return r.increase(o),{opInfos:[{type:"increase",path:e.createPath(this.getParentCreatedAt()),value:o.getValue()}],reverseOp:this.toReverseOperation()}}toReverseOperation(){const e=this.value.deepcopy(),r=e.getType()===ft.Long?e.getValue().multiply(-1):e.getValue()*-1;return Qi.create(this.getParentCreatedAt(),et.of(r,e.getCreatedAt()))}getEffectedCreatedAt(){return this.getParentCreatedAt()}toTestString(){return`${this.getParentCreatedAt().toTestString()}.INCREASE.${this.value.toJSON()}`}getValue(){return this.value}}class Yr extends fn{constructor(e,n,r,o,s,u,c){super(e,c);T(this,"fromPos");T(this,"toPos");T(this,"maxCreatedAtMapByActor");T(this,"attributes");T(this,"attributesToRemove");this.fromPos=n,this.toPos=r,this.maxCreatedAtMapByActor=o,this.attributes=s,this.attributesToRemove=u}static create(e,n,r,o,s,u){return new Yr(e,n,r,o,s,new Array,u)}static createTreeRemoveStyleOperation(e,n,r,o,s,u){return new Yr(e,n,r,o,new Map,s,u)}execute(e){const n=e.findByCreatedAt(this.getParentCreatedAt());if(!n)throw new ne(te.ErrInvalidArgument,`fail to find ${this.getParentCreatedAt()}`);if(!(n instanceof Yt))throw new ne(te.ErrInvalidArgument,"fail to execute, only Tree can execute edit");const r=n;let o,s;if(this.attributes.size){const u={};[...this.attributes].forEach(([c,m])=>u[c]=m),[,s,o]=r.style([this.fromPos,this.toPos],u,this.getExecutedAt(),this.maxCreatedAtMapByActor)}else{const u=this.attributesToRemove;[,s,o]=r.removeStyle([this.fromPos,this.toPos],u,this.getExecutedAt(),this.maxCreatedAtMapByActor)}for(const u of s)e.registerGCPair(u);return{opInfos:o.map(({from:u,to:c,value:m,fromPath:y,toPath:d})=>({type:"tree-style",from:u,to:c,value:this.attributes.size?{attributes:m}:{attributesToRemove:m},fromPath:y,toPath:d,path:e.createPath(this.getParentCreatedAt())}))}}getEffectedCreatedAt(){return this.getParentCreatedAt()}toTestString(){const e=this.getParentCreatedAt().toTestString(),n=`${this.fromPos.getLeftSiblingID().getCreatedAt().toTestString()}:${this.fromPos.getLeftSiblingID().getOffset()}`,r=`${this.toPos.getLeftSiblingID().getCreatedAt().toTestString()}:${this.toPos.getLeftSiblingID().getOffset()}`;return`${e}.STYLE(${n},${r},${Object.entries(this.attributes||{}).map(([o,s])=>`${o}:"${s}"`).join(" ")})`}getFromPos(){return this.fromPos}getToPos(){return this.toPos}getAttributes(){return this.attributes}getAttributesToRemove(){return this.attributesToRemove}getMaxCreatedAtMapByActor(){return this.maxCreatedAtMapByActor}}function qf(i){const t=new wa,e=t.data;for(const[n,r]of Object.entries(i))e[n]=JSON.stringify(r);return t}function Ff(i){if(i.type===pi.Put)return new mo({type:Ni.PUT,presence:qf(i.presence)});if(i.type===pi.Clear)return new mo({type:Ni.CLEAR});throw new ne(te.ErrUnimplemented,"unimplemented type")}function jf(i){return new au({serverSeq:i.getServerSeq(),clientSeq:i.getClientSeq()})}function wu(i){return new Es({clientSeq:i.getClientSeq(),lamport:i.getLamport(),actorId:Da(i.getActorID()),versionVector:xa(i.getVersionVector())})}function ke(i){if(i)return new xe({lamport:i.getLamport(),delimiter:i.getDelimiter(),actorId:Da(i.getActorID())})}function xa(i){if(!i)return;const t=new xs;for(const[e,n]of i)t.vector[e]=BigInt(n.toString());return t}function Au(i){switch(i){case ft.Null:return Re.NULL;case ft.Boolean:return Re.BOOLEAN;case ft.Integer:return Re.INTEGER;case ft.Long:return Re.LONG;case ft.Double:return Re.DOUBLE;case ft.String:return Re.STRING;case ft.Bytes:return Re.BYTES;case ft.Date:return Re.DATE;default:throw new ne(te.ErrInvalidType,`unsupported type: ${i}`)}}function Tu(i){switch(i){case Un.IntegerCnt:return Re.INTEGER_CNT;case Un.LongCnt:return Re.LONG_CNT;default:throw new ne(te.ErrInvalidType,`unsupported type: ${i}`)}}function Ms(i){if(i instanceof xt)return new Mt({type:Re.JSON_OBJECT,createdAt:ke(i.getCreatedAt()),value:Du(i)});if(i instanceof Rt)return new Mt({type:Re.JSON_ARRAY,createdAt:ke(i.getCreatedAt()),value:yh(i)});if(i instanceof Gt)return new Mt({type:Re.TEXT,createdAt:ke(i.getCreatedAt())});if(i instanceof et)return new Mt({type:Au(i.getType()),createdAt:ke(i.getCreatedAt()),value:i.toBytes()});if(i instanceof Dt)return new Mt({type:Tu(i.getType()),createdAt:ke(i.getCreatedAt()),value:i.toBytes()});if(i instanceof Yt)return new Mt({type:Re.TREE,createdAt:ke(i.getCreatedAt()),value:bh(i)});throw new ne(te.ErrUnimplemented,"unimplemented element")}function Uf(i){return new go({createdAt:ke(i.getCreatedAt()),offset:i.getOffset()})}function Fo(i){return new Zr({createdAt:ke(i.getID().getCreatedAt()),offset:i.getID().getOffset(),relativeOffset:i.getRelativeOffset()})}function jo(i){return new Ii({parentId:co(i.getParentID()),leftSiblingId:co(i.getLeftSiblingID())})}function co(i){return new fi({createdAt:ke(i.getCreatedAt()),offset:i.getOffset()})}function Su(i){const t=new ba;if(i instanceof _i){const e=i,n=new ts;n.parentCreatedAt=ke(e.getParentCreatedAt()),n.key=e.getKey(),n.value=Ms(e.getValue()),n.executedAt=ke(e.getExecutedAt()),t.body.case="set",t.body.value=n}else if(i instanceof xo){const e=i,n=new ns;n.parentCreatedAt=ke(e.getParentCreatedAt()),n.prevCreatedAt=ke(e.getPrevCreatedAt()),n.value=Ms(e.getValue()),n.executedAt=ke(e.getExecutedAt()),t.body.case="add",t.body.value=n}else if(i instanceof ci){const e=i,n=new rs;n.parentCreatedAt=ke(e.getParentCreatedAt()),n.prevCreatedAt=ke(e.getPrevCreatedAt()),n.createdAt=ke(e.getCreatedAt()),n.executedAt=ke(e.getExecutedAt()),t.body.case="move",t.body.value=n}else if(i instanceof mi){const e=i,n=new is;n.parentCreatedAt=ke(e.getParentCreatedAt()),n.createdAt=ke(e.getCreatedAt()),n.executedAt=ke(e.getExecutedAt()),t.body.case="remove",t.body.value=n}else if(i instanceof ko){const e=i,n=new os;n.parentCreatedAt=ke(e.getParentCreatedAt()),n.from=Fo(e.getFromPos()),n.to=Fo(e.getToPos());const r=n.createdAtMapByActor;for(const[s,u]of e.getMaxCreatedAtMapByActor())r[s]=ke(u);n.content=e.getContent();const o=n.attributes;for(const[s,u]of e.getAttributes())o[s]=u;n.executedAt=ke(e.getExecutedAt()),t.body.case="edit",t.body.value=n}else if(i instanceof Oo){const e=i,n=new ss;n.parentCreatedAt=ke(e.getParentCreatedAt()),n.from=Fo(e.getFromPos()),n.to=Fo(e.getToPos());const r=n.createdAtMapByActor;for(const[s,u]of e.getMaxCreatedAtMapByActor())r[s]=ke(u);const o=n.attributes;for(const[s,u]of e.getAttributes())o[s]=u;n.executedAt=ke(e.getExecutedAt()),t.body.case="style",t.body.value=n}else if(i instanceof Qi){const e=i,n=new as;n.parentCreatedAt=ke(e.getParentCreatedAt()),n.value=Ms(e.getValue()),n.executedAt=ke(e.getExecutedAt()),t.body.case="increase",t.body.value=n}else if(i instanceof Io){const e=i,n=new ls,r=n.createdAtMapByActor;for(const[o,s]of e.getMaxCreatedAtMapByActor())r[o]=ke(s);n.parentCreatedAt=ke(e.getParentCreatedAt()),n.from=jo(e.getFromPos()),n.to=jo(e.getToPos()),n.contents=Wf(e.getContents()),n.splitLevel=e.getSplitLevel(),n.executedAt=ke(e.getExecutedAt()),t.body.case="treeEdit",t.body.value=n}else if(i instanceof Yr){const e=i,n=new us;n.parentCreatedAt=ke(e.getParentCreatedAt()),n.from=jo(e.getFromPos()),n.to=jo(e.getToPos());const r=n.createdAtMapByActor;for(const[s,u]of e.getMaxCreatedAtMapByActor())r[s]=ke(u);const o=e.getAttributesToRemove();if(o.length>0)n.attributesToRemove=o;else{const s=n.attributes;for(const[u,c]of e.getAttributes())s[u]=c}n.executedAt=ke(e.getExecutedAt()),t.body.case="treeStyle",t.body.value=n}else throw new ne(te.ErrUnimplemented,"unimplemented operation");return t}function Jf(i){const t=[];for(const e of i)t.push(Su(e));return t}function $f(i){const t=new ou({id:wu(i.getID()),message:i.getMessage()});return i.hasOperations()&&(t.operations=Jf(i.getOperations())),i.hasPresenceChange()&&(t.presenceChange=Ff(i.getPresenceChange())),t}function zf(i){const t=[];for(const e of i)t.push($f(e));return t}function Vf(i){const t=[];for(const e of i)t.push(new su({key:e.getStrKey(),element:Oa(e.getValue())}));return t}function Kf(i){const t=[];for(const e of i)t.push(new ms({element:Oa(e.getValue())}));return t}function Hf(i){const t=[];for(const e of i){const n=new ys;n.id=Uf(e.getID()),n.value=e.getValue().getContent(),n.removedAt=ke(e.getRemovedAt());const r=n.attributes,o=e.getValue().getAttrs();for(const s of o){const u=new Wi;u.value=s.getValue(),u.updatedAt=ke(s.getUpdatedAt()),r[s.getKey()]=u}t.push(n)}return t}function Wf(i){const t=[];if(!i||!i.length)return t;for(const e of i)t.push(new vs({content:ka(e)}));return t}function Gf(i){const t={};for(const e of i)t[e.getKey()]=new Wi({value:e.getValue(),updatedAt:ke(e.getUpdatedAt()),isRemoved:e.isRemoved()});return t}function ka(i){if(!i)return[];const t=[];return ks(i,(e,n)=>{const r=new po({id:co(e.id),type:e.type,removedAt:ke(e.removedAt),depth:n});e.isText&&(r.value=e.value),e.insPrevID&&(r.insPrevId=co(e.insPrevID)),e.insNextID&&(r.insNextId=co(e.insNextID)),e.attrs&&(r.attributes=Gf(e.attrs)),t.push(r)}),t}function Yf(i){const t=new kt;return t.body.case="jsonObject",t.body.value=new cs({nodes:Vf(i.getRHT()),createdAt:ke(i.getCreatedAt()),movedAt:ke(i.getMovedAt()),removedAt:ke(i.getRemovedAt())}),t}function Eu(i){const t=new kt;return t.body.case="jsonArray",t.body.value=new fs({nodes:Kf(i.getElements()),createdAt:ke(i.getCreatedAt()),movedAt:ke(i.getMovedAt()),removedAt:ke(i.getRemovedAt())}),t}function Zf(i){const t=new kt;return t.body.case="primitive",t.body.value=new hs({type:Au(i.getType()),value:i.toBytes(),createdAt:ke(i.getCreatedAt()),movedAt:ke(i.getMovedAt()),removedAt:ke(i.getRemovedAt())}),t}function Xf(i){const t=new kt;return t.body.case="text",t.body.value=new ds({nodes:Hf(i.getRGATreeSplit()),createdAt:ke(i.getCreatedAt()),movedAt:ke(i.getMovedAt()),removedAt:ke(i.getRemovedAt())}),t}function Qf(i){const t=new kt;return t.body.case="counter",t.body.value=new gs({type:Tu(i.getType()),value:i.toBytes(),createdAt:ke(i.getCreatedAt()),movedAt:ke(i.getMovedAt()),removedAt:ke(i.getRemovedAt())}),t}function xu(i){const t=new kt;return t.body.case="tree",t.body.value=new ps({nodes:ka(i.getRoot()),createdAt:ke(i.getCreatedAt()),movedAt:ke(i.getMovedAt()),removedAt:ke(i.getRemovedAt())}),t}function Oa(i){if(i instanceof xt)return Yf(i);if(i instanceof Rt)return Eu(i);if(i instanceof et)return Zf(i);if(i instanceof Gt)return Xf(i);if(i instanceof Dt)return Qf(i);if(i instanceof Yt)return xu(i);throw new ne(te.ErrUnimplemented,"unimplemented element")}function eh(i){return new Qr({documentKey:i.getDocumentKey(),checkpoint:jf(i.getCheckpoint()),isRemoved:i.getIsRemoved(),changes:zf(i.getChanges()),snapshot:i.getSnapshot(),versionVector:xa(i.getVersionVector()),minSyncedTicket:ke(i.getMinSyncedTicket())})}function Sl(i){const t=i.findDetails(mf);for(const e of t)if(e.metadata.code)return e.metadata.code;return""}function ku(i){return zr.of(i.clientSeq,BigInt(i.lamport),La(i.actorId),Ia(i.versionVector),BigInt(i.serverSeq))}function Ia(i){if(!i)return;const t=new zi;return Object.entries(i.vector).forEach(([e,n])=>{t.set(e,BigInt(n.toString()))}),t}function Ie(i){if(i)return Lt.of(BigInt(i.lamport),i.delimiter,La(i.actorId))}function Na(i){const t={};return Object.entries(i.data).forEach(([e,n])=>{t[e]=JSON.parse(n)}),t}function th(i){const t=i.type;if(t===Ni.PUT){const e=Na(i.presence);return{type:pi.Put,presence:e}}if(t===Ni.CLEAR)return{type:pi.Clear};throw new ne(te.ErrInvalidType,`unsupported type: ${t}`)}function nh(i){const t=new Map;return Object.entries(i).forEach(([e,n])=>{t.set(e,Na(n))}),t}function Ou(i){switch(i){case Re.NULL:return ft.Null;case Re.BOOLEAN:return ft.Boolean;case Re.INTEGER:return ft.Integer;case Re.LONG:return ft.Long;case Re.DOUBLE:return ft.Double;case Re.STRING:return ft.String;case Re.BYTES:return ft.Bytes;case Re.DATE:return ft.Date}throw new ne(te.ErrUnimplemented,`unimplemented value type: ${i}`)}function As(i){switch(i){case Re.INTEGER_CNT:return Un.IntegerCnt;case Re.LONG_CNT:return Un.LongCnt}throw new ne(te.ErrUnimplemented,`unimplemented value type: ${i}`)}function qs(i){switch(i.type){case Re.JSON_OBJECT:return i.value?Ru(i.value):xt.create(Ie(i.createdAt));case Re.JSON_ARRAY:return i.value?mh(i.value):Rt.create(Ie(i.createdAt));case Re.TEXT:return Gt.create(Xi.create(),Ie(i.createdAt));case Re.TREE:return vh(i.value);case Re.NULL:case Re.BOOLEAN:case Re.INTEGER:case Re.LONG:case Re.DOUBLE:case Re.STRING:case Re.BYTES:case Re.DATE:return et.of(et.valueFromBytes(Ou(i.type),i.value),Ie(i.createdAt));case Re.INTEGER_CNT:case Re.LONG_CNT:return Dt.create(As(i.type),Dt.valueFromBytes(As(i.type),i.value),Ie(i.createdAt))}}function Uo(i){return cn.of(jn.of(Ie(i.createdAt),i.offset),i.relativeOffset)}function Iu(i){return jn.of(Ie(i.createdAt),i.offset)}function rh(i){const t=wo.create(i.value);Object.entries(i.attributes).forEach(([n,r])=>{t.setAttr(n,r.value,Ie(r.updatedAt))});const e=di.create(Iu(i.id),t);return e.remove(Ie(i.removedAt)),e}function Mi(i){return ln.of(fo(i.parentId),fo(i.leftSiblingId))}function fo(i){return pt.of(Ie(i.createdAt),i.offset)}function ih(i){if(!i.length)return;const t=[];return i.forEach(e=>{const n=_a(e.content);t.push(n)}),t}function _a(i){if(i.length===0)return;const t=[];for(const r of i)t.push(sh(r));const e=t[t.length-1],n=new Map;n.set(i[t.length-1].depth,t[t.length-1]);for(let r=t.length-2;r>=0;r--)n.get(i[r].depth-1).prepend(t[r]),n.set(i[r].depth,t[r]);return e.updateDescendantsSize(),Yt.create(e,un).getRoot()}function oh(i){const t=Xr.create();for(const[e,n]of Object.entries(i))t.setInternal(e,n.value,Ie(n.updatedAt),n.isRemoved);return t}function sh(i){const t=fo(i.id),e=Ct.create(t,i.type),n=Object.entries(i.attributes);return e.isText?e.value=i.value:n.length&&(e.attrs=oh(i.attributes)),i.insPrevId&&(e.insPrevID=fo(i.insPrevId)),i.insNextId&&(e.insNextID=fo(i.insNextId)),e.removedAt=Ie(i.removedAt),e}function Nu(i){if(i.body.case==="set"){const t=i.body.value;return _i.create(t.key,qs(t.value),Ie(t.parentCreatedAt),Ie(t.executedAt))}else if(i.body.case==="add"){const t=i.body.value;return xo.create(Ie(t.parentCreatedAt),Ie(t.prevCreatedAt),qs(t.value),Ie(t.executedAt))}else if(i.body.case==="move"){const t=i.body.value;return ci.create(Ie(t.parentCreatedAt),Ie(t.prevCreatedAt),Ie(t.createdAt),Ie(t.executedAt))}else if(i.body.case==="remove"){const t=i.body.value;return mi.create(Ie(t.parentCreatedAt),Ie(t.createdAt),Ie(t.executedAt))}else if(i.body.case==="edit"){const t=i.body.value,e=new Map;Object.entries(t.createdAtMapByActor).forEach(([r,o])=>{e.set(r,Ie(o))});const n=new Map;return Object.entries(t.attributes).forEach(([r,o])=>{n.set(r,o)}),ko.create(Ie(t.parentCreatedAt),Uo(t.from),Uo(t.to),e,t.content,n,Ie(t.executedAt))}else if(i.body.case==="style"){const t=i.body.value,e=new Map;Object.entries(t.createdAtMapByActor).forEach(([r,o])=>{e.set(r,Ie(o))});const n=new Map;return Object.entries(t.attributes).forEach(([r,o])=>{n.set(r,o)}),Oo.create(Ie(t.parentCreatedAt),Uo(t.from),Uo(t.to),e,n,Ie(t.executedAt))}else{if(i.body.case==="select")return;if(i.body.case==="increase"){const t=i.body.value;return Qi.create(Ie(t.parentCreatedAt),qs(t.value),Ie(t.executedAt))}else if(i.body.case==="treeEdit"){const t=i.body.value,e=new Map;return Object.entries(t.createdAtMapByActor).forEach(([n,r])=>{e.set(n,Ie(r))}),Io.create(Ie(t.parentCreatedAt),Mi(t.from),Mi(t.to),ih(t.contents),t.splitLevel,e,Ie(t.executedAt))}else if(i.body.case==="treeStyle"){const t=i.body.value,e=new Map,n=t.attributesToRemove,r=new Map;return t!=null&&t.createdAtMapByActor&&Object.entries(t.createdAtMapByActor).forEach(([o,s])=>{r.set(o,Ie(s))}),(n==null?void 0:n.length)>0?Yr.createTreeRemoveStyleOperation(Ie(t.parentCreatedAt),Mi(t.from),Mi(t.to),r,n,Ie(t.executedAt)):(Object.entries(t.attributes).forEach(([o,s])=>{e.set(o,s)}),Yr.create(Ie(t.parentCreatedAt),Mi(t.from),Mi(t.to),r,e,Ie(t.executedAt)))}else throw new ne(te.ErrUnimplemented,"unimplemented operation")}}function ah(i){const t=[];for(const e of i){const n=Nu(e);n&&t.push(n)}return t}function _u(i){const t=[];for(const e of i)t.push(Zi.create({id:ku(e.id),operations:ah(e.operations),presenceChange:e.presenceChange?th(e.presenceChange):void 0,message:e.message}));return t}function lh(i){return Vi.of(BigInt(i.serverSeq),i.clientSeq)}function uh(i){return Os.create(i.documentKey,lh(i.checkpoint),i.isRemoved,_u(i.changes),Ia(i.versionVector),i.snapshot,Ie(i.minSyncedTicket))}function Pu(i){const t=new yo;for(const n of i.nodes){const r=Pa(n.element);t.set(n.key,r,r.getPositionedAt())}const e=new xt(Ie(i.createdAt),t);return e.setMovedAt(Ie(i.movedAt)),e.setRemovedAt(Ie(i.removedAt)),e}function Cu(i){const t=new bo;for(const n of i.nodes)t.insert(Pa(n.element));const e=new Rt(Ie(i.createdAt),t);return e.setMovedAt(Ie(i.movedAt)),e.setRemovedAt(Ie(i.removedAt)),e}function ch(i){const t=et.of(et.valueFromBytes(Ou(i.type),i.value),Ie(i.createdAt));return t.setMovedAt(Ie(i.movedAt)),t.setRemovedAt(Ie(i.removedAt)),t}function fh(i){const t=new Xi;let e=t.getHead();for(const r of i.nodes){const o=t.insertAfter(e,rh(r));r.insPrevId&&o.setInsPrev(t.findNode(Iu(r.insPrevId))),e=o}const n=new Gt(t,Ie(i.createdAt));return n.setMovedAt(Ie(i.movedAt)),n.setRemovedAt(Ie(i.removedAt)),n}function hh(i){const t=Dt.create(As(i.type),Dt.valueFromBytes(As(i.type),i.value),Ie(i.createdAt));return t.setMovedAt(Ie(i.movedAt)),t.setRemovedAt(Ie(i.removedAt)),t}function Lu(i){const t=_a(i.nodes);return Yt.create(t,Ie(i.createdAt))}function Pa(i){if(i.body.case==="jsonObject")return Pu(i.body.value);if(i.body.case==="jsonArray")return Cu(i.body.value);if(i.body.case==="primitive")return ch(i.body.value);if(i.body.case==="text")return fh(i.body.value);if(i.body.case==="counter")return hh(i.body.value);if(i.body.case==="tree")return Lu(i.body.value);throw new ne(te.ErrUnimplemented,"unimplemented element")}function dh(i){if(!i)return{root:xt.create(un),presences:new Map};const t=zs.fromBinary(i);return{root:Pa(t.root),presences:nh(t.presences)}}function gh(i){const t=xa(i);return Ca(t.toBinary())}function ph(i){const t=Ra(i),e=xs.fromBinary(t);return Ia(e)}function Ru(i){if(!i)throw new ne(te.ErrInvalidArgument,"bytes is empty");const t=kt.fromBinary(i);return Pu(t.body.value)}function Du(i){return Oa(i).toBinary()}function mh(i){if(!i)throw new ne(te.ErrInvalidArgument,"bytes is empty");const t=kt.fromBinary(i);return Cu(t.body.value)}function yh(i){return Eu(i).toBinary()}function vh(i){if(!i)throw new ne(te.ErrInvalidArgument,"bytes is empty");const t=kt.fromBinary(i);return Lu(t.body.value)}function bh(i){return xu(i).toBinary()}function Ca(i){return i?Array.from(i).map(t=>t.toString(16).padStart(2,"0")).join(""):""}function La(i){return Ca(i)}function Ra(i){return new Uint8Array(i.match(/.{1,2}/g).map(t=>parseInt(t,16)))}function Da(i){return Ra(i)}function wh(i){const t=Es.fromBinary(i);return ku(t)}function Ah(i){const t=ba.fromBinary(i);return Nu(t)}const at={fromPresence:Na,toChangePack:eh,fromChangePack:uh,fromChanges:_u,toTreeNodes:ka,fromTreeNodes:_a,objectToBytes:Du,bytesToObject:Ru,bytesToSnapshot:dh,bytesToHex:Ca,hexToBytes:Ra,toHexString:La,toUint8Array:Da,toOperation:Su,toChangeID:wu,PbChangeID:Es,bytesToChangeID:wh,bytesToOperation:Ah,versionVectorToHex:gh,hexToVersionVector:ph};var wt=(i=>(i[i.Trivial=0]="Trivial",i[i.Debug=1]="Debug",i[i.Info=2]="Info",i[i.Warn=3]="Warn",i[i.Error=4]="Error",i[i.Fatal=5]="Fatal",i))(wt||{});let bi=3;function Bu(i){bi=i}const Ne={trivial:(...i)=>{bi>0||typeof console<"u"&&console.log("YORKIE T:",...i)},debug:(...i)=>{bi>1||typeof console<"u"&&console.log("YORKIE D:",...i)},info:(...i)=>{bi>2||typeof console<"u"&&console.log("YORKIE I:",...i)},warn:(...i)=>{bi>3||typeof console<"u"&&(typeof console.warn<"u"?console.warn("YORKIE W:",...i):console.log("YORKIE W:",...i))},error:(...i)=>{bi>4||typeof console<"u"&&(typeof console.error<"u"?console.error("YORKIE E:",...i):console.log("YORKIE E:",...i))},fatal:(...i)=>{typeof console<"u"&&(typeof console.error<"u"?console.error("YORKIE F:",...i):console.log("YORKIE F:",...i))},isEnabled:i=>bi<=i};function Mu(){return"xxxxxxxx-xxxx-4xxxy-xxxx-xxxxxxxxxxx".replace(/[xy]/g,i=>{const t=Math.random()*16|0;return(i==="x"?t:t&3|8).toString(16)})}class Th{constructor(t,e,n,r,o){T(this,"reconnectStreamDelay");T(this,"doc");T(this,"docID");T(this,"syncMode");T(this,"remoteChangeEventReceived");T(this,"watchStream");T(this,"watchLoopTimerID");T(this,"watchAbortController");T(this,"unsubscribeBroadcastEvent");this.reconnectStreamDelay=t,this.doc=e,this.docID=n,this.syncMode=r,this.remoteChangeEventReceived=!1,this.unsubscribeBroadcastEvent=o}changeSyncMode(t){this.syncMode=t}needRealtimeSync(){return this.syncMode===Zo.RealtimeSyncOff?!1:this.syncMode===Zo.RealtimePushOnly?this.doc.hasLocalChanges():this.syncMode!==Zo.Manual&&(this.doc.hasLocalChanges()||this.remoteChangeEventReceived)}async runWatchLoop(t){const e=async()=>{if(this.watchStream)return Promise.resolve();this.watchLoopTimerID&&(clearTimeout(this.watchLoopTimerID),this.watchLoopTimerID=void 0);try{[this.watchStream,this.watchAbortController]=await t(()=>{this.watchStream=void 0,this.watchAbortController=void 0,this.watchLoopTimerID=setTimeout(e,this.reconnectStreamDelay)})}catch{}};await e()}cancelWatchStream(){this.watchStream&&this.watchAbortController&&(this.watchAbortController.abort(),this.watchStream=void 0,this.watchAbortController=void 0),clearTimeout(this.watchLoopTimerID),this.watchLoopTimerID=void 0}}const Fs=()=>{};class Sh{constructor(t){T(this,"finalized",!1);T(this,"observers",[]);T(this,"finalError");try{t(this)}catch(e){this.error(e)}}next(t){this.forEachObserver(e=>{e.next(t)})}error(t){this.forEachObserver(e=>{e.error(t)}),this.close(t)}complete(){this.forEachObserver(t=>{t.complete()}),this.close()}subscribe(t,e,n){let r;if(!t)throw new ne(te.ErrInvalidArgument,"missing observer");if(this.finalized)throw new ne(te.ErrRefused,"observable is finalized due to previous error");typeof t=="object"?r=t:r={next:t,error:e,complete:n},r.next===void 0&&(r.next=Fs),r.error===void 0&&(r.error=Fs),r.complete===void 0&&(r.complete=Fs);const o=Mu(),s=this.unsubscribeOne.bind(this,o);if(this.observers.push({subscriptionID:o,observer:r}),this.finalized)try{this.finalError?r.error(this.finalError):r.complete()}catch(u){Ne.warn(u)}return s}unsubscribeOne(t){var e;this.observers=(e=this.observers)==null?void 0:e.filter(n=>n.subscriptionID!==t)}forEachObserver(t){if(!this.finalized)for(let e=0;et}}class Ji{constructor(t,e,n,r){T(this,"id");T(this,"delimiter");T(this,"message");T(this,"root");T(this,"operations");T(this,"presenceChange");T(this,"previousPresence");T(this,"reversePresenceKeys");this.id=t,this.delimiter=uu,this.root=e,this.operations=[],this.previousPresence=sn(n),this.presenceChange=void 0,this.reversePresenceKeys=new Set,this.message=r}static create(t,e,n,r){return new Ji(t,e,n,r)}push(t){this.operations.push(t)}registerElement(t,e){this.root.registerElement(t,e)}registerRemovedElement(t){this.root.registerRemovedElement(t)}registerGCPair(t){this.root.registerGCPair(t)}getChange(){return Zi.create({id:this.id,operations:this.operations,presenceChange:this.presenceChange,message:this.message})}hasChange(){return this.operations.length>0||this.presenceChange!==void 0}setPresenceChange(t){this.presenceChange=t}setReversePresence(t,e){for(const n of Object.keys(t))e!=null&&e.addToHistory?this.reversePresenceKeys.add(n):this.reversePresenceKeys.delete(n)}getReversePresence(){if(this.reversePresenceKeys.size===0)return;const t={};for(const e of this.reversePresenceKeys)t[e]=this.previousPresence[e];return t}issueTimeTicket(){return this.delimiter+=1,this.id.createTimeTicket(this.delimiter)}getLastTimeTicket(){return this.id.createTimeTicket(this.delimiter)}}class Ao{constructor(t){T(this,"rootObject");T(this,"elementPairMapByCreatedAt");T(this,"gcElementSetByCreatedAt");T(this,"gcPairMap");this.rootObject=t,this.elementPairMapByCreatedAt=new Map,this.gcElementSetByCreatedAt=new Set,this.gcPairMap=new Map,this.registerElement(t,void 0),t.getDescendants(e=>{if(e.getRemovedAt()&&this.registerRemovedElement(e),e instanceof Gt||e instanceof Yt)for(const n of e.getGCPairs())this.registerGCPair(n);return!1})}static create(){return new Ao(xt.create(un))}findByCreatedAt(t){const e=this.elementPairMapByCreatedAt.get(t.toIDString());if(e)return e.element}findElementPairByCreatedAt(t){return this.elementPairMapByCreatedAt.get(t.toIDString())}createSubPaths(t){let e=this.elementPairMapByCreatedAt.get(t.toIDString());if(!e)return[];const n=[];for(;e.parent;){const r=e.element.getCreatedAt(),o=e.parent.subPathOf(r);if(o===void 0)throw new ne(te.ErrInvalidArgument,`cant find the given element: ${r.toIDString()}`);n.unshift(o),e=this.elementPairMapByCreatedAt.get(e.parent.getCreatedAt().toIDString())}return n.unshift("$"),n}createPath(t){return this.createSubPaths(t).join(".")}registerElement(t,e){this.elementPairMapByCreatedAt.set(t.getCreatedAt().toIDString(),{parent:e,element:t}),t instanceof hi&&t.getDescendants((n,r)=>(this.registerElement(n,r),!1))}deregisterElement(t){let e=0;const n=r=>{const o=r.getCreatedAt().toIDString();this.elementPairMapByCreatedAt.delete(o),this.gcElementSetByCreatedAt.delete(o),e++};return n(t),t instanceof hi&&t.getDescendants(r=>(n(r),!1)),e}registerRemovedElement(t){this.gcElementSetByCreatedAt.add(t.getCreatedAt().toIDString())}registerGCPair(t){if(this.gcPairMap.get(t.child.toIDString())){this.gcPairMap.delete(t.child.toIDString());return}this.gcPairMap.set(t.child.toIDString(),t)}getElementMapSize(){return this.elementPairMapByCreatedAt.size}getGarbageElementSetSize(){const t=new Set;for(const e of this.gcElementSetByCreatedAt){t.add(e);const n=this.elementPairMapByCreatedAt.get(e);n.element instanceof hi&&n.element.getDescendants(r=>(t.add(r.getCreatedAt().toIDString()),!1))}return t.size}getObject(){return this.rootObject}getGarbageLen(){return this.getGarbageElementSetSize()+this.gcPairMap.size}deepcopy(){return new Ao(this.rootObject.deepcopy())}garbageCollect(t){let e=0;for(const n of this.gcElementSetByCreatedAt){const r=this.elementPairMapByCreatedAt.get(n),o=r.element.getRemovedAt();o&&(t!=null&&t.afterOrEqual(o))&&(r.parent.purge(r.element),e+=this.deregisterElement(r.element))}for(const[,n]of this.gcPairMap){const r=n.child.getRemovedAt();r&&(t!=null&&t.afterOrEqual(r))&&(n.parent.purge(n.child),this.gcPairMap.delete(n.child.toIDString()),e+=1)}return e}toJSON(){return this.rootObject.toJSON()}toSortedJSON(){return this.rootObject.toSortedJSON()}getStats(){return{elements:this.getElementMapSize(),gcPairs:this.gcPairMap.size,gcElements:this.getGarbageElementSetSize()}}}function qu(i,t){const e=new To(i);return new Proxy(t,e.getHandlers())}class To{constructor(t){T(this,"context");T(this,"handlers");this.context=t,this.handlers={set:(e,n,r)=>(Ne.isEnabled(wt.Trivial)&&Ne.trivial(`obj[${n}]=${JSON.stringify(r)}`),To.setInternal(t,e,n,r),!0),get:(e,n)=>(Ne.isEnabled(wt.Trivial)&&Ne.trivial(`obj[${n}]`),n==="getID"?()=>e.getCreatedAt():n==="toJSON"||n==="toString"?()=>e.toJSON():n==="toJS"?()=>e.toJS():n==="toJSForTest"?()=>e.toJSForTest():wi(t,e.get(n))),ownKeys:e=>e.getKeys(),getOwnPropertyDescriptor:()=>({enumerable:!0,configurable:!0}),deleteProperty:(e,n)=>(Ne.isEnabled(wt.Trivial)&&Ne.trivial(`obj[${n}]`),To.deleteInternal(t,e,n),!0)}}static setInternal(t,e,n,r){if(n.includes("."))throw new ne(te.ErrInvalidObjectKey,"key must not contain the '.'.");const o=t.issueTimeTicket(),s=Ts(t,r,o),u=e.set(n,s,o);t.registerElement(s,e),u&&t.registerRemovedElement(u),t.push(_i.create(n,s.deepcopy(),e.getCreatedAt(),o))}static buildObjectMembers(t,e){const n={};for(const[r,o]of Object.entries(e)){if(r.includes("."))throw new ne(te.ErrInvalidObjectKey,"key must not contain the '.'.");const s=t.issueTimeTicket(),u=Ts(t,o,s);n[r]=u}return n}static deleteInternal(t,e,n){const r=t.issueTimeTicket(),o=e.deleteByKey(n,r);o&&(t.push(mi.create(e.getCreatedAt(),o.getCreatedAt(),r)),t.registerRemovedElement(o))}getHandlers(){return this.handlers}}function xh(i,t){const e=new nt(i,t);return new Proxy(t,e.getHandlers())}function kh(i){return typeof i=="string"||i instanceof String?!isNaN(i):!1}function Oh(i){return["concat","entries","every","filter","find","findIndex","forEach","join","keys","map","reduce","reduceRight","slice","some","toLocaleString","toString","values"].includes(i)}class nt{constructor(t,e){T(this,"context");T(this,"handlers");T(this,"array");this.context=t,this.array=e,this.handlers={get:(n,r,o)=>r==="getID"?()=>n.getCreatedAt():r==="getElementByID"?s=>{const u=n.getByID(s);if(!(!u||u.isRemoved()))return oi(t,u)}:r==="getElementByIndex"?s=>{const u=n.get(s);return oi(t,u)}:r==="getLast"?()=>oi(t,n.getLast()):r==="deleteByID"?s=>{const u=nt.deleteInternalByID(t,n,s);return oi(t,u)}:r==="insertAfter"?(s,u)=>{const c=nt.insertAfterInternal(t,n,s,u);return oi(t,c)}:r==="insertBefore"?(s,u)=>{const c=nt.insertBeforeInternal(t,n,s,u);return oi(t,c)}:r==="moveBefore"?(s,u)=>{nt.moveBeforeInternal(t,n,s,u)}:r==="moveAfter"?(s,u)=>{nt.moveAfterInternal(t,n,s,u)}:r==="moveFront"?s=>{nt.moveFrontInternal(t,n,s)}:r==="moveLast"?s=>{nt.moveLastInternal(t,n,s)}:kh(r)?wi(t,n.get(Number(r))):r==="push"?s=>nt.pushInternal(t,n,s):r==="splice"?(s,u,...c)=>nt.splice(t,n,s,u,...c):r==="length"?n.length:typeof r=="symbol"&&r===Symbol.iterator?nt.iteratorInternal.bind(this,t,n):r==="includes"?(s,u)=>nt.includes(t,n,s,u):r==="indexOf"?(s,u)=>nt.indexOf(t,n,s,u):r==="lastIndexOf"?(s,u)=>nt.lastIndexOf(t,n,s,u):r==="toJSForTest"?()=>n.toJSForTest():r==="toTestString"?()=>nt.toTestString(n):typeof r=="string"&&Oh(r)?(...s)=>{const u=Array.from(n).map(c=>wi(t,c));return Array.prototype[r].apply(u,s)}:Reflect.get(n,r,o),deleteProperty:(n,r)=>(Ne.isEnabled(wt.Trivial)&&Ne.trivial(`array[${r}]`),nt.deleteInternalByIndex(t,n,Number.parseInt(r)),!0)}}static*iteratorInternal(t,e){for(const n of e)yield oi(t,n)}static buildArrayElements(t,e){const n=[];for(const r of e){const o=t.issueTimeTicket(),s=Ts(t,r,o);n.push(s)}return n}static pushInternal(t,e,n){return nt.insertAfterInternal(t,e,e.getLastCreatedAt(),n),e.length}static moveBeforeInternal(t,e,n,r){const o=t.issueTimeTicket(),s=e.getPrevCreatedAt(n);e.moveAfter(s,r,o),t.push(ci.create(e.getCreatedAt(),s,r,o))}static moveAfterInternal(t,e,n,r){const o=t.issueTimeTicket();e.moveAfter(n,r,o),t.push(ci.create(e.getCreatedAt(),n,r,o))}static moveFrontInternal(t,e,n){const r=t.issueTimeTicket(),o=e.getHead();e.moveAfter(o.getCreatedAt(),n,r),t.push(ci.create(e.getCreatedAt(),o.getCreatedAt(),n,r))}static moveLastInternal(t,e,n){const r=t.issueTimeTicket(),o=e.getLastCreatedAt();e.moveAfter(o,n,r),t.push(ci.create(e.getCreatedAt(),o,n,r))}static insertAfterInternal(t,e,n,r){const o=t.issueTimeTicket(),s=Ts(t,r,o);return e.insertAfter(n,s),t.registerElement(s,e),t.push(xo.create(e.getCreatedAt(),n,s.deepcopy(),o)),s}static insertBeforeInternal(t,e,n,r){return nt.insertAfterInternal(t,e,e.getPrevCreatedAt(n),r)}static deleteInternalByIndex(t,e,n){const r=t.issueTimeTicket(),o=e.deleteByIndex(n,r);if(o)return t.push(mi.create(e.getCreatedAt(),o.getCreatedAt(),r)),t.registerRemovedElement(o),o}static deleteInternalByID(t,e,n){const r=t.issueTimeTicket(),o=e.delete(n,r);return t.push(mi.create(e.getCreatedAt(),o.getCreatedAt(),r)),t.registerRemovedElement(o),o}static splice(t,e,n,r,...o){const s=e.length,u=n>=0?Math.min(n,s):Math.max(s+n,0),c=r===void 0?s:r<0?u:Math.min(u+r,s),m=[];for(let y=u;y=o)return!1;if(et.isSupport(n))return Array.from(e).map(m=>wi(t,m)).includes(n,s);for(let c=s;c=o)return-1;if(et.isSupport(n))return Array.from(e).map(m=>wi(t,m)).indexOf(n,s);for(let c=s;c=o?o-1:r<0?r+o:r;if(s<0)return-1;if(et.isSupport(n))return Array.from(e).map(m=>wi(t,m)).lastIndexOf(n,s);for(let c=s;c>0;c--)if(((u=e.get(c))==null?void 0:u.getID())===n.getID())return c;return-1}static toTestString(t){return t.toTestString()}getHandlers(){return this.handlers}}let Is=class{constructor(t,e){T(this,"context");T(this,"text");this.context=t,this.text=e}initialize(t,e){this.context=t,this.text=e}getID(){return this.text.getID()}edit(t,e,n,r){if(!this.context||!this.text)throw new ne(te.ErrNotInitialized,"Text is not initialized yet");if(t>e)throw new ne(te.ErrInvalidArgument,"from should be less than or equal to to");const o=this.text.indexRangeToPosRange(t,e);Ne.isEnabled(wt.Debug)&&Ne.debug(`EDIT: f:${t}->${o[0].toTestString()}, t:${e}->${o[1].toTestString()} c:${n}`);const s=r?Gi(r):void 0,u=this.context.issueTimeTicket(),[c,,m,y]=this.text.edit(o,n,u,s);for(const d of m)this.context.registerGCPair(d);return this.context.push(new ko(this.text.getCreatedAt(),o[0],o[1],c,n,s?new Map(Object.entries(s)):new Map,u)),this.text.findIndexesFromRange(y)}delete(t,e){return this.edit(t,e,"")}empty(){return this.edit(0,this.length,"")}setStyle(t,e,n){if(!this.context||!this.text)throw new ne(te.ErrNotInitialized,"Text is not initialized yet");if(t>e)throw new ne(te.ErrInvalidArgument,"from should be less than or equal to to");const r=this.text.indexRangeToPosRange(t,e);Ne.isEnabled(wt.Debug)&&Ne.debug(`STYL: f:${t}->${r[0].toTestString()}, t:${e}->${r[1].toTestString()} a:${JSON.stringify(n)}`);const o=Gi(n),s=this.context.issueTimeTicket(),[u,c]=this.text.setStyle(r,o,s);for(const m of c)this.context.registerGCPair(m);return this.context.push(new Oo(this.text.getCreatedAt(),r[0],r[1],u,new Map(Object.entries(o)),s)),!0}indexRangeToPosRange(t){if(!this.context||!this.text)throw new ne(te.ErrNotInitialized,"Text is not initialized yet");const e=this.text.indexRangeToPosRange(t[0],t[1]);return[e[0].toStruct(),e[1].toStruct()]}posRangeToIndexRange(t){if(!this.context||!this.text)throw new ne(te.ErrNotInitialized,"Text is not initialized yet");const e=this.text.findIndexesFromRange([cn.fromStruct(t[0]),cn.fromStruct(t[1])]);return[e[0],e[1]]}toTestString(){if(!this.context||!this.text)throw new ne(te.ErrNotInitialized,"Text is not initialized yet");return this.text.toTestString()}values(){if(!this.context||!this.text)throw new ne(te.ErrNotInitialized,"Text is not initialized yet");return this.text.values()}get length(){return this.text.length}getTreeByIndex(){return this.text.getTreeByIndex()}getTreeByID(){return this.text.getTreeByID()}toString(){if(!this.context||!this.text)throw new ne(te.ErrNotInitialized,"Text is not initialized yet");return this.text.toString()}toJSON(){if(!this.context||!this.text)throw new ne(te.ErrNotInitialized,"Text is not initialized yet");return this.text.toJSON()}toJSForTest(){if(!this.context||!this.text)throw new ne(te.ErrNotInitialized,"Text is not initialized yet");return this.text.toJSForTest()}createRangeForTest(t,e){if(!this.context||!this.text)throw new ne(te.ErrNotInitialized,"Text is not initialized yet");return this.text.indexRangeToPosRange(t,e)}};class Ns{constructor(t,e){T(this,"valueType");T(this,"value");T(this,"context");T(this,"counter");this.valueType=t,this.value=e}initialize(t,e){this.valueType=e.getValueType(),this.context=t,this.counter=e,this.value=e.getValue()}getID(){return this.counter.getID()}getValue(){return this.value}getValueType(){return this.valueType}increase(t){if(!this.context||!this.counter)throw new ne(te.ErrNotInitialized,"Counter is not initialized yet");const e=this.context.issueTimeTicket(),n=et.of(t,e);if(!n.isNumericType())throw new TypeError(`Unsupported type of value: ${typeof n.getValue()}`);return this.counter.increase(n),this.context.push(Qi.create(this.counter.getCreatedAt(),n,e)),this}toJSForTest(){if(!this.context||!this.counter)throw new ne(te.ErrNotInitialized,"Counter is not initialized yet");return this.counter.toJSForTest()}}function Ba(i,t,e){const{type:n}=i,r=e.issueTimeTicket();if(n===Gr){Fu(i);const{value:o}=i,s=Ct.create(pt.of(r,0),n,o);t.append(s)}else{const{children:o=[]}=i,{attributes:s}=i;let u;if(typeof s=="object"&&!lu(s)){const m=Gi(s);u=new Xr;for(const[y,d]of Object.entries(m))u.set(y,d,r)}const c=Ct.create(pt.of(r,0),n,void 0,u);t.append(c);for(const m of o)Ba(m,c,e)}}function Ih(i,t){const{type:e}=t,n=i.issueTimeTicket();let r;if(t.type===Gr){const{value:o}=t;r=Ct.create(pt.of(n,0),e,o)}else if(t){const{children:o=[]}=t,{attributes:s}=t;let u;if(typeof s=="object"&&!lu(s)){const c=Gi(s);u=new Xr;for(const[m,y]of Object.entries(c))u.set(m,y,n)}r=Ct.create(pt.of(i.issueTimeTicket(),0),e,void 0,u);for(const c of o)Ba(c,r,i)}return r}function Fu(i){if(!i.value.length)throw new ne(te.ErrInvalidArgument,"text node cannot have empty value");return!0}function El(i){if(!i.length)return!0;if(i[0].type===Gr)for(const e of i){const{type:n}=e;if(n!==Gr)throw new ne(te.ErrInvalidArgument,"element node and text node cannot be passed together");Fu(e)}else for(const e of i){const{type:n}=e;if(n===Gr)throw new ne(te.ErrInvalidArgument,"element node and text node cannot be passed together")}return!0}class _s{constructor(t){T(this,"initialRoot");T(this,"context");T(this,"tree");this.initialRoot=t}initialize(t,e){this.context=t,this.tree=e}getID(){return this.tree.getID()}buildRoot(t){if(!this.initialRoot)return Ct.create(pt.of(t.issueTimeTicket(),0),kf);const e=Ct.create(pt.of(t.issueTimeTicket(),0),this.initialRoot.type);for(const n of this.initialRoot.children)Ba(n,e,t);return e}getSize(){if(!this.context||!this.tree)throw new ne(te.ErrNotInitialized,"Tree is not initialized yet");return this.tree.getSize()}getNodeSize(){if(!this.context||!this.tree)throw new ne(te.ErrNotInitialized,"Tree is not initialized yet");return this.tree.getNodeSize()}getIndexTree(){if(!this.context||!this.tree)throw new ne(te.ErrNotInitialized,"Tree is not initialized yet");return this.tree.getIndexTree()}styleByPath(t,e){if(!this.context||!this.tree)throw new ne(te.ErrNotInitialized,"Tree is not initialized yet");if(!t.length)throw new ne(te.ErrInvalidArgument,"path should not be empty");const[n,r]=this.tree.pathToPosRange(t),o=this.context.issueTimeTicket(),s=e?Gi(e):void 0,[u]=this.tree.style([n,r],s,o);this.context.push(Yr.create(this.tree.getCreatedAt(),n,r,u,s?new Map(Object.entries(s)):new Map,o))}style(t,e,n){if(!this.context||!this.tree)throw new ne(te.ErrNotInitialized,"Tree is not initialized yet");if(t>e)throw new ne(te.ErrInvalidArgument,"from should be less than or equal to to");const r=this.tree.findPos(t),o=this.tree.findPos(e),s=this.context.issueTimeTicket(),u=n?Gi(n):void 0,[c,m]=this.tree.style([r,o],u,s);for(const y of m)this.context.registerGCPair(y);this.context.push(Yr.create(this.tree.getCreatedAt(),r,o,c,u?new Map(Object.entries(u)):new Map,s))}removeStyle(t,e,n){if(!this.context||!this.tree)throw new ne(te.ErrNotInitialized,"Tree is not initialized yet");if(t>e)throw new ne(te.ErrInvalidArgument,"from should be less than or equal to to");const r=this.tree.findPos(t),o=this.tree.findPos(e),s=this.context.issueTimeTicket(),[u,c]=this.tree.removeStyle([r,o],n,s);for(const m of c)this.context.registerGCPair(m);this.context.push(Yr.createTreeRemoveStyleOperation(this.tree.getCreatedAt(),r,o,u,n,s))}editInternal(t,e,n,r=0){var m;if(n.length!==0&&n[0]&&(El(n),n[0].type!==Gr))for(const y of n){const{children:d=[]}=y;El(d)}const o=this.context.getLastTimeTicket();let s=new Array;if(((m=n[0])==null?void 0:m.type)===Gr){let y="";for(const d of n){const{value:l}=d;y+=l}s.push(Ct.create(pt.of(this.context.issueTimeTicket(),0),Gr,y))}else s=n.map(y=>y&&Ih(this.context,y)).filter(y=>y);const[,u,c]=this.tree.edit([t,e],s.length?s.map(y=>y==null?void 0:y.deepcopy()):void 0,r,o,()=>this.context.issueTimeTicket());for(const y of u)this.context.registerGCPair(y);return this.context.push(Io.create(this.tree.getCreatedAt(),t,e,s.length?s:void 0,r,c,o)),!0}editByPath(t,e,n,r=0){if(!this.context||!this.tree)throw new ne(te.ErrNotInitialized,"Tree is not initialized yet");if(t.length!==e.length)throw new ne(te.ErrInvalidArgument,"path length should be equal");if(!t.length||!e.length)throw new ne(te.ErrInvalidArgument,"path should not be empty");const o=this.tree.pathToPos(t),s=this.tree.pathToPos(e);return this.editInternal(o,s,n?[n]:[],r)}editBulkByPath(t,e,n,r=0){if(!this.context||!this.tree)throw new ne(te.ErrNotInitialized,"Tree is not initialized yet");if(t.length!==e.length)throw new ne(te.ErrInvalidArgument,"path length should be equal");if(!t.length||!e.length)throw new ne(te.ErrInvalidArgument,"path should not be empty");const o=this.tree.pathToPos(t),s=this.tree.pathToPos(e);return this.editInternal(o,s,n,r)}edit(t,e,n,r=0){if(!this.context||!this.tree)throw new ne(te.ErrNotInitialized,"Tree is not initialized yet");if(t>e)throw new ne(te.ErrInvalidArgument,"from should be less than or equal to to");const o=this.tree.findPos(t),s=this.tree.findPos(e);return this.editInternal(o,s,n?[n]:[],r)}editBulk(t,e,n,r=0){if(!this.context||!this.tree)throw new ne(te.ErrNotInitialized,"Tree is not initialized yet");if(t>e)throw new ne(te.ErrInvalidArgument,"from should be less than or equal to to");const o=this.tree.findPos(t),s=this.tree.findPos(e);return this.editInternal(o,s,n,r)}toXML(){if(!this.context||!this.tree)throw new ne(te.ErrNotInitialized,"Tree is not initialized yet");return this.tree.toXML()}toJSON(){if(!this.context||!this.tree)throw new ne(te.ErrNotInitialized,"Tree is not initialized yet");return this.tree.toJSON()}toJSForTest(){if(!this.context||!this.tree)throw new ne(te.ErrNotInitialized,"Tree is not initialized yet");return this.tree.toJSForTest()}toJSInfoForTest(){if(!this.context||!this.tree)throw new ne(te.ErrNotInitialized,"Tree is not initialized yet");return this.tree.toJSInfoForTest()}getRootTreeNode(){if(!this.context||!this.tree)throw new ne(te.ErrNotInitialized,"Tree is not initialized yet");return this.tree.getRootTreeNode()}indexToPath(t){if(!this.context||!this.tree)throw new ne(te.ErrNotInitialized,"Tree is not initialized yet");return this.tree.indexToPath(t)}pathToIndex(t){if(!this.context||!this.tree)throw new ne(te.ErrNotInitialized,"Tree is not initialized yet");return this.tree.pathToIndex(t)}pathRangeToPosRange(t){if(!this.context||!this.tree)throw new ne(te.ErrNotInitialized,"Tree is not initialized yet");const e=[this.tree.pathToIndex(t[0]),this.tree.pathToIndex(t[1])],n=this.tree.indexRangeToPosRange(e);return[n[0].toStruct(),n[1].toStruct()]}indexRangeToPosRange(t){if(!this.context||!this.tree)throw new ne(te.ErrNotInitialized,"Tree is not initialized yet");return this.tree.indexRangeToPosStructRange(t)}posRangeToIndexRange(t){if(!this.context||!this.tree)throw new ne(te.ErrNotInitialized,"Tree is not initialized yet");const e=[ln.fromStruct(t[0]),ln.fromStruct(t[1])];return this.tree.posRangeToIndexRange(e)}posRangeToPathRange(t){if(!this.context||!this.tree)throw new ne(te.ErrNotInitialized,"Tree is not initialized yet");const e=[ln.fromStruct(t[0]),ln.fromStruct(t[1])];return this.tree.posRangeToPathRange(e)}}function xl(i,t){return qu(i,t)}function oi(i,t){if(t){if(t instanceof et)return t;if(t instanceof xt)return qu(i,t);if(t instanceof Rt)return xh(i,t);if(t instanceof Gt)return new Is(i,t);if(t instanceof Dt){const e=new Ns(Un.IntegerCnt,0);return e.initialize(i,t),e}else if(t instanceof Yt){const e=new _s;return e.initialize(i,t),e}}else return;throw new TypeError(`Unsupported type of element: ${typeof t}`)}function wi(i,t){const e=oi(i,t);return e instanceof et?e.getValue():e}function Ts(i,t,e){let n;if(et.isSupport(t))n=et.of(t,e);else if(Array.isArray(t))n=Rt.create(e,nt.buildArrayElements(i,t));else if(typeof t=="object")t instanceof Is?(n=Gt.create(Xi.create(),e),t.initialize(i,n)):t instanceof Ns?(n=Dt.create(t.getValueType(),t.getValue(),e),t.initialize(i,n)):t instanceof _s?(n=Yt.create(t.buildRoot(i),e),t.initialize(i,n)):n=xt.create(e,To.buildObjectMembers(i,t));else throw new TypeError(`Unsupported type of value: ${typeof t}`);return n}const kl=50;class Nh{constructor(){T(this,"undoStack",[]);T(this,"redoStack",[])}hasUndo(){return this.undoStack.length>0}hasRedo(){return this.redoStack.length>0}pushUndo(t){this.undoStack.length>=kl&&this.undoStack.shift(),this.undoStack.push(t)}popUndo(){return this.undoStack.pop()}pushRedo(t){this.redoStack.length>=kl&&this.redoStack.shift(),this.redoStack.push(t)}popRedo(){return this.redoStack.pop()}clearRedo(){this.redoStack=[]}getUndoStackForTest(){return this.undoStack}getRedoStackForTest(){return this.redoStack}}const _h="yorkie-devtools-panel",Ph="yorkie-devtools-sdk";let qi="disconnected";const Ol=new Map,Yo=new Map;typeof window<"u"&&(window.transactionEventsByDocKey=Yo);function Jo(i,t){(t!=null&&t.force||qi!=="disconnected")&&window.postMessage({source:Ph,...i},"*")}function Ch(i){if(!i.isEnableDevtools()||typeof window>"u"||Ol.has(i.getKey()))return;Yo.set(i.getKey(),[]);const t=i.subscribe("all",e=>{e.some(n=>n.type!==gt.StatusChanged&&n.type!==gt.Snapshot&&n.type!==gt.LocalChange&&n.type!==gt.RemoteChange&&n.type!==gt.Initialized&&n.type!==gt.Watched&&n.type!==gt.Unwatched&&n.type!==gt.PresenceChanged)||(Yo.get(i.getKey()).push(e),qi==="synced"&&Jo({msg:"doc::sync::partial",docKey:i.getKey(),event:e}))});Ol.set(i.getKey(),[t]),Jo({msg:"refresh-devtools"},{force:!0}),window.addEventListener("message",e=>{var r;if(((r=e.data)==null?void 0:r.source)!==_h)return;switch(e.data.msg){case"devtools::connect":if(qi!=="disconnected")break;qi="connected",Jo({msg:"doc::available",docKey:i.getKey()}),Ne.info(`[YD] Devtools connected. Doc: ${i.getKey()}`);break;case"devtools::disconnect":qi="disconnected",Ne.info(`[YD] Devtools disconnected. Doc: ${i.getKey()}`);break;case"devtools::subscribe":qi="synced",Jo({msg:"doc::sync::full",docKey:i.getKey(),events:Yo.get(i.getKey())}),Ne.info(`[YD] Devtools subscribed. Doc: ${i.getKey()}`);break}})}var si=(i=>(i.Detached="detached",i.Attached="attached",i.Removed="removed",i))(si||{}),gt=(i=>(i.StatusChanged="status-changed",i.ConnectionChanged="connection-changed",i.SyncStatusChanged="sync-status-changed",i.Snapshot="snapshot",i.LocalChange="local-change",i.RemoteChange="remote-change",i.Initialized="initialized",i.Watched="watched",i.Unwatched="unwatched",i.PresenceChanged="presence-changed",i.Broadcast="broadcast",i.LocalBroadcast="local-broadcast",i))(gt||{}),So=(i=>(i.Connected="connected",i.Disconnected="disconnected",i))(So||{}),ma=(i=>(i.Synced="synced",i.SyncFailed="sync-failed",i))(ma||{});class ju{constructor(t,e){T(this,"key");T(this,"status");T(this,"opts");T(this,"changeID");T(this,"checkpoint");T(this,"localChanges");T(this,"root");T(this,"clone");T(this,"eventStream");T(this,"eventStreamObserver");T(this,"onlineClients");T(this,"presences");T(this,"history");T(this,"internalHistory");T(this,"isUpdating");this.opts=e||{},this.key=t,this.status="detached",this.root=Ao.create(),this.changeID=Df,this.checkpoint=Bf,this.localChanges=[],this.eventStream=Eh(n=>{this.eventStreamObserver=n}),this.onlineClients=new Set,this.presences=new Map,this.isUpdating=!1,this.internalHistory=new Nh,this.history={canUndo:this.canUndo.bind(this),canRedo:this.canRedo.bind(this),undo:this.undo.bind(this),redo:this.redo.bind(this)},Ch(this)}update(t,e){if(this.getStatus()==="removed")throw new ne(te.ErrDocumentRemoved,`${this.key} is removed`);this.ensureClone();const n=this.changeID.getActorID(),r=Ji.create(this.changeID.next(),this.clone.root,this.clone.presences.get(n)||{},e);try{const o=xl(r,this.clone.root.getObject());this.presences.has(n)||this.clone.presences.set(n,{}),this.isUpdating=!0,t(o,new Bs(r,this.clone.presences.get(n)))}catch(o){throw this.clone=void 0,o}finally{this.isUpdating=!1}if(r.hasChange()){Ne.isEnabled(wt.Trivial)&&Ne.trivial(`trying to update a local change: ${this.toJSON()}`);const o=r.getChange(),{opInfos:s,reverseOps:u}=o.execute(this.root,this.presences,Ye.Local),c=r.getReversePresence();c&&u.push({type:"presence",value:c}),this.localChanges.push(o),u.length>0&&this.internalHistory.pushUndo(u),s.length>0&&this.internalHistory.clearRedo(),this.changeID=o.getID();const m=[];s.length>0&&m.push({type:"local-change",source:Ye.Local,value:{message:o.getMessage()||"",operations:s,actor:n,clientSeq:o.getID().getClientSeq(),serverSeq:o.getID().getServerSeq()},rawChange:this.isEnableDevtools()?o.toStruct():void 0}),o.hasPresenceChange()&&m.push({type:"presence-changed",source:Ye.Local,value:{clientID:n,presence:this.getPresence(n)}}),this.publish(m),Ne.isEnabled(wt.Trivial)&&Ne.trivial(`after update a local change: ${this.toJSON()}`)}}subscribe(t,e,n,r){if(typeof t=="string"){if(typeof e!="function")throw new ne(te.ErrInvalidArgument,"Second argument must be a callback function");if(t==="presence"){const u=e;return this.eventStream.subscribe(c=>{for(const m of c)m.type!=="initialized"&&m.type!=="watched"&&m.type!=="unwatched"&&m.type!=="presence-changed"||u(m)},n,r)}if(t==="my-presence"){const u=e;return this.eventStream.subscribe(c=>{for(const m of c)m.type!=="initialized"&&m.type!=="presence-changed"||m.type==="presence-changed"&&m.value.clientID!==this.changeID.getActorID()||u(m)},n,r)}if(t==="others"){const u=e;return this.eventStream.subscribe(c=>{for(const m of c)m.type!=="watched"&&m.type!=="unwatched"&&m.type!=="presence-changed"||m.value.clientID!==this.changeID.getActorID()&&u(m)},n,r)}if(t==="connection"){const u=e;return this.eventStream.subscribe(c=>{for(const m of c)m.type==="connection-changed"&&u(m)},n,r)}if(t==="status"){const u=e;return this.eventStream.subscribe(c=>{for(const m of c)m.type==="status-changed"&&u(m)},n,r)}if(t==="sync"){const u=e;return this.eventStream.subscribe(c=>{for(const m of c)m.type==="sync-status-changed"&&u(m)},n,r)}if(t==="local-broadcast"){const u=e;return this.eventStream.subscribe(c=>{for(const m of c)m.type==="local-broadcast"&&u(m)},n)}if(t==="broadcast"){const u=e;return this.eventStream.subscribe(c=>{for(const m of c)m.type==="broadcast"&&u(m)},n)}if(t==="all"){const u=e;return this.eventStream.subscribe(u,n,r)}const o=t,s=e;return this.eventStream.subscribe(u=>{for(const c of u){if(c.type!=="local-change"&&c.type!=="remote-change")continue;const m=[];for(const y of c.value.operations)this.isSameElementOrChildOf(y.path,o)&&m.push(y);m.length&&s({...c,value:{...c.value,operations:m}})}},n,r)}if(typeof t=="function"){const o=t,s=e,u=n;return this.eventStream.subscribe(c=>{for(const m of c)m.type!=="snapshot"&&m.type!=="local-change"&&m.type!=="remote-change"||o(m)},s,u)}throw new ne(te.ErrInvalidArgument,`"${t}" is not a valid`)}publish(t){this.eventStreamObserver&&this.eventStreamObserver.next(t)}isSameElementOrChildOf(t,e){if(e===t)return!0;const n=t.split(".");return e.split(".").every((o,s)=>o===n[s])}applyChangePack(t){const e=t.hasSnapshot();for(e?this.applySnapshot(t.getCheckpoint().getServerSeq(),t.getVersionVector(),t.getSnapshot()):t.hasChanges()&&this.applyChanges(t.getChanges(),Ye.Remote);this.localChanges.length&&!(this.localChanges[0].getID().getClientSeq()>t.getCheckpoint().getClientSeq());)this.localChanges.shift();e&&this.applyChanges(this.localChanges,Ye.Remote),this.checkpoint=this.checkpoint.forward(t.getCheckpoint()),e||this.garbageCollect(t.getVersionVector()),e||this.filterVersionVector(t.getVersionVector()),t.getIsRemoved()&&this.applyStatus("removed"),Ne.isEnabled(wt.Trivial)&&Ne.trivial(`${this.root.toJSON()}`)}getCheckpoint(){return this.checkpoint}getChangeID(){return this.changeID}hasLocalChanges(){return this.localChanges.length>0}ensureClone(){this.clone||(this.clone={root:this.root.deepcopy(),presences:sn(this.presences)})}createChangePack(){const t=Array.from(this.localChanges),e=this.checkpoint.increaseClientSeq(t.length);return Os.create(this.key,e,!1,t,this.getVersionVector())}setActor(t){for(const e of this.localChanges)e.setActor(t);this.changeID=this.changeID.setActor(t)}isEnableDevtools(){return!!this.opts.enableDevtools}getKey(){return this.key}getStatus(){return this.status}getCloneRoot(){if(this.clone)return this.clone.root.getObject()}getRoot(){this.ensureClone();const t=Ji.create(this.changeID.next(),this.clone.root,this.clone.presences.get(this.changeID.getActorID())||{});return xl(t,this.clone.root.getObject())}garbageCollect(t){return this.opts.disableGC?0:(this.clone&&this.clone.root.garbageCollect(t),this.root.garbageCollect(t))}getRootObject(){return this.root.getObject()}getGarbageLen(){return this.root.getGarbageLen()}getGarbageLenFromClone(){return this.clone.root.getGarbageLen()}toJSON(){return this.root.toJSON()}toSortedJSON(){return this.root.toSortedJSON()}getStats(){return this.root.getStats()}toJSForTest(){return{...this.getRoot().toJSForTest(),key:"root"}}applySnapshot(t,e,n){const{root:r,presences:o}=at.bytesToSnapshot(n);this.root=new Ao(r),this.presences=o,this.changeID=this.changeID.setClocks(t,e),this.clone=void 0,this.publish([{type:"snapshot",source:Ye.Remote,value:{serverSeq:t.toString(),snapshot:this.isEnableDevtools()?at.bytesToHex(n):void 0,snapshotVector:at.versionVectorToHex(e)}}])}applyChanges(t,e){Ne.isEnabled(wt.Debug)&&Ne.debug(`trying to apply ${t.length} remote changes.elements:${this.root.getElementMapSize()}, removeds:${this.root.getGarbageElementSetSize()}`),Ne.isEnabled(wt.Trivial)&&Ne.trivial(t.map(n=>`${n.getID().toTestString()} ${n.toTestString()}`).join(` + */var Ht=null;try{Ht=new WebAssembly.Instance(new WebAssembly.Module(new Uint8Array([0,97,115,109,1,0,0,0,1,13,2,96,0,1,127,96,4,127,127,127,127,1,127,3,7,6,0,1,1,1,1,1,6,6,1,127,1,65,0,11,7,50,6,3,109,117,108,0,1,5,100,105,118,95,115,0,2,5,100,105,118,95,117,0,3,5,114,101,109,95,115,0,4,5,114,101,109,95,117,0,5,8,103,101,116,95,104,105,103,104,0,0,10,191,1,6,4,0,35,0,11,36,1,1,126,32,0,173,32,1,173,66,32,134,132,32,2,173,32,3,173,66,32,134,132,126,34,4,66,32,135,167,36,0,32,4,167,11,36,1,1,126,32,0,173,32,1,173,66,32,134,132,32,2,173,32,3,173,66,32,134,132,127,34,4,66,32,135,167,36,0,32,4,167,11,36,1,1,126,32,0,173,32,1,173,66,32,134,132,32,2,173,32,3,173,66,32,134,132,128,34,4,66,32,135,167,36,0,32,4,167,11,36,1,1,126,32,0,173,32,1,173,66,32,134,132,32,2,173,32,3,173,66,32,134,132,129,34,4,66,32,135,167,36,0,32,4,167,11,36,1,1,126,32,0,173,32,1,173,66,32,134,132,32,2,173,32,3,173,66,32,134,132,130,34,4,66,32,135,167,36,0,32,4,167,11])),{}).exports}catch{}function Ve(i,t,e){this.low=i|0,this.high=t|0,this.unsigned=!!e}Ve.prototype.__isLong__;Object.defineProperty(Ve.prototype,"__isLong__",{value:!0});function yt(i){return(i&&i.__isLong__)===!0}function ml(i){var t=Math.clz32(i&-i);return i?31-t:t}Ve.isLong=yt;var yl={},vl={};function Pi(i,t){var e,n,r;return t?(i>>>=0,(r=0<=i&&i<256)&&(n=vl[i],n)?n:(e=Ke(i,0,!0),r&&(vl[i]=e),e)):(i|=0,(r=-128<=i&&i<128)&&(n=yl[i],n)?n:(e=Ke(i,i<0?-1:0,!1),r&&(yl[i]=e),e))}Ve.fromInt=Pi;function Wt(i,t){if(isNaN(i))return t?Wr:an;if(t){if(i<0)return Wr;if(i>=fu)return gu}else{if(i<=-wl)return Et;if(i+1>=wl)return du}return i<0?Wt(-i,t).neg():Ke(i%Yi|0,i/Yi|0,t)}Ve.fromNumber=Wt;function Ke(i,t,e){return new Ve(i,t,e)}Ve.fromBits=Ke;var bs=Math.pow;function Sa(i,t,e){if(i.length===0)throw Error("empty string");if(typeof t=="number"?(e=t,t=!1):t=!!t,i==="NaN"||i==="Infinity"||i==="+Infinity"||i==="-Infinity")return t?Wr:an;if(e=e||10,e<2||360)throw Error("interior hyphen");if(n===0)return Sa(i.substring(1),t,e).neg();for(var r=Wt(bs(e,8)),o=an,s=0;s>>0:this.low};he.toNumber=function(){return this.unsigned?(this.high>>>0)*Yi+(this.low>>>0):this.high*Yi+(this.low>>>0)};he.toString=function(t){if(t=t||10,t<2||36>>0,y=m.toString(t);if(s=c,s.isZero())return y+u;for(;y.length<6;)y="0"+y;u=""+y+u}};he.getHighBits=function(){return this.high};he.getHighBitsUnsigned=function(){return this.high>>>0};he.getLowBits=function(){return this.low};he.getLowBitsUnsigned=function(){return this.low>>>0};he.getNumBitsAbs=function(){if(this.isNegative())return this.eq(Et)?64:this.neg().getNumBitsAbs();for(var t=this.high!=0?this.high:this.low,e=31;e>0&&!(t&1<=0};he.isOdd=function(){return(this.low&1)===1};he.isEven=function(){return(this.low&1)===0};he.equals=function(t){return yt(t)||(t=hn(t)),this.unsigned!==t.unsigned&&this.high>>>31===1&&t.high>>>31===1?!1:this.high===t.high&&this.low===t.low};he.eq=he.equals;he.notEquals=function(t){return!this.eq(t)};he.neq=he.notEquals;he.ne=he.notEquals;he.lessThan=function(t){return this.comp(t)<0};he.lt=he.lessThan;he.lessThanOrEqual=function(t){return this.comp(t)<=0};he.lte=he.lessThanOrEqual;he.le=he.lessThanOrEqual;he.greaterThan=function(t){return this.comp(t)>0};he.gt=he.greaterThan;he.greaterThanOrEqual=function(t){return this.comp(t)>=0};he.gte=he.greaterThanOrEqual;he.ge=he.greaterThanOrEqual;he.compare=function(t){if(yt(t)||(t=hn(t)),this.eq(t))return 0;var e=this.isNegative(),n=t.isNegative();return e&&!n?-1:!e&&n?1:this.unsigned?t.high>>>0>this.high>>>0||t.high===this.high&&t.low>>>0>this.low>>>0?-1:1:this.sub(t).isNegative()?-1:1};he.comp=he.compare;he.negate=function(){return!this.unsigned&&this.eq(Et)?Et:this.not().add(Ui)};he.neg=he.negate;he.add=function(t){yt(t)||(t=hn(t));var e=this.high>>>16,n=this.high&65535,r=this.low>>>16,o=this.low&65535,s=t.high>>>16,u=t.high&65535,c=t.low>>>16,m=t.low&65535,y=0,d=0,l=0,a=0;return a+=o+m,l+=a>>>16,a&=65535,l+=r+c,d+=l>>>16,l&=65535,d+=n+u,y+=d>>>16,d&=65535,y+=e+s,y&=65535,Ke(l<<16|a,y<<16|d,this.unsigned)};he.subtract=function(t){return yt(t)||(t=hn(t)),this.add(t.neg())};he.sub=he.subtract;he.multiply=function(t){if(this.isZero())return this;if(yt(t)||(t=hn(t)),Ht){var e=Ht.mul(this.low,this.high,t.low,t.high);return Ke(e,Ht.get_high(),this.unsigned)}if(t.isZero())return this.unsigned?Wr:an;if(this.eq(Et))return t.isOdd()?Et:an;if(t.eq(Et))return this.isOdd()?Et:an;if(this.isNegative())return t.isNegative()?this.neg().mul(t.neg()):this.neg().mul(t).neg();if(t.isNegative())return this.mul(t.neg()).neg();if(this.lt(Al)&&t.lt(Al))return Wt(this.toNumber()*t.toNumber(),this.unsigned);var n=this.high>>>16,r=this.high&65535,o=this.low>>>16,s=this.low&65535,u=t.high>>>16,c=t.high&65535,m=t.low>>>16,y=t.low&65535,d=0,l=0,a=0,p=0;return p+=s*y,a+=p>>>16,p&=65535,a+=o*y,l+=a>>>16,a&=65535,a+=s*m,l+=a>>>16,a&=65535,l+=r*y,d+=l>>>16,l&=65535,l+=o*m,d+=l>>>16,l&=65535,l+=s*c,d+=l>>>16,l&=65535,d+=n*y+r*m+o*c+s*u,d&=65535,Ke(a<<16|p,d<<16|l,this.unsigned)};he.mul=he.multiply;he.divide=function(t){if(yt(t)||(t=hn(t)),t.isZero())throw Error("division by zero");if(Ht){if(!this.unsigned&&this.high===-2147483648&&t.low===-1&&t.high===-1)return this;var e=(this.unsigned?Ht.div_u:Ht.div_s)(this.low,this.high,t.low,t.high);return Ke(e,Ht.get_high(),this.unsigned)}if(this.isZero())return this.unsigned?Wr:an;var n,r,o;if(this.unsigned){if(t.unsigned||(t=t.toUnsigned()),t.gt(this))return Wr;if(t.gt(this.shru(1)))return hu;o=Wr}else{if(this.eq(Et)){if(t.eq(Ui)||t.eq(da))return Et;if(t.eq(Et))return Ui;var s=this.shr(1);return n=s.div(t).shl(1),n.eq(an)?t.isNegative()?Ui:da:(r=this.sub(t.mul(n)),o=n.add(r.div(t)),o)}else if(t.eq(Et))return this.unsigned?Wr:an;if(this.isNegative())return t.isNegative()?this.neg().div(t.neg()):this.neg().div(t).neg();if(t.isNegative())return this.div(t.neg()).neg();o=an}for(r=this;r.gte(t);){n=Math.max(1,Math.floor(r.toNumber()/t.toNumber()));for(var u=Math.ceil(Math.log(n)/Math.LN2),c=u<=48?1:bs(2,u-48),m=Wt(n),y=m.mul(t);y.isNegative()||y.gt(r);)n-=c,m=Wt(n,this.unsigned),y=m.mul(t);m.isZero()&&(m=Ui),o=o.add(m),r=r.sub(y)}return o};he.div=he.divide;he.modulo=function(t){if(yt(t)||(t=hn(t)),Ht){var e=(this.unsigned?Ht.rem_u:Ht.rem_s)(this.low,this.high,t.low,t.high);return Ke(e,Ht.get_high(),this.unsigned)}return this.sub(this.div(t).mul(t))};he.mod=he.modulo;he.rem=he.modulo;he.not=function(){return Ke(~this.low,~this.high,this.unsigned)};he.countLeadingZeros=function(){return this.high?Math.clz32(this.high):Math.clz32(this.low)+32};he.clz=he.countLeadingZeros;he.countTrailingZeros=function(){return this.low?ml(this.low):ml(this.high)+32};he.ctz=he.countTrailingZeros;he.and=function(t){return yt(t)||(t=hn(t)),Ke(this.low&t.low,this.high&t.high,this.unsigned)};he.or=function(t){return yt(t)||(t=hn(t)),Ke(this.low|t.low,this.high|t.high,this.unsigned)};he.xor=function(t){return yt(t)||(t=hn(t)),Ke(this.low^t.low,this.high^t.high,this.unsigned)};he.shiftLeft=function(t){return yt(t)&&(t=t.toInt()),(t&=63)===0?this:t<32?Ke(this.low<>>32-t,this.unsigned):Ke(0,this.low<>>t|this.high<<32-t,this.high>>t,this.unsigned):Ke(this.high>>t-32,this.high>=0?0:-1,this.unsigned)};he.shr=he.shiftRight;he.shiftRightUnsigned=function(t){return yt(t)&&(t=t.toInt()),(t&=63)===0?this:t<32?Ke(this.low>>>t|this.high<<32-t,this.high>>>t,this.unsigned):t===32?Ke(this.high,0,this.unsigned):Ke(this.high>>>t-32,0,this.unsigned)};he.shru=he.shiftRightUnsigned;he.shr_u=he.shiftRightUnsigned;he.rotateLeft=function(t){var e;return yt(t)&&(t=t.toInt()),(t&=63)===0?this:t===32?Ke(this.high,this.low,this.unsigned):t<32?(e=32-t,Ke(this.low<>>e,this.high<>>e,this.unsigned)):(t-=32,e=32-t,Ke(this.high<>>e,this.low<>>e,this.unsigned))};he.rotl=he.rotateLeft;he.rotateRight=function(t){var e;return yt(t)&&(t=t.toInt()),(t&=63)===0?this:t===32?Ke(this.high,this.low,this.unsigned):t<32?(e=32-t,Ke(this.high<>>t,this.low<>>t,this.unsigned)):(t-=32,e=32-t,Ke(this.low<>>t,this.high<>>t,this.unsigned))};he.rotr=he.rotateRight;he.toSigned=function(){return this.unsigned?Ke(this.low,this.high,!1):this};he.toUnsigned=function(){return this.unsigned?this:Ke(this.low,this.high,!0)};he.toBytes=function(t){return t?this.toBytesLE():this.toBytesBE()};he.toBytesLE=function(){var t=this.high,e=this.low;return[e&255,e>>>8&255,e>>>16&255,e>>>24,t&255,t>>>8&255,t>>>16&255,t>>>24]};he.toBytesBE=function(){var t=this.high,e=this.low;return[t>>>24,t>>>16&255,t>>>8&255,t&255,e>>>24,e>>>16&255,e>>>8&255,e&255]};Ve.fromBytes=function(t,e,n){return n?Ve.fromBytesLE(t,e):Ve.fromBytesBE(t,e)};Ve.fromBytesLE=function(t,e){return new Ve(t[0]|t[1]<<8|t[2]<<16|t[3]<<24,t[4]|t[5]<<8|t[6]<<16|t[7]<<24,e)};Ve.fromBytesBE=function(t,e){return new Ve(t[4]<<24|t[5]<<16|t[6]<<8|t[7],t[0]<<24|t[1]<<16|t[2]<<8|t[3],e)};var ft=(i=>(i[i.Null=0]="Null",i[i.Boolean=1]="Boolean",i[i.Integer=2]="Integer",i[i.Long=3]="Long",i[i.Double=4]="Double",i[i.String=5]="String",i[i.Bytes=6]="Bytes",i[i.Date=7]="Date",i))(ft||{});class et extends Eo{constructor(e,n){super(n);T(this,"valueType");T(this,"value");this.valueType=et.getPrimitiveType(e),this.value=e===void 0?null:e}static of(e,n){return new et(e,n)}static valueFromBytes(e,n){switch(e){case 0:return null;case 1:return!!n[0];case 2:return n[0]|n[1]<<8|n[2]<<16|n[3]<<24;case 4:{const r=new DataView(n.buffer);return n.forEach(function(o,s){r.setUint8(s,o)}),r.getFloat64(0,!0)}case 5:return new TextDecoder("utf-8").decode(n);case 3:return Ve.fromBytesLE(Array.from(n));case 6:return n;case 7:return new Date(Ve.fromBytesLE(Array.from(n),!0).toNumber());default:throw new ne(te.ErrUnimplemented,`unimplemented type: ${e}`)}}toJSON(){return this.valueType===5?`"${Fn(this.value)}"`:`${this.value}`}toSortedJSON(){return this.toJSON()}toJSForTest(){return{createdAt:this.getCreatedAt().toTestString(),value:this.value,type:"YORKIE_PRIMITIVE"}}deepcopy(){const e=et.of(this.value,this.getCreatedAt());return e.setMovedAt(this.getMovedAt()),e.setRemovedAt(this.getRemovedAt()),e}getType(){return this.valueType}static getPrimitiveType(e){switch(typeof e){case"undefined":return 0;case"boolean":return 1;case"number":return this.isInteger(e)?2:4;case"string":return 5;case"object":if(e===null)return 0;if(e instanceof Ve)return 3;if(e instanceof Uint8Array)return 6;if(e instanceof Date)return 7}}static isSupport(e){return et.getPrimitiveType(e)!==void 0}static isInteger(e){return e%1===0}isNumericType(){const e=this.valueType;return e===2||e===3||e===4}getValue(){return this.value}toBytes(){switch(this.valueType){case 0:return new Uint8Array;case 1:return this.value?new Uint8Array([1]):new Uint8Array([0]);case 2:{const e=this.value;return new Uint8Array([e&255,e>>8&255,e>>16&255,e>>24&255])}case 4:{const e=this.value,n=new Uint8Array(8);return new DataView(n.buffer).setFloat64(0,e,!0),n}case 5:return new TextEncoder().encode(this.value);case 3:{const n=this.value.toBytesLE();return Uint8Array.from(n)}case 6:return this.value;case 7:{const e=this.value,n=Ve.fromNumber(e.getTime(),!0).toBytesLE();return Uint8Array.from(n)}default:throw new ne(te.ErrUnimplemented,`unimplemented type: ${this.valueType}`)}}}class ws extends cu{constructor(e){super(e);T(this,"prev");T(this,"next");this.value=e}static createAfter(e,n){const r=new ws(n),o=e.next;return e.next=r,r.prev=e,r.next=o,o&&(o.prev=r),r}remove(e){return this.value.remove(e)}getCreatedAt(){return this.value.getCreatedAt()}getPositionedAt(){return this.value.getPositionedAt()}release(){this.prev&&(this.prev.next=this.next),this.next&&(this.next.prev=this.prev),this.prev=void 0,this.next=void 0}getLength(){return this.value.isRemoved()?0:1}getPrev(){return this.prev}getNext(){return this.next}getValue(){return this.value}isRemoved(){return this.value.isRemoved()}}class bo{constructor(){T(this,"dummyHead");T(this,"last");T(this,"nodeMapByIndex");T(this,"nodeMapByCreatedAt");const t=et.of(0,un);t.setRemovedAt(un),this.dummyHead=new ws(t),this.last=this.dummyHead,this.nodeMapByIndex=new vo,this.nodeMapByCreatedAt=new Map,this.nodeMapByIndex.insert(this.dummyHead),this.nodeMapByCreatedAt.set(this.dummyHead.getCreatedAt().toIDString(),this.dummyHead)}static create(){return new bo}get length(){return this.nodeMapByIndex.length}findNextBeforeExecutedAt(t,e){let n=this.nodeMapByCreatedAt.get(t.toIDString());if(!n)throw new ne(te.ErrInvalidArgument,`cant find the given node: ${t.toIDString()}`);for(;n.getNext()&&n.getNext().getPositionedAt().after(e);)n=n.getNext();return n}release(t){this.last===t&&(this.last=t.getPrev()),t.release(),this.nodeMapByIndex.delete(t),this.nodeMapByCreatedAt.delete(t.getValue().getCreatedAt().toIDString())}insertAfter(t,e,n=e.getCreatedAt()){const r=this.findNextBeforeExecutedAt(t,n),o=ws.createAfter(r,e);r===this.last&&(this.last=o),this.nodeMapByIndex.insertAfter(r,o),this.nodeMapByCreatedAt.set(o.getCreatedAt().toIDString(),o)}moveAfter(t,e,n){const r=this.nodeMapByCreatedAt.get(t.toIDString());if(!r)throw new ne(te.ErrInvalidArgument,`cant find the given node: ${t.toIDString()}`);const o=this.nodeMapByCreatedAt.get(e.toIDString());if(!o)throw new ne(te.ErrInvalidArgument,`cant find the given node: ${e.toIDString()}`);r!==o&&(!o.getValue().getMovedAt()||n.after(o.getValue().getMovedAt()))&&(this.release(o),this.insertAfter(r.getCreatedAt(),o.getValue(),n),o.getValue().setMovedAt(n))}insert(t){this.insertAfter(this.last.getCreatedAt(),t)}getByID(t){return this.nodeMapByCreatedAt.get(t.toIDString())}subPathOf(t){const e=this.nodeMapByCreatedAt.get(t.toIDString());if(e)return String(this.nodeMapByIndex.indexOf(e))}purge(t){const e=this.nodeMapByCreatedAt.get(t.getCreatedAt().toIDString());if(!e)throw new ne(te.ErrInvalidArgument,`fail to find the given createdAt: ${t.getCreatedAt().toIDString()}`);this.release(e)}getByIndex(t){if(t>=this.length)return;const[e,n]=this.nodeMapByIndex.find(t);let r=e;if(t===0&&e===this.dummyHead||n>0)do r&&(r=r.getNext());while(r&&r.isRemoved());return r}getPrevCreatedAt(t){let e=this.nodeMapByCreatedAt.get(t.toIDString());do e=e.getPrev();while(this.dummyHead!==e&&e.isRemoved());return e.getValue().getCreatedAt()}delete(t,e){const n=this.nodeMapByCreatedAt.get(t.toIDString()),r=n.isRemoved();return n.remove(e)&&!r&&this.nodeMapByIndex.splayNode(n),n.getValue()}deleteByIndex(t,e){const n=this.getByIndex(t);if(n)return n.remove(e)&&this.nodeMapByIndex.splayNode(n),n.getValue()}getHead(){return this.dummyHead.getValue()}getLast(){return this.last.getValue()}getLastCreatedAt(){return this.last.getCreatedAt()}toTestString(){const t=[];for(const e of this){const n=`${e.getCreatedAt().toIDString()}:${e.getValue().toJSON()}`;e.isRemoved()?t.push(`{${n}}`):t.push(`[${n}]`)}return t.join("")}*[Symbol.iterator](){let t=this.dummyHead.getNext();for(;t;)yield t,t=t.getNext()}}class Rt extends hi{constructor(e,n){super(e);T(this,"elements");this.elements=n}static create(e,n){if(!n)return new Rt(e,bo.create());const r=bo.create();for(const o of n)r.insertAfter(r.getLastCreatedAt(),o.deepcopy());return new Rt(e,r)}subPathOf(e){return this.elements.subPathOf(e)}purge(e){this.elements.purge(e)}insertAfter(e,n){this.elements.insertAfter(e,n)}moveAfter(e,n,r){this.elements.moveAfter(e,n,r)}get(e){const n=this.elements.getByIndex(e);return n==null?void 0:n.getValue()}getByID(e){const n=this.elements.getByID(e);return n==null?void 0:n.getValue()}getHead(){return this.elements.getHead()}getLast(){return this.elements.getLast()}getPrevCreatedAt(e){return this.elements.getPrevCreatedAt(e)}delete(e,n){return this.elements.delete(e,n)}deleteByIndex(e,n){return this.elements.deleteByIndex(e,n)}getLastCreatedAt(){return this.elements.getLastCreatedAt()}get length(){return this.elements.length}*[Symbol.iterator](){for(const e of this.elements)e.isRemoved()||(yield e.getValue())}toTestString(){return this.elements.toTestString()}getDescendants(e){for(const n of this.elements){const r=n.getValue();if(e(r,this))return;r instanceof hi&&r.getDescendants(e)}}toJSON(){const e=[];for(const n of this)e.push(n.toJSON());return`[${e.join(",")}]`}toJS(){return JSON.parse(this.toJSON())}toJSForTest(){const e={};for(let n=0;n({...a,value:a.value?{attributes:$i(a.value.getAttributes()),content:a.value.getContent()}:{attributes:void 0,content:""},type:"content"}));return[m,l,y,[c,c]]}setStyle(e,n,r,o){const[,s]=this.rgaTreeSplit.findNodeWithSplit(e[1],r),[,u]=this.rgaTreeSplit.findNodeWithSplit(e[0],r),c=[],m=this.rgaTreeSplit.findBetween(u,s),y=new Map,d=[];for(const a of m){const p=a.getCreatedAt().getActorID(),b=o!=null&&o.size?o.has(p)?o.get(p):un:uo;if(a.canStyle(r,b)){const w=y.get(p),v=a.getCreatedAt();(!w||v.after(w))&&y.set(p,v),d.push(a)}}const l=[];for(const a of d){if(a.isRemoved())continue;const[p,b]=this.rgaTreeSplit.findIndexesFromRange(a.createPosRange());c.push({type:"style",actor:r.getActorID(),from:p,to:b,value:{attributes:$i(n)}});for(const[w,v]of Object.entries(n)){const[h]=a.getValue().setAttr(w,v,r);h!==void 0&&l.push({parent:a.getValue(),child:h})}}return[y,l,c]}indexRangeToPosRange(e,n){const r=this.rgaTreeSplit.indexToPos(e);return e===n?[r,r]:[r,this.rgaTreeSplit.indexToPos(n)]}get length(){return this.rgaTreeSplit.length}getTreeByIndex(){return this.rgaTreeSplit.getTreeByIndex()}getTreeByID(){return this.rgaTreeSplit.getTreeByID()}toJSON(){const e=[];for(const n of this.rgaTreeSplit)n.isRemoved()||e.push(n.getValue().toJSON());return`[${e.join(",")}]`}toSortedJSON(){return this.toJSON()}toJSForTest(){return{createdAt:this.getCreatedAt().toTestString(),value:JSON.parse(this.toJSON()),type:"YORKIE_TEXT"}}toString(){return this.rgaTreeSplit.toString()}values(){const e=[];for(const n of this.rgaTreeSplit)if(!n.isRemoved()){const r=n.getValue();e.push({attributes:$i(r.getAttributes()),content:r.getContent()})}return e}getRGATreeSplit(){return this.rgaTreeSplit}toTestString(){return this.rgaTreeSplit.toTestString()}deepcopy(){const e=new Gt(this.rgaTreeSplit.deepcopy(),this.getCreatedAt());return e.remove(this.getRemovedAt()),e}findIndexesFromRange(e){return this.rgaTreeSplit.findIndexesFromRange(e)}getGCPairs(){const e=[];for(const n of this.rgaTreeSplit){n.getRemovedAt()&&e.push({parent:this.rgaTreeSplit,child:n});for(const r of n.getValue().getGCPairs())e.push(r)}return e}}class ko extends fn{constructor(e,n,r,o,s,u,c){super(e,c);T(this,"fromPos");T(this,"toPos");T(this,"maxCreatedAtMapByActor");T(this,"content");T(this,"attributes");this.fromPos=n,this.toPos=r,this.maxCreatedAtMapByActor=o,this.content=s,this.attributes=u}static create(e,n,r,o,s,u,c){return new ko(e,n,r,o,s,u,c)}execute(e){const n=e.findByCreatedAt(this.getParentCreatedAt());if(!n)throw new ne(te.ErrInvalidArgument,`fail to find ${this.getParentCreatedAt()}`);if(!(n instanceof Gt))throw new ne(te.ErrInvalidArgument,"fail to execute, only Text can execute edit");const r=n,[,o,s]=r.edit([this.fromPos,this.toPos],this.content,this.getExecutedAt(),Object.fromEntries(this.attributes),this.maxCreatedAtMapByActor);for(const u of s)e.registerGCPair(u);return{opInfos:o.map(({from:u,to:c,value:m})=>({type:"edit",from:u,to:c,value:m,path:e.createPath(this.getParentCreatedAt())}))}}getEffectedCreatedAt(){return this.getParentCreatedAt()}toTestString(){const e=this.getParentCreatedAt().toTestString(),n=this.fromPos.toTestString(),r=this.toPos.toTestString(),o=this.content;return`${e}.EDIT(${n},${r},${o})`}getFromPos(){return this.fromPos}getToPos(){return this.toPos}getContent(){return this.content}getAttributes(){return this.attributes||new Map}getMaxCreatedAtMapByActor(){return this.maxCreatedAtMapByActor}}class Oo extends fn{constructor(e,n,r,o,s,u){super(e,u);T(this,"fromPos");T(this,"toPos");T(this,"maxCreatedAtMapByActor");T(this,"attributes");this.fromPos=n,this.toPos=r,this.maxCreatedAtMapByActor=o,this.attributes=s}static create(e,n,r,o,s,u){return new Oo(e,n,r,o,s,u)}execute(e){const n=e.findByCreatedAt(this.getParentCreatedAt());if(!n)throw new ne(te.ErrInvalidArgument,`fail to find ${this.getParentCreatedAt()}`);if(!(n instanceof Gt))throw new ne(te.ErrInvalidArgument,"fail to execute, only Text can execute edit");const r=n,[,o,s]=r.setStyle([this.fromPos,this.toPos],this.attributes?Object.fromEntries(this.attributes):{},this.getExecutedAt(),this.maxCreatedAtMapByActor);for(const u of o)e.registerGCPair(u);return{opInfos:s.map(({from:u,to:c,value:m})=>({type:"style",from:u,to:c,value:m,path:e.createPath(this.getParentCreatedAt())}))}}getEffectedCreatedAt(){return this.getParentCreatedAt()}toTestString(){const e=this.getParentCreatedAt().toTestString(),n=this.fromPos.toTestString(),r=this.toPos.toTestString(),o=this.attributes;return`${e}.STYL(${n},${r},${JSON.stringify(o)})`}getFromPos(){return this.fromPos}getToPos(){return this.toPos}getAttributes(){return this.attributes}getMaxCreatedAtMapByActor(){return this.maxCreatedAtMapByActor}}const xf=2,kf="root",Gr="text";function oo(i,t){let e=0;const n=i.children;for(let r=0;r0)throw new ne(te.ErrRefused,"Text node cannot have children")}updateAncestorsSize(){let t=this.parent;const e=this.isRemoved?-1:1;for(;t&&(t.size+=this.paddedSize*e,!t.isRemoved);)t=t.parent}updateDescendantsSize(){let t=0;for(const e of this._children){const n=e.updateDescendantsSize();e.isRemoved||(t+=n)}return this.size+=t,this.paddedSize}get isText(){return this.type===Gr}get paddedSize(){return this.size+(this.isText?0:xf)}isAncestorOf(t){return If(this,t)}get nextSibling(){const t=this.parent.findOffset(this),e=this.parent.children[t+1];if(e)return e}get prevSibling(){const t=this.parent.findOffset(this),e=this.parent.children[t-1];if(e)return e}splitText(t,e){if(t===0||t===this.size)return;const n=this.value.slice(0,t),r=this.value.slice(t);if(!r.length)return;this.value=n;const o=this.cloneText(t+e);return o.value=r,this.parent.insertAfterInternal(o,this),o}get children(){return this._children.filter(t=>!t.isRemoved)}get allChildren(){return[...this._children]}hasTextChild(){return this.children.length>0&&this.children.every(t=>t.isText)}append(...t){if(this.isText)throw new ne(te.ErrRefused,"Text node cannot have children");this._children.push(...t);for(const e of t)e.parent=this,e.updateAncestorsSize()}prepend(...t){if(this.isText)throw new ne(te.ErrRefused,"Text node cannot have children");this._children.unshift(...t);for(const e of t)e.parent=this}insertBefore(t,e){if(this.isText)throw new ne(te.ErrRefused,"Text node cannot have children");const n=this._children.indexOf(e);if(n===-1)throw new ne(te.ErrInvalidArgument,"child not found");this.insertAtInternal(t,n),t.updateAncestorsSize()}insertAfter(t,e){if(this.isText)throw new ne(te.ErrRefused,"Text node cannot have children");const n=this._children.indexOf(e);if(n===-1)throw new ne(te.ErrInvalidArgument,"child not found");this.insertAtInternal(t,n+1),t.updateAncestorsSize()}insertAt(t,e){if(this.isText)throw new ne(te.ErrRefused,"Text node cannot have children");this.insertAtInternal(t,e),t.updateAncestorsSize()}removeChild(t){if(this.isText)throw new ne(te.ErrRefused,"Text node cannot have children");const e=this._children.indexOf(t);if(e===-1)throw new ne(te.ErrInvalidArgument,"child not found");this._children.splice(e,1),t.parent=void 0}splitElement(t,e){const n=this.cloneElement(e);this.parent.insertAfterInternal(n,this),n.updateAncestorsSize();const r=this.children.slice(0,t),o=this.children.slice(t);this._children=r,n._children=o,this.size=this._children.reduce((s,u)=>s+u.paddedSize,0),n.size=n._children.reduce((s,u)=>s+u.paddedSize,0);for(const s of n._children)s.parent=n;return n}insertAfterInternal(t,e){if(this.isText)throw new ne(te.ErrRefused,"Text node cannot have children");const n=this._children.indexOf(e);if(n===-1)throw new ne(te.ErrInvalidArgument,"child not found");this.insertAtInternal(t,n+1)}insertAtInternal(t,e){if(this.isText)throw new ne(te.ErrRefused,"Text node cannot have children");this._children.splice(e,0,t),t.parent=this}findOffset(t){if(this.isText)throw new ne(te.ErrRefused,"Text node cannot have children");if(t.isRemoved){const e=this._children.indexOf(t);return this.allChildren.splice(0,e).filter(r=>!r.isRemoved).length}return this.children.indexOf(t)}findBranchOffset(t){if(this.isText)throw new ne(te.ErrRefused,"Text node cannot have children");let e=t;for(;e;){const n=this._children.indexOf(e);if(n!==-1)return n;e=e.parent}return-1}}function If(i,t){if(i===t)return!1;for(;t.parent;){if(t.parent===i)return!0;t=t.parent}return!1}var ut=(i=>(i.Start="Start",i.End="End",i.Text="Text",i))(ut||{});function pu(i,t,e,n){if(t>e)throw new ne(te.ErrInvalidArgument,`from is greater than to: ${t} > ${e}`);if(t>i.size)throw new ne(te.ErrInvalidArgument,`from is out of range: ${t} > ${i.size}`);if(e>i.size)throw new ne(te.ErrInvalidArgument,`to is out of range: ${e} > ${i.size}`);if(t===e)return;let r=0;for(const o of i.children){if(t-o.paddedSizeo.size;(o.isText||c)&&n([o,o.isText?"Text":"Start"],m),pu(o,Math.max(0,s),Math.min(u,o.size),n),m&&n([o,"End"],m)}r+=o.paddedSize}}function mu(i,t,e=0){for(const n of i.children)mu(n,t,e+1);t(i,e)}function ks(i,t,e=0){for(const n of i._children)ks(n,t,e+1);t(i,e)}function ga(i,t,e=!0){if(t>i.size)throw new ne(te.ErrInvalidArgument,`index is out of range: ${t} > ${i.size}`);if(i.isText)return{node:i,offset:t};let n=0,r=0;for(const o of i.children){if(e&&o.isText&&o.size>=t-r)return ga(o,t-r,e);if(t===r)return{node:i,offset:n};if(!e&&o.paddedSize===t-r)return{node:i,offset:n+1};if(o.paddedSize>t-r)return ga(o,t-r-1,e);r+=o.paddedSize,n+=1}return{node:i,offset:n}}function yu(i){return i.isText||i.children.length===0?i:yu(i.children[0])}function Nf(i,t){if(i.sizei===t?0:i0)if(e.right)e.right.parent=e,e=e.right;else return e;else if(n<0)if(e.left)e.left.parent=e,e=e.left;else{let r=e.parent,o=e;for(;r&&o===r.left;)o=r,r=r.parent;return r}else return e}}lastEntry(){if(!this.root)return this.root;let t=this.root;for(;t.right;)t=t.right;return t}size(){return this.counter}isEmpty(){return this.counter===0}getInternal(t,e){for(;e;){const n=this.comparator(t,e.key);if(n===0)return e;n<0?e=e.left:n>0&&(e=e.right)}}putInternal(t,e,n){if(!n)return this.counter+=1,new Cf(t,e,!0);const r=this.comparator(t,n.key);return r<0?n.left=this.putInternal(t,e,n.left):r>0?n.right=this.putInternal(t,e,n.right):n.value=e,this.isRed(n.right)&&!this.isRed(n.left)&&(n=this.rotateLeft(n)),this.isRed(n.left)&&this.isRed(n.left.left)&&(n=this.rotateRight(n)),this.isRed(n.left)&&this.isRed(n.right)&&this.flipColors(n),n}removeInternal(t,e){if(this.comparator(e,t.key)<0)!this.isRed(t.left)&&!this.isRed(t.left.left)&&(t=this.moveRedLeft(t)),t.left=this.removeInternal(t.left,e);else{if(this.isRed(t.left)&&(t=this.rotateRight(t)),this.comparator(e,t.key)===0&&!t.right){this.counter-=1;return}if(!this.isRed(t.right)&&!this.isRed(t.right.left)&&(t=this.moveRedRight(t)),this.comparator(e,t.key)===0){this.counter-=1;const n=this.min(t.right);t.value=n.value,t.key=n.key,t.right=this.removeMin(t.right)}else t.right=this.removeInternal(t.right,e)}return this.fixUp(t)}min(t){return t.left?this.min(t.left):t}removeMin(t){if(t.left)return!this.isRed(t.left)&&!this.isRed(t.left.left)&&(t=this.moveRedLeft(t)),t.left=this.removeMin(t.left),this.fixUp(t)}fixUp(t){return this.isRed(t.right)&&(t=this.rotateLeft(t)),this.isRed(t.left)&&this.isRed(t.left.left)&&(t=this.rotateRight(t)),this.isRed(t.left)&&this.isRed(t.right)&&this.flipColors(t),t}moveRedLeft(t){return this.flipColors(t),this.isRed(t.right.left)&&(t.right=this.rotateRight(t.right),t=this.rotateLeft(t),this.flipColors(t)),t}moveRedRight(t){return this.flipColors(t),this.isRed(t.left.left)&&(t=this.rotateRight(t),this.flipColors(t)),t}isRed(t){return t&&t.isRed}rotateLeft(t){const e=t.right;return t.right=e.left,e.left=t,e.isRed=e.left.isRed,e.left.isRed=!0,e}rotateRight(t){const e=t.left;return t.left=e.right,e.right=t,e.isRed=e.right.isRed,e.right.isRed=!0,e}flipColors(t){t.isRed=!t.isRed,t.left.isRed=!t.left.isRed,t.right.isRed=!t.right.isRed}}class ln{constructor(t,e){T(this,"parentID");T(this,"leftSiblingID");this.parentID=t,this.leftSiblingID=e}static of(t,e){return new ln(t,e)}static fromTreePos(t){const{offset:e}=t;let{node:n}=t,r;return n.isText?(n.parent.children[0]===n&&e===0?r=n.parent:r=n,n=n.parent):e===0?r=n:r=n.children[e-1],ln.of(n.id,pt.of(r.getCreatedAt(),r.getOffset()+e))}getParentID(){return this.parentID}static fromStruct(t){return ln.of(pt.of(Lt.fromStruct(t.parentID.createdAt),t.parentID.offset),pt.of(Lt.fromStruct(t.leftSiblingID.createdAt),t.leftSiblingID.offset))}toStruct(){return{parentID:{createdAt:this.getParentID().getCreatedAt().toStruct(),offset:this.getParentID().getOffset()},leftSiblingID:{createdAt:this.getLeftSiblingID().getCreatedAt().toStruct(),offset:this.getLeftSiblingID().getOffset()}}}toTreeNodePair(t){const e=this.getParentID(),n=this.getLeftSiblingID(),r=t.findFloorNode(e);let o=t.findFloorNode(n);if(!r||!o)throw new ne(te.ErrRefused,`cannot find node of CRDTTreePos(${e.toTestString()}, ${n.toTestString()})`);return!n.equals(e)&&n.getOffset()>0&&n.getOffset()===o.id.getOffset()&&o.insPrevID&&(o=t.findFloorNode(o.insPrevID)),[r,o]}getLeftSiblingID(){return this.leftSiblingID}equals(t){return this.getParentID().getCreatedAt().equals(t.getParentID().getCreatedAt())&&this.getParentID().getOffset()===t.getParentID().getOffset()&&this.getLeftSiblingID().getCreatedAt().equals(t.getLeftSiblingID().getCreatedAt())&&this.getLeftSiblingID().getOffset()===t.getLeftSiblingID().getOffset()}}class pt{constructor(t,e){T(this,"createdAt");T(this,"offset");this.createdAt=t,this.offset=e}static of(t,e){return new pt(t,e)}static fromStruct(t){return pt.of(Lt.fromStruct(t.createdAt),t.offset)}static createComparator(){return(t,e)=>{const n=t.getCreatedAt().compare(e.getCreatedAt());return n!==0?n:t.getOffset()>e.getOffset()?1:t.getOffset(){const o=r.deepcopy();return o.parent=e,o}),e.insPrevID=this.insPrevID,e.insNextID=this.insNextID,e}get value(){if(!this.isText)throw new ne(te.ErrInvalidType,`cannot get value of element node: ${this.type}`);return this._value}set value(e){if(!this.isText)throw new ne(te.ErrInvalidType,`cannot set value of element node: ${this.type}`);this._value=e,this.size=e.length}get isRemoved(){return!!this.removedAt}remove(e){const n=!this.removedAt;(!this.removedAt||this.removedAt.compare(e)>0)&&(this.removedAt=e),n&&this.updateAncestorsSize()}cloneText(e){return new Ct(pt.of(this.id.getCreatedAt(),e),this.type,void 0,void 0,this.removedAt)}cloneElement(e){return new Ct(pt.of(e(),0),this.type,void 0,void 0,this.removedAt)}split(e,n,r){const o=this.isText?this.splitText(n,this.id.getOffset()):this.splitElement(n,r);if(o){if(o.insPrevID=this.id,this.insNextID){const s=e.findFloorNode(this.insNextID);s.insPrevID=o.id,o.insNextID=this.insNextID}this.insNextID=o.id,e.registerNode(o)}return o}getCreatedAt(){return this.id.getCreatedAt()}getOffset(){return this.id.getOffset()}canDelete(e,n){return!this.getCreatedAt().after(n)&&(!this.removedAt||e.after(this.removedAt))}canStyle(e,n){return this.isText?!1:!this.getCreatedAt().after(n)&&(!this.removedAt||e.after(this.removedAt))}setAttrs(e,n){this.attrs||(this.attrs=new Xr);const r=new Array;for(const[o,s]of Object.entries(e))r.push(this.attrs.set(o,s,n));return r}purge(e){this.attrs&&this.attrs.purge(e)}getGCPairs(){const e=[];if(!this.attrs)return e;for(const n of this.attrs)n.getRemovedAt()&&e.push({parent:this,child:n});return e}}function pa(i){var e;if(i.isText){const n=i;return{type:n.type,value:n.value}}const t={type:i.type,children:i.children.map(pa)};return i.attrs&&(t.attributes=$i((e=i.attrs)==null?void 0:e.toObject())),t}function Ea(i){if(i.isText)return i.value;let t="";return i.attrs&&i.attrs.size()&&(t=" "+Array.from(i.attrs).filter(e=>!e.isRemoved()).sort((e,n)=>e.getKey().localeCompare(n.getKey())).map(e=>{const n=JSON.parse(e.getValue());return typeof n=="string"?`${e.getKey()}="${n}"`:`${e.getKey()}="${Fn(e.getValue())}"`}).join(" ")),`<${i.type}${t}>${i.children.map(e=>Ea(e)).join("")}`}function bu(i){if(i.isText){const t=i;return{type:t.type,value:t.value,size:t.size,isRemoved:t.isRemoved}}return{type:i.type,children:i.children.map(bu),size:i.size,isRemoved:i.isRemoved}}class Yt extends Eo{constructor(e,n){super(n);T(this,"indexTree");T(this,"nodeMapByID");this.indexTree=new _f(e),this.nodeMapByID=new vu(pt.createComparator()),this.indexTree.traverseAll(r=>{this.nodeMapByID.put(r.id,r)})}static create(e,n){return new Yt(e,n)}findFloorNode(e){const n=this.nodeMapByID.floorEntry(e);if(!(!n||!n.key.getCreatedAt().equals(e.getCreatedAt())))return n.value}registerNode(e){this.nodeMapByID.put(e.id,e)}findNodesAndSplitText(e,n){const[r,o]=e.toTreeNodePair(this);let s=o;const u=r===s,c=s.parent&&!u?s.parent:r;if(s.isText&&s.split(this,e.getLeftSiblingID().getOffset()-s.id.getOffset()),n){const m=c.allChildren,y=u?0:m.indexOf(s)+1;for(let d=y;d{const b=p.getCreatedAt().getActorID(),w=o?o.has(b)?o.get(b):un:uo;if(p.canStyle(r,w)&&n){const v=l.get(b),h=p.getCreatedAt();(!v||h.after(v))&&l.set(b,h);const g=p.setAttrs(n,r),f=g.reduce((E,[,O])=>(O&&(E[O.getKey()]=d[O.getKey()]),E),{}),A=p.parent,S=p.prevSibling||p.parent;Object.keys(f).length>0&&y.push({type:"style",from:this.toIndex(A,S),to:this.toIndex(p,p),fromPath:this.toPath(A,S),toPath:this.toPath(p,p),actor:r.getActorID(),value:f});for(const[E]of g)E&&a.push({parent:p,child:E})}}),[l,a,y]}removeStyle(e,n,r,o){const[s,u]=this.findNodesAndSplitText(e[0],r),[c,m]=this.findNodesAndSplitText(e[1],r),y=[],d=new Map,l=[];return this.traverseInPosRange(s,u,c,m,([a])=>{const p=a.getCreatedAt().getActorID(),b=o?o.has(p)?o.get(p):un:uo;if(a.canStyle(r,b)&&n){const w=d.get(p),v=a.getCreatedAt();(!w||v.after(w))&&d.set(p,v),a.attrs||(a.attrs=new Xr);for(const f of n){const A=a.attrs.remove(f,r);for(const S of A)l.push({parent:a,child:S})}const h=a.parent,g=a.prevSibling||a.parent;y.push({actor:r.getActorID(),type:"removeStyle",from:this.toIndex(h,g),to:this.toIndex(a,a),fromPath:this.toPath(h,g),toPath:this.toPath(a,a),value:n})}}),[d,l,y]}edit(e,n,r,o,s,u){const[c,m]=this.findNodesAndSplitText(e[0],o),[y,d]=this.findNodesAndSplitText(e[1],o),l=this.toIndex(c,m),a=this.toPath(c,m),p=[],b=[],w=[],v=new Map;this.traverseInPosRange(c,m,y,d,([f,A],S)=>{if(A===ut.Start&&!S)for(const P of f.children)w.push(P);const E=f.getCreatedAt().getActorID(),O=u?u.has(E)?u.get(E):un:uo;if(f.canDelete(o,O)||p.includes(f.parent)){const P=v.get(E),k=f.getCreatedAt();(!P||k.after(P))&&v.set(E,k),(A===ut.Text||A===ut.Start)&&p.push(f),b.push([f,A])}});const h=this.makeDeletionChanges(b,o),g=[];for(const f of p)f.remove(o),f.isRemoved&&g.push({parent:this,child:f});for(const f of w)f.removedAt||c.append(f);if(r>0){let f=0,A=c,S=m;for(;f{c.isRemoved&&(E.remove(o),g.push({parent:this,child:E})),this.nodeMapByID.put(E.id,E)}),S.isRemoved||f.push(S);if(f.length){const S=f.map(E=>pa(E));h.length&&h[h.length-1].from===l?h[h.length-1].value=S:h.push({type:"content",from:l,to:l,fromPath:a,toPath:a,actor:o.getActorID(),value:S})}}return[h,g,v]}editT(e,n,r,o,s){const u=this.findPos(e[0]),c=this.findPos(e[1]);this.edit([u,c],n,r,o,s)}move(e,n,r){throw new ne(te.ErrUnimplemented,`not implemented: ${e}, ${n}, ${r}`)}purge(e){var o;(o=e.parent)==null||o.removeChild(e),this.nodeMapByID.remove(e.id);const n=e.insPrevID,r=e.insNextID;if(n){const s=this.findFloorNode(n);s.insNextID=r}if(r){const s=this.findFloorNode(r);s.insPrevID=n}e.insPrevID=void 0,e.insNextID=void 0}getGCPairs(){const e=[];return this.indexTree.traverse(n=>{n.getRemovedAt()&&e.push({parent:this,child:n});for(const r of n.getGCPairs())e.push(r)}),e}findPos(e,n=!0){const r=this.indexTree.findTreePos(e,n);return ln.fromTreePos(r)}pathToPosRange(e){const n=this.pathToIndex(e);return[this.findPos(n),this.findPos(n+1)]}pathToPos(e){const n=this.indexTree.pathToIndex(e);return this.findPos(n)}getRoot(){return this.indexTree.getRoot()}getSize(){return this.indexTree.size}getNodeSize(){return this.nodeMapByID.size()}getIndexTree(){return this.indexTree}toXML(){return Ea(this.indexTree.getRoot())}toJSON(){return JSON.stringify(this.getRootTreeNode())}toJSForTest(){return{createdAt:this.getCreatedAt().toTestString(),value:JSON.parse(this.toJSON()),type:"YORKIE_TREE"}}toJSInfoForTest(){const e=this.indexTree.getRoot(),n=(r,o=void 0,s=void 0,u=0)=>{var a,p,b,w;let c,m,y;const d=r.isText?{node:r,offset:0}:o&&s?this.toTreePos(o,s):null;d&&(c=this.indexTree.indexOf(d),m=this.indexTree.treePosToPath(d),y=ln.fromTreePos(d).toStruct());const l={type:r.type,parent:o==null?void 0:o.id.toTestString(),size:r.size,id:r.id.toTestString(),removedAt:(a=r.removedAt)==null?void 0:a.toTestString(),insPrev:(p=r.insPrevID)==null?void 0:p.toTestString(),insNext:(b=r.insNextID)==null?void 0:b.toTestString(),value:r.isText?r.value:void 0,isRemoved:r.isRemoved,children:[],depth:u,attributes:r.attrs?$i((w=r.attrs)==null?void 0:w.toObject()):void 0,index:c,path:m,pos:y};for(let v=0;v0&&v===r[r.length-1].to?(r[r.length-1].to=h,r[r.length-1].toPath=this.toPath(w,a)):r.push({type:"content",from:v,to:h,fromPath:this.toPath(b,d),toPath:this.toPath(w,a),actor:n.getActorID()}))}return r.reverse()}findRightToken([e,n]){if(n===ut.Start){const c=e.allChildren;return c.length>0?[c[0],c[0].isText?ut.Text:ut.Start]:[e,ut.End]}const r=e.parent,o=r.allChildren,s=o.indexOf(e);if(r&&s===o.length-1)return[r,ut.End];const u=o[s+1];return[u,u.isText?ut.Text:ut.Start]}findLeftToken([e,n]){if(n===ut.End){const c=e.allChildren;if(c.length>0){const m=c[c.length-1];return[m,m.isText?ut.Text:ut.End]}return[e,ut.Start]}const r=e.parent,o=r.allChildren,s=o.indexOf(e);if(r&&s===0)return[r,ut.Start];const u=o[s-1];return[u,u.isText?ut.Text:ut.End]}}class Io extends fn{constructor(e,n,r,o,s,u,c){super(e,c);T(this,"fromPos");T(this,"toPos");T(this,"contents");T(this,"splitLevel");T(this,"maxCreatedAtMapByActor");this.fromPos=n,this.toPos=r,this.contents=o,this.splitLevel=s,this.maxCreatedAtMapByActor=u}static create(e,n,r,o,s,u,c){return new Io(e,n,r,o,s,u,c)}execute(e){var c;const n=e.findByCreatedAt(this.getParentCreatedAt());if(!n)throw new ne(te.ErrInvalidArgument,`fail to find ${this.getParentCreatedAt()}`);if(!(n instanceof Yt))throw new ne(te.ErrInvalidArgument,"fail to execute, only Tree can execute edit");const r=this.getExecutedAt(),o=n,[s,u]=o.edit([this.fromPos,this.toPos],(c=this.contents)==null?void 0:c.map(m=>m.deepcopy()),this.splitLevel,r,(()=>{let m=r.getDelimiter();return this.contents!==void 0&&(m+=this.contents.length),()=>Lt.of(r.getLamport(),++m,r.getActorID())})(),this.maxCreatedAtMapByActor);for(const m of u)e.registerGCPair(m);return{opInfos:s.map(({from:m,to:y,value:d,splitLevel:l,fromPath:a,toPath:p})=>({type:"tree-edit",path:e.createPath(this.getParentCreatedAt()),from:m,to:y,value:d,splitLevel:l,fromPath:a,toPath:p}))}}getEffectedCreatedAt(){return this.getParentCreatedAt()}toTestString(){const e=this.getParentCreatedAt().toTestString(),n=`${this.fromPos.getLeftSiblingID().getCreatedAt().toTestString()}/${this.fromPos.getLeftSiblingID().getOffset()}`,r=`${this.toPos.getLeftSiblingID().getCreatedAt().toTestString()}/${this.toPos.getLeftSiblingID().getOffset()}`,o=this.contents||[];return`${e}.EDIT(${n},${r},${o.map(s=>Ea(s)).join("")})`}getFromPos(){return this.fromPos}getToPos(){return this.toPos}getContents(){return this.contents}getSplitLevel(){return this.splitLevel}getMaxCreatedAtMapByActor(){return this.maxCreatedAtMapByActor}}class zi{constructor(t){T(this,"vector");this.vector=t||new Map}set(t,e){this.vector.set(t,e)}get(t){return this.vector.get(t)}maxLamport(){let t=BigInt(0);for(const[,e]of this)e>t&&(t=e);return t}max(t){const e=new Map;for(const[n,r]of t){const o=this.vector.get(n),s=o&&o>r?o:r;e.set(n,s)}for(const[n,r]of this){const o=t.get(n),s=o&&o>r?o:r;e.set(n,s)}return new zi(e)}afterOrEqual(t){const e=this.vector.get(t.getActorID());return e===void 0?!1:e>=t.getLamport()}deepcopy(){const t=new Map;for(const[e,n]of this.vector)t.set(e,n);return new zi(t)}filter(t){const e=new Map;for(const[n]of t){const r=this.vector.get(n);r!==void 0&&e.set(n,r)}return new zi(e)}size(){return this.vector.size}*[Symbol.iterator](){for(const[t,e]of this.vector)yield[t,e]}}const Rf=new zi(new Map);class zr{constructor(t,e,n,r,o){T(this,"clientSeq");T(this,"serverSeq");T(this,"lamport");T(this,"actor");T(this,"versionVector");this.clientSeq=t,this.serverSeq=o,this.lamport=e,this.versionVector=r,this.actor=n}static of(t,e,n,r,o){return new zr(t,e,n,r,o)}next(){const t=this.versionVector.deepcopy();return t.set(this.actor,this.lamport+1n),new zr(this.clientSeq+1,this.lamport+1n,this.actor,t)}syncClocks(t){const e=t.lamport>this.lamport?t.lamport+1n:this.lamport+1n,n=this.versionVector.max(t.versionVector),r=new zr(this.clientSeq,e,this.actor,n);return r.versionVector.set(this.actor,e),r}setClocks(t,e){const n=t>this.lamport?t:this.lamport+1n,r=this.versionVector.max(e);return r.set(this.actor,n),zr.of(this.clientSeq,n,this.actor,r)}createTimeTicket(t){return Lt.of(this.lamport,t,this.actor)}setActor(t){return new zr(this.clientSeq,this.lamport,t,this.versionVector,this.serverSeq)}setVersionVector(t){return new zr(this.clientSeq,this.lamport,this.actor,t,this.serverSeq)}getClientSeq(){return this.clientSeq}getServerSeq(){return this.serverSeq?this.serverSeq.toString():""}getLamport(){return this.lamport}getLamportAsString(){return this.lamport.toString()}getActorID(){return this.actor}getVersionVector(){return this.versionVector}toTestString(){return`${this.lamport.toString()}:${this.actor.slice(-2)}:${this.clientSeq}`}}const Df=new zr(0,0n,Aa,Rf);class Zi{constructor({id:t,operations:e,presenceChange:n,message:r}){T(this,"id");T(this,"operations");T(this,"presenceChange");T(this,"message");this.id=t,this.operations=e||[],this.presenceChange=n,this.message=r}static create({id:t,operations:e,presenceChange:n,message:r}){return new Zi({id:t,operations:e,presenceChange:n,message:r})}getID(){return this.id}getMessage(){return this.message}hasOperations(){return this.operations.length>0}getOperations(){return this.operations}setActor(t){for(const e of this.operations)e.setActor(t);this.id=this.id.setActor(t)}hasPresenceChange(){return this.presenceChange!==void 0}getPresenceChange(){return this.presenceChange}execute(t,e,n){const r=[],o=[];for(const s of this.operations){const u=s.execute(t,n);if(!u)continue;const{opInfos:c,reverseOp:m}=u;r.push(...c),m&&o.unshift(m)}return this.presenceChange&&(this.presenceChange.type===pi.Put?e.set(this.id.getActorID(),sn(this.presenceChange.presence)):e.delete(this.id.getActorID())),{opInfos:r,reverseOps:o}}toTestString(){return`${this.operations.map(t=>t.toTestString()).join(",")}`}toStruct(){return{changeID:at.bytesToHex(at.toChangeID(this.getID()).toBinary()),message:this.getMessage(),operations:this.getOperations().map(t=>at.bytesToHex(at.toOperation(t).toBinary())),presenceChange:this.getPresenceChange()}}static fromStruct(t){const{changeID:e,operations:n,presenceChange:r,message:o}=t;return Zi.create({id:at.bytesToChangeID(at.hexToBytes(e)),operations:n==null?void 0:n.map(s=>at.bytesToOperation(at.hexToBytes(s))),presenceChange:r,message:o})}}class Os{constructor(t,e,n,r,o,s,u){T(this,"documentKey");T(this,"checkpoint");T(this,"isRemoved");T(this,"changes");T(this,"snapshot");T(this,"minSyncedTicket");T(this,"versionVector");this.documentKey=t,this.checkpoint=e,this.isRemoved=n,this.changes=r,this.snapshot=s,this.minSyncedTicket=u,this.versionVector=o}static create(t,e,n,r,o,s,u){return new Os(t,e,n,r,o,s,u)}getDocumentKey(){return this.documentKey}getCheckpoint(){return this.checkpoint}getIsRemoved(){return this.isRemoved}getChanges(){return this.changes}hasChanges(){return this.changes.length>0}getChangeSize(){return this.changes.length}hasSnapshot(){return!!this.snapshot&&!!this.snapshot.length}getSnapshot(){return this.snapshot}getMinSyncedTicket(){return this.minSyncedTicket}getVersionVector(){return this.versionVector}}class Vi{constructor(t,e){T(this,"serverSeq");T(this,"clientSeq");this.serverSeq=t,this.clientSeq=e}static of(t,e){return new Vi(t,e)}increaseClientSeq(t){return t===0?this:new Vi(this.serverSeq,this.clientSeq+t)}forward(t){if(this.equals(t))return this;const e=this.serverSeq>t.serverSeq?this.serverSeq:t.serverSeq,n=Math.max(this.clientSeq,t.clientSeq);return Vi.of(e,n)}getServerSeqAsString(){return this.serverSeq.toString()}getClientSeq(){return this.clientSeq}getServerSeq(){return this.serverSeq}equals(t){return this.clientSeq===t.clientSeq&&this.serverSeq==t.serverSeq}toTestString(){return`serverSeq=${this.serverSeq}, clientSeq=${this.clientSeq}`}}const Bf=new Vi(0n,0);class jn{constructor(t,e){T(this,"createdAt");T(this,"offset");this.createdAt=t,this.offset=e}static of(t,e){return new jn(t,e)}static fromStruct(t){return jn.of(Lt.fromStruct(t.createdAt),t.offset)}getCreatedAt(){return this.createdAt}getOffset(){return this.offset}equals(t){return this.createdAt.compare(t.createdAt)===0&&this.offset===t.offset}hasSameCreatedAt(t){return this.createdAt.compare(t.createdAt)===0}split(t){return new jn(this.createdAt,this.offset+t)}toStruct(){return{createdAt:this.createdAt.toStruct(),offset:this.offset}}toTestString(){return`${this.createdAt.toTestString()}:${this.offset}`}toIDString(){return`${this.createdAt.toIDString()}:${this.offset}`}}const Mf=jn.of(un,0);class cn{constructor(t,e){T(this,"id");T(this,"relativeOffset");this.id=t,this.relativeOffset=e}static of(t,e){return new cn(t,e)}static fromStruct(t){const e=jn.fromStruct(t.id);return cn.of(e,t.relativeOffset)}getID(){return this.id}getRelativeOffset(){return this.relativeOffset}getAbsoluteID(){return jn.of(this.id.getCreatedAt(),this.id.getOffset()+this.relativeOffset)}toTestString(){return`${this.id.toTestString()}:${this.relativeOffset}`}toStruct(){return{id:this.id.toStruct(),relativeOffset:this.relativeOffset}}equals(t){return this.id.equals(t.id)?this.relativeOffset===t.relativeOffset:!1}}class di extends cu{constructor(e,n,r){super(n);T(this,"id");T(this,"removedAt");T(this,"prev");T(this,"next");T(this,"insPrev");T(this,"insNext");this.id=e,this.removedAt=r}static create(e,n){return new di(e,n)}static createComparator(){return(e,n)=>{const r=e.getCreatedAt().compare(n.getCreatedAt());return r!==0?r:e.getOffset()>n.getOffset()?1:e.getOffset()0&&e.getID().getOffset()==t.getOffset()){if(!e.hasInsPrev())return e;e=e.getInsPrev()}return e}findFloorNode(t){const e=this.treeByID.floorEntry(t);if(e&&!(!e.key.equals(t)&&!e.key.hasSameCreatedAt(t)))return e.value}findBetween(t,e){const n=[];let r=t;for(;r&&r!==e;)n.push(r),r=r.getNext();return n}splitNode(t,e){if(e>t.getContentLength())throw new ne(te.ErrInvalidArgument,"offset should be less than or equal to length");if(e===0)return t;if(e===t.getContentLength())return t.getNext();const n=t.split(e);this.treeByIndex.updateWeight(n),this.insertAfter(t,n);const r=t.getInsNext();return r&&r.setInsPrev(n),n.setInsPrev(t),n}deleteNodes(t,e,n){if(!t.length)return[[],new Map,new Map];const[r,o]=this.filterNodes(t,e,n),s=new Map,u=new Map,c=this.makeChanges(o,e);for(const m of r){const y=m.getCreatedAt().getActorID();(!s.has(y)||m.getID().getCreatedAt().after(s.get(y)))&&s.set(y,m.getID().getCreatedAt()),u.set(m.getID().toIDString(),m),m.remove(e)}return this.deleteIndexNodes(o),[c,s,u]}filterNodes(t,e,n){const r=!!n,o=[],s=[],[u,c]=this.findEdgesOfCandidates(t);s.push(u);for(const m of t){const y=m.getCreatedAt().getActorID(),d=r?n.has(y)?n.get(y):un:uo;m.canDelete(e,d)?o.push(m):s.push(m)}return s.push(c),[o,s]}findEdgesOfCandidates(t){return[t[0].getPrev(),t[t.length-1].getNext()]}makeChanges(t,e){const n=[];let r,o;for(let s=0;si<0?Math.ceil(i):Math.floor(i);var Un=(i=>(i[i.IntegerCnt=0]="IntegerCnt",i[i.LongCnt=1]="LongCnt",i))(Un||{});class Dt extends Eo{constructor(e,n,r){super(r);T(this,"valueType");T(this,"value");switch(this.valueType=e,e){case 0:typeof n=="number"?n>Math.pow(2,31)-1||n<-Math.pow(2,31)?this.value=Ve.fromNumber(n).toInt():this.value=Tl(n):this.value=n.toInt();break;case 1:typeof n=="number"?this.value=Ve.fromNumber(n):this.value=n;break;default:throw new ne(te.ErrUnimplemented,`unimplemented type: ${e}`)}}static create(e,n,r){return new Dt(e,n,r)}static valueFromBytes(e,n){switch(e){case 0:return n[0]|n[1]<<8|n[2]<<16|n[3]<<24;case 1:return Ve.fromBytesLE(Array.from(n));default:throw new ne(te.ErrUnimplemented,`unimplemented type: ${e}`)}}toJSON(){return`${this.value}`}toSortedJSON(){return this.toJSON()}toJSForTest(){return{createdAt:this.getCreatedAt().toTestString(),value:this.value,type:"YORKIE_COUNTER"}}deepcopy(){const e=Dt.create(this.valueType,this.value,this.getCreatedAt());return e.setMovedAt(this.getMovedAt()),e}getType(){return this.valueType}static getCounterType(e){switch(typeof e){case"object":return e instanceof Ve?1:void 0;case"number":return e>Math.pow(2,31)-1||e<-Math.pow(2,31)?1:0;default:return}}static isSupport(e){return!!Dt.getCounterType(e)}static isInteger(e){return e%1===0}isNumericType(){const e=this.valueType;return e===0||e===1}getValueType(){return this.valueType}getValue(){return this.value}toBytes(){switch(this.valueType){case 0:{const e=this.value;return new Uint8Array([e&255,e>>8&255,e>>16&255,e>>24&255])}case 1:{const n=this.value.toBytesLE();return Uint8Array.from(n)}default:throw new ne(te.ErrUnimplemented,`unimplemented type: ${this.valueType}`)}}increase(e){function n(r){if(!r.isNumericType())throw new TypeError(`Unsupported type of value: ${typeof r.getValue()}`)}return n(this),n(e),this.valueType===1?this.value=this.value.add(e.getValue()):e.getType()===ft.Long?this.value=this.value+e.getValue().toInt():this.value=Ve.fromNumber(this.value+Tl(e.getValue())).toInt(),this}}class Qi extends fn{constructor(e,n,r){super(e,r);T(this,"value");this.value=n}static create(e,n,r){return new Qi(e,n,r)}execute(e){const n=e.findByCreatedAt(this.getParentCreatedAt());if(!n)throw new ne(te.ErrInvalidArgument,`fail to find ${this.getParentCreatedAt()}`);if(!(n instanceof Dt))throw new ne(te.ErrInvalidArgument,"fail to execute, only Counter can execute increase");const r=n,o=this.value.deepcopy();return r.increase(o),{opInfos:[{type:"increase",path:e.createPath(this.getParentCreatedAt()),value:o.getValue()}],reverseOp:this.toReverseOperation()}}toReverseOperation(){const e=this.value.deepcopy(),r=e.getType()===ft.Long?e.getValue().multiply(-1):e.getValue()*-1;return Qi.create(this.getParentCreatedAt(),et.of(r,e.getCreatedAt()))}getEffectedCreatedAt(){return this.getParentCreatedAt()}toTestString(){return`${this.getParentCreatedAt().toTestString()}.INCREASE.${this.value.toJSON()}`}getValue(){return this.value}}class Yr extends fn{constructor(e,n,r,o,s,u,c){super(e,c);T(this,"fromPos");T(this,"toPos");T(this,"maxCreatedAtMapByActor");T(this,"attributes");T(this,"attributesToRemove");this.fromPos=n,this.toPos=r,this.maxCreatedAtMapByActor=o,this.attributes=s,this.attributesToRemove=u}static create(e,n,r,o,s,u){return new Yr(e,n,r,o,s,new Array,u)}static createTreeRemoveStyleOperation(e,n,r,o,s,u){return new Yr(e,n,r,o,new Map,s,u)}execute(e){const n=e.findByCreatedAt(this.getParentCreatedAt());if(!n)throw new ne(te.ErrInvalidArgument,`fail to find ${this.getParentCreatedAt()}`);if(!(n instanceof Yt))throw new ne(te.ErrInvalidArgument,"fail to execute, only Tree can execute edit");const r=n;let o,s;if(this.attributes.size){const u={};[...this.attributes].forEach(([c,m])=>u[c]=m),[,s,o]=r.style([this.fromPos,this.toPos],u,this.getExecutedAt(),this.maxCreatedAtMapByActor)}else{const u=this.attributesToRemove;[,s,o]=r.removeStyle([this.fromPos,this.toPos],u,this.getExecutedAt(),this.maxCreatedAtMapByActor)}for(const u of s)e.registerGCPair(u);return{opInfos:o.map(({from:u,to:c,value:m,fromPath:y,toPath:d})=>({type:"tree-style",from:u,to:c,value:this.attributes.size?{attributes:m}:{attributesToRemove:m},fromPath:y,toPath:d,path:e.createPath(this.getParentCreatedAt())}))}}getEffectedCreatedAt(){return this.getParentCreatedAt()}toTestString(){const e=this.getParentCreatedAt().toTestString(),n=`${this.fromPos.getLeftSiblingID().getCreatedAt().toTestString()}:${this.fromPos.getLeftSiblingID().getOffset()}`,r=`${this.toPos.getLeftSiblingID().getCreatedAt().toTestString()}:${this.toPos.getLeftSiblingID().getOffset()}`;return`${e}.STYLE(${n},${r},${Object.entries(this.attributes||{}).map(([o,s])=>`${o}:"${s}"`).join(" ")})`}getFromPos(){return this.fromPos}getToPos(){return this.toPos}getAttributes(){return this.attributes}getAttributesToRemove(){return this.attributesToRemove}getMaxCreatedAtMapByActor(){return this.maxCreatedAtMapByActor}}function qf(i){const t=new wa,e=t.data;for(const[n,r]of Object.entries(i))e[n]=JSON.stringify(r);return t}function Ff(i){if(i.type===pi.Put)return new mo({type:Ni.PUT,presence:qf(i.presence)});if(i.type===pi.Clear)return new mo({type:Ni.CLEAR});throw new ne(te.ErrUnimplemented,"unimplemented type")}function jf(i){return new au({serverSeq:i.getServerSeq(),clientSeq:i.getClientSeq()})}function wu(i){return new Es({clientSeq:i.getClientSeq(),lamport:i.getLamport(),actorId:Da(i.getActorID()),versionVector:xa(i.getVersionVector())})}function ke(i){if(i)return new xe({lamport:i.getLamport(),delimiter:i.getDelimiter(),actorId:Da(i.getActorID())})}function xa(i){if(!i)return;const t=new xs;for(const[e,n]of i)t.vector[e]=BigInt(n.toString());return t}function Au(i){switch(i){case ft.Null:return Re.NULL;case ft.Boolean:return Re.BOOLEAN;case ft.Integer:return Re.INTEGER;case ft.Long:return Re.LONG;case ft.Double:return Re.DOUBLE;case ft.String:return Re.STRING;case ft.Bytes:return Re.BYTES;case ft.Date:return Re.DATE;default:throw new ne(te.ErrInvalidType,`unsupported type: ${i}`)}}function Tu(i){switch(i){case Un.IntegerCnt:return Re.INTEGER_CNT;case Un.LongCnt:return Re.LONG_CNT;default:throw new ne(te.ErrInvalidType,`unsupported type: ${i}`)}}function Ms(i){if(i instanceof xt)return new Mt({type:Re.JSON_OBJECT,createdAt:ke(i.getCreatedAt()),value:Du(i)});if(i instanceof Rt)return new Mt({type:Re.JSON_ARRAY,createdAt:ke(i.getCreatedAt()),value:yh(i)});if(i instanceof Gt)return new Mt({type:Re.TEXT,createdAt:ke(i.getCreatedAt())});if(i instanceof et)return new Mt({type:Au(i.getType()),createdAt:ke(i.getCreatedAt()),value:i.toBytes()});if(i instanceof Dt)return new Mt({type:Tu(i.getType()),createdAt:ke(i.getCreatedAt()),value:i.toBytes()});if(i instanceof Yt)return new Mt({type:Re.TREE,createdAt:ke(i.getCreatedAt()),value:bh(i)});throw new ne(te.ErrUnimplemented,"unimplemented element")}function Uf(i){return new go({createdAt:ke(i.getCreatedAt()),offset:i.getOffset()})}function Fo(i){return new Zr({createdAt:ke(i.getID().getCreatedAt()),offset:i.getID().getOffset(),relativeOffset:i.getRelativeOffset()})}function jo(i){return new Ii({parentId:co(i.getParentID()),leftSiblingId:co(i.getLeftSiblingID())})}function co(i){return new fi({createdAt:ke(i.getCreatedAt()),offset:i.getOffset()})}function Su(i){const t=new ba;if(i instanceof _i){const e=i,n=new ts;n.parentCreatedAt=ke(e.getParentCreatedAt()),n.key=e.getKey(),n.value=Ms(e.getValue()),n.executedAt=ke(e.getExecutedAt()),t.body.case="set",t.body.value=n}else if(i instanceof xo){const e=i,n=new ns;n.parentCreatedAt=ke(e.getParentCreatedAt()),n.prevCreatedAt=ke(e.getPrevCreatedAt()),n.value=Ms(e.getValue()),n.executedAt=ke(e.getExecutedAt()),t.body.case="add",t.body.value=n}else if(i instanceof ci){const e=i,n=new rs;n.parentCreatedAt=ke(e.getParentCreatedAt()),n.prevCreatedAt=ke(e.getPrevCreatedAt()),n.createdAt=ke(e.getCreatedAt()),n.executedAt=ke(e.getExecutedAt()),t.body.case="move",t.body.value=n}else if(i instanceof mi){const e=i,n=new is;n.parentCreatedAt=ke(e.getParentCreatedAt()),n.createdAt=ke(e.getCreatedAt()),n.executedAt=ke(e.getExecutedAt()),t.body.case="remove",t.body.value=n}else if(i instanceof ko){const e=i,n=new os;n.parentCreatedAt=ke(e.getParentCreatedAt()),n.from=Fo(e.getFromPos()),n.to=Fo(e.getToPos());const r=n.createdAtMapByActor;for(const[s,u]of e.getMaxCreatedAtMapByActor())r[s]=ke(u);n.content=e.getContent();const o=n.attributes;for(const[s,u]of e.getAttributes())o[s]=u;n.executedAt=ke(e.getExecutedAt()),t.body.case="edit",t.body.value=n}else if(i instanceof Oo){const e=i,n=new ss;n.parentCreatedAt=ke(e.getParentCreatedAt()),n.from=Fo(e.getFromPos()),n.to=Fo(e.getToPos());const r=n.createdAtMapByActor;for(const[s,u]of e.getMaxCreatedAtMapByActor())r[s]=ke(u);const o=n.attributes;for(const[s,u]of e.getAttributes())o[s]=u;n.executedAt=ke(e.getExecutedAt()),t.body.case="style",t.body.value=n}else if(i instanceof Qi){const e=i,n=new as;n.parentCreatedAt=ke(e.getParentCreatedAt()),n.value=Ms(e.getValue()),n.executedAt=ke(e.getExecutedAt()),t.body.case="increase",t.body.value=n}else if(i instanceof Io){const e=i,n=new ls,r=n.createdAtMapByActor;for(const[o,s]of e.getMaxCreatedAtMapByActor())r[o]=ke(s);n.parentCreatedAt=ke(e.getParentCreatedAt()),n.from=jo(e.getFromPos()),n.to=jo(e.getToPos()),n.contents=Wf(e.getContents()),n.splitLevel=e.getSplitLevel(),n.executedAt=ke(e.getExecutedAt()),t.body.case="treeEdit",t.body.value=n}else if(i instanceof Yr){const e=i,n=new us;n.parentCreatedAt=ke(e.getParentCreatedAt()),n.from=jo(e.getFromPos()),n.to=jo(e.getToPos());const r=n.createdAtMapByActor;for(const[s,u]of e.getMaxCreatedAtMapByActor())r[s]=ke(u);const o=e.getAttributesToRemove();if(o.length>0)n.attributesToRemove=o;else{const s=n.attributes;for(const[u,c]of e.getAttributes())s[u]=c}n.executedAt=ke(e.getExecutedAt()),t.body.case="treeStyle",t.body.value=n}else throw new ne(te.ErrUnimplemented,"unimplemented operation");return t}function Jf(i){const t=[];for(const e of i)t.push(Su(e));return t}function $f(i){const t=new ou({id:wu(i.getID()),message:i.getMessage()});return i.hasOperations()&&(t.operations=Jf(i.getOperations())),i.hasPresenceChange()&&(t.presenceChange=Ff(i.getPresenceChange())),t}function zf(i){const t=[];for(const e of i)t.push($f(e));return t}function Vf(i){const t=[];for(const e of i)t.push(new su({key:e.getStrKey(),element:Oa(e.getValue())}));return t}function Kf(i){const t=[];for(const e of i)t.push(new ms({element:Oa(e.getValue())}));return t}function Hf(i){const t=[];for(const e of i){const n=new ys;n.id=Uf(e.getID()),n.value=e.getValue().getContent(),n.removedAt=ke(e.getRemovedAt());const r=n.attributes,o=e.getValue().getAttrs();for(const s of o){const u=new Wi;u.value=s.getValue(),u.updatedAt=ke(s.getUpdatedAt()),r[s.getKey()]=u}t.push(n)}return t}function Wf(i){const t=[];if(!i||!i.length)return t;for(const e of i)t.push(new vs({content:ka(e)}));return t}function Gf(i){const t={};for(const e of i)t[e.getKey()]=new Wi({value:e.getValue(),updatedAt:ke(e.getUpdatedAt()),isRemoved:e.isRemoved()});return t}function ka(i){if(!i)return[];const t=[];return ks(i,(e,n)=>{const r=new po({id:co(e.id),type:e.type,removedAt:ke(e.removedAt),depth:n});e.isText&&(r.value=e.value),e.insPrevID&&(r.insPrevId=co(e.insPrevID)),e.insNextID&&(r.insNextId=co(e.insNextID)),e.attrs&&(r.attributes=Gf(e.attrs)),t.push(r)}),t}function Yf(i){const t=new kt;return t.body.case="jsonObject",t.body.value=new cs({nodes:Vf(i.getRHT()),createdAt:ke(i.getCreatedAt()),movedAt:ke(i.getMovedAt()),removedAt:ke(i.getRemovedAt())}),t}function Eu(i){const t=new kt;return t.body.case="jsonArray",t.body.value=new fs({nodes:Kf(i.getElements()),createdAt:ke(i.getCreatedAt()),movedAt:ke(i.getMovedAt()),removedAt:ke(i.getRemovedAt())}),t}function Zf(i){const t=new kt;return t.body.case="primitive",t.body.value=new hs({type:Au(i.getType()),value:i.toBytes(),createdAt:ke(i.getCreatedAt()),movedAt:ke(i.getMovedAt()),removedAt:ke(i.getRemovedAt())}),t}function Xf(i){const t=new kt;return t.body.case="text",t.body.value=new ds({nodes:Hf(i.getRGATreeSplit()),createdAt:ke(i.getCreatedAt()),movedAt:ke(i.getMovedAt()),removedAt:ke(i.getRemovedAt())}),t}function Qf(i){const t=new kt;return t.body.case="counter",t.body.value=new gs({type:Tu(i.getType()),value:i.toBytes(),createdAt:ke(i.getCreatedAt()),movedAt:ke(i.getMovedAt()),removedAt:ke(i.getRemovedAt())}),t}function xu(i){const t=new kt;return t.body.case="tree",t.body.value=new ps({nodes:ka(i.getRoot()),createdAt:ke(i.getCreatedAt()),movedAt:ke(i.getMovedAt()),removedAt:ke(i.getRemovedAt())}),t}function Oa(i){if(i instanceof xt)return Yf(i);if(i instanceof Rt)return Eu(i);if(i instanceof et)return Zf(i);if(i instanceof Gt)return Xf(i);if(i instanceof Dt)return Qf(i);if(i instanceof Yt)return xu(i);throw new ne(te.ErrUnimplemented,"unimplemented element")}function eh(i){return new Qr({documentKey:i.getDocumentKey(),checkpoint:jf(i.getCheckpoint()),isRemoved:i.getIsRemoved(),changes:zf(i.getChanges()),snapshot:i.getSnapshot(),versionVector:xa(i.getVersionVector()),minSyncedTicket:ke(i.getMinSyncedTicket())})}function Sl(i){const t=i.findDetails(mf);for(const e of t)if(e.metadata.code)return e.metadata.code;return""}function ku(i){return zr.of(i.clientSeq,BigInt(i.lamport),La(i.actorId),Ia(i.versionVector),BigInt(i.serverSeq))}function Ia(i){if(!i)return;const t=new zi;return Object.entries(i.vector).forEach(([e,n])=>{t.set(e,BigInt(n.toString()))}),t}function Ie(i){if(i)return Lt.of(BigInt(i.lamport),i.delimiter,La(i.actorId))}function Na(i){const t={};return Object.entries(i.data).forEach(([e,n])=>{t[e]=JSON.parse(n)}),t}function th(i){const t=i.type;if(t===Ni.PUT){const e=Na(i.presence);return{type:pi.Put,presence:e}}if(t===Ni.CLEAR)return{type:pi.Clear};throw new ne(te.ErrInvalidType,`unsupported type: ${t}`)}function nh(i){const t=new Map;return Object.entries(i).forEach(([e,n])=>{t.set(e,Na(n))}),t}function Ou(i){switch(i){case Re.NULL:return ft.Null;case Re.BOOLEAN:return ft.Boolean;case Re.INTEGER:return ft.Integer;case Re.LONG:return ft.Long;case Re.DOUBLE:return ft.Double;case Re.STRING:return ft.String;case Re.BYTES:return ft.Bytes;case Re.DATE:return ft.Date}throw new ne(te.ErrUnimplemented,`unimplemented value type: ${i}`)}function As(i){switch(i){case Re.INTEGER_CNT:return Un.IntegerCnt;case Re.LONG_CNT:return Un.LongCnt}throw new ne(te.ErrUnimplemented,`unimplemented value type: ${i}`)}function qs(i){switch(i.type){case Re.JSON_OBJECT:return i.value?Ru(i.value):xt.create(Ie(i.createdAt));case Re.JSON_ARRAY:return i.value?mh(i.value):Rt.create(Ie(i.createdAt));case Re.TEXT:return Gt.create(Xi.create(),Ie(i.createdAt));case Re.TREE:return vh(i.value);case Re.NULL:case Re.BOOLEAN:case Re.INTEGER:case Re.LONG:case Re.DOUBLE:case Re.STRING:case Re.BYTES:case Re.DATE:return et.of(et.valueFromBytes(Ou(i.type),i.value),Ie(i.createdAt));case Re.INTEGER_CNT:case Re.LONG_CNT:return Dt.create(As(i.type),Dt.valueFromBytes(As(i.type),i.value),Ie(i.createdAt))}}function Uo(i){return cn.of(jn.of(Ie(i.createdAt),i.offset),i.relativeOffset)}function Iu(i){return jn.of(Ie(i.createdAt),i.offset)}function rh(i){const t=wo.create(i.value);Object.entries(i.attributes).forEach(([n,r])=>{t.setAttr(n,r.value,Ie(r.updatedAt))});const e=di.create(Iu(i.id),t);return e.remove(Ie(i.removedAt)),e}function Mi(i){return ln.of(fo(i.parentId),fo(i.leftSiblingId))}function fo(i){return pt.of(Ie(i.createdAt),i.offset)}function ih(i){if(!i.length)return;const t=[];return i.forEach(e=>{const n=_a(e.content);t.push(n)}),t}function _a(i){if(i.length===0)return;const t=[];for(const r of i)t.push(sh(r));const e=t[t.length-1],n=new Map;n.set(i[t.length-1].depth,t[t.length-1]);for(let r=t.length-2;r>=0;r--)n.get(i[r].depth-1).prepend(t[r]),n.set(i[r].depth,t[r]);return e.updateDescendantsSize(),Yt.create(e,un).getRoot()}function oh(i){const t=Xr.create();for(const[e,n]of Object.entries(i))t.setInternal(e,n.value,Ie(n.updatedAt),n.isRemoved);return t}function sh(i){const t=fo(i.id),e=Ct.create(t,i.type),n=Object.entries(i.attributes);return e.isText?e.value=i.value:n.length&&(e.attrs=oh(i.attributes)),i.insPrevId&&(e.insPrevID=fo(i.insPrevId)),i.insNextId&&(e.insNextID=fo(i.insNextId)),e.removedAt=Ie(i.removedAt),e}function Nu(i){if(i.body.case==="set"){const t=i.body.value;return _i.create(t.key,qs(t.value),Ie(t.parentCreatedAt),Ie(t.executedAt))}else if(i.body.case==="add"){const t=i.body.value;return xo.create(Ie(t.parentCreatedAt),Ie(t.prevCreatedAt),qs(t.value),Ie(t.executedAt))}else if(i.body.case==="move"){const t=i.body.value;return ci.create(Ie(t.parentCreatedAt),Ie(t.prevCreatedAt),Ie(t.createdAt),Ie(t.executedAt))}else if(i.body.case==="remove"){const t=i.body.value;return mi.create(Ie(t.parentCreatedAt),Ie(t.createdAt),Ie(t.executedAt))}else if(i.body.case==="edit"){const t=i.body.value,e=new Map;Object.entries(t.createdAtMapByActor).forEach(([r,o])=>{e.set(r,Ie(o))});const n=new Map;return Object.entries(t.attributes).forEach(([r,o])=>{n.set(r,o)}),ko.create(Ie(t.parentCreatedAt),Uo(t.from),Uo(t.to),e,t.content,n,Ie(t.executedAt))}else if(i.body.case==="style"){const t=i.body.value,e=new Map;Object.entries(t.createdAtMapByActor).forEach(([r,o])=>{e.set(r,Ie(o))});const n=new Map;return Object.entries(t.attributes).forEach(([r,o])=>{n.set(r,o)}),Oo.create(Ie(t.parentCreatedAt),Uo(t.from),Uo(t.to),e,n,Ie(t.executedAt))}else{if(i.body.case==="select")return;if(i.body.case==="increase"){const t=i.body.value;return Qi.create(Ie(t.parentCreatedAt),qs(t.value),Ie(t.executedAt))}else if(i.body.case==="treeEdit"){const t=i.body.value,e=new Map;return Object.entries(t.createdAtMapByActor).forEach(([n,r])=>{e.set(n,Ie(r))}),Io.create(Ie(t.parentCreatedAt),Mi(t.from),Mi(t.to),ih(t.contents),t.splitLevel,e,Ie(t.executedAt))}else if(i.body.case==="treeStyle"){const t=i.body.value,e=new Map,n=t.attributesToRemove,r=new Map;return t!=null&&t.createdAtMapByActor&&Object.entries(t.createdAtMapByActor).forEach(([o,s])=>{r.set(o,Ie(s))}),(n==null?void 0:n.length)>0?Yr.createTreeRemoveStyleOperation(Ie(t.parentCreatedAt),Mi(t.from),Mi(t.to),r,n,Ie(t.executedAt)):(Object.entries(t.attributes).forEach(([o,s])=>{e.set(o,s)}),Yr.create(Ie(t.parentCreatedAt),Mi(t.from),Mi(t.to),r,e,Ie(t.executedAt)))}else throw new ne(te.ErrUnimplemented,"unimplemented operation")}}function ah(i){const t=[];for(const e of i){const n=Nu(e);n&&t.push(n)}return t}function _u(i){const t=[];for(const e of i)t.push(Zi.create({id:ku(e.id),operations:ah(e.operations),presenceChange:e.presenceChange?th(e.presenceChange):void 0,message:e.message}));return t}function lh(i){return Vi.of(BigInt(i.serverSeq),i.clientSeq)}function uh(i){return Os.create(i.documentKey,lh(i.checkpoint),i.isRemoved,_u(i.changes),Ia(i.versionVector),i.snapshot,Ie(i.minSyncedTicket))}function Pu(i){const t=new yo;for(const n of i.nodes){const r=Pa(n.element);t.set(n.key,r,r.getPositionedAt())}const e=new xt(Ie(i.createdAt),t);return e.setMovedAt(Ie(i.movedAt)),e.setRemovedAt(Ie(i.removedAt)),e}function Cu(i){const t=new bo;for(const n of i.nodes)t.insert(Pa(n.element));const e=new Rt(Ie(i.createdAt),t);return e.setMovedAt(Ie(i.movedAt)),e.setRemovedAt(Ie(i.removedAt)),e}function ch(i){const t=et.of(et.valueFromBytes(Ou(i.type),i.value),Ie(i.createdAt));return t.setMovedAt(Ie(i.movedAt)),t.setRemovedAt(Ie(i.removedAt)),t}function fh(i){const t=new Xi;let e=t.getHead();for(const r of i.nodes){const o=t.insertAfter(e,rh(r));r.insPrevId&&o.setInsPrev(t.findNode(Iu(r.insPrevId))),e=o}const n=new Gt(t,Ie(i.createdAt));return n.setMovedAt(Ie(i.movedAt)),n.setRemovedAt(Ie(i.removedAt)),n}function hh(i){const t=Dt.create(As(i.type),Dt.valueFromBytes(As(i.type),i.value),Ie(i.createdAt));return t.setMovedAt(Ie(i.movedAt)),t.setRemovedAt(Ie(i.removedAt)),t}function Lu(i){const t=_a(i.nodes);return Yt.create(t,Ie(i.createdAt))}function Pa(i){if(i.body.case==="jsonObject")return Pu(i.body.value);if(i.body.case==="jsonArray")return Cu(i.body.value);if(i.body.case==="primitive")return ch(i.body.value);if(i.body.case==="text")return fh(i.body.value);if(i.body.case==="counter")return hh(i.body.value);if(i.body.case==="tree")return Lu(i.body.value);throw new ne(te.ErrUnimplemented,"unimplemented element")}function dh(i){if(!i)return{root:xt.create(un),presences:new Map};const t=zs.fromBinary(i);return{root:Pa(t.root),presences:nh(t.presences)}}function gh(i){const t=xa(i);return Ca(t.toBinary())}function ph(i){const t=Ra(i),e=xs.fromBinary(t);return Ia(e)}function Ru(i){if(!i)throw new ne(te.ErrInvalidArgument,"bytes is empty");const t=kt.fromBinary(i);return Pu(t.body.value)}function Du(i){return Oa(i).toBinary()}function mh(i){if(!i)throw new ne(te.ErrInvalidArgument,"bytes is empty");const t=kt.fromBinary(i);return Cu(t.body.value)}function yh(i){return Eu(i).toBinary()}function vh(i){if(!i)throw new ne(te.ErrInvalidArgument,"bytes is empty");const t=kt.fromBinary(i);return Lu(t.body.value)}function bh(i){return xu(i).toBinary()}function Ca(i){return i?Array.from(i).map(t=>t.toString(16).padStart(2,"0")).join(""):""}function La(i){return Ca(i)}function Ra(i){return new Uint8Array(i.match(/.{1,2}/g).map(t=>parseInt(t,16)))}function Da(i){return Ra(i)}function wh(i){const t=Es.fromBinary(i);return ku(t)}function Ah(i){const t=ba.fromBinary(i);return Nu(t)}const at={fromPresence:Na,toChangePack:eh,fromChangePack:uh,fromChanges:_u,toTreeNodes:ka,fromTreeNodes:_a,objectToBytes:Du,bytesToObject:Ru,bytesToSnapshot:dh,bytesToHex:Ca,hexToBytes:Ra,toHexString:La,toUint8Array:Da,toOperation:Su,toChangeID:wu,PbChangeID:Es,bytesToChangeID:wh,bytesToOperation:Ah,versionVectorToHex:gh,hexToVersionVector:ph};var wt=(i=>(i[i.Trivial=0]="Trivial",i[i.Debug=1]="Debug",i[i.Info=2]="Info",i[i.Warn=3]="Warn",i[i.Error=4]="Error",i[i.Fatal=5]="Fatal",i))(wt||{});let bi=3;function Bu(i){bi=i}const Ne={trivial:(...i)=>{bi>0||typeof console<"u"&&console.log("YORKIE T:",...i)},debug:(...i)=>{bi>1||typeof console<"u"&&console.log("YORKIE D:",...i)},info:(...i)=>{bi>2||typeof console<"u"&&console.log("YORKIE I:",...i)},warn:(...i)=>{bi>3||typeof console<"u"&&(typeof console.warn<"u"?console.warn("YORKIE W:",...i):console.log("YORKIE W:",...i))},error:(...i)=>{bi>4||typeof console<"u"&&(typeof console.error<"u"?console.error("YORKIE E:",...i):console.log("YORKIE E:",...i))},fatal:(...i)=>{typeof console<"u"&&(typeof console.error<"u"?console.error("YORKIE F:",...i):console.log("YORKIE F:",...i))},isEnabled:i=>bi<=i};function Mu(){return"xxxxxxxx-xxxx-4xxxy-xxxx-xxxxxxxxxxx".replace(/[xy]/g,i=>{const t=Math.random()*16|0;return(i==="x"?t:t&3|8).toString(16)})}class Th{constructor(t,e,n,r,o){T(this,"reconnectStreamDelay");T(this,"doc");T(this,"docID");T(this,"syncMode");T(this,"remoteChangeEventReceived");T(this,"watchStream");T(this,"watchLoopTimerID");T(this,"watchAbortController");T(this,"unsubscribeBroadcastEvent");this.reconnectStreamDelay=t,this.doc=e,this.docID=n,this.syncMode=r,this.remoteChangeEventReceived=!1,this.unsubscribeBroadcastEvent=o}changeSyncMode(t){this.syncMode=t}needRealtimeSync(){return this.syncMode===Zo.RealtimeSyncOff?!1:this.syncMode===Zo.RealtimePushOnly?this.doc.hasLocalChanges():this.syncMode!==Zo.Manual&&(this.doc.hasLocalChanges()||this.remoteChangeEventReceived)}async runWatchLoop(t){const e=async()=>{if(this.watchStream)return Promise.resolve();this.watchLoopTimerID&&(clearTimeout(this.watchLoopTimerID),this.watchLoopTimerID=void 0);try{[this.watchStream,this.watchAbortController]=await t(()=>{this.watchStream=void 0,this.watchAbortController=void 0,this.watchLoopTimerID=setTimeout(e,this.reconnectStreamDelay)})}catch{}};await e()}cancelWatchStream(){this.watchStream&&this.watchAbortController&&(this.watchAbortController.abort(),this.watchStream=void 0,this.watchAbortController=void 0),clearTimeout(this.watchLoopTimerID),this.watchLoopTimerID=void 0}}const Fs=()=>{};class Sh{constructor(t){T(this,"finalized",!1);T(this,"observers",[]);T(this,"finalError");try{t(this)}catch(e){this.error(e)}}next(t){this.forEachObserver(e=>{e.next(t)})}error(t){this.forEachObserver(e=>{e.error(t)}),this.close(t)}complete(){this.forEachObserver(t=>{t.complete()}),this.close()}subscribe(t,e,n){let r;if(!t)throw new ne(te.ErrInvalidArgument,"missing observer");if(this.finalized)throw new ne(te.ErrRefused,"observable is finalized due to previous error");typeof t=="object"?r=t:r={next:t,error:e,complete:n},r.next===void 0&&(r.next=Fs),r.error===void 0&&(r.error=Fs),r.complete===void 0&&(r.complete=Fs);const o=Mu(),s=this.unsubscribeOne.bind(this,o);if(this.observers.push({subscriptionID:o,observer:r}),this.finalized)try{this.finalError?r.error(this.finalError):r.complete()}catch(u){Ne.warn(u)}return s}unsubscribeOne(t){var e;this.observers=(e=this.observers)==null?void 0:e.filter(n=>n.subscriptionID!==t)}forEachObserver(t){if(!this.finalized)for(let e=0;et}}class Ji{constructor(t,e,n,r){T(this,"id");T(this,"delimiter");T(this,"message");T(this,"root");T(this,"operations");T(this,"presenceChange");T(this,"previousPresence");T(this,"reversePresenceKeys");this.id=t,this.delimiter=uu,this.root=e,this.operations=[],this.previousPresence=sn(n),this.presenceChange=void 0,this.reversePresenceKeys=new Set,this.message=r}static create(t,e,n,r){return new Ji(t,e,n,r)}push(t){this.operations.push(t)}registerElement(t,e){this.root.registerElement(t,e)}registerRemovedElement(t){this.root.registerRemovedElement(t)}registerGCPair(t){this.root.registerGCPair(t)}getChange(){return Zi.create({id:this.id,operations:this.operations,presenceChange:this.presenceChange,message:this.message})}hasChange(){return this.operations.length>0||this.presenceChange!==void 0}setPresenceChange(t){this.presenceChange=t}setReversePresence(t,e){for(const n of Object.keys(t))e!=null&&e.addToHistory?this.reversePresenceKeys.add(n):this.reversePresenceKeys.delete(n)}getReversePresence(){if(this.reversePresenceKeys.size===0)return;const t={};for(const e of this.reversePresenceKeys)t[e]=this.previousPresence[e];return t}issueTimeTicket(){return this.delimiter+=1,this.id.createTimeTicket(this.delimiter)}getLastTimeTicket(){return this.id.createTimeTicket(this.delimiter)}}class Ao{constructor(t){T(this,"rootObject");T(this,"elementPairMapByCreatedAt");T(this,"gcElementSetByCreatedAt");T(this,"gcPairMap");this.rootObject=t,this.elementPairMapByCreatedAt=new Map,this.gcElementSetByCreatedAt=new Set,this.gcPairMap=new Map,this.registerElement(t,void 0),t.getDescendants(e=>{if(e.getRemovedAt()&&this.registerRemovedElement(e),e instanceof Gt||e instanceof Yt)for(const n of e.getGCPairs())this.registerGCPair(n);return!1})}static create(){return new Ao(xt.create(un))}findByCreatedAt(t){const e=this.elementPairMapByCreatedAt.get(t.toIDString());if(e)return e.element}findElementPairByCreatedAt(t){return this.elementPairMapByCreatedAt.get(t.toIDString())}createSubPaths(t){let e=this.elementPairMapByCreatedAt.get(t.toIDString());if(!e)return[];const n=[];for(;e.parent;){const r=e.element.getCreatedAt(),o=e.parent.subPathOf(r);if(o===void 0)throw new ne(te.ErrInvalidArgument,`cant find the given element: ${r.toIDString()}`);n.unshift(o),e=this.elementPairMapByCreatedAt.get(e.parent.getCreatedAt().toIDString())}return n.unshift("$"),n}createPath(t){return this.createSubPaths(t).join(".")}registerElement(t,e){this.elementPairMapByCreatedAt.set(t.getCreatedAt().toIDString(),{parent:e,element:t}),t instanceof hi&&t.getDescendants((n,r)=>(this.registerElement(n,r),!1))}deregisterElement(t){let e=0;const n=r=>{const o=r.getCreatedAt().toIDString();this.elementPairMapByCreatedAt.delete(o),this.gcElementSetByCreatedAt.delete(o),e++};return n(t),t instanceof hi&&t.getDescendants(r=>(n(r),!1)),e}registerRemovedElement(t){this.gcElementSetByCreatedAt.add(t.getCreatedAt().toIDString())}registerGCPair(t){if(this.gcPairMap.get(t.child.toIDString())){this.gcPairMap.delete(t.child.toIDString());return}this.gcPairMap.set(t.child.toIDString(),t)}getElementMapSize(){return this.elementPairMapByCreatedAt.size}getGarbageElementSetSize(){const t=new Set;for(const e of this.gcElementSetByCreatedAt){t.add(e);const n=this.elementPairMapByCreatedAt.get(e);n.element instanceof hi&&n.element.getDescendants(r=>(t.add(r.getCreatedAt().toIDString()),!1))}return t.size}getObject(){return this.rootObject}getGarbageLen(){return this.getGarbageElementSetSize()+this.gcPairMap.size}deepcopy(){return new Ao(this.rootObject.deepcopy())}garbageCollect(t){let e=0;for(const n of this.gcElementSetByCreatedAt){const r=this.elementPairMapByCreatedAt.get(n),o=r.element.getRemovedAt();o&&(t!=null&&t.afterOrEqual(o))&&(r.parent.purge(r.element),e+=this.deregisterElement(r.element))}for(const[,n]of this.gcPairMap){const r=n.child.getRemovedAt();r&&(t!=null&&t.afterOrEqual(r))&&(n.parent.purge(n.child),this.gcPairMap.delete(n.child.toIDString()),e+=1)}return e}toJSON(){return this.rootObject.toJSON()}toSortedJSON(){return this.rootObject.toSortedJSON()}getStats(){return{elements:this.getElementMapSize(),gcPairs:this.gcPairMap.size,gcElements:this.getGarbageElementSetSize()}}}function qu(i,t){const e=new To(i);return new Proxy(t,e.getHandlers())}class To{constructor(t){T(this,"context");T(this,"handlers");this.context=t,this.handlers={set:(e,n,r)=>(Ne.isEnabled(wt.Trivial)&&Ne.trivial(`obj[${n}]=${JSON.stringify(r)}`),To.setInternal(t,e,n,r),!0),get:(e,n)=>(Ne.isEnabled(wt.Trivial)&&Ne.trivial(`obj[${n}]`),n==="getID"?()=>e.getCreatedAt():n==="toJSON"||n==="toString"?()=>e.toJSON():n==="toJS"?()=>e.toJS():n==="toJSForTest"?()=>e.toJSForTest():wi(t,e.get(n))),ownKeys:e=>e.getKeys(),getOwnPropertyDescriptor:()=>({enumerable:!0,configurable:!0}),deleteProperty:(e,n)=>(Ne.isEnabled(wt.Trivial)&&Ne.trivial(`obj[${n}]`),To.deleteInternal(t,e,n),!0)}}static setInternal(t,e,n,r){if(n.includes("."))throw new ne(te.ErrInvalidObjectKey,"key must not contain the '.'.");const o=t.issueTimeTicket(),s=Ts(t,r,o),u=e.set(n,s,o);t.registerElement(s,e),u&&t.registerRemovedElement(u),t.push(_i.create(n,s.deepcopy(),e.getCreatedAt(),o))}static buildObjectMembers(t,e){const n={};for(const[r,o]of Object.entries(e)){if(r.includes("."))throw new ne(te.ErrInvalidObjectKey,"key must not contain the '.'.");const s=t.issueTimeTicket(),u=Ts(t,o,s);n[r]=u}return n}static deleteInternal(t,e,n){const r=t.issueTimeTicket(),o=e.deleteByKey(n,r);o&&(t.push(mi.create(e.getCreatedAt(),o.getCreatedAt(),r)),t.registerRemovedElement(o))}getHandlers(){return this.handlers}}function xh(i,t){const e=new nt(i,t);return new Proxy(t,e.getHandlers())}function kh(i){return typeof i=="string"||i instanceof String?!isNaN(i):!1}function Oh(i){return["concat","entries","every","filter","find","findIndex","forEach","join","keys","map","reduce","reduceRight","slice","some","toLocaleString","toString","values"].includes(i)}class nt{constructor(t,e){T(this,"context");T(this,"handlers");T(this,"array");this.context=t,this.array=e,this.handlers={get:(n,r,o)=>r==="getID"?()=>n.getCreatedAt():r==="getElementByID"?s=>{const u=n.getByID(s);if(!(!u||u.isRemoved()))return oi(t,u)}:r==="getElementByIndex"?s=>{const u=n.get(s);return oi(t,u)}:r==="getLast"?()=>oi(t,n.getLast()):r==="deleteByID"?s=>{const u=nt.deleteInternalByID(t,n,s);return oi(t,u)}:r==="insertAfter"?(s,u)=>{const c=nt.insertAfterInternal(t,n,s,u);return oi(t,c)}:r==="insertBefore"?(s,u)=>{const c=nt.insertBeforeInternal(t,n,s,u);return oi(t,c)}:r==="moveBefore"?(s,u)=>{nt.moveBeforeInternal(t,n,s,u)}:r==="moveAfter"?(s,u)=>{nt.moveAfterInternal(t,n,s,u)}:r==="moveFront"?s=>{nt.moveFrontInternal(t,n,s)}:r==="moveLast"?s=>{nt.moveLastInternal(t,n,s)}:kh(r)?wi(t,n.get(Number(r))):r==="push"?s=>nt.pushInternal(t,n,s):r==="splice"?(s,u,...c)=>nt.splice(t,n,s,u,...c):r==="length"?n.length:typeof r=="symbol"&&r===Symbol.iterator?nt.iteratorInternal.bind(this,t,n):r==="includes"?(s,u)=>nt.includes(t,n,s,u):r==="indexOf"?(s,u)=>nt.indexOf(t,n,s,u):r==="lastIndexOf"?(s,u)=>nt.lastIndexOf(t,n,s,u):r==="toJSForTest"?()=>n.toJSForTest():r==="toTestString"?()=>nt.toTestString(n):typeof r=="string"&&Oh(r)?(...s)=>{const u=Array.from(n).map(c=>wi(t,c));return Array.prototype[r].apply(u,s)}:Reflect.get(n,r,o),deleteProperty:(n,r)=>(Ne.isEnabled(wt.Trivial)&&Ne.trivial(`array[${r}]`),nt.deleteInternalByIndex(t,n,Number.parseInt(r)),!0)}}static*iteratorInternal(t,e){for(const n of e)yield oi(t,n)}static buildArrayElements(t,e){const n=[];for(const r of e){const o=t.issueTimeTicket(),s=Ts(t,r,o);n.push(s)}return n}static pushInternal(t,e,n){return nt.insertAfterInternal(t,e,e.getLastCreatedAt(),n),e.length}static moveBeforeInternal(t,e,n,r){const o=t.issueTimeTicket(),s=e.getPrevCreatedAt(n);e.moveAfter(s,r,o),t.push(ci.create(e.getCreatedAt(),s,r,o))}static moveAfterInternal(t,e,n,r){const o=t.issueTimeTicket();e.moveAfter(n,r,o),t.push(ci.create(e.getCreatedAt(),n,r,o))}static moveFrontInternal(t,e,n){const r=t.issueTimeTicket(),o=e.getHead();e.moveAfter(o.getCreatedAt(),n,r),t.push(ci.create(e.getCreatedAt(),o.getCreatedAt(),n,r))}static moveLastInternal(t,e,n){const r=t.issueTimeTicket(),o=e.getLastCreatedAt();e.moveAfter(o,n,r),t.push(ci.create(e.getCreatedAt(),o,n,r))}static insertAfterInternal(t,e,n,r){const o=t.issueTimeTicket(),s=Ts(t,r,o);return e.insertAfter(n,s),t.registerElement(s,e),t.push(xo.create(e.getCreatedAt(),n,s.deepcopy(),o)),s}static insertBeforeInternal(t,e,n,r){return nt.insertAfterInternal(t,e,e.getPrevCreatedAt(n),r)}static deleteInternalByIndex(t,e,n){const r=t.issueTimeTicket(),o=e.deleteByIndex(n,r);if(o)return t.push(mi.create(e.getCreatedAt(),o.getCreatedAt(),r)),t.registerRemovedElement(o),o}static deleteInternalByID(t,e,n){const r=t.issueTimeTicket(),o=e.delete(n,r);return t.push(mi.create(e.getCreatedAt(),o.getCreatedAt(),r)),t.registerRemovedElement(o),o}static splice(t,e,n,r,...o){const s=e.length,u=n>=0?Math.min(n,s):Math.max(s+n,0),c=r===void 0?s:r<0?u:Math.min(u+r,s),m=[];for(let y=u;y=o)return!1;if(et.isSupport(n))return Array.from(e).map(m=>wi(t,m)).includes(n,s);for(let c=s;c=o)return-1;if(et.isSupport(n))return Array.from(e).map(m=>wi(t,m)).indexOf(n,s);for(let c=s;c=o?o-1:r<0?r+o:r;if(s<0)return-1;if(et.isSupport(n))return Array.from(e).map(m=>wi(t,m)).lastIndexOf(n,s);for(let c=s;c>0;c--)if(((u=e.get(c))==null?void 0:u.getID())===n.getID())return c;return-1}static toTestString(t){return t.toTestString()}getHandlers(){return this.handlers}}let Is=class{constructor(t,e){T(this,"context");T(this,"text");this.context=t,this.text=e}initialize(t,e){this.context=t,this.text=e}getID(){return this.text.getID()}edit(t,e,n,r){if(!this.context||!this.text)throw new ne(te.ErrNotInitialized,"Text is not initialized yet");if(t>e)throw new ne(te.ErrInvalidArgument,"from should be less than or equal to to");const o=this.text.indexRangeToPosRange(t,e);Ne.isEnabled(wt.Debug)&&Ne.debug(`EDIT: f:${t}->${o[0].toTestString()}, t:${e}->${o[1].toTestString()} c:${n}`);const s=r?Gi(r):void 0,u=this.context.issueTimeTicket(),[c,,m,y]=this.text.edit(o,n,u,s);for(const d of m)this.context.registerGCPair(d);return this.context.push(new ko(this.text.getCreatedAt(),o[0],o[1],c,n,s?new Map(Object.entries(s)):new Map,u)),this.text.findIndexesFromRange(y)}delete(t,e){return this.edit(t,e,"")}empty(){return this.edit(0,this.length,"")}setStyle(t,e,n){if(!this.context||!this.text)throw new ne(te.ErrNotInitialized,"Text is not initialized yet");if(t>e)throw new ne(te.ErrInvalidArgument,"from should be less than or equal to to");const r=this.text.indexRangeToPosRange(t,e);Ne.isEnabled(wt.Debug)&&Ne.debug(`STYL: f:${t}->${r[0].toTestString()}, t:${e}->${r[1].toTestString()} a:${JSON.stringify(n)}`);const o=Gi(n),s=this.context.issueTimeTicket(),[u,c]=this.text.setStyle(r,o,s);for(const m of c)this.context.registerGCPair(m);return this.context.push(new Oo(this.text.getCreatedAt(),r[0],r[1],u,new Map(Object.entries(o)),s)),!0}indexRangeToPosRange(t){if(!this.context||!this.text)throw new ne(te.ErrNotInitialized,"Text is not initialized yet");const e=this.text.indexRangeToPosRange(t[0],t[1]);return[e[0].toStruct(),e[1].toStruct()]}posRangeToIndexRange(t){if(!this.context||!this.text)throw new ne(te.ErrNotInitialized,"Text is not initialized yet");const e=this.text.findIndexesFromRange([cn.fromStruct(t[0]),cn.fromStruct(t[1])]);return[e[0],e[1]]}toTestString(){if(!this.context||!this.text)throw new ne(te.ErrNotInitialized,"Text is not initialized yet");return this.text.toTestString()}values(){if(!this.context||!this.text)throw new ne(te.ErrNotInitialized,"Text is not initialized yet");return this.text.values()}get length(){return this.text.length}getTreeByIndex(){return this.text.getTreeByIndex()}getTreeByID(){return this.text.getTreeByID()}toString(){if(!this.context||!this.text)throw new ne(te.ErrNotInitialized,"Text is not initialized yet");return this.text.toString()}toJSON(){if(!this.context||!this.text)throw new ne(te.ErrNotInitialized,"Text is not initialized yet");return this.text.toJSON()}toJSForTest(){if(!this.context||!this.text)throw new ne(te.ErrNotInitialized,"Text is not initialized yet");return this.text.toJSForTest()}createRangeForTest(t,e){if(!this.context||!this.text)throw new ne(te.ErrNotInitialized,"Text is not initialized yet");return this.text.indexRangeToPosRange(t,e)}};class Ns{constructor(t,e){T(this,"valueType");T(this,"value");T(this,"context");T(this,"counter");this.valueType=t,this.value=e}initialize(t,e){this.valueType=e.getValueType(),this.context=t,this.counter=e,this.value=e.getValue()}getID(){return this.counter.getID()}getValue(){return this.value}getValueType(){return this.valueType}increase(t){if(!this.context||!this.counter)throw new ne(te.ErrNotInitialized,"Counter is not initialized yet");const e=this.context.issueTimeTicket(),n=et.of(t,e);if(!n.isNumericType())throw new TypeError(`Unsupported type of value: ${typeof n.getValue()}`);return this.counter.increase(n),this.context.push(Qi.create(this.counter.getCreatedAt(),n,e)),this}toJSForTest(){if(!this.context||!this.counter)throw new ne(te.ErrNotInitialized,"Counter is not initialized yet");return this.counter.toJSForTest()}}function Ba(i,t,e){const{type:n}=i,r=e.issueTimeTicket();if(n===Gr){Fu(i);const{value:o}=i,s=Ct.create(pt.of(r,0),n,o);t.append(s)}else{const{children:o=[]}=i,{attributes:s}=i;let u;if(typeof s=="object"&&!lu(s)){const m=Gi(s);u=new Xr;for(const[y,d]of Object.entries(m))u.set(y,d,r)}const c=Ct.create(pt.of(r,0),n,void 0,u);t.append(c);for(const m of o)Ba(m,c,e)}}function Ih(i,t){const{type:e}=t,n=i.issueTimeTicket();let r;if(t.type===Gr){const{value:o}=t;r=Ct.create(pt.of(n,0),e,o)}else if(t){const{children:o=[]}=t,{attributes:s}=t;let u;if(typeof s=="object"&&!lu(s)){const c=Gi(s);u=new Xr;for(const[m,y]of Object.entries(c))u.set(m,y,n)}r=Ct.create(pt.of(i.issueTimeTicket(),0),e,void 0,u);for(const c of o)Ba(c,r,i)}return r}function Fu(i){if(!i.value.length)throw new ne(te.ErrInvalidArgument,"text node cannot have empty value");return!0}function El(i){if(!i.length)return!0;if(i[0].type===Gr)for(const e of i){const{type:n}=e;if(n!==Gr)throw new ne(te.ErrInvalidArgument,"element node and text node cannot be passed together");Fu(e)}else for(const e of i){const{type:n}=e;if(n===Gr)throw new ne(te.ErrInvalidArgument,"element node and text node cannot be passed together")}return!0}class _s{constructor(t){T(this,"initialRoot");T(this,"context");T(this,"tree");this.initialRoot=t}initialize(t,e){this.context=t,this.tree=e}getID(){return this.tree.getID()}buildRoot(t){if(!this.initialRoot)return Ct.create(pt.of(t.issueTimeTicket(),0),kf);const e=Ct.create(pt.of(t.issueTimeTicket(),0),this.initialRoot.type);for(const n of this.initialRoot.children)Ba(n,e,t);return e}getSize(){if(!this.context||!this.tree)throw new ne(te.ErrNotInitialized,"Tree is not initialized yet");return this.tree.getSize()}getNodeSize(){if(!this.context||!this.tree)throw new ne(te.ErrNotInitialized,"Tree is not initialized yet");return this.tree.getNodeSize()}getIndexTree(){if(!this.context||!this.tree)throw new ne(te.ErrNotInitialized,"Tree is not initialized yet");return this.tree.getIndexTree()}styleByPath(t,e){if(!this.context||!this.tree)throw new ne(te.ErrNotInitialized,"Tree is not initialized yet");if(!t.length)throw new ne(te.ErrInvalidArgument,"path should not be empty");const[n,r]=this.tree.pathToPosRange(t),o=this.context.issueTimeTicket(),s=e?Gi(e):void 0,[u]=this.tree.style([n,r],s,o);this.context.push(Yr.create(this.tree.getCreatedAt(),n,r,u,s?new Map(Object.entries(s)):new Map,o))}style(t,e,n){if(!this.context||!this.tree)throw new ne(te.ErrNotInitialized,"Tree is not initialized yet");if(t>e)throw new ne(te.ErrInvalidArgument,"from should be less than or equal to to");const r=this.tree.findPos(t),o=this.tree.findPos(e),s=this.context.issueTimeTicket(),u=n?Gi(n):void 0,[c,m]=this.tree.style([r,o],u,s);for(const y of m)this.context.registerGCPair(y);this.context.push(Yr.create(this.tree.getCreatedAt(),r,o,c,u?new Map(Object.entries(u)):new Map,s))}removeStyle(t,e,n){if(!this.context||!this.tree)throw new ne(te.ErrNotInitialized,"Tree is not initialized yet");if(t>e)throw new ne(te.ErrInvalidArgument,"from should be less than or equal to to");const r=this.tree.findPos(t),o=this.tree.findPos(e),s=this.context.issueTimeTicket(),[u,c]=this.tree.removeStyle([r,o],n,s);for(const m of c)this.context.registerGCPair(m);this.context.push(Yr.createTreeRemoveStyleOperation(this.tree.getCreatedAt(),r,o,u,n,s))}editInternal(t,e,n,r=0){var m;if(n.length!==0&&n[0]&&(El(n),n[0].type!==Gr))for(const y of n){const{children:d=[]}=y;El(d)}const o=this.context.getLastTimeTicket();let s=new Array;if(((m=n[0])==null?void 0:m.type)===Gr){let y="";for(const d of n){const{value:l}=d;y+=l}s.push(Ct.create(pt.of(this.context.issueTimeTicket(),0),Gr,y))}else s=n.map(y=>y&&Ih(this.context,y)).filter(y=>y);const[,u,c]=this.tree.edit([t,e],s.length?s.map(y=>y==null?void 0:y.deepcopy()):void 0,r,o,()=>this.context.issueTimeTicket());for(const y of u)this.context.registerGCPair(y);return this.context.push(Io.create(this.tree.getCreatedAt(),t,e,s.length?s:void 0,r,c,o)),!0}editByPath(t,e,n,r=0){if(!this.context||!this.tree)throw new ne(te.ErrNotInitialized,"Tree is not initialized yet");if(t.length!==e.length)throw new ne(te.ErrInvalidArgument,"path length should be equal");if(!t.length||!e.length)throw new ne(te.ErrInvalidArgument,"path should not be empty");const o=this.tree.pathToPos(t),s=this.tree.pathToPos(e);return this.editInternal(o,s,n?[n]:[],r)}editBulkByPath(t,e,n,r=0){if(!this.context||!this.tree)throw new ne(te.ErrNotInitialized,"Tree is not initialized yet");if(t.length!==e.length)throw new ne(te.ErrInvalidArgument,"path length should be equal");if(!t.length||!e.length)throw new ne(te.ErrInvalidArgument,"path should not be empty");const o=this.tree.pathToPos(t),s=this.tree.pathToPos(e);return this.editInternal(o,s,n,r)}edit(t,e,n,r=0){if(!this.context||!this.tree)throw new ne(te.ErrNotInitialized,"Tree is not initialized yet");if(t>e)throw new ne(te.ErrInvalidArgument,"from should be less than or equal to to");const o=this.tree.findPos(t),s=this.tree.findPos(e);return this.editInternal(o,s,n?[n]:[],r)}editBulk(t,e,n,r=0){if(!this.context||!this.tree)throw new ne(te.ErrNotInitialized,"Tree is not initialized yet");if(t>e)throw new ne(te.ErrInvalidArgument,"from should be less than or equal to to");const o=this.tree.findPos(t),s=this.tree.findPos(e);return this.editInternal(o,s,n,r)}toXML(){if(!this.context||!this.tree)throw new ne(te.ErrNotInitialized,"Tree is not initialized yet");return this.tree.toXML()}toJSON(){if(!this.context||!this.tree)throw new ne(te.ErrNotInitialized,"Tree is not initialized yet");return this.tree.toJSON()}toJSForTest(){if(!this.context||!this.tree)throw new ne(te.ErrNotInitialized,"Tree is not initialized yet");return this.tree.toJSForTest()}toJSInfoForTest(){if(!this.context||!this.tree)throw new ne(te.ErrNotInitialized,"Tree is not initialized yet");return this.tree.toJSInfoForTest()}getRootTreeNode(){if(!this.context||!this.tree)throw new ne(te.ErrNotInitialized,"Tree is not initialized yet");return this.tree.getRootTreeNode()}indexToPath(t){if(!this.context||!this.tree)throw new ne(te.ErrNotInitialized,"Tree is not initialized yet");return this.tree.indexToPath(t)}pathToIndex(t){if(!this.context||!this.tree)throw new ne(te.ErrNotInitialized,"Tree is not initialized yet");return this.tree.pathToIndex(t)}pathRangeToPosRange(t){if(!this.context||!this.tree)throw new ne(te.ErrNotInitialized,"Tree is not initialized yet");const e=[this.tree.pathToIndex(t[0]),this.tree.pathToIndex(t[1])],n=this.tree.indexRangeToPosRange(e);return[n[0].toStruct(),n[1].toStruct()]}indexRangeToPosRange(t){if(!this.context||!this.tree)throw new ne(te.ErrNotInitialized,"Tree is not initialized yet");return this.tree.indexRangeToPosStructRange(t)}posRangeToIndexRange(t){if(!this.context||!this.tree)throw new ne(te.ErrNotInitialized,"Tree is not initialized yet");const e=[ln.fromStruct(t[0]),ln.fromStruct(t[1])];return this.tree.posRangeToIndexRange(e)}posRangeToPathRange(t){if(!this.context||!this.tree)throw new ne(te.ErrNotInitialized,"Tree is not initialized yet");const e=[ln.fromStruct(t[0]),ln.fromStruct(t[1])];return this.tree.posRangeToPathRange(e)}}function xl(i,t){return qu(i,t)}function oi(i,t){if(t){if(t instanceof et)return t;if(t instanceof xt)return qu(i,t);if(t instanceof Rt)return xh(i,t);if(t instanceof Gt)return new Is(i,t);if(t instanceof Dt){const e=new Ns(Un.IntegerCnt,0);return e.initialize(i,t),e}else if(t instanceof Yt){const e=new _s;return e.initialize(i,t),e}}else return;throw new TypeError(`Unsupported type of element: ${typeof t}`)}function wi(i,t){const e=oi(i,t);return e instanceof et?e.getValue():e}function Ts(i,t,e){let n;if(et.isSupport(t))n=et.of(t,e);else if(Array.isArray(t))n=Rt.create(e,nt.buildArrayElements(i,t));else if(typeof t=="object")t instanceof Is?(n=Gt.create(Xi.create(),e),t.initialize(i,n)):t instanceof Ns?(n=Dt.create(t.getValueType(),t.getValue(),e),t.initialize(i,n)):t instanceof _s?(n=Yt.create(t.buildRoot(i),e),t.initialize(i,n)):n=xt.create(e,To.buildObjectMembers(i,t));else throw new TypeError(`Unsupported type of value: ${typeof t}`);return n}const kl=50;class Nh{constructor(){T(this,"undoStack",[]);T(this,"redoStack",[])}hasUndo(){return this.undoStack.length>0}hasRedo(){return this.redoStack.length>0}pushUndo(t){this.undoStack.length>=kl&&this.undoStack.shift(),this.undoStack.push(t)}popUndo(){return this.undoStack.pop()}pushRedo(t){this.redoStack.length>=kl&&this.redoStack.shift(),this.redoStack.push(t)}popRedo(){return this.redoStack.pop()}clearRedo(){this.redoStack=[]}getUndoStackForTest(){return this.undoStack}getRedoStackForTest(){return this.redoStack}}const _h="yorkie-devtools-panel",Ph="yorkie-devtools-sdk";let qi="disconnected";const Ol=new Map,Yo=new Map;typeof window<"u"&&(window.transactionEventsByDocKey=Yo);function Jo(i,t){(t!=null&&t.force||qi!=="disconnected")&&window.postMessage({source:Ph,...i},"*")}function Ch(i){if(!i.isEnableDevtools()||typeof window>"u"||Ol.has(i.getKey()))return;Yo.set(i.getKey(),[]);const t=i.subscribe("all",e=>{e.some(n=>n.type!==gt.StatusChanged&&n.type!==gt.Snapshot&&n.type!==gt.LocalChange&&n.type!==gt.RemoteChange&&n.type!==gt.Initialized&&n.type!==gt.Watched&&n.type!==gt.Unwatched&&n.type!==gt.PresenceChanged)||(Yo.get(i.getKey()).push(e),qi==="synced"&&Jo({msg:"doc::sync::partial",docKey:i.getKey(),event:e}))});Ol.set(i.getKey(),[t]),Jo({msg:"refresh-devtools"},{force:!0}),window.addEventListener("message",e=>{var r;if(((r=e.data)==null?void 0:r.source)!==_h)return;switch(e.data.msg){case"devtools::connect":if(qi!=="disconnected")break;qi="connected",Jo({msg:"doc::available",docKey:i.getKey()}),Ne.info(`[YD] Devtools connected. Doc: ${i.getKey()}`);break;case"devtools::disconnect":qi="disconnected",Ne.info(`[YD] Devtools disconnected. Doc: ${i.getKey()}`);break;case"devtools::subscribe":qi="synced",Jo({msg:"doc::sync::full",docKey:i.getKey(),events:Yo.get(i.getKey())}),Ne.info(`[YD] Devtools subscribed. Doc: ${i.getKey()}`);break}})}var si=(i=>(i.Detached="detached",i.Attached="attached",i.Removed="removed",i))(si||{}),gt=(i=>(i.StatusChanged="status-changed",i.ConnectionChanged="connection-changed",i.SyncStatusChanged="sync-status-changed",i.Snapshot="snapshot",i.LocalChange="local-change",i.RemoteChange="remote-change",i.Initialized="initialized",i.Watched="watched",i.Unwatched="unwatched",i.PresenceChanged="presence-changed",i.Broadcast="broadcast",i.LocalBroadcast="local-broadcast",i))(gt||{}),So=(i=>(i.Connected="connected",i.Disconnected="disconnected",i))(So||{}),ma=(i=>(i.Synced="synced",i.SyncFailed="sync-failed",i))(ma||{});class ju{constructor(t,e){T(this,"key");T(this,"status");T(this,"opts");T(this,"changeID");T(this,"checkpoint");T(this,"localChanges");T(this,"root");T(this,"clone");T(this,"eventStream");T(this,"eventStreamObserver");T(this,"onlineClients");T(this,"presences");T(this,"history");T(this,"internalHistory");T(this,"isUpdating");this.opts=e||{},this.key=t,this.status="detached",this.root=Ao.create(),this.changeID=Df,this.checkpoint=Bf,this.localChanges=[],this.eventStream=Eh(n=>{this.eventStreamObserver=n}),this.onlineClients=new Set,this.presences=new Map,this.isUpdating=!1,this.internalHistory=new Nh,this.history={canUndo:this.canUndo.bind(this),canRedo:this.canRedo.bind(this),undo:this.undo.bind(this),redo:this.redo.bind(this)},Ch(this)}update(t,e){if(this.getStatus()==="removed")throw new ne(te.ErrDocumentRemoved,`${this.key} is removed`);this.ensureClone();const n=this.changeID.getActorID(),r=Ji.create(this.changeID.next(),this.clone.root,this.clone.presences.get(n)||{},e);try{const o=xl(r,this.clone.root.getObject());this.presences.has(n)||this.clone.presences.set(n,{}),this.isUpdating=!0,t(o,new Bs(r,this.clone.presences.get(n)))}catch(o){throw this.clone=void 0,o}finally{this.isUpdating=!1}if(r.hasChange()){Ne.isEnabled(wt.Trivial)&&Ne.trivial(`trying to update a local change: ${this.toJSON()}`);const o=r.getChange(),{opInfos:s,reverseOps:u}=o.execute(this.root,this.presences,Ye.Local),c=r.getReversePresence();c&&u.push({type:"presence",value:c}),this.localChanges.push(o),u.length>0&&this.internalHistory.pushUndo(u),s.length>0&&this.internalHistory.clearRedo(),this.changeID=o.getID();const m=[];s.length>0&&m.push({type:"local-change",source:Ye.Local,value:{message:o.getMessage()||"",operations:s,actor:n,clientSeq:o.getID().getClientSeq(),serverSeq:o.getID().getServerSeq()},rawChange:this.isEnableDevtools()?o.toStruct():void 0}),o.hasPresenceChange()&&m.push({type:"presence-changed",source:Ye.Local,value:{clientID:n,presence:this.getPresence(n)}}),this.publish(m),Ne.isEnabled(wt.Trivial)&&Ne.trivial(`after update a local change: ${this.toJSON()}`)}}subscribe(t,e,n,r){if(typeof t=="string"){if(typeof e!="function")throw new ne(te.ErrInvalidArgument,"Second argument must be a callback function");if(t==="presence"){const u=e;return this.eventStream.subscribe(c=>{for(const m of c)m.type!=="initialized"&&m.type!=="watched"&&m.type!=="unwatched"&&m.type!=="presence-changed"||u(m)},n,r)}if(t==="my-presence"){const u=e;return this.eventStream.subscribe(c=>{for(const m of c)m.type!=="initialized"&&m.type!=="presence-changed"||m.type==="presence-changed"&&m.value.clientID!==this.changeID.getActorID()||u(m)},n,r)}if(t==="others"){const u=e;return this.eventStream.subscribe(c=>{for(const m of c)m.type!=="watched"&&m.type!=="unwatched"&&m.type!=="presence-changed"||m.value.clientID!==this.changeID.getActorID()&&u(m)},n,r)}if(t==="connection"){const u=e;return this.eventStream.subscribe(c=>{for(const m of c)m.type==="connection-changed"&&u(m)},n,r)}if(t==="status"){const u=e;return this.eventStream.subscribe(c=>{for(const m of c)m.type==="status-changed"&&u(m)},n,r)}if(t==="sync"){const u=e;return this.eventStream.subscribe(c=>{for(const m of c)m.type==="sync-status-changed"&&u(m)},n,r)}if(t==="local-broadcast"){const u=e;return this.eventStream.subscribe(c=>{for(const m of c)m.type==="local-broadcast"&&u(m)},n)}if(t==="broadcast"){const u=e;return this.eventStream.subscribe(c=>{for(const m of c)m.type==="broadcast"&&u(m)},n)}if(t==="all"){const u=e;return this.eventStream.subscribe(u,n,r)}const o=t,s=e;return this.eventStream.subscribe(u=>{for(const c of u){if(c.type!=="local-change"&&c.type!=="remote-change")continue;const m=[];for(const y of c.value.operations)this.isSameElementOrChildOf(y.path,o)&&m.push(y);m.length&&s({...c,value:{...c.value,operations:m}})}},n,r)}if(typeof t=="function"){const o=t,s=e,u=n;return this.eventStream.subscribe(c=>{for(const m of c)m.type!=="snapshot"&&m.type!=="local-change"&&m.type!=="remote-change"||o(m)},s,u)}throw new ne(te.ErrInvalidArgument,`"${t}" is not a valid`)}publish(t){this.eventStreamObserver&&this.eventStreamObserver.next(t)}isSameElementOrChildOf(t,e){if(e===t)return!0;const n=t.split(".");return e.split(".").every((o,s)=>o===n[s])}removePushedLocalChanges(t){for(;this.localChanges.length&&!(this.localChanges[0].getID().getClientSeq()>t);)this.localChanges.shift()}applyChangePack(t){const e=t.hasSnapshot();e?this.applySnapshot(t.getCheckpoint().getServerSeq(),t.getVersionVector(),t.getSnapshot(),t.getCheckpoint().getClientSeq()):(this.applyChanges(t.getChanges(),Ye.Remote),this.removePushedLocalChanges(t.getCheckpoint().getClientSeq())),this.checkpoint=this.checkpoint.forward(t.getCheckpoint()),e||this.garbageCollect(t.getVersionVector()),e||this.filterVersionVector(t.getVersionVector()),t.getIsRemoved()&&this.applyStatus("removed"),Ne.isEnabled(wt.Trivial)&&Ne.trivial(`${this.root.toJSON()}`)}getCheckpoint(){return this.checkpoint}getChangeID(){return this.changeID}hasLocalChanges(){return this.localChanges.length>0}ensureClone(){this.clone||(this.clone={root:this.root.deepcopy(),presences:sn(this.presences)})}createChangePack(){const t=Array.from(this.localChanges),e=this.checkpoint.increaseClientSeq(t.length);return Os.create(this.key,e,!1,t,this.getVersionVector())}setActor(t){for(const e of this.localChanges)e.setActor(t);this.changeID=this.changeID.setActor(t)}isEnableDevtools(){return!!this.opts.enableDevtools}getKey(){return this.key}getStatus(){return this.status}getCloneRoot(){if(this.clone)return this.clone.root.getObject()}getRoot(){this.ensureClone();const t=Ji.create(this.changeID.next(),this.clone.root,this.clone.presences.get(this.changeID.getActorID())||{});return xl(t,this.clone.root.getObject())}garbageCollect(t){return this.opts.disableGC?0:(this.clone&&this.clone.root.garbageCollect(t),this.root.garbageCollect(t))}getRootObject(){return this.root.getObject()}getGarbageLen(){return this.root.getGarbageLen()}getGarbageLenFromClone(){return this.clone.root.getGarbageLen()}toJSON(){return this.root.toJSON()}toSortedJSON(){return this.root.toSortedJSON()}getStats(){return this.root.getStats()}toJSForTest(){return{...this.getRoot().toJSForTest(),key:"root"}}applySnapshot(t,e,n,r=-1){const{root:o,presences:s}=at.bytesToSnapshot(n);this.root=new Ao(o),this.presences=s,this.changeID=this.changeID.setClocks(t,e),this.clone=void 0,this.removePushedLocalChanges(r),this.applyChanges(this.localChanges,Ye.Local),this.publish([{type:"snapshot",source:Ye.Remote,value:{serverSeq:t.toString(),snapshot:this.isEnableDevtools()?at.bytesToHex(n):void 0,snapshotVector:at.versionVectorToHex(e)}}])}applyChanges(t,e){Ne.isEnabled(wt.Debug)&&Ne.debug(`trying to apply ${t.length} remote changes.elements:${this.root.getElementMapSize()}, removeds:${this.root.getGarbageElementSetSize()}`),Ne.isEnabled(wt.Trivial)&&Ne.trivial(t.map(n=>`${n.getID().toTestString()} ${n.toTestString()}`).join(` `));for(const n of t)this.applyChange(n,e);Ne.isEnabled(wt.Debug)&&Ne.debug(`after appling ${t.length} remote changes.elements:${this.root.getElementMapSize()}, removeds:${this.root.getGarbageElementSetSize()}`)}applyChange(t,e){this.ensureClone(),t.execute(this.clone.root,this.clone.presences,e);const n=[],r=t.getID().getActorID();if(t.hasPresenceChange()&&this.onlineClients.has(r)){const s=t.getPresenceChange();switch(s.type){case pi.Put:n.push(this.presences.has(r)?{type:"presence-changed",source:e,value:{clientID:r,presence:s.presence}}:{type:"watched",source:Ye.Remote,value:{clientID:r,presence:s.presence}});break;case pi.Clear:n.push({type:"unwatched",source:Ye.Remote,value:{clientID:r,presence:this.getPresence(r)}}),this.removeOnlineClient(r);break}}const{opInfos:o}=t.execute(this.root,this.presences,e);if(this.changeID=this.changeID.syncClocks(t.getID()),o.length>0){const s=this.isEnableDevtools()?t.toStruct():void 0;n.push(e===Ye.Remote?{type:"remote-change",source:e,value:{actor:r,clientSeq:t.getID().getClientSeq(),serverSeq:t.getID().getServerSeq(),message:t.getMessage()||"",operations:o},rawChange:s}:{type:"local-change",source:e,value:{actor:r,clientSeq:t.getID().getClientSeq(),serverSeq:t.getID().getServerSeq(),message:t.getMessage()||"",operations:o},rawChange:s})}n.length>0&&this.publish(n)}applyWatchStream(t){if(t.body.case==="initialization"){const e=t.body.value.clientIds,n=new Set;for(const r of e)r!==this.changeID.getActorID()&&n.add(r);this.setOnlineClients(n),this.publish([{type:"initialized",source:Ye.Local,value:this.getPresences()}]);return}if(t.body.case==="event"){const{type:e,publisher:n}=t.body.value,r=[];if(e===Oi.DOCUMENT_WATCHED){if(this.onlineClients.has(n)&&this.hasPresence(n))return;this.addOnlineClient(n),this.hasPresence(n)&&r.push({type:"watched",source:Ye.Remote,value:{clientID:n,presence:this.getPresence(n)}})}else if(e===Oi.DOCUMENT_UNWATCHED){const o=this.getPresence(n);this.removeOnlineClient(n),o&&r.push({type:"unwatched",source:Ye.Remote,value:{clientID:n,presence:o}})}else if(e===Oi.DOCUMENT_BROADCAST&&t.body.value.body){const{topic:o,payload:s}=t.body.value.body,u=new TextDecoder;r.push({type:"broadcast",value:{clientID:n,topic:o,payload:JSON.parse(u.decode(s))}})}r.length>0&&this.publish(r)}}applyStatus(t){this.status=t,t==="detached"&&this.setActor(Aa),this.publish([{source:t==="removed"?Ye.Remote:Ye.Local,type:"status-changed",value:t==="attached"?{status:t,actorID:this.changeID.getActorID()}:{status:t}}])}applyDocEvent(t){if(t.type==="status-changed"){this.applyStatus(t.value.status),t.value.status==="attached"&&this.setActor(t.value.actorID);return}if(t.type==="snapshot"){const{snapshot:e,serverSeq:n,snapshotVector:r}=t.value;if(!e)return;this.applySnapshot(BigInt(n),at.hexToVersionVector(r),at.hexToBytes(e));return}if(t.type==="local-change"||t.type==="remote-change"){if(!t.rawChange)return;const e=Zi.fromStruct(t.rawChange);this.applyChange(e,t.source)}if(t.type==="initialized"){const e=new Set;for(const{clientID:n,presence:r}of t.value)e.add(n),this.presences.set(n,r);this.setOnlineClients(e);return}if(t.type==="watched"){const{clientID:e,presence:n}=t.value;this.addOnlineClient(e),this.presences.set(e,n);return}if(t.type==="unwatched"){const{clientID:e}=t.value;this.removeOnlineClient(e),this.presences.delete(e)}if(t.type==="presence-changed"){const{clientID:e,presence:n}=t.value;this.presences.set(e,n)}}applyTransactionEvent(t){for(const e of t)this.applyDocEvent(e)}getValueByPath(t){if(!t.startsWith("$"))throw new ne(te.ErrInvalidArgument,'path must start with "$"');const e=t.split(".");e.shift();let n=this.getRoot();for(const r of e)if(n=n[r],n===void 0)return;return n}setOnlineClients(t){this.onlineClients=t}resetOnlineClients(){this.onlineClients=new Set}addOnlineClient(t){this.onlineClients.add(t)}removeOnlineClient(t){this.onlineClients.delete(t)}hasPresence(t){return this.presences.has(t)}getMyPresence(){if(this.status!=="attached")return{};const t=this.presences.get(this.changeID.getActorID());return t?sn(t):{}}getPresence(t){if(t===this.changeID.getActorID())return this.getMyPresence();if(!this.onlineClients.has(t))return;const e=this.presences.get(t);return e?sn(e):void 0}getPresenceForTest(t){const e=this.presences.get(t);return e?sn(e):void 0}getPresences(){const t=[];t.push({clientID:this.changeID.getActorID(),presence:sn(this.getMyPresence())});for(const e of this.onlineClients)this.presences.has(e)&&t.push({clientID:e,presence:sn(this.presences.get(e))});return t}getSelfForTest(){return{clientID:this.getChangeID().getActorID(),presence:this.getMyPresence()}}getOthersForTest(){const t=this.getChangeID().getActorID();return this.getPresences().filter(e=>e.clientID!==t).sort((e,n)=>e.clientID>n.clientID?1:-1)}canUndo(){return this.internalHistory.hasUndo()&&!this.isUpdating}filterVersionVector(t){const n=this.changeID.getVersionVector().filter(t);this.changeID=this.changeID.setVersionVector(n)}canRedo(){return this.internalHistory.hasRedo()&&!this.isUpdating}undo(){if(this.isUpdating)throw new ne(te.ErrRefused,"Undo is not allowed during an update");const t=this.internalHistory.popUndo();if(t===void 0)throw new ne(te.ErrRefused,"There is no operation to be undone");this.ensureClone();const e=Ji.create(this.changeID.next(),this.clone.root,this.clone.presences.get(this.changeID.getActorID())||{});for(const m of t){if(!(m instanceof fn)){new Bs(e,sn(this.clone.presences.get(this.changeID.getActorID()))).set(m.value,{addToHistory:!0});continue}const y=e.issueTimeTicket();m.setExecutedAt(y),e.push(m)}const n=e.getChange();n.execute(this.clone.root,this.clone.presences,Ye.UndoRedo);const{opInfos:r,reverseOps:o}=n.execute(this.root,this.presences,Ye.UndoRedo),s=e.getReversePresence();if(s&&o.push({type:"presence",value:s}),o.length>0&&this.internalHistory.pushRedo(o),!n.hasPresenceChange()&&r.length===0)return;this.localChanges.push(n),this.changeID=n.getID();const u=this.changeID.getActorID(),c=[];r.length>0&&c.push({type:"local-change",source:Ye.UndoRedo,value:{message:n.getMessage()||"",operations:r,actor:u,clientSeq:n.getID().getClientSeq(),serverSeq:n.getID().getServerSeq()},rawChange:this.isEnableDevtools()?n.toStruct():void 0}),n.hasPresenceChange()&&c.push({type:"presence-changed",source:Ye.UndoRedo,value:{clientID:u,presence:this.getPresence(u)}}),this.publish(c)}redo(){if(this.isUpdating)throw new ne(te.ErrRefused,"Redo is not allowed during an update");const t=this.internalHistory.popRedo();if(t===void 0)throw new ne(te.ErrRefused,"There is no operation to be redone");this.ensureClone();const e=Ji.create(this.changeID.next(),this.clone.root,this.clone.presences.get(this.changeID.getActorID())||{});for(const m of t){if(!(m instanceof fn)){new Bs(e,sn(this.clone.presences.get(this.changeID.getActorID()))).set(m.value,{addToHistory:!0});continue}const y=e.issueTimeTicket();m.setExecutedAt(y),e.push(m)}const n=e.getChange();n.execute(this.clone.root,this.clone.presences,Ye.UndoRedo);const{opInfos:r,reverseOps:o}=n.execute(this.root,this.presences,Ye.UndoRedo),s=e.getReversePresence();if(s&&o.push({type:"presence",value:s}),o.length>0&&this.internalHistory.pushUndo(o),!n.hasPresenceChange()&&r.length===0)return;this.localChanges.push(n),this.changeID=n.getID();const u=this.changeID.getActorID(),c=[];r.length>0&&c.push({type:"local-change",source:Ye.UndoRedo,value:{message:n.getMessage()||"",operations:r,actor:u,clientSeq:n.getID().getClientSeq(),serverSeq:n.getID().getServerSeq()},rawChange:this.isEnableDevtools()?n.toStruct():void 0}),n.hasPresenceChange()&&c.push({type:"presence-changed",source:Ye.UndoRedo,value:{clientID:u,presence:this.getPresence(u)}}),this.publish(c)}getUndoStackForTest(){return this.internalHistory.getUndoStackForTest()}getRedoStackForTest(){return this.internalHistory.getRedoStackForTest()}broadcast(t,e,n){const r={type:"local-broadcast",value:{topic:t,payload:e},options:n};this.publish([r])}getVersionVector(){return this.changeID.getVersionVector()}}function Lh(i,t){return e=>async n=>(i&&n.header.set("x-api-key",i),t&&n.header.set("authorization",t),await e(n))}const Rh="yorkie-js-sdk",Dh="0.5.4",Bh="Yorkie JS SDK",Mh="./src/yorkie.ts",qh={access:"public",main:"./dist/yorkie-js-sdk.js",typings:"./dist/yorkie-js-sdk.d.ts"},Fh=["dist"],jh={build:"tsc && vite build","build:proto":"npx buf generate","build:docs":"typedoc","build:ghpages":"mkdir -p ghpages/examples && cp -r docs ghpages/api-reference && find ../../examples -name 'dist' -type d -exec sh -c 'cp -r {} ghpages/examples/$(basename $(dirname {}))' \\;",dev:"vite build -c vite.preview.ts && vite preview",test:"vitest run","test:watch":"vitest","test:bench":"vitest bench","test:ci":"vitest run --coverage","test:yorkie.dev":"TEST_RPC_ADDR=https://api.yorkie.dev vitest run --coverage",prepare:"pnpm build"},Uh={node:">=18.0.0",npm:">=7.1.0"},Jh={type:"git",url:"git+https://github.com/yorkie-team/yorkie-js-sdk.git"},$h={name:"hackerwins",email:"susukang98@gmail.com"},zh="Apache-2.0",Vh={url:"https://github.com/yorkie-team/yorkie-js-sdk/issues"},Kh="https://github.com/yorkie-team/yorkie-js-sdk#readme",Hh={"@buf/googleapis_googleapis.bufbuild_es":"^1.4.0-20240524201209-f0e53af8f2fc.3","@bufbuild/buf":"^1.28.1","@bufbuild/protoc-gen-es":"^1.6.0","@connectrpc/protoc-gen-connect-es":"^1.4.0","@types/google-protobuf":"^3.15.5","@types/long":"^4.0.1","@typescript-eslint/eslint-plugin":"^6.21.0","@typescript-eslint/parser":"^6.21.0","@vitest/coverage-istanbul":"^0.34.5","@vitest/coverage-v8":"^0.34.5","eslint-plugin-tsdoc":"^0.2.16",prettier:"^2.7.1","ts-node":"^10.9.1",typedoc:"^0.25.13",typescript:"^5.3.3","typescript-transform-paths":"^3.3.1",vite:"^5.0.12","vite-plugin-commonjs":"^0.10.1","vite-plugin-dts":"^3.9.1","vite-tsconfig-paths":"^4.2.1",vitest:"^0.34.5"},Wh={"@bufbuild/protobuf":"^1.6.0","@connectrpc/connect":"^1.4.0","@connectrpc/connect-web":"^1.4.0",long:"^5.2.0"},Il={name:Rh,version:Dh,description:Bh,main:Mh,publishConfig:qh,files:Fh,scripts:jh,engines:Uh,repository:Jh,author:$h,license:zh,bugs:Vh,homepage:Kh,devDependencies:Hh,dependencies:Wh};function Gh(){return i=>async t=>(t.header.set("x-yorkie-user-agent",Il.name+"/"+Il.version),await i(t))}const Yh=i=>{try{if(JSON.stringify(i)===void 0)return!1}catch{return!1}return!0};var Zo=(i=>(i.Manual="manual",i.Realtime="realtime",i.RealtimePushOnly="realtime-pushonly",i.RealtimeSyncOff="realtime-syncoff",i))(Zo||{});const $o={syncLoopDuration:50,retrySyncLoopDelay:1e3,reconnectStreamDelay:1e3},js={maxRetries:1/0,initialRetryInterval:1e3,maxBackoff:2e4};class Uu{constructor(t,e){T(this,"id");T(this,"key");T(this,"status");T(this,"attachmentMap");T(this,"apiKey");T(this,"conditions");T(this,"syncLoopDuration");T(this,"reconnectStreamDelay");T(this,"retrySyncLoopDelay");T(this,"rpcClient");T(this,"taskQueue");T(this,"processing",!1);e=e||$o,this.key=e.key?e.key:Mu(),this.status="deactivated",this.attachmentMap=new Map,this.apiKey=e.apiKey||"",this.conditions={SyncLoop:!1,WatchLoop:!1},this.syncLoopDuration=e.syncLoopDuration||$o.syncLoopDuration,this.reconnectStreamDelay=e.reconnectStreamDelay||$o.reconnectStreamDelay,this.retrySyncLoopDelay=e.retrySyncLoopDelay||$o.retrySyncLoopDelay,this.rpcClient=Vc(pf,gf({baseUrl:t,interceptors:[Lh(e.apiKey,e.token),Gh()]})),this.taskQueue=[]}activate(){return this.isActive()?Promise.resolve():this.enqueueTask(async()=>this.rpcClient.activateClient({clientKey:this.key},{headers:{"x-shard-key":this.apiKey}}).then(t=>{this.id=t.clientId,this.status="activated",this.runSyncLoop(),Ne.info(`[AC] c:"${this.getKey()}" activated, id:"${this.id}"`)}).catch(t=>{throw Ne.error(`[AC] c:"${this.getKey()}" err :`,t),this.handleConnectError(t),t}))}deactivate(){return this.status==="deactivated"?Promise.resolve():this.enqueueTask(async()=>this.rpcClient.deactivateClient({clientId:this.id},{headers:{"x-shard-key":this.apiKey}}).then(()=>{this.deactivateInternal(),Ne.info(`[DC] c"${this.getKey()}" deactivated`)}).catch(t=>{throw Ne.error(`[DC] c:"${this.getKey()}" err :`,t),this.handleConnectError(t),t}))}attach(t,e={}){if(!this.isActive())throw new ne(te.ErrClientNotActivated,`${this.key} is not active`);if(t.getStatus()!==si.Detached)throw new ne(te.ErrDocumentNotDetached,`${t.getKey()} is not detached`);t.setActor(this.id),t.update((o,s)=>s.set(e.initialPresence||{}));const n=t.subscribe("local-broadcast",async o=>{var y;const{topic:s,payload:u}=o.value,c=(y=o.options)==null?void 0:y.error,m=o.options;try{await this.broadcast(t.getKey(),s,u,m)}catch(d){d instanceof Error&&(c==null||c(d))}}),r=e.syncMode??"realtime";return this.enqueueTask(async()=>this.rpcClient.attachDocument({clientId:this.id,changePack:at.toChangePack(t.createChangePack())},{headers:{"x-shard-key":`${this.apiKey}/${t.getKey()}`}}).then(async o=>{const s=at.fromChangePack(o.changePack);if(t.applyChangePack(s),t.getStatus()===si.Removed)return t;t.applyStatus(si.Attached),this.attachmentMap.set(t.getKey(),new Th(this.reconnectStreamDelay,t,o.documentId,r,n)),r!=="manual"&&await this.runWatchLoop(t.getKey()),Ne.info(`[AD] c:"${this.getKey()}" attaches d:"${t.getKey()}"`);const u=t.getRootObject();if(e.initialRoot){const c=e.initialRoot;t.update(m=>{for(const[y,d]of Object.entries(c))if(!u.has(y)){const l=y;m[l]=d}})}return t}).catch(o=>{throw Ne.error(`[AD] c:"${this.getKey()}" err :`,o),this.handleConnectError(o),o}))}detach(t,e={}){if(!this.isActive())throw new ne(te.ErrClientNotActivated,`${this.key} is not active`);const n=this.attachmentMap.get(t.getKey());if(!n)throw new ne(te.ErrDocumentNotAttached,`${t.getKey()} is not attached`);return t.update((r,o)=>o.clear()),this.enqueueTask(async()=>this.rpcClient.detachDocument({clientId:this.id,documentId:n.docID,changePack:at.toChangePack(t.createChangePack()),removeIfNotAttached:e.removeIfNotAttached??!1},{headers:{"x-shard-key":`${this.apiKey}/${t.getKey()}`}}).then(r=>{const o=at.fromChangePack(r.changePack);return t.applyChangePack(o),t.getStatus()!==si.Removed&&t.applyStatus(si.Detached),this.detachInternal(t.getKey()),Ne.info(`[DD] c:"${this.getKey()}" detaches d:"${t.getKey()}"`),t}).catch(r=>{throw Ne.error(`[DD] c:"${this.getKey()}" err :`,r),this.handleConnectError(r),r}))}async changeSyncMode(t,e){if(!this.isActive())throw new ne(te.ErrClientNotActivated,`${this.key} is not active`);const n=this.attachmentMap.get(t.getKey());if(!n)throw new ne(te.ErrDocumentNotAttached,`${t.getKey()} is not attached`);const r=n.syncMode;return r===e?t:(n.changeSyncMode(e),e==="manual"?(n.cancelWatchStream(),t):(e==="realtime"&&(n.remoteChangeEventReceived=!0),r==="manual"&&await this.runWatchLoop(t.getKey()),t))}sync(t){if(!this.isActive())throw new ne(te.ErrClientNotActivated,`${this.key} is not active`);if(t){const e=this.attachmentMap.get(t.getKey());if(!e)throw new ne(te.ErrDocumentNotAttached,`${t.getKey()} is not attached`);return this.enqueueTask(async()=>this.syncInternal(e,"realtime").catch(n=>{throw Ne.error(`[SY] c:"${this.getKey()}" err :`,n),this.handleConnectError(n),n}))}return this.enqueueTask(async()=>{const e=[];for(const[,n]of this.attachmentMap)e.push(this.syncInternal(n,n.syncMode));return Promise.all(e).catch(n=>{throw Ne.error(`[SY] c:"${this.getKey()}" err :`,n),this.handleConnectError(n),n})})}remove(t){if(!this.isActive())throw new ne(te.ErrClientNotActivated,`${this.key} is not active`);const e=this.attachmentMap.get(t.getKey());if(!e)throw new ne(te.ErrDocumentNotAttached,`${t.getKey()} is not attached`);t.setActor(this.id);const n=at.toChangePack(t.createChangePack());return n.isRemoved=!0,this.enqueueTask(async()=>this.rpcClient.removeDocument({clientId:this.id,documentId:e.docID,changePack:n},{headers:{"x-shard-key":`${this.apiKey}/${t.getKey()}`}}).then(r=>{const o=at.fromChangePack(r.changePack);t.applyChangePack(o),this.detachInternal(t.getKey()),Ne.info(`[RD] c:"${this.getKey()}" removes d:"${t.getKey()}"`)}).catch(r=>{throw Ne.error(`[RD] c:"${this.getKey()}" err :`,r),this.handleConnectError(r),r}))}getID(){return this.id}getKey(){return this.key}isActive(){return this.status==="activated"}getStatus(){return this.status}getCondition(t){return this.conditions[t]}broadcast(t,e,n,r){if(!this.isActive())throw new ne(te.ErrClientNotActivated,`${this.key} is not active`);const o=this.attachmentMap.get(t);if(!o)throw new ne(te.ErrDocumentNotAttached,`${t} is not attached`);if(!Yh(n))throw new ne(te.ErrInvalidArgument,"payload is not serializable");const s=(r==null?void 0:r.maxRetries)??js.maxRetries,u=js.maxBackoff;let c=0;const m=d=>Math.min(js.initialRetryInterval*2**d,u),y=async()=>this.enqueueTask(async()=>this.rpcClient.broadcast({clientId:this.id,documentId:o.docID,topic:e,payload:new TextEncoder().encode(JSON.stringify(n))},{headers:{"x-shard-key":`${this.apiKey}/${t}`}}).then(()=>{Ne.info(`[BC] c:"${this.getKey()}" broadcasts d:"${t}" t:"${e}"`)}).catch(d=>{if(Ne.error(`[BC] c:"${this.getKey()}" err:`,d),this.handleConnectError(d))if(cy(),m(c-1)),Ne.info(`[BC] c:"${this.getKey()}" retry attempt ${c}/${s}`);else throw Ne.error(`[BC] c:"${this.getKey()}" exceeded maximum retry attempts`),d;else throw d}));return y()}runSyncLoop(){const t=()=>{if(!this.isActive()){Ne.debug(`[SL] c:"${this.getKey()}" exit sync loop`),this.conditions.SyncLoop=!1;return}const e=[];for(const[,n]of this.attachmentMap)n.needRealtimeSync()&&(n.remoteChangeEventReceived=!1,e.push(this.syncInternal(n,n.syncMode)));Promise.all(e).then(()=>setTimeout(t,this.syncLoopDuration)).catch(n=>{Ne.error(`[SL] c:"${this.getKey()}" sync failed:`,n),this.handleConnectError(n)?setTimeout(t,this.retrySyncLoopDelay):this.conditions.SyncLoop=!1})};Ne.debug(`[SL] c:"${this.getKey()}" run sync loop`),this.conditions.SyncLoop=!0,t()}async runWatchLoop(t){const e=this.attachmentMap.get(t);if(!e)throw new ne(te.ErrDocumentNotAttached,`${t} is not attached`);return this.conditions.WatchLoop=!0,e.runWatchLoop(n=>{if(!this.isActive())return this.conditions.WatchLoop=!1,Promise.reject(new ne(te.ErrClientNotActivated,`${this.key} is not active`));const r=new AbortController,o=this.rpcClient.watchDocument({clientId:this.id,documentId:e.docID},{headers:{"x-shard-key":`${this.apiKey}/${t}`},signal:r.signal});return e.doc.publish([{type:gt.ConnectionChanged,value:So.Connected}]),Ne.info(`[WD] c:"${this.getKey()}" watches d:"${t}"`),new Promise((s,u)=>{(async()=>{try{for await(const m of o)this.handleWatchDocumentsResponse(e,m),m.body.case==="initialization"&&s([o,r])}catch(m){e.doc.resetOnlineClients(),e.doc.publish([{type:gt.Initialized,source:Ye.Local,value:e.doc.getPresences()}]),e.doc.publish([{type:gt.ConnectionChanged,value:So.Disconnected}]),Ne.debug(`[WD] c:"${this.getKey()}" unwatches`),this.handleConnectError(m)?n():this.conditions.WatchLoop=!1,u(m)}})()})})}handleWatchDocumentsResponse(t,e){if(e.body.case==="event"&&e.body.value.type===Oi.DOCUMENT_CHANGED){t.remoteChangeEventReceived=!0;return}t.doc.applyWatchStream(e)}deactivateInternal(){this.status="deactivated";for(const[t,e]of this.attachmentMap)this.detachInternal(t),e.doc.applyStatus(si.Detached)}detachInternal(t){const e=this.attachmentMap.get(t);e&&(e.cancelWatchStream(),e.unsubscribeBroadcastEvent(),this.attachmentMap.delete(t))}syncInternal(t,e){const{doc:n,docID:r}=t,o=n.createChangePack();return this.rpcClient.pushPullChanges({clientId:this.id,documentId:r,changePack:at.toChangePack(o),pushOnly:e==="realtime-pushonly"},{headers:{"x-shard-key":`${this.apiKey}/${n.getKey()}`}}).then(s=>{const u=at.fromChangePack(s.changePack);if(u.hasChanges()&&(t.syncMode==="realtime-pushonly"||t.syncMode==="realtime-syncoff"))return n;n.applyChangePack(u),t.doc.publish([{type:gt.SyncStatusChanged,value:ma.Synced}]),n.getStatus()===si.Removed&&this.detachInternal(n.getKey());const c=n.getKey(),m=u.getChangeSize();return Ne.info(`[PP] c:"${this.getKey()}" sync d:"${c}", push:${o.getChangeSize()} pull:${m} cp:${u.getCheckpoint().toTestString()}`),n}).catch(s=>{throw n.publish([{type:gt.SyncStatusChanged,value:ma.SyncFailed}]),Ne.error(`[PP] c:"${this.getKey()}" err :`,s),s})}handleConnectError(t){return t instanceof ct?t.code===Ge.Canceled||t.code===Ge.Unknown||t.code===Ge.ResourceExhausted||t.code===Ge.Unavailable?!0:((Sl(t)===te.ErrClientNotActivated||Sl(t)===te.ErrClientNotFound)&&this.deactivateInternal(),!1):!1}enqueueTask(t){return new Promise((e,n)=>{this.taskQueue.push(()=>t().then(e).catch(n)),this.processing||this.processNext()})}async processNext(){if(this.taskQueue.length===0){this.processing=!1;return}try{this.processing=!0,await this.taskQueue.shift()()}catch{Ne.error(`[TQ] c:"${this.getKey()}" process failed, id:"${this.id}"`)}this.processNext()}}const Us={Client:Uu,Document:ju,Primitive:et,Text:Is,Counter:Ns,Tree:_s,LogLevel:wt,setLogLevel:Bu,IntType:Un.IntegerCnt,LongType:Un.LongCnt};typeof globalThis<"u"&&(globalThis.yorkie={Client:Uu,Document:ju,Primitive:et,Text:Is,Counter:Ns,Tree:_s,LogLevel:wt,setLogLevel:Bu,IntType:Un.IntegerCnt,LongType:Un.LongCnt});var Zh=typeof globalThis<"u"?globalThis:typeof window<"u"?window:typeof global<"u"?global:typeof self<"u"?self:{};function Ju(i){return i&&i.__esModule&&Object.prototype.hasOwnProperty.call(i,"default")?i.default:i}var $u={exports:{}};/*! * Quill Editor v1.3.7 * https://quilljs.com/ diff --git a/examples/vanilla-quill/index.html b/examples/vanilla-quill/index.html index 3da691b48..34819972f 100644 --- a/examples/vanilla-quill/index.html +++ b/examples/vanilla-quill/index.html @@ -4,7 +4,7 @@ Yorkie + Quill Example - + diff --git a/examples/vuejs-kanban/assets/index-aMQmcurO.js b/examples/vuejs-kanban/assets/index-zFTIUwA1.js similarity index 99% rename from examples/vuejs-kanban/assets/index-aMQmcurO.js rename to examples/vuejs-kanban/assets/index-zFTIUwA1.js index cc682066b..e367bbf83 100644 --- a/examples/vuejs-kanban/assets/index-aMQmcurO.js +++ b/examples/vuejs-kanban/assets/index-zFTIUwA1.js @@ -19,5 +19,5 @@ var Zf=Object.defineProperty;var Qf=(r,e,t)=>e in r?Zf(r,e,{enumerable:!0,config * limitations under the License. * * SPDX-License-Identifier: Apache-2.0 - */var it=null;try{it=new WebAssembly.Instance(new WebAssembly.Module(new Uint8Array([0,97,115,109,1,0,0,0,1,13,2,96,0,1,127,96,4,127,127,127,127,1,127,3,7,6,0,1,1,1,1,1,6,6,1,127,1,65,0,11,7,50,6,3,109,117,108,0,1,5,100,105,118,95,115,0,2,5,100,105,118,95,117,0,3,5,114,101,109,95,115,0,4,5,114,101,109,95,117,0,5,8,103,101,116,95,104,105,103,104,0,0,10,191,1,6,4,0,35,0,11,36,1,1,126,32,0,173,32,1,173,66,32,134,132,32,2,173,32,3,173,66,32,134,132,126,34,4,66,32,135,167,36,0,32,4,167,11,36,1,1,126,32,0,173,32,1,173,66,32,134,132,32,2,173,32,3,173,66,32,134,132,127,34,4,66,32,135,167,36,0,32,4,167,11,36,1,1,126,32,0,173,32,1,173,66,32,134,132,32,2,173,32,3,173,66,32,134,132,128,34,4,66,32,135,167,36,0,32,4,167,11,36,1,1,126,32,0,173,32,1,173,66,32,134,132,32,2,173,32,3,173,66,32,134,132,129,34,4,66,32,135,167,36,0,32,4,167,11,36,1,1,126,32,0,173,32,1,173,66,32,134,132,32,2,173,32,3,173,66,32,134,132,130,34,4,66,32,135,167,36,0,32,4,167,11])),{}).exports}catch{}function X(r,e,t){this.low=r|0,this.high=e|0,this.unsigned=!!t}X.prototype.__isLong__;Object.defineProperty(X.prototype,"__isLong__",{value:!0});function Ce(r){return(r&&r.__isLong__)===!0}function Lu(r){var e=Math.clz32(r&-r);return r?31-e:e}X.isLong=Ce;var Ju={},Mu={};function zn(r,e){var t,n,s;return e?(r>>>=0,(s=0<=r&&r<256)&&(n=Mu[r],n)?n:(t=Q(r,0,!0),s&&(Mu[r]=t),t)):(r|=0,(s=-128<=r&&r<128)&&(n=Ju[r],n)?n:(t=Q(r,r<0?-1:0,!1),s&&(Ju[r]=t),t))}X.fromInt=zn;function ot(r,e){if(isNaN(r))return e?Xr:pt;if(e){if(r<0)return Xr;if(r>=vf)return Tf}else{if(r<=-Uu)return Je;if(r+1>=Uu)return bf}return r<0?ot(-r,e).neg():Q(r%hs|0,r/hs|0,e)}X.fromNumber=ot;function Q(r,e,t){return new X(r,e,t)}X.fromBits=Q;var Qi=Math.pow;function rc(r,e,t){if(r.length===0)throw Error("empty string");if(typeof e=="number"?(t=e,e=!1):e=!!e,r==="NaN"||r==="Infinity"||r==="+Infinity"||r==="-Infinity")return e?Xr:pt;if(t=t||10,t<2||360)throw Error("interior hyphen");if(n===0)return rc(r.substring(1),e,t).neg();for(var s=ot(Qi(t,8)),i=pt,o=0;o>>0:this.low};k.toNumber=function(){return this.unsigned?(this.high>>>0)*hs+(this.low>>>0):this.high*hs+(this.low>>>0)};k.toString=function(e){if(e=e||10,e<2||36>>0,h=l.toString(e);if(o=u,o.isZero())return h+a;for(;h.length<6;)h="0"+h;a=""+h+a}};k.getHighBits=function(){return this.high};k.getHighBitsUnsigned=function(){return this.high>>>0};k.getLowBits=function(){return this.low};k.getLowBitsUnsigned=function(){return this.low>>>0};k.getNumBitsAbs=function(){if(this.isNegative())return this.eq(Je)?64:this.neg().getNumBitsAbs();for(var e=this.high!=0?this.high:this.low,t=31;t>0&&!(e&1<=0};k.isOdd=function(){return(this.low&1)===1};k.isEven=function(){return(this.low&1)===0};k.equals=function(e){return Ce(e)||(e=At(e)),this.unsigned!==e.unsigned&&this.high>>>31===1&&e.high>>>31===1?!1:this.high===e.high&&this.low===e.low};k.eq=k.equals;k.notEquals=function(e){return!this.eq(e)};k.neq=k.notEquals;k.ne=k.notEquals;k.lessThan=function(e){return this.comp(e)<0};k.lt=k.lessThan;k.lessThanOrEqual=function(e){return this.comp(e)<=0};k.lte=k.lessThanOrEqual;k.le=k.lessThanOrEqual;k.greaterThan=function(e){return this.comp(e)>0};k.gt=k.greaterThan;k.greaterThanOrEqual=function(e){return this.comp(e)>=0};k.gte=k.greaterThanOrEqual;k.ge=k.greaterThanOrEqual;k.compare=function(e){if(Ce(e)||(e=At(e)),this.eq(e))return 0;var t=this.isNegative(),n=e.isNegative();return t&&!n?-1:!t&&n?1:this.unsigned?e.high>>>0>this.high>>>0||e.high===this.high&&e.low>>>0>this.low>>>0?-1:1:this.sub(e).isNegative()?-1:1};k.comp=k.compare;k.negate=function(){return!this.unsigned&&this.eq(Je)?Je:this.not().add(_n)};k.neg=k.negate;k.add=function(e){Ce(e)||(e=At(e));var t=this.high>>>16,n=this.high&65535,s=this.low>>>16,i=this.low&65535,o=e.high>>>16,a=e.high&65535,u=e.low>>>16,l=e.low&65535,h=0,g=0,v=0,m=0;return m+=i+l,v+=m>>>16,m&=65535,v+=s+u,g+=v>>>16,v&=65535,g+=n+a,h+=g>>>16,g&=65535,h+=t+o,h&=65535,Q(v<<16|m,h<<16|g,this.unsigned)};k.subtract=function(e){return Ce(e)||(e=At(e)),this.add(e.neg())};k.sub=k.subtract;k.multiply=function(e){if(this.isZero())return this;if(Ce(e)||(e=At(e)),it){var t=it.mul(this.low,this.high,e.low,e.high);return Q(t,it.get_high(),this.unsigned)}if(e.isZero())return this.unsigned?Xr:pt;if(this.eq(Je))return e.isOdd()?Je:pt;if(e.eq(Je))return this.isOdd()?Je:pt;if(this.isNegative())return e.isNegative()?this.neg().mul(e.neg()):this.neg().mul(e).neg();if(e.isNegative())return this.mul(e.neg()).neg();if(this.lt(qu)&&e.lt(qu))return ot(this.toNumber()*e.toNumber(),this.unsigned);var n=this.high>>>16,s=this.high&65535,i=this.low>>>16,o=this.low&65535,a=e.high>>>16,u=e.high&65535,l=e.low>>>16,h=e.low&65535,g=0,v=0,m=0,A=0;return A+=o*h,m+=A>>>16,A&=65535,m+=i*h,v+=m>>>16,m&=65535,m+=o*l,v+=m>>>16,m&=65535,v+=s*h,g+=v>>>16,v&=65535,v+=i*l,g+=v>>>16,v&=65535,v+=o*u,g+=v>>>16,v&=65535,g+=n*h+s*l+i*u+o*a,g&=65535,Q(m<<16|A,g<<16|v,this.unsigned)};k.mul=k.multiply;k.divide=function(e){if(Ce(e)||(e=At(e)),e.isZero())throw Error("division by zero");if(it){if(!this.unsigned&&this.high===-2147483648&&e.low===-1&&e.high===-1)return this;var t=(this.unsigned?it.div_u:it.div_s)(this.low,this.high,e.low,e.high);return Q(t,it.get_high(),this.unsigned)}if(this.isZero())return this.unsigned?Xr:pt;var n,s,i;if(this.unsigned){if(e.unsigned||(e=e.toUnsigned()),e.gt(this))return Xr;if(e.gt(this.shru(1)))return wf;i=Xr}else{if(this.eq(Je)){if(e.eq(_n)||e.eq(Ia))return Je;if(e.eq(Je))return _n;var o=this.shr(1);return n=o.div(e).shl(1),n.eq(pt)?e.isNegative()?_n:Ia:(s=this.sub(e.mul(n)),i=n.add(s.div(e)),i)}else if(e.eq(Je))return this.unsigned?Xr:pt;if(this.isNegative())return e.isNegative()?this.neg().div(e.neg()):this.neg().div(e).neg();if(e.isNegative())return this.div(e.neg()).neg();i=pt}for(s=this;s.gte(e);){n=Math.max(1,Math.floor(s.toNumber()/e.toNumber()));for(var a=Math.ceil(Math.log(n)/Math.LN2),u=a<=48?1:Qi(2,a-48),l=ot(n),h=l.mul(e);h.isNegative()||h.gt(s);)n-=u,l=ot(n,this.unsigned),h=l.mul(e);l.isZero()&&(l=_n),i=i.add(l),s=s.sub(h)}return i};k.div=k.divide;k.modulo=function(e){if(Ce(e)||(e=At(e)),it){var t=(this.unsigned?it.rem_u:it.rem_s)(this.low,this.high,e.low,e.high);return Q(t,it.get_high(),this.unsigned)}return this.sub(this.div(e).mul(e))};k.mod=k.modulo;k.rem=k.modulo;k.not=function(){return Q(~this.low,~this.high,this.unsigned)};k.countLeadingZeros=function(){return this.high?Math.clz32(this.high):Math.clz32(this.low)+32};k.clz=k.countLeadingZeros;k.countTrailingZeros=function(){return this.low?Lu(this.low):Lu(this.high)+32};k.ctz=k.countTrailingZeros;k.and=function(e){return Ce(e)||(e=At(e)),Q(this.low&e.low,this.high&e.high,this.unsigned)};k.or=function(e){return Ce(e)||(e=At(e)),Q(this.low|e.low,this.high|e.high,this.unsigned)};k.xor=function(e){return Ce(e)||(e=At(e)),Q(this.low^e.low,this.high^e.high,this.unsigned)};k.shiftLeft=function(e){return Ce(e)&&(e=e.toInt()),(e&=63)===0?this:e<32?Q(this.low<>>32-e,this.unsigned):Q(0,this.low<>>e|this.high<<32-e,this.high>>e,this.unsigned):Q(this.high>>e-32,this.high>=0?0:-1,this.unsigned)};k.shr=k.shiftRight;k.shiftRightUnsigned=function(e){return Ce(e)&&(e=e.toInt()),(e&=63)===0?this:e<32?Q(this.low>>>e|this.high<<32-e,this.high>>>e,this.unsigned):e===32?Q(this.high,0,this.unsigned):Q(this.high>>>e-32,0,this.unsigned)};k.shru=k.shiftRightUnsigned;k.shr_u=k.shiftRightUnsigned;k.rotateLeft=function(e){var t;return Ce(e)&&(e=e.toInt()),(e&=63)===0?this:e===32?Q(this.high,this.low,this.unsigned):e<32?(t=32-e,Q(this.low<>>t,this.high<>>t,this.unsigned)):(e-=32,t=32-e,Q(this.high<>>t,this.low<>>t,this.unsigned))};k.rotl=k.rotateLeft;k.rotateRight=function(e){var t;return Ce(e)&&(e=e.toInt()),(e&=63)===0?this:e===32?Q(this.high,this.low,this.unsigned):e<32?(t=32-e,Q(this.high<>>e,this.low<>>e,this.unsigned)):(e-=32,t=32-e,Q(this.low<>>e,this.high<>>e,this.unsigned))};k.rotr=k.rotateRight;k.toSigned=function(){return this.unsigned?Q(this.low,this.high,!1):this};k.toUnsigned=function(){return this.unsigned?this:Q(this.low,this.high,!0)};k.toBytes=function(e){return e?this.toBytesLE():this.toBytesBE()};k.toBytesLE=function(){var e=this.high,t=this.low;return[t&255,t>>>8&255,t>>>16&255,t>>>24,e&255,e>>>8&255,e>>>16&255,e>>>24]};k.toBytesBE=function(){var e=this.high,t=this.low;return[e>>>24,e>>>16&255,e>>>8&255,e&255,t>>>24,t>>>16&255,t>>>8&255,t&255]};X.fromBytes=function(e,t,n){return n?X.fromBytesLE(e,t):X.fromBytesBE(e,t)};X.fromBytesLE=function(e,t){return new X(e[0]|e[1]<<8|e[2]<<16|e[3]<<24,e[4]|e[5]<<8|e[6]<<16|e[7]<<24,t)};X.fromBytesBE=function(e,t){return new X(e[4]<<24|e[5]<<16|e[6]<<8|e[7],e[0]<<24|e[1]<<16|e[2]<<8|e[3],t)};var be=(r=>(r[r.Null=0]="Null",r[r.Boolean=1]="Boolean",r[r.Integer=2]="Integer",r[r.Long=3]="Long",r[r.Double=4]="Double",r[r.String=5]="String",r[r.Bytes=6]="Bytes",r[r.Date=7]="Date",r))(be||{});class le extends Gs{constructor(t,n){super(n);c(this,"valueType");c(this,"value");this.valueType=le.getPrimitiveType(t),this.value=t===void 0?null:t}static of(t,n){return new le(t,n)}static valueFromBytes(t,n){switch(t){case 0:return null;case 1:return!!n[0];case 2:return n[0]|n[1]<<8|n[2]<<16|n[3]<<24;case 4:{const s=new DataView(n.buffer);return n.forEach(function(i,o){s.setUint8(o,i)}),s.getFloat64(0,!0)}case 5:return new TextDecoder("utf-8").decode(n);case 3:return X.fromBytesLE(Array.from(n));case 6:return n;case 7:return new Date(X.fromBytesLE(Array.from(n),!0).toNumber());default:throw new w(y.ErrUnimplemented,`unimplemented type: ${t}`)}}toJSON(){return this.valueType===5?`"${$t(this.value)}"`:`${this.value}`}toSortedJSON(){return this.toJSON()}toJSForTest(){return{createdAt:this.getCreatedAt().toTestString(),value:this.value,type:"YORKIE_PRIMITIVE"}}deepcopy(){const t=le.of(this.value,this.getCreatedAt());return t.setMovedAt(this.getMovedAt()),t.setRemovedAt(this.getRemovedAt()),t}getType(){return this.valueType}static getPrimitiveType(t){switch(typeof t){case"undefined":return 0;case"boolean":return 1;case"number":return this.isInteger(t)?2:4;case"string":return 5;case"object":if(t===null)return 0;if(t instanceof X)return 3;if(t instanceof Uint8Array)return 6;if(t instanceof Date)return 7}}static isSupport(t){return le.getPrimitiveType(t)!==void 0}static isInteger(t){return t%1===0}isNumericType(){const t=this.valueType;return t===2||t===3||t===4}getValue(){return this.value}toBytes(){switch(this.valueType){case 0:return new Uint8Array;case 1:return this.value?new Uint8Array([1]):new Uint8Array([0]);case 2:{const t=this.value;return new Uint8Array([t&255,t>>8&255,t>>16&255,t>>24&255])}case 4:{const t=this.value,n=new Uint8Array(8);return new DataView(n.buffer).setFloat64(0,t,!0),n}case 5:return new TextEncoder().encode(this.value);case 3:{const n=this.value.toBytesLE();return Uint8Array.from(n)}case 6:return this.value;case 7:{const t=this.value,n=X.fromNumber(t.getTime(),!0).toBytesLE();return Uint8Array.from(n)}default:throw new w(y.ErrUnimplemented,`unimplemented type: ${this.valueType}`)}}}class eo extends yf{constructor(t){super(t);c(this,"prev");c(this,"next");this.value=t}static createAfter(t,n){const s=new eo(n),i=t.next;return t.next=s,s.prev=t,s.next=i,i&&(i.prev=s),s}remove(t){return this.value.remove(t)}getCreatedAt(){return this.value.getCreatedAt()}getPositionedAt(){return this.value.getPositionedAt()}release(){this.prev&&(this.prev.next=this.next),this.next&&(this.next.prev=this.prev),this.prev=void 0,this.next=void 0}getLength(){return this.value.isRemoved()?0:1}getPrev(){return this.prev}getNext(){return this.next}getValue(){return this.value}isRemoved(){return this.value.isRemoved()}}class Ks{constructor(){c(this,"dummyHead");c(this,"last");c(this,"nodeMapByIndex");c(this,"nodeMapByCreatedAt");const e=le.of(0,wt);e.setRemovedAt(wt),this.dummyHead=new eo(e),this.last=this.dummyHead,this.nodeMapByIndex=new zs,this.nodeMapByCreatedAt=new Map,this.nodeMapByIndex.insert(this.dummyHead),this.nodeMapByCreatedAt.set(this.dummyHead.getCreatedAt().toIDString(),this.dummyHead)}static create(){return new Ks}get length(){return this.nodeMapByIndex.length}findNextBeforeExecutedAt(e,t){let n=this.nodeMapByCreatedAt.get(e.toIDString());if(!n)throw new w(y.ErrInvalidArgument,`cant find the given node: ${e.toIDString()}`);for(;n.getNext()&&n.getNext().getPositionedAt().after(t);)n=n.getNext();return n}release(e){this.last===e&&(this.last=e.getPrev()),e.release(),this.nodeMapByIndex.delete(e),this.nodeMapByCreatedAt.delete(e.getValue().getCreatedAt().toIDString())}insertAfter(e,t,n=t.getCreatedAt()){const s=this.findNextBeforeExecutedAt(e,n),i=eo.createAfter(s,t);s===this.last&&(this.last=i),this.nodeMapByIndex.insertAfter(s,i),this.nodeMapByCreatedAt.set(i.getCreatedAt().toIDString(),i)}moveAfter(e,t,n){const s=this.nodeMapByCreatedAt.get(e.toIDString());if(!s)throw new w(y.ErrInvalidArgument,`cant find the given node: ${e.toIDString()}`);const i=this.nodeMapByCreatedAt.get(t.toIDString());if(!i)throw new w(y.ErrInvalidArgument,`cant find the given node: ${t.toIDString()}`);s!==i&&(!i.getValue().getMovedAt()||n.after(i.getValue().getMovedAt()))&&(this.release(i),this.insertAfter(s.getCreatedAt(),i.getValue(),n),i.getValue().setMovedAt(n))}insert(e){this.insertAfter(this.last.getCreatedAt(),e)}getByID(e){return this.nodeMapByCreatedAt.get(e.toIDString())}subPathOf(e){const t=this.nodeMapByCreatedAt.get(e.toIDString());if(t)return String(this.nodeMapByIndex.indexOf(t))}purge(e){const t=this.nodeMapByCreatedAt.get(e.getCreatedAt().toIDString());if(!t)throw new w(y.ErrInvalidArgument,`fail to find the given createdAt: ${e.getCreatedAt().toIDString()}`);this.release(t)}getByIndex(e){if(e>=this.length)return;const[t,n]=this.nodeMapByIndex.find(e);let s=t;if(e===0&&t===this.dummyHead||n>0)do s&&(s=s.getNext());while(s&&s.isRemoved());return s}getPrevCreatedAt(e){let t=this.nodeMapByCreatedAt.get(e.toIDString());do t=t.getPrev();while(this.dummyHead!==t&&t.isRemoved());return t.getValue().getCreatedAt()}delete(e,t){const n=this.nodeMapByCreatedAt.get(e.toIDString()),s=n.isRemoved();return n.remove(t)&&!s&&this.nodeMapByIndex.splayNode(n),n.getValue()}deleteByIndex(e,t){const n=this.getByIndex(e);if(n)return n.remove(t)&&this.nodeMapByIndex.splayNode(n),n.getValue()}getHead(){return this.dummyHead.getValue()}getLast(){return this.last.getValue()}getLastCreatedAt(){return this.last.getCreatedAt()}toTestString(){const e=[];for(const t of this){const n=`${t.getCreatedAt().toIDString()}:${t.getValue().toJSON()}`;t.isRemoved()?e.push(`{${n}}`):e.push(`[${n}]`)}return e.join("")}*[Symbol.iterator](){let e=this.dummyHead.getNext();for(;e;)yield e,e=e.getNext()}}class je extends pn{constructor(t,n){super(t);c(this,"elements");this.elements=n}static create(t,n){if(!n)return new je(t,Ks.create());const s=Ks.create();for(const i of n)s.insertAfter(s.getLastCreatedAt(),i.deepcopy());return new je(t,s)}subPathOf(t){return this.elements.subPathOf(t)}purge(t){this.elements.purge(t)}insertAfter(t,n){this.elements.insertAfter(t,n)}moveAfter(t,n,s){this.elements.moveAfter(t,n,s)}get(t){const n=this.elements.getByIndex(t);return n==null?void 0:n.getValue()}getByID(t){const n=this.elements.getByID(t);return n==null?void 0:n.getValue()}getHead(){return this.elements.getHead()}getLast(){return this.elements.getLast()}getPrevCreatedAt(t){return this.elements.getPrevCreatedAt(t)}delete(t,n){return this.elements.delete(t,n)}deleteByIndex(t,n){return this.elements.deleteByIndex(t,n)}getLastCreatedAt(){return this.elements.getLastCreatedAt()}get length(){return this.elements.length}*[Symbol.iterator](){for(const t of this.elements)t.isRemoved()||(yield t.getValue())}toTestString(){return this.elements.toTestString()}getDescendants(t){for(const n of this.elements){const s=n.getValue();if(t(s,this))return;s instanceof pn&&s.getDescendants(t)}}toJSON(){const t=[];for(const n of this)t.push(n.toJSON());return`[${t.join(",")}]`}toJS(){return JSON.parse(this.toJSON())}toJSForTest(){const t={};for(let n=0;n({...m,value:m.value?{attributes:rs(m.value.getAttributes()),content:m.value.getContent()}:{attributes:void 0,content:""},type:"content"}));return[l,v,h,[u,u]]}setStyle(t,n,s,i){const[,o]=this.rgaTreeSplit.findNodeWithSplit(t[1],s),[,a]=this.rgaTreeSplit.findNodeWithSplit(t[0],s),u=[],l=this.rgaTreeSplit.findBetween(a,o),h=new Map,g=[];for(const m of l){const A=m.getCreatedAt().getActorID(),E=i!=null&&i.size?i.has(A)?i.get(A):wt:Ns;if(m.canStyle(s,E)){const R=h.get(A),$=m.getCreatedAt();(!R||$.after(R))&&h.set(A,$),g.push(m)}}const v=[];for(const m of g){if(m.isRemoved())continue;const[A,E]=this.rgaTreeSplit.findIndexesFromRange(m.createPosRange());u.push({type:"style",actor:s.getActorID(),from:A,to:E,value:{attributes:rs(n)}});for(const[R,$]of Object.entries(n)){const[U]=m.getValue().setAttr(R,$,s);U!==void 0&&v.push({parent:m.getValue(),child:U})}}return[h,v,u]}indexRangeToPosRange(t,n){const s=this.rgaTreeSplit.indexToPos(t);return t===n?[s,s]:[s,this.rgaTreeSplit.indexToPos(n)]}get length(){return this.rgaTreeSplit.length}getTreeByIndex(){return this.rgaTreeSplit.getTreeByIndex()}getTreeByID(){return this.rgaTreeSplit.getTreeByID()}toJSON(){const t=[];for(const n of this.rgaTreeSplit)n.isRemoved()||t.push(n.getValue().toJSON());return`[${t.join(",")}]`}toSortedJSON(){return this.toJSON()}toJSForTest(){return{createdAt:this.getCreatedAt().toTestString(),value:JSON.parse(this.toJSON()),type:"YORKIE_TEXT"}}toString(){return this.rgaTreeSplit.toString()}values(){const t=[];for(const n of this.rgaTreeSplit)if(!n.isRemoved()){const s=n.getValue();t.push({attributes:rs(s.getAttributes()),content:s.getContent()})}return t}getRGATreeSplit(){return this.rgaTreeSplit}toTestString(){return this.rgaTreeSplit.toTestString()}deepcopy(){const t=new at(this.rgaTreeSplit.deepcopy(),this.getCreatedAt());return t.remove(this.getRemovedAt()),t}findIndexesFromRange(t){return this.rgaTreeSplit.findIndexesFromRange(t)}getGCPairs(){const t=[];for(const n of this.rgaTreeSplit){n.getRemovedAt()&&t.push({parent:this.rgaTreeSplit,child:n});for(const s of n.getValue().getGCPairs())t.push(s)}return t}}class _s extends Tt{constructor(t,n,s,i,o,a,u){super(t,u);c(this,"fromPos");c(this,"toPos");c(this,"maxCreatedAtMapByActor");c(this,"content");c(this,"attributes");this.fromPos=n,this.toPos=s,this.maxCreatedAtMapByActor=i,this.content=o,this.attributes=a}static create(t,n,s,i,o,a,u){return new _s(t,n,s,i,o,a,u)}execute(t){const n=t.findByCreatedAt(this.getParentCreatedAt());if(!n)throw new w(y.ErrInvalidArgument,`fail to find ${this.getParentCreatedAt()}`);if(!(n instanceof at))throw new w(y.ErrInvalidArgument,"fail to execute, only Text can execute edit");const s=n,[,i,o]=s.edit([this.fromPos,this.toPos],this.content,this.getExecutedAt(),Object.fromEntries(this.attributes),this.maxCreatedAtMapByActor);for(const a of o)t.registerGCPair(a);return{opInfos:i.map(({from:a,to:u,value:l})=>({type:"edit",from:a,to:u,value:l,path:t.createPath(this.getParentCreatedAt())}))}}getEffectedCreatedAt(){return this.getParentCreatedAt()}toTestString(){const t=this.getParentCreatedAt().toTestString(),n=this.fromPos.toTestString(),s=this.toPos.toTestString(),i=this.content;return`${t}.EDIT(${n},${s},${i})`}getFromPos(){return this.fromPos}getToPos(){return this.toPos}getContent(){return this.content}getAttributes(){return this.attributes||new Map}getMaxCreatedAtMapByActor(){return this.maxCreatedAtMapByActor}}class Xs extends Tt{constructor(t,n,s,i,o,a){super(t,a);c(this,"fromPos");c(this,"toPos");c(this,"maxCreatedAtMapByActor");c(this,"attributes");this.fromPos=n,this.toPos=s,this.maxCreatedAtMapByActor=i,this.attributes=o}static create(t,n,s,i,o,a){return new Xs(t,n,s,i,o,a)}execute(t){const n=t.findByCreatedAt(this.getParentCreatedAt());if(!n)throw new w(y.ErrInvalidArgument,`fail to find ${this.getParentCreatedAt()}`);if(!(n instanceof at))throw new w(y.ErrInvalidArgument,"fail to execute, only Text can execute edit");const s=n,[,i,o]=s.setStyle([this.fromPos,this.toPos],this.attributes?Object.fromEntries(this.attributes):{},this.getExecutedAt(),this.maxCreatedAtMapByActor);for(const a of i)t.registerGCPair(a);return{opInfos:o.map(({from:a,to:u,value:l})=>({type:"style",from:a,to:u,value:l,path:t.createPath(this.getParentCreatedAt())}))}}getEffectedCreatedAt(){return this.getParentCreatedAt()}toTestString(){const t=this.getParentCreatedAt().toTestString(),n=this.fromPos.toTestString(),s=this.toPos.toTestString(),i=this.attributes;return`${t}.STYL(${n},${s},${JSON.stringify(i)})`}getFromPos(){return this.fromPos}getToPos(){return this.toPos}getAttributes(){return this.attributes}getMaxCreatedAtMapByActor(){return this.maxCreatedAtMapByActor}}const np=2,sp="root",Zr="text";function As(r,e){let t=0;const n=r.children;for(let s=0;s0)throw new w(y.ErrRefused,"Text node cannot have children")}updateAncestorsSize(){let e=this.parent;const t=this.isRemoved?-1:1;for(;e&&(e.size+=this.paddedSize*t,!e.isRemoved);)e=e.parent}updateDescendantsSize(){let e=0;for(const t of this._children){const n=t.updateDescendantsSize();t.isRemoved||(e+=n)}return this.size+=e,this.paddedSize}get isText(){return this.type===Zr}get paddedSize(){return this.size+(this.isText?0:np)}isAncestorOf(e){return op(this,e)}get nextSibling(){const e=this.parent.findOffset(this),t=this.parent.children[e+1];if(t)return t}get prevSibling(){const e=this.parent.findOffset(this),t=this.parent.children[e-1];if(t)return t}splitText(e,t){if(e===0||e===this.size)return;const n=this.value.slice(0,e),s=this.value.slice(e);if(!s.length)return;this.value=n;const i=this.cloneText(e+t);return i.value=s,this.parent.insertAfterInternal(i,this),i}get children(){return this._children.filter(e=>!e.isRemoved)}get allChildren(){return[...this._children]}hasTextChild(){return this.children.length>0&&this.children.every(e=>e.isText)}append(...e){if(this.isText)throw new w(y.ErrRefused,"Text node cannot have children");this._children.push(...e);for(const t of e)t.parent=this,t.updateAncestorsSize()}prepend(...e){if(this.isText)throw new w(y.ErrRefused,"Text node cannot have children");this._children.unshift(...e);for(const t of e)t.parent=this}insertBefore(e,t){if(this.isText)throw new w(y.ErrRefused,"Text node cannot have children");const n=this._children.indexOf(t);if(n===-1)throw new w(y.ErrInvalidArgument,"child not found");this.insertAtInternal(e,n),e.updateAncestorsSize()}insertAfter(e,t){if(this.isText)throw new w(y.ErrRefused,"Text node cannot have children");const n=this._children.indexOf(t);if(n===-1)throw new w(y.ErrInvalidArgument,"child not found");this.insertAtInternal(e,n+1),e.updateAncestorsSize()}insertAt(e,t){if(this.isText)throw new w(y.ErrRefused,"Text node cannot have children");this.insertAtInternal(e,t),e.updateAncestorsSize()}removeChild(e){if(this.isText)throw new w(y.ErrRefused,"Text node cannot have children");const t=this._children.indexOf(e);if(t===-1)throw new w(y.ErrInvalidArgument,"child not found");this._children.splice(t,1),e.parent=void 0}splitElement(e,t){const n=this.cloneElement(t);this.parent.insertAfterInternal(n,this),n.updateAncestorsSize();const s=this.children.slice(0,e),i=this.children.slice(e);this._children=s,n._children=i,this.size=this._children.reduce((o,a)=>o+a.paddedSize,0),n.size=n._children.reduce((o,a)=>o+a.paddedSize,0);for(const o of n._children)o.parent=n;return n}insertAfterInternal(e,t){if(this.isText)throw new w(y.ErrRefused,"Text node cannot have children");const n=this._children.indexOf(t);if(n===-1)throw new w(y.ErrInvalidArgument,"child not found");this.insertAtInternal(e,n+1)}insertAtInternal(e,t){if(this.isText)throw new w(y.ErrRefused,"Text node cannot have children");this._children.splice(t,0,e),e.parent=this}findOffset(e){if(this.isText)throw new w(y.ErrRefused,"Text node cannot have children");if(e.isRemoved){const t=this._children.indexOf(e);return this.allChildren.splice(0,t).filter(s=>!s.isRemoved).length}return this.children.indexOf(e)}findBranchOffset(e){if(this.isText)throw new w(y.ErrRefused,"Text node cannot have children");let t=e;for(;t;){const n=this._children.indexOf(t);if(n!==-1)return n;t=t.parent}return-1}}function op(r,e){if(r===e)return!1;for(;e.parent;){if(e.parent===r)return!0;e=e.parent}return!1}var ve=(r=>(r.Start="Start",r.End="End",r.Text="Text",r))(ve||{});function Af(r,e,t,n){if(e>t)throw new w(y.ErrInvalidArgument,`from is greater than to: ${e} > ${t}`);if(e>r.size)throw new w(y.ErrInvalidArgument,`from is out of range: ${e} > ${r.size}`);if(t>r.size)throw new w(y.ErrInvalidArgument,`to is out of range: ${t} > ${r.size}`);if(e===t)return;let s=0;for(const i of r.children){if(e-i.paddedSizei.size;(i.isText||u)&&n([i,i.isText?"Text":"Start"],l),Af(i,Math.max(0,o),Math.min(a,i.size),n),l&&n([i,"End"],l)}s+=i.paddedSize}}function If(r,e,t=0){for(const n of r.children)If(n,e,t+1);e(r,t)}function yo(r,e,t=0){for(const n of r._children)yo(n,e,t+1);e(r,t)}function Sa(r,e,t=!0){if(e>r.size)throw new w(y.ErrInvalidArgument,`index is out of range: ${e} > ${r.size}`);if(r.isText)return{node:r,offset:e};let n=0,s=0;for(const i of r.children){if(t&&i.isText&&i.size>=e-s)return Sa(i,e-s,t);if(e===s)return{node:r,offset:n};if(!t&&i.paddedSize===e-s)return{node:r,offset:n+1};if(i.paddedSize>e-s)return Sa(i,e-s-1,t);s+=i.paddedSize,n+=1}return{node:r,offset:n}}function Sf(r){return r.isText||r.children.length===0?r:Sf(r.children[0])}function ap(r,e){if(r.sizer===e?0:r0)if(t.right)t.right.parent=t,t=t.right;else return t;else if(n<0)if(t.left)t.left.parent=t,t=t.left;else{let s=t.parent,i=t;for(;s&&i===s.left;)i=s,s=s.parent;return s}else return t}}lastEntry(){if(!this.root)return this.root;let e=this.root;for(;e.right;)e=e.right;return e}size(){return this.counter}isEmpty(){return this.counter===0}getInternal(e,t){for(;t;){const n=this.comparator(e,t.key);if(n===0)return t;n<0?t=t.left:n>0&&(t=t.right)}}putInternal(e,t,n){if(!n)return this.counter+=1,new lp(e,t,!0);const s=this.comparator(e,n.key);return s<0?n.left=this.putInternal(e,t,n.left):s>0?n.right=this.putInternal(e,t,n.right):n.value=t,this.isRed(n.right)&&!this.isRed(n.left)&&(n=this.rotateLeft(n)),this.isRed(n.left)&&this.isRed(n.left.left)&&(n=this.rotateRight(n)),this.isRed(n.left)&&this.isRed(n.right)&&this.flipColors(n),n}removeInternal(e,t){if(this.comparator(t,e.key)<0)!this.isRed(e.left)&&!this.isRed(e.left.left)&&(e=this.moveRedLeft(e)),e.left=this.removeInternal(e.left,t);else{if(this.isRed(e.left)&&(e=this.rotateRight(e)),this.comparator(t,e.key)===0&&!e.right){this.counter-=1;return}if(!this.isRed(e.right)&&!this.isRed(e.right.left)&&(e=this.moveRedRight(e)),this.comparator(t,e.key)===0){this.counter-=1;const n=this.min(e.right);e.value=n.value,e.key=n.key,e.right=this.removeMin(e.right)}else e.right=this.removeInternal(e.right,t)}return this.fixUp(e)}min(e){return e.left?this.min(e.left):e}removeMin(e){if(e.left)return!this.isRed(e.left)&&!this.isRed(e.left.left)&&(e=this.moveRedLeft(e)),e.left=this.removeMin(e.left),this.fixUp(e)}fixUp(e){return this.isRed(e.right)&&(e=this.rotateLeft(e)),this.isRed(e.left)&&this.isRed(e.left.left)&&(e=this.rotateRight(e)),this.isRed(e.left)&&this.isRed(e.right)&&this.flipColors(e),e}moveRedLeft(e){return this.flipColors(e),this.isRed(e.right.left)&&(e.right=this.rotateRight(e.right),e=this.rotateLeft(e),this.flipColors(e)),e}moveRedRight(e){return this.flipColors(e),this.isRed(e.left.left)&&(e=this.rotateRight(e),this.flipColors(e)),e}isRed(e){return e&&e.isRed}rotateLeft(e){const t=e.right;return e.right=t.left,t.left=e,t.isRed=t.left.isRed,t.left.isRed=!0,t}rotateRight(e){const t=e.left;return e.left=t.right,t.right=e,t.isRed=t.right.isRed,t.right.isRed=!0,t}flipColors(e){e.isRed=!e.isRed,e.left.isRed=!e.left.isRed,e.right.isRed=!e.right.isRed}}class yt{constructor(e,t){c(this,"parentID");c(this,"leftSiblingID");this.parentID=e,this.leftSiblingID=t}static of(e,t){return new yt(e,t)}static fromTreePos(e){const{offset:t}=e;let{node:n}=e,s;return n.isText?(n.parent.children[0]===n&&t===0?s=n.parent:s=n,n=n.parent):t===0?s=n:s=n.children[t-1],yt.of(n.id,Ae.of(s.getCreatedAt(),s.getOffset()+t))}getParentID(){return this.parentID}static fromStruct(e){return yt.of(Ae.of(Ke.fromStruct(e.parentID.createdAt),e.parentID.offset),Ae.of(Ke.fromStruct(e.leftSiblingID.createdAt),e.leftSiblingID.offset))}toStruct(){return{parentID:{createdAt:this.getParentID().getCreatedAt().toStruct(),offset:this.getParentID().getOffset()},leftSiblingID:{createdAt:this.getLeftSiblingID().getCreatedAt().toStruct(),offset:this.getLeftSiblingID().getOffset()}}}toTreeNodePair(e){const t=this.getParentID(),n=this.getLeftSiblingID(),s=e.findFloorNode(t);let i=e.findFloorNode(n);if(!s||!i)throw new w(y.ErrRefused,`cannot find node of CRDTTreePos(${t.toTestString()}, ${n.toTestString()})`);return!n.equals(t)&&n.getOffset()>0&&n.getOffset()===i.id.getOffset()&&i.insPrevID&&(i=e.findFloorNode(i.insPrevID)),[s,i]}getLeftSiblingID(){return this.leftSiblingID}equals(e){return this.getParentID().getCreatedAt().equals(e.getParentID().getCreatedAt())&&this.getParentID().getOffset()===e.getParentID().getOffset()&&this.getLeftSiblingID().getCreatedAt().equals(e.getLeftSiblingID().getCreatedAt())&&this.getLeftSiblingID().getOffset()===e.getLeftSiblingID().getOffset()}}class Ae{constructor(e,t){c(this,"createdAt");c(this,"offset");this.createdAt=e,this.offset=t}static of(e,t){return new Ae(e,t)}static fromStruct(e){return Ae.of(Ke.fromStruct(e.createdAt),e.offset)}static createComparator(){return(e,t)=>{const n=e.getCreatedAt().compare(t.getCreatedAt());return n!==0?n:e.getOffset()>t.getOffset()?1:e.getOffset(){const i=s.deepcopy();return i.parent=t,i}),t.insPrevID=this.insPrevID,t.insNextID=this.insNextID,t}get value(){if(!this.isText)throw new w(y.ErrInvalidType,`cannot get value of element node: ${this.type}`);return this._value}set value(t){if(!this.isText)throw new w(y.ErrInvalidType,`cannot set value of element node: ${this.type}`);this._value=t,this.size=t.length}get isRemoved(){return!!this.removedAt}remove(t){const n=!this.removedAt;(!this.removedAt||this.removedAt.compare(t)>0)&&(this.removedAt=t),n&&this.updateAncestorsSize()}cloneText(t){return new ze(Ae.of(this.id.getCreatedAt(),t),this.type,void 0,void 0,this.removedAt)}cloneElement(t){return new ze(Ae.of(t(),0),this.type,void 0,void 0,this.removedAt)}split(t,n,s){const i=this.isText?this.splitText(n,this.id.getOffset()):this.splitElement(n,s);if(i){if(i.insPrevID=this.id,this.insNextID){const o=t.findFloorNode(this.insNextID);o.insPrevID=i.id,i.insNextID=this.insNextID}this.insNextID=i.id,t.registerNode(i)}return i}getCreatedAt(){return this.id.getCreatedAt()}getOffset(){return this.id.getOffset()}canDelete(t,n){return!this.getCreatedAt().after(n)&&(!this.removedAt||t.after(this.removedAt))}canStyle(t,n){return this.isText?!1:!this.getCreatedAt().after(n)&&(!this.removedAt||t.after(this.removedAt))}setAttrs(t,n){this.attrs||(this.attrs=new rn);const s=new Array;for(const[i,o]of Object.entries(t))s.push(this.attrs.set(i,o,n));return s}purge(t){this.attrs&&this.attrs.purge(t)}getGCPairs(){const t=[];if(!this.attrs)return t;for(const n of this.attrs)n.getRemovedAt()&&t.push({parent:this,child:n});return t}}function xa(r){var t;if(r.isText){const n=r;return{type:n.type,value:n.value}}const e={type:r.type,children:r.children.map(xa)};return r.attrs&&(e.attributes=rs((t=r.attrs)==null?void 0:t.toObject())),e}function nc(r){if(r.isText)return r.value;let e="";return r.attrs&&r.attrs.size()&&(e=" "+Array.from(r.attrs).filter(t=>!t.isRemoved()).sort((t,n)=>t.getKey().localeCompare(n.getKey())).map(t=>{const n=JSON.parse(t.getValue());return typeof n=="string"?`${t.getKey()}="${n}"`:`${t.getKey()}="${$t(t.getValue())}"`}).join(" ")),`<${r.type}${e}>${r.children.map(t=>nc(t)).join("")}`}function kf(r){if(r.isText){const e=r;return{type:e.type,value:e.value,size:e.size,isRemoved:e.isRemoved}}return{type:r.type,children:r.children.map(kf),size:r.size,isRemoved:r.isRemoved}}class ct extends Gs{constructor(t,n){super(n);c(this,"indexTree");c(this,"nodeMapByID");this.indexTree=new cp(t),this.nodeMapByID=new xf(Ae.createComparator()),this.indexTree.traverseAll(s=>{this.nodeMapByID.put(s.id,s)})}static create(t,n){return new ct(t,n)}findFloorNode(t){const n=this.nodeMapByID.floorEntry(t);if(!(!n||!n.key.getCreatedAt().equals(t.getCreatedAt())))return n.value}registerNode(t){this.nodeMapByID.put(t.id,t)}findNodesAndSplitText(t,n){const[s,i]=t.toTreeNodePair(this);let o=i;const a=s===o,u=o.parent&&!a?o.parent:s;if(o.isText&&o.split(this,t.getLeftSiblingID().getOffset()-o.id.getOffset()),n){const l=u.allChildren,h=a?0:l.indexOf(o)+1;for(let g=h;g{const E=A.getCreatedAt().getActorID(),R=i?i.has(E)?i.get(E):wt:Ns;if(A.canStyle(s,R)&&n){const $=v.get(E),U=A.getCreatedAt();(!$||U.after($))&&v.set(E,U);const _=A.setAttrs(n,s),D=_.reduce((ae,[,Se])=>(Se&&(ae[Se.getKey()]=g[Se.getKey()]),ae),{}),G=A.parent,ee=A.prevSibling||A.parent;Object.keys(D).length>0&&h.push({type:"style",from:this.toIndex(G,ee),to:this.toIndex(A,A),fromPath:this.toPath(G,ee),toPath:this.toPath(A,A),actor:s.getActorID(),value:D});for(const[ae]of _)ae&&m.push({parent:A,child:ae})}}),[v,m,h]}removeStyle(t,n,s,i){const[o,a]=this.findNodesAndSplitText(t[0],s),[u,l]=this.findNodesAndSplitText(t[1],s),h=[],g=new Map,v=[];return this.traverseInPosRange(o,a,u,l,([m])=>{const A=m.getCreatedAt().getActorID(),E=i?i.has(A)?i.get(A):wt:Ns;if(m.canStyle(s,E)&&n){const R=g.get(A),$=m.getCreatedAt();(!R||$.after(R))&&g.set(A,$),m.attrs||(m.attrs=new rn);for(const D of n){const G=m.attrs.remove(D,s);for(const ee of G)v.push({parent:m,child:ee})}const U=m.parent,_=m.prevSibling||m.parent;h.push({actor:s.getActorID(),type:"removeStyle",from:this.toIndex(U,_),to:this.toIndex(m,m),fromPath:this.toPath(U,_),toPath:this.toPath(m,m),value:n})}}),[g,v,h]}edit(t,n,s,i,o,a){const[u,l]=this.findNodesAndSplitText(t[0],i),[h,g]=this.findNodesAndSplitText(t[1],i),v=this.toIndex(u,l),m=this.toPath(u,l),A=[],E=[],R=[],$=new Map;this.traverseInPosRange(u,l,h,g,([D,G],ee)=>{if(G===ve.Start&&!ee)for(const ut of D.children)R.push(ut);const ae=D.getCreatedAt().getActorID(),Se=a?a.has(ae)?a.get(ae):wt:Ns;if(D.canDelete(i,Se)||A.includes(D.parent)){const ut=$.get(ae),He=D.getCreatedAt();(!ut||He.after(ut))&&$.set(ae,He),(G===ve.Text||G===ve.Start)&&A.push(D),E.push([D,G])}});const U=this.makeDeletionChanges(E,i),_=[];for(const D of A)D.remove(i),D.isRemoved&&_.push({parent:this,child:D});for(const D of R)D.removedAt||u.append(D);if(s>0){let D=0,G=u,ee=l;for(;D{u.isRemoved&&(ae.remove(i),_.push({parent:this,child:ae})),this.nodeMapByID.put(ae.id,ae)}),ee.isRemoved||D.push(ee);if(D.length){const ee=D.map(ae=>xa(ae));U.length&&U[U.length-1].from===v?U[U.length-1].value=ee:U.push({type:"content",from:v,to:v,fromPath:m,toPath:m,actor:i.getActorID(),value:ee})}}return[U,_,$]}editT(t,n,s,i,o){const a=this.findPos(t[0]),u=this.findPos(t[1]);this.edit([a,u],n,s,i,o)}move(t,n,s){throw new w(y.ErrUnimplemented,`not implemented: ${t}, ${n}, ${s}`)}purge(t){var i;(i=t.parent)==null||i.removeChild(t),this.nodeMapByID.remove(t.id);const n=t.insPrevID,s=t.insNextID;if(n){const o=this.findFloorNode(n);o.insNextID=s}if(s){const o=this.findFloorNode(s);o.insPrevID=n}t.insPrevID=void 0,t.insNextID=void 0}getGCPairs(){const t=[];return this.indexTree.traverse(n=>{n.getRemovedAt()&&t.push({parent:this,child:n});for(const s of n.getGCPairs())t.push(s)}),t}findPos(t,n=!0){const s=this.indexTree.findTreePos(t,n);return yt.fromTreePos(s)}pathToPosRange(t){const n=this.pathToIndex(t);return[this.findPos(n),this.findPos(n+1)]}pathToPos(t){const n=this.indexTree.pathToIndex(t);return this.findPos(n)}getRoot(){return this.indexTree.getRoot()}getSize(){return this.indexTree.size}getNodeSize(){return this.nodeMapByID.size()}getIndexTree(){return this.indexTree}toXML(){return nc(this.indexTree.getRoot())}toJSON(){return JSON.stringify(this.getRootTreeNode())}toJSForTest(){return{createdAt:this.getCreatedAt().toTestString(),value:JSON.parse(this.toJSON()),type:"YORKIE_TREE"}}toJSInfoForTest(){const t=this.indexTree.getRoot(),n=(s,i=void 0,o=void 0,a=0)=>{var m,A,E,R;let u,l,h;const g=s.isText?{node:s,offset:0}:i&&o?this.toTreePos(i,o):null;g&&(u=this.indexTree.indexOf(g),l=this.indexTree.treePosToPath(g),h=yt.fromTreePos(g).toStruct());const v={type:s.type,parent:i==null?void 0:i.id.toTestString(),size:s.size,id:s.id.toTestString(),removedAt:(m=s.removedAt)==null?void 0:m.toTestString(),insPrev:(A=s.insPrevID)==null?void 0:A.toTestString(),insNext:(E=s.insNextID)==null?void 0:E.toTestString(),value:s.isText?s.value:void 0,isRemoved:s.isRemoved,children:[],depth:a,attributes:s.attrs?rs((R=s.attrs)==null?void 0:R.toObject()):void 0,index:u,path:l,pos:h};for(let $=0;$0&&$===s[s.length-1].to?(s[s.length-1].to=U,s[s.length-1].toPath=this.toPath(R,m)):s.push({type:"content",from:$,to:U,fromPath:this.toPath(E,g),toPath:this.toPath(R,m),actor:n.getActorID()}))}return s.reverse()}findRightToken([t,n]){if(n===ve.Start){const u=t.allChildren;return u.length>0?[u[0],u[0].isText?ve.Text:ve.Start]:[t,ve.End]}const s=t.parent,i=s.allChildren,o=i.indexOf(t);if(s&&o===i.length-1)return[s,ve.End];const a=i[o+1];return[a,a.isText?ve.Text:ve.Start]}findLeftToken([t,n]){if(n===ve.End){const u=t.allChildren;if(u.length>0){const l=u[u.length-1];return[l,l.isText?ve.Text:ve.End]}return[t,ve.Start]}const s=t.parent,i=s.allChildren,o=i.indexOf(t);if(s&&o===0)return[s,ve.Start];const a=i[o-1];return[a,a.isText?ve.Text:ve.End]}}class Zs extends Tt{constructor(t,n,s,i,o,a,u){super(t,u);c(this,"fromPos");c(this,"toPos");c(this,"contents");c(this,"splitLevel");c(this,"maxCreatedAtMapByActor");this.fromPos=n,this.toPos=s,this.contents=i,this.splitLevel=o,this.maxCreatedAtMapByActor=a}static create(t,n,s,i,o,a,u){return new Zs(t,n,s,i,o,a,u)}execute(t){var u;const n=t.findByCreatedAt(this.getParentCreatedAt());if(!n)throw new w(y.ErrInvalidArgument,`fail to find ${this.getParentCreatedAt()}`);if(!(n instanceof ct))throw new w(y.ErrInvalidArgument,"fail to execute, only Tree can execute edit");const s=this.getExecutedAt(),i=n,[o,a]=i.edit([this.fromPos,this.toPos],(u=this.contents)==null?void 0:u.map(l=>l.deepcopy()),this.splitLevel,s,(()=>{let l=s.getDelimiter();return this.contents!==void 0&&(l+=this.contents.length),()=>Ke.of(s.getLamport(),++l,s.getActorID())})(),this.maxCreatedAtMapByActor);for(const l of a)t.registerGCPair(l);return{opInfos:o.map(({from:l,to:h,value:g,splitLevel:v,fromPath:m,toPath:A})=>({type:"tree-edit",path:t.createPath(this.getParentCreatedAt()),from:l,to:h,value:g,splitLevel:v,fromPath:m,toPath:A}))}}getEffectedCreatedAt(){return this.getParentCreatedAt()}toTestString(){const t=this.getParentCreatedAt().toTestString(),n=`${this.fromPos.getLeftSiblingID().getCreatedAt().toTestString()}/${this.fromPos.getLeftSiblingID().getOffset()}`,s=`${this.toPos.getLeftSiblingID().getCreatedAt().toTestString()}/${this.toPos.getLeftSiblingID().getOffset()}`,i=this.contents||[];return`${t}.EDIT(${n},${s},${i.map(o=>nc(o)).join("")})`}getFromPos(){return this.fromPos}getToPos(){return this.toPos}getContents(){return this.contents}getSplitLevel(){return this.splitLevel}getMaxCreatedAtMapByActor(){return this.maxCreatedAtMapByActor}}class ns{constructor(e){c(this,"vector");this.vector=e||new Map}set(e,t){this.vector.set(e,t)}get(e){return this.vector.get(e)}maxLamport(){let e=BigInt(0);for(const[,t]of this)t>e&&(e=t);return e}max(e){const t=new Map;for(const[n,s]of e){const i=this.vector.get(n),o=i&&i>s?i:s;t.set(n,o)}for(const[n,s]of this){const i=e.get(n),o=i&&i>s?i:s;t.set(n,o)}return new ns(t)}afterOrEqual(e){const t=this.vector.get(e.getActorID());return t===void 0?!1:t>=e.getLamport()}deepcopy(){const e=new Map;for(const[t,n]of this.vector)e.set(t,n);return new ns(e)}filter(e){const t=new Map;for(const[n]of e){const s=this.vector.get(n);s!==void 0&&t.set(n,s)}return new ns(t)}size(){return this.vector.size}*[Symbol.iterator](){for(const[e,t]of this.vector)yield[e,t]}}const hp=new ns(new Map);class Hr{constructor(e,t,n,s,i){c(this,"clientSeq");c(this,"serverSeq");c(this,"lamport");c(this,"actor");c(this,"versionVector");this.clientSeq=e,this.serverSeq=i,this.lamport=t,this.versionVector=s,this.actor=n}static of(e,t,n,s,i){return new Hr(e,t,n,s,i)}next(){const e=this.versionVector.deepcopy();return e.set(this.actor,this.lamport+1n),new Hr(this.clientSeq+1,this.lamport+1n,this.actor,e)}syncClocks(e){const t=e.lamport>this.lamport?e.lamport+1n:this.lamport+1n,n=this.versionVector.max(e.versionVector),s=new Hr(this.clientSeq,t,this.actor,n);return s.versionVector.set(this.actor,t),s}setClocks(e,t){const n=e>this.lamport?e:this.lamport+1n,s=this.versionVector.max(t);return s.set(this.actor,n),Hr.of(this.clientSeq,n,this.actor,s)}createTimeTicket(e){return Ke.of(this.lamport,e,this.actor)}setActor(e){return new Hr(this.clientSeq,this.lamport,e,this.versionVector,this.serverSeq)}setVersionVector(e){return new Hr(this.clientSeq,this.lamport,this.actor,e,this.serverSeq)}getClientSeq(){return this.clientSeq}getServerSeq(){return this.serverSeq?this.serverSeq.toString():""}getLamport(){return this.lamport}getLamportAsString(){return this.lamport.toString()}getActorID(){return this.actor}getVersionVector(){return this.versionVector}toTestString(){return`${this.lamport.toString()}:${this.actor.slice(-2)}:${this.clientSeq}`}}const dp=new Hr(0,0n,ec,hp);class ds{constructor({id:e,operations:t,presenceChange:n,message:s}){c(this,"id");c(this,"operations");c(this,"presenceChange");c(this,"message");this.id=e,this.operations=t||[],this.presenceChange=n,this.message=s}static create({id:e,operations:t,presenceChange:n,message:s}){return new ds({id:e,operations:t,presenceChange:n,message:s})}getID(){return this.id}getMessage(){return this.message}hasOperations(){return this.operations.length>0}getOperations(){return this.operations}setActor(e){for(const t of this.operations)t.setActor(e);this.id=this.id.setActor(e)}hasPresenceChange(){return this.presenceChange!==void 0}getPresenceChange(){return this.presenceChange}execute(e,t,n){const s=[],i=[];for(const o of this.operations){const a=o.execute(e,n);if(!a)continue;const{opInfos:u,reverseOp:l}=a;s.push(...u),l&&i.unshift(l)}return this.presenceChange&&(this.presenceChange.type===bn.Put?t.set(this.id.getActorID(),ht(this.presenceChange.presence)):t.delete(this.id.getActorID())),{opInfos:s,reverseOps:i}}toTestString(){return`${this.operations.map(e=>e.toTestString()).join(",")}`}toStruct(){return{changeID:me.bytesToHex(me.toChangeID(this.getID()).toBinary()),message:this.getMessage(),operations:this.getOperations().map(e=>me.bytesToHex(me.toOperation(e).toBinary())),presenceChange:this.getPresenceChange()}}static fromStruct(e){const{changeID:t,operations:n,presenceChange:s,message:i}=e;return ds.create({id:me.bytesToChangeID(me.hexToBytes(t)),operations:n==null?void 0:n.map(o=>me.bytesToOperation(me.hexToBytes(o))),presenceChange:s,message:i})}}class vo{constructor(e,t,n,s,i,o,a){c(this,"documentKey");c(this,"checkpoint");c(this,"isRemoved");c(this,"changes");c(this,"snapshot");c(this,"minSyncedTicket");c(this,"versionVector");this.documentKey=e,this.checkpoint=t,this.isRemoved=n,this.changes=s,this.snapshot=o,this.minSyncedTicket=a,this.versionVector=i}static create(e,t,n,s,i,o,a){return new vo(e,t,n,s,i,o,a)}getDocumentKey(){return this.documentKey}getCheckpoint(){return this.checkpoint}getIsRemoved(){return this.isRemoved}getChanges(){return this.changes}hasChanges(){return this.changes.length>0}getChangeSize(){return this.changes.length}hasSnapshot(){return!!this.snapshot&&!!this.snapshot.length}getSnapshot(){return this.snapshot}getMinSyncedTicket(){return this.minSyncedTicket}getVersionVector(){return this.versionVector}}class ss{constructor(e,t){c(this,"serverSeq");c(this,"clientSeq");this.serverSeq=e,this.clientSeq=t}static of(e,t){return new ss(e,t)}increaseClientSeq(e){return e===0?this:new ss(this.serverSeq,this.clientSeq+e)}forward(e){if(this.equals(e))return this;const t=this.serverSeq>e.serverSeq?this.serverSeq:e.serverSeq,n=Math.max(this.clientSeq,e.clientSeq);return ss.of(t,n)}getServerSeqAsString(){return this.serverSeq.toString()}getClientSeq(){return this.clientSeq}getServerSeq(){return this.serverSeq}equals(e){return this.clientSeq===e.clientSeq&&this.serverSeq==e.serverSeq}toTestString(){return`serverSeq=${this.serverSeq}, clientSeq=${this.clientSeq}`}}const gp=new ss(0n,0);class qt{constructor(e,t){c(this,"createdAt");c(this,"offset");this.createdAt=e,this.offset=t}static of(e,t){return new qt(e,t)}static fromStruct(e){return qt.of(Ke.fromStruct(e.createdAt),e.offset)}getCreatedAt(){return this.createdAt}getOffset(){return this.offset}equals(e){return this.createdAt.compare(e.createdAt)===0&&this.offset===e.offset}hasSameCreatedAt(e){return this.createdAt.compare(e.createdAt)===0}split(e){return new qt(this.createdAt,this.offset+e)}toStruct(){return{createdAt:this.createdAt.toStruct(),offset:this.offset}}toTestString(){return`${this.createdAt.toTestString()}:${this.offset}`}toIDString(){return`${this.createdAt.toIDString()}:${this.offset}`}}const mp=qt.of(wt,0);class bt{constructor(e,t){c(this,"id");c(this,"relativeOffset");this.id=e,this.relativeOffset=t}static of(e,t){return new bt(e,t)}static fromStruct(e){const t=qt.fromStruct(e.id);return bt.of(t,e.relativeOffset)}getID(){return this.id}getRelativeOffset(){return this.relativeOffset}getAbsoluteID(){return qt.of(this.id.getCreatedAt(),this.id.getOffset()+this.relativeOffset)}toTestString(){return`${this.id.toTestString()}:${this.relativeOffset}`}toStruct(){return{id:this.id.toStruct(),relativeOffset:this.relativeOffset}}equals(e){return this.id.equals(e.id)?this.relativeOffset===e.relativeOffset:!1}}class yn extends yf{constructor(t,n,s){super(n);c(this,"id");c(this,"removedAt");c(this,"prev");c(this,"next");c(this,"insPrev");c(this,"insNext");this.id=t,this.removedAt=s}static create(t,n){return new yn(t,n)}static createComparator(){return(t,n)=>{const s=t.getCreatedAt().compare(n.getCreatedAt());return s!==0?s:t.getOffset()>n.getOffset()?1:t.getOffset()0&&t.getID().getOffset()==e.getOffset()){if(!t.hasInsPrev())return t;t=t.getInsPrev()}return t}findFloorNode(e){const t=this.treeByID.floorEntry(e);if(t&&!(!t.key.equals(e)&&!t.key.hasSameCreatedAt(e)))return t.value}findBetween(e,t){const n=[];let s=e;for(;s&&s!==t;)n.push(s),s=s.getNext();return n}splitNode(e,t){if(t>e.getContentLength())throw new w(y.ErrInvalidArgument,"offset should be less than or equal to length");if(t===0)return e;if(t===e.getContentLength())return e.getNext();const n=e.split(t);this.treeByIndex.updateWeight(n),this.insertAfter(e,n);const s=e.getInsNext();return s&&s.setInsPrev(n),n.setInsPrev(e),n}deleteNodes(e,t,n){if(!e.length)return[[],new Map,new Map];const[s,i]=this.filterNodes(e,t,n),o=new Map,a=new Map,u=this.makeChanges(i,t);for(const l of s){const h=l.getCreatedAt().getActorID();(!o.has(h)||l.getID().getCreatedAt().after(o.get(h)))&&o.set(h,l.getID().getCreatedAt()),a.set(l.getID().toIDString(),l),l.remove(t)}return this.deleteIndexNodes(i),[u,o,a]}filterNodes(e,t,n){const s=!!n,i=[],o=[],[a,u]=this.findEdgesOfCandidates(e);o.push(a);for(const l of e){const h=l.getCreatedAt().getActorID(),g=s?n.has(h)?n.get(h):wt:Ns;l.canDelete(t,g)?i.push(l):o.push(l)}return o.push(u),[i,o]}findEdgesOfCandidates(e){return[e[0].getPrev(),e[e.length-1].getNext()]}makeChanges(e,t){const n=[];let s,i;for(let o=0;or<0?Math.ceil(r):Math.floor(r);var Vt=(r=>(r[r.IntegerCnt=0]="IntegerCnt",r[r.LongCnt=1]="LongCnt",r))(Vt||{});class We extends Gs{constructor(t,n,s){super(s);c(this,"valueType");c(this,"value");switch(this.valueType=t,t){case 0:typeof n=="number"?n>Math.pow(2,31)-1||n<-Math.pow(2,31)?this.value=X.fromNumber(n).toInt():this.value=Vu(n):this.value=n.toInt();break;case 1:typeof n=="number"?this.value=X.fromNumber(n):this.value=n;break;default:throw new w(y.ErrUnimplemented,`unimplemented type: ${t}`)}}static create(t,n,s){return new We(t,n,s)}static valueFromBytes(t,n){switch(t){case 0:return n[0]|n[1]<<8|n[2]<<16|n[3]<<24;case 1:return X.fromBytesLE(Array.from(n));default:throw new w(y.ErrUnimplemented,`unimplemented type: ${t}`)}}toJSON(){return`${this.value}`}toSortedJSON(){return this.toJSON()}toJSForTest(){return{createdAt:this.getCreatedAt().toTestString(),value:this.value,type:"YORKIE_COUNTER"}}deepcopy(){const t=We.create(this.valueType,this.value,this.getCreatedAt());return t.setMovedAt(this.getMovedAt()),t}getType(){return this.valueType}static getCounterType(t){switch(typeof t){case"object":return t instanceof X?1:void 0;case"number":return t>Math.pow(2,31)-1||t<-Math.pow(2,31)?1:0;default:return}}static isSupport(t){return!!We.getCounterType(t)}static isInteger(t){return t%1===0}isNumericType(){const t=this.valueType;return t===0||t===1}getValueType(){return this.valueType}getValue(){return this.value}toBytes(){switch(this.valueType){case 0:{const t=this.value;return new Uint8Array([t&255,t>>8&255,t>>16&255,t>>24&255])}case 1:{const n=this.value.toBytesLE();return Uint8Array.from(n)}default:throw new w(y.ErrUnimplemented,`unimplemented type: ${this.valueType}`)}}increase(t){function n(s){if(!s.isNumericType())throw new TypeError(`Unsupported type of value: ${typeof s.getValue()}`)}return n(this),n(t),this.valueType===1?this.value=this.value.add(t.getValue()):t.getType()===be.Long?this.value=this.value+t.getValue().toInt():this.value=X.fromNumber(this.value+Vu(t.getValue())).toInt(),this}}class ms extends Tt{constructor(t,n,s){super(t,s);c(this,"value");this.value=n}static create(t,n,s){return new ms(t,n,s)}execute(t){const n=t.findByCreatedAt(this.getParentCreatedAt());if(!n)throw new w(y.ErrInvalidArgument,`fail to find ${this.getParentCreatedAt()}`);if(!(n instanceof We))throw new w(y.ErrInvalidArgument,"fail to execute, only Counter can execute increase");const s=n,i=this.value.deepcopy();return s.increase(i),{opInfos:[{type:"increase",path:t.createPath(this.getParentCreatedAt()),value:i.getValue()}],reverseOp:this.toReverseOperation()}}toReverseOperation(){const t=this.value.deepcopy(),s=t.getType()===be.Long?t.getValue().multiply(-1):t.getValue()*-1;return ms.create(this.getParentCreatedAt(),le.of(s,t.getCreatedAt()))}getEffectedCreatedAt(){return this.getParentCreatedAt()}toTestString(){return`${this.getParentCreatedAt().toTestString()}.INCREASE.${this.value.toJSON()}`}getValue(){return this.value}}class Qr extends Tt{constructor(t,n,s,i,o,a,u){super(t,u);c(this,"fromPos");c(this,"toPos");c(this,"maxCreatedAtMapByActor");c(this,"attributes");c(this,"attributesToRemove");this.fromPos=n,this.toPos=s,this.maxCreatedAtMapByActor=i,this.attributes=o,this.attributesToRemove=a}static create(t,n,s,i,o,a){return new Qr(t,n,s,i,o,new Array,a)}static createTreeRemoveStyleOperation(t,n,s,i,o,a){return new Qr(t,n,s,i,new Map,o,a)}execute(t){const n=t.findByCreatedAt(this.getParentCreatedAt());if(!n)throw new w(y.ErrInvalidArgument,`fail to find ${this.getParentCreatedAt()}`);if(!(n instanceof ct))throw new w(y.ErrInvalidArgument,"fail to execute, only Tree can execute edit");const s=n;let i,o;if(this.attributes.size){const a={};[...this.attributes].forEach(([u,l])=>a[u]=l),[,o,i]=s.style([this.fromPos,this.toPos],a,this.getExecutedAt(),this.maxCreatedAtMapByActor)}else{const a=this.attributesToRemove;[,o,i]=s.removeStyle([this.fromPos,this.toPos],a,this.getExecutedAt(),this.maxCreatedAtMapByActor)}for(const a of o)t.registerGCPair(a);return{opInfos:i.map(({from:a,to:u,value:l,fromPath:h,toPath:g})=>({type:"tree-style",from:a,to:u,value:this.attributes.size?{attributes:l}:{attributesToRemove:l},fromPath:h,toPath:g,path:t.createPath(this.getParentCreatedAt())}))}}getEffectedCreatedAt(){return this.getParentCreatedAt()}toTestString(){const t=this.getParentCreatedAt().toTestString(),n=`${this.fromPos.getLeftSiblingID().getCreatedAt().toTestString()}:${this.fromPos.getLeftSiblingID().getOffset()}`,s=`${this.toPos.getLeftSiblingID().getCreatedAt().toTestString()}:${this.toPos.getLeftSiblingID().getOffset()}`;return`${t}.STYLE(${n},${s},${Object.entries(this.attributes||{}).map(([i,o])=>`${i}:"${o}"`).join(" ")})`}getFromPos(){return this.fromPos}getToPos(){return this.toPos}getAttributes(){return this.attributes}getAttributesToRemove(){return this.attributesToRemove}getMaxCreatedAtMapByActor(){return this.maxCreatedAtMapByActor}}function pp(r){const e=new Qa,t=e.data;for(const[n,s]of Object.entries(r))t[n]=JSON.stringify(s);return e}function yp(r){if(r.type===bn.Put)return new qs({type:Un.PUT,presence:pp(r.presence)});if(r.type===bn.Clear)return new qs({type:Un.CLEAR});throw new w(y.ErrUnimplemented,"unimplemented type")}function vp(r){return new gf({serverSeq:r.getServerSeq(),clientSeq:r.getClientSeq()})}function Ef(r){return new mo({clientSeq:r.getClientSeq(),lamport:r.getLamport(),actorId:gc(r.getActorID()),versionVector:sc(r.getVersionVector())})}function J(r){if(r)return new L({lamport:r.getLamport(),delimiter:r.getDelimiter(),actorId:gc(r.getActorID())})}function sc(r){if(!r)return;const e=new po;for(const[t,n]of r)e.vector[t]=BigInt(n.toString());return e}function Cf(r){switch(r){case be.Null:return W.NULL;case be.Boolean:return W.BOOLEAN;case be.Integer:return W.INTEGER;case be.Long:return W.LONG;case be.Double:return W.DOUBLE;case be.String:return W.STRING;case be.Bytes:return W.BYTES;case be.Date:return W.DATE;default:throw new w(y.ErrInvalidType,`unsupported type: ${r}`)}}function Nf(r){switch(r){case Vt.IntegerCnt:return W.INTEGER_CNT;case Vt.LongCnt:return W.LONG_CNT;default:throw new w(y.ErrInvalidType,`unsupported type: ${r}`)}}function Fo(r){if(r instanceof Me)return new Ye({type:W.JSON_OBJECT,createdAt:J(r.getCreatedAt()),value:Vf(r)});if(r instanceof je)return new Ye({type:W.JSON_ARRAY,createdAt:J(r.getCreatedAt()),value:Yp(r)});if(r instanceof at)return new Ye({type:W.TEXT,createdAt:J(r.getCreatedAt())});if(r instanceof le)return new Ye({type:Cf(r.getType()),createdAt:J(r.getCreatedAt()),value:r.toBytes()});if(r instanceof We)return new Ye({type:Nf(r.getType()),createdAt:J(r.getCreatedAt()),value:r.toBytes()});if(r instanceof ct)return new Ye({type:W.TREE,createdAt:J(r.getCreatedAt()),value:Xp(r)});throw new w(y.ErrUnimplemented,"unimplemented element")}function wp(r){return new $s({createdAt:J(r.getCreatedAt()),offset:r.getOffset()})}function fi(r){return new tn({createdAt:J(r.getID().getCreatedAt()),offset:r.getID().getOffset(),relativeOffset:r.getRelativeOffset()})}function hi(r){return new $n({parentId:Ps(r.getParentID()),leftSiblingId:Ps(r.getLeftSiblingID())})}function Ps(r){return new mn({createdAt:J(r.getCreatedAt()),offset:r.getOffset()})}function Pf(r){const e=new Za;if(r instanceof qn){const t=r,n=new Fi;n.parentCreatedAt=J(t.getParentCreatedAt()),n.key=t.getKey(),n.value=Fo(t.getValue()),n.executedAt=J(t.getExecutedAt()),e.body.case="set",e.body.value=n}else if(r instanceof Ys){const t=r,n=new Li;n.parentCreatedAt=J(t.getParentCreatedAt()),n.prevCreatedAt=J(t.getPrevCreatedAt()),n.value=Fo(t.getValue()),n.executedAt=J(t.getExecutedAt()),e.body.case="add",e.body.value=n}else if(r instanceof hn){const t=r,n=new Ji;n.parentCreatedAt=J(t.getParentCreatedAt()),n.prevCreatedAt=J(t.getPrevCreatedAt()),n.createdAt=J(t.getCreatedAt()),n.executedAt=J(t.getExecutedAt()),e.body.case="move",e.body.value=n}else if(r instanceof Tn){const t=r,n=new Mi;n.parentCreatedAt=J(t.getParentCreatedAt()),n.createdAt=J(t.getCreatedAt()),n.executedAt=J(t.getExecutedAt()),e.body.case="remove",e.body.value=n}else if(r instanceof _s){const t=r,n=new $i;n.parentCreatedAt=J(t.getParentCreatedAt()),n.from=fi(t.getFromPos()),n.to=fi(t.getToPos());const s=n.createdAtMapByActor;for(const[o,a]of t.getMaxCreatedAtMapByActor())s[o]=J(a);n.content=t.getContent();const i=n.attributes;for(const[o,a]of t.getAttributes())i[o]=a;n.executedAt=J(t.getExecutedAt()),e.body.case="edit",e.body.value=n}else if(r instanceof Xs){const t=r,n=new Ui;n.parentCreatedAt=J(t.getParentCreatedAt()),n.from=fi(t.getFromPos()),n.to=fi(t.getToPos());const s=n.createdAtMapByActor;for(const[o,a]of t.getMaxCreatedAtMapByActor())s[o]=J(a);const i=n.attributes;for(const[o,a]of t.getAttributes())i[o]=a;n.executedAt=J(t.getExecutedAt()),e.body.case="style",e.body.value=n}else if(r instanceof ms){const t=r,n=new qi;n.parentCreatedAt=J(t.getParentCreatedAt()),n.value=Fo(t.getValue()),n.executedAt=J(t.getExecutedAt()),e.body.case="increase",e.body.value=n}else if(r instanceof Zs){const t=r,n=new Vi,s=n.createdAtMapByActor;for(const[i,o]of t.getMaxCreatedAtMapByActor())s[i]=J(o);n.parentCreatedAt=J(t.getParentCreatedAt()),n.from=hi(t.getFromPos()),n.to=hi(t.getToPos()),n.contents=kp(t.getContents()),n.splitLevel=t.getSplitLevel(),n.executedAt=J(t.getExecutedAt()),e.body.case="treeEdit",e.body.value=n}else if(r instanceof Qr){const t=r,n=new zi;n.parentCreatedAt=J(t.getParentCreatedAt()),n.from=hi(t.getFromPos()),n.to=hi(t.getToPos());const s=n.createdAtMapByActor;for(const[o,a]of t.getMaxCreatedAtMapByActor())s[o]=J(a);const i=t.getAttributesToRemove();if(i.length>0)n.attributesToRemove=i;else{const o=n.attributes;for(const[a,u]of t.getAttributes())o[a]=u}n.executedAt=J(t.getExecutedAt()),e.body.case="treeStyle",e.body.value=n}else throw new w(y.ErrUnimplemented,"unimplemented operation");return e}function bp(r){const e=[];for(const t of r)e.push(Pf(t));return e}function Tp(r){const e=new hf({id:Ef(r.getID()),message:r.getMessage()});return r.hasOperations()&&(e.operations=bp(r.getOperations())),r.hasPresenceChange()&&(e.presenceChange=yp(r.getPresenceChange())),e}function Ap(r){const e=[];for(const t of r)e.push(Tp(t));return e}function Ip(r){const e=[];for(const t of r)e.push(new df({key:t.getStrKey(),element:oc(t.getValue())}));return e}function Sp(r){const e=[];for(const t of r)e.push(new _i({element:oc(t.getValue())}));return e}function xp(r){const e=[];for(const t of r){const n=new Xi;n.id=wp(t.getID()),n.value=t.getValue().getContent(),n.removedAt=J(t.getRemovedAt());const s=n.attributes,i=t.getValue().getAttrs();for(const o of i){const a=new ls;a.value=o.getValue(),a.updatedAt=J(o.getUpdatedAt()),s[o.getKey()]=a}e.push(n)}return e}function kp(r){const e=[];if(!r||!r.length)return e;for(const t of r)e.push(new Zi({content:ic(t)}));return e}function Ep(r){const e={};for(const t of r)e[t.getKey()]=new ls({value:t.getValue(),updatedAt:J(t.getUpdatedAt()),isRemoved:t.isRemoved()});return e}function ic(r){if(!r)return[];const e=[];return yo(r,(t,n)=>{const s=new Us({id:Ps(t.id),type:t.type,removedAt:J(t.removedAt),depth:n});t.isText&&(s.value=t.value),t.insPrevID&&(s.insPrevId=Ps(t.insPrevID)),t.insNextID&&(s.insNextId=Ps(t.insNextID)),t.attrs&&(s.attributes=Ep(t.attrs)),e.push(s)}),e}function Cp(r){const e=new Ue;return e.body.case="jsonObject",e.body.value=new Ki({nodes:Ip(r.getRHT()),createdAt:J(r.getCreatedAt()),movedAt:J(r.getMovedAt()),removedAt:J(r.getRemovedAt())}),e}function Of(r){const e=new Ue;return e.body.case="jsonArray",e.body.value=new ji({nodes:Sp(r.getElements()),createdAt:J(r.getCreatedAt()),movedAt:J(r.getMovedAt()),removedAt:J(r.getRemovedAt())}),e}function Np(r){const e=new Ue;return e.body.case="primitive",e.body.value=new Wi({type:Cf(r.getType()),value:r.toBytes(),createdAt:J(r.getCreatedAt()),movedAt:J(r.getMovedAt()),removedAt:J(r.getRemovedAt())}),e}function Pp(r){const e=new Ue;return e.body.case="text",e.body.value=new Hi({nodes:xp(r.getRGATreeSplit()),createdAt:J(r.getCreatedAt()),movedAt:J(r.getMovedAt()),removedAt:J(r.getRemovedAt())}),e}function Op(r){const e=new Ue;return e.body.case="counter",e.body.value=new Gi({type:Nf(r.getType()),value:r.toBytes(),createdAt:J(r.getCreatedAt()),movedAt:J(r.getMovedAt()),removedAt:J(r.getRemovedAt())}),e}function Df(r){const e=new Ue;return e.body.case="tree",e.body.value=new Yi({nodes:ic(r.getRoot()),createdAt:J(r.getCreatedAt()),movedAt:J(r.getMovedAt()),removedAt:J(r.getRemovedAt())}),e}function oc(r){if(r instanceof Me)return Cp(r);if(r instanceof je)return Of(r);if(r instanceof le)return Np(r);if(r instanceof at)return Pp(r);if(r instanceof We)return Op(r);if(r instanceof ct)return Df(r);throw new w(y.ErrUnimplemented,"unimplemented element")}function Dp(r){return new sn({documentKey:r.getDocumentKey(),checkpoint:vp(r.getCheckpoint()),isRemoved:r.getIsRemoved(),changes:Ap(r.getChanges()),snapshot:r.getSnapshot(),versionVector:sc(r.getVersionVector()),minSyncedTicket:J(r.getMinSyncedTicket())})}function zu(r){const e=r.findDetails(Gm);for(const t of e)if(t.metadata.code)return t.metadata.code;return""}function Bf(r){return Hr.of(r.clientSeq,BigInt(r.lamport),hc(r.actorId),ac(r.versionVector),BigInt(r.serverSeq))}function ac(r){if(!r)return;const e=new ns;return Object.entries(r.vector).forEach(([t,n])=>{e.set(t,BigInt(n.toString()))}),e}function M(r){if(r)return Ke.of(BigInt(r.lamport),r.delimiter,hc(r.actorId))}function cc(r){const e={};return Object.entries(r.data).forEach(([t,n])=>{e[t]=JSON.parse(n)}),e}function Bp(r){const e=r.type;if(e===Un.PUT){const t=cc(r.presence);return{type:bn.Put,presence:t}}if(e===Un.CLEAR)return{type:bn.Clear};throw new w(y.ErrInvalidType,`unsupported type: ${e}`)}function Rp(r){const e=new Map;return Object.entries(r).forEach(([t,n])=>{e.set(t,cc(n))}),e}function Rf(r){switch(r){case W.NULL:return be.Null;case W.BOOLEAN:return be.Boolean;case W.INTEGER:return be.Integer;case W.LONG:return be.Long;case W.DOUBLE:return be.Double;case W.STRING:return be.String;case W.BYTES:return be.Bytes;case W.DATE:return be.Date}throw new w(y.ErrUnimplemented,`unimplemented value type: ${r}`)}function to(r){switch(r){case W.INTEGER_CNT:return Vt.IntegerCnt;case W.LONG_CNT:return Vt.LongCnt}throw new w(y.ErrUnimplemented,`unimplemented value type: ${r}`)}function Lo(r){switch(r.type){case W.JSON_OBJECT:return r.value?qf(r.value):Me.create(M(r.createdAt));case W.JSON_ARRAY:return r.value?Gp(r.value):je.create(M(r.createdAt));case W.TEXT:return at.create(gs.create(),M(r.createdAt));case W.TREE:return _p(r.value);case W.NULL:case W.BOOLEAN:case W.INTEGER:case W.LONG:case W.DOUBLE:case W.STRING:case W.BYTES:case W.DATE:return le.of(le.valueFromBytes(Rf(r.type),r.value),M(r.createdAt));case W.INTEGER_CNT:case W.LONG_CNT:return We.create(to(r.type),We.valueFromBytes(to(r.type),r.value),M(r.createdAt))}}function di(r){return bt.of(qt.of(M(r.createdAt),r.offset),r.relativeOffset)}function Ff(r){return qt.of(M(r.createdAt),r.offset)}function Fp(r){const e=js.create(r.value);Object.entries(r.attributes).forEach(([n,s])=>{e.setAttr(n,s.value,M(s.updatedAt))});const t=yn.create(Ff(r.id),e);return t.remove(M(r.removedAt)),t}function Hn(r){return yt.of(Os(r.parentId),Os(r.leftSiblingId))}function Os(r){return Ae.of(M(r.createdAt),r.offset)}function Lp(r){if(!r.length)return;const e=[];return r.forEach(t=>{const n=uc(t.content);e.push(n)}),e}function uc(r){if(r.length===0)return;const e=[];for(const s of r)e.push(Mp(s));const t=e[e.length-1],n=new Map;n.set(r[e.length-1].depth,e[e.length-1]);for(let s=e.length-2;s>=0;s--)n.get(r[s].depth-1).prepend(e[s]),n.set(r[s].depth,e[s]);return t.updateDescendantsSize(),ct.create(t,wt).getRoot()}function Jp(r){const e=rn.create();for(const[t,n]of Object.entries(r))e.setInternal(t,n.value,M(n.updatedAt),n.isRemoved);return e}function Mp(r){const e=Os(r.id),t=ze.create(e,r.type),n=Object.entries(r.attributes);return t.isText?t.value=r.value:n.length&&(t.attrs=Jp(r.attributes)),r.insPrevId&&(t.insPrevID=Os(r.insPrevId)),r.insNextId&&(t.insNextID=Os(r.insNextId)),t.removedAt=M(r.removedAt),t}function Lf(r){if(r.body.case==="set"){const e=r.body.value;return qn.create(e.key,Lo(e.value),M(e.parentCreatedAt),M(e.executedAt))}else if(r.body.case==="add"){const e=r.body.value;return Ys.create(M(e.parentCreatedAt),M(e.prevCreatedAt),Lo(e.value),M(e.executedAt))}else if(r.body.case==="move"){const e=r.body.value;return hn.create(M(e.parentCreatedAt),M(e.prevCreatedAt),M(e.createdAt),M(e.executedAt))}else if(r.body.case==="remove"){const e=r.body.value;return Tn.create(M(e.parentCreatedAt),M(e.createdAt),M(e.executedAt))}else if(r.body.case==="edit"){const e=r.body.value,t=new Map;Object.entries(e.createdAtMapByActor).forEach(([s,i])=>{t.set(s,M(i))});const n=new Map;return Object.entries(e.attributes).forEach(([s,i])=>{n.set(s,i)}),_s.create(M(e.parentCreatedAt),di(e.from),di(e.to),t,e.content,n,M(e.executedAt))}else if(r.body.case==="style"){const e=r.body.value,t=new Map;Object.entries(e.createdAtMapByActor).forEach(([s,i])=>{t.set(s,M(i))});const n=new Map;return Object.entries(e.attributes).forEach(([s,i])=>{n.set(s,i)}),Xs.create(M(e.parentCreatedAt),di(e.from),di(e.to),t,n,M(e.executedAt))}else{if(r.body.case==="select")return;if(r.body.case==="increase"){const e=r.body.value;return ms.create(M(e.parentCreatedAt),Lo(e.value),M(e.executedAt))}else if(r.body.case==="treeEdit"){const e=r.body.value,t=new Map;return Object.entries(e.createdAtMapByActor).forEach(([n,s])=>{t.set(n,M(s))}),Zs.create(M(e.parentCreatedAt),Hn(e.from),Hn(e.to),Lp(e.contents),e.splitLevel,t,M(e.executedAt))}else if(r.body.case==="treeStyle"){const e=r.body.value,t=new Map,n=e.attributesToRemove,s=new Map;return e!=null&&e.createdAtMapByActor&&Object.entries(e.createdAtMapByActor).forEach(([i,o])=>{s.set(i,M(o))}),(n==null?void 0:n.length)>0?Qr.createTreeRemoveStyleOperation(M(e.parentCreatedAt),Hn(e.from),Hn(e.to),s,n,M(e.executedAt)):(Object.entries(e.attributes).forEach(([i,o])=>{t.set(i,o)}),Qr.create(M(e.parentCreatedAt),Hn(e.from),Hn(e.to),s,t,M(e.executedAt)))}else throw new w(y.ErrUnimplemented,"unimplemented operation")}}function $p(r){const e=[];for(const t of r){const n=Lf(t);n&&e.push(n)}return e}function Jf(r){const e=[];for(const t of r)e.push(ds.create({id:Bf(t.id),operations:$p(t.operations),presenceChange:t.presenceChange?Bp(t.presenceChange):void 0,message:t.message}));return e}function Up(r){return ss.of(BigInt(r.serverSeq),r.clientSeq)}function qp(r){return vo.create(r.documentKey,Up(r.checkpoint),r.isRemoved,Jf(r.changes),ac(r.versionVector),r.snapshot,M(r.minSyncedTicket))}function Mf(r){const e=new Vs;for(const n of r.nodes){const s=lc(n.element);e.set(n.key,s,s.getPositionedAt())}const t=new Me(M(r.createdAt),e);return t.setMovedAt(M(r.movedAt)),t.setRemovedAt(M(r.removedAt)),t}function $f(r){const e=new Ks;for(const n of r.nodes)e.insert(lc(n.element));const t=new je(M(r.createdAt),e);return t.setMovedAt(M(r.movedAt)),t.setRemovedAt(M(r.removedAt)),t}function Vp(r){const e=le.of(le.valueFromBytes(Rf(r.type),r.value),M(r.createdAt));return e.setMovedAt(M(r.movedAt)),e.setRemovedAt(M(r.removedAt)),e}function zp(r){const e=new gs;let t=e.getHead();for(const s of r.nodes){const i=e.insertAfter(t,Fp(s));s.insPrevId&&i.setInsPrev(e.findNode(Ff(s.insPrevId))),t=i}const n=new at(e,M(r.createdAt));return n.setMovedAt(M(r.movedAt)),n.setRemovedAt(M(r.removedAt)),n}function Kp(r){const e=We.create(to(r.type),We.valueFromBytes(to(r.type),r.value),M(r.createdAt));return e.setMovedAt(M(r.movedAt)),e.setRemovedAt(M(r.removedAt)),e}function Uf(r){const e=uc(r.nodes);return ct.create(e,M(r.createdAt))}function lc(r){if(r.body.case==="jsonObject")return Mf(r.body.value);if(r.body.case==="jsonArray")return $f(r.body.value);if(r.body.case==="primitive")return Vp(r.body.value);if(r.body.case==="text")return zp(r.body.value);if(r.body.case==="counter")return Kp(r.body.value);if(r.body.case==="tree")return Uf(r.body.value);throw new w(y.ErrUnimplemented,"unimplemented element")}function jp(r){if(!r)return{root:Me.create(wt),presences:new Map};const e=ea.fromBinary(r);return{root:lc(e.root),presences:Rp(e.presences)}}function Wp(r){const e=sc(r);return fc(e.toBinary())}function Hp(r){const e=dc(r),t=po.fromBinary(e);return ac(t)}function qf(r){if(!r)throw new w(y.ErrInvalidArgument,"bytes is empty");const e=Ue.fromBinary(r);return Mf(e.body.value)}function Vf(r){return oc(r).toBinary()}function Gp(r){if(!r)throw new w(y.ErrInvalidArgument,"bytes is empty");const e=Ue.fromBinary(r);return $f(e.body.value)}function Yp(r){return Of(r).toBinary()}function _p(r){if(!r)throw new w(y.ErrInvalidArgument,"bytes is empty");const e=Ue.fromBinary(r);return Uf(e.body.value)}function Xp(r){return Df(r).toBinary()}function fc(r){return r?Array.from(r).map(e=>e.toString(16).padStart(2,"0")).join(""):""}function hc(r){return fc(r)}function dc(r){return new Uint8Array(r.match(/.{1,2}/g).map(e=>parseInt(e,16)))}function gc(r){return dc(r)}function Zp(r){const e=mo.fromBinary(r);return Bf(e)}function Qp(r){const e=Za.fromBinary(r);return Lf(e)}const me={fromPresence:cc,toChangePack:Dp,fromChangePack:qp,fromChanges:Jf,toTreeNodes:ic,fromTreeNodes:uc,objectToBytes:Vf,bytesToObject:qf,bytesToSnapshot:jp,bytesToHex:fc,hexToBytes:dc,toHexString:hc,toUint8Array:gc,toOperation:Pf,toChangeID:Ef,PbChangeID:mo,bytesToChangeID:Zp,bytesToOperation:Qp,versionVectorToHex:Wp,hexToVersionVector:Hp};var Be=(r=>(r[r.Trivial=0]="Trivial",r[r.Debug=1]="Debug",r[r.Info=2]="Info",r[r.Warn=3]="Warn",r[r.Error=4]="Error",r[r.Fatal=5]="Fatal",r))(Be||{});let En=3;function zf(r){En=r}const z={trivial:(...r)=>{En>0||typeof console<"u"&&console.log("YORKIE T:",...r)},debug:(...r)=>{En>1||typeof console<"u"&&console.log("YORKIE D:",...r)},info:(...r)=>{En>2||typeof console<"u"&&console.log("YORKIE I:",...r)},warn:(...r)=>{En>3||typeof console<"u"&&(typeof console.warn<"u"?console.warn("YORKIE W:",...r):console.log("YORKIE W:",...r))},error:(...r)=>{En>4||typeof console<"u"&&(typeof console.error<"u"?console.error("YORKIE E:",...r):console.log("YORKIE E:",...r))},fatal:(...r)=>{typeof console<"u"&&(typeof console.error<"u"?console.error("YORKIE F:",...r):console.log("YORKIE F:",...r))},isEnabled:r=>En<=r};function Kf(){return"xxxxxxxx-xxxx-4xxxy-xxxx-xxxxxxxxxxx".replace(/[xy]/g,r=>{const e=Math.random()*16|0;return(r==="x"?e:e&3|8).toString(16)})}class ey{constructor(e,t,n,s,i){c(this,"reconnectStreamDelay");c(this,"doc");c(this,"docID");c(this,"syncMode");c(this,"remoteChangeEventReceived");c(this,"watchStream");c(this,"watchLoopTimerID");c(this,"watchAbortController");c(this,"unsubscribeBroadcastEvent");this.reconnectStreamDelay=e,this.doc=t,this.docID=n,this.syncMode=s,this.remoteChangeEventReceived=!1,this.unsubscribeBroadcastEvent=i}changeSyncMode(e){this.syncMode=e}needRealtimeSync(){return this.syncMode===Ei.RealtimeSyncOff?!1:this.syncMode===Ei.RealtimePushOnly?this.doc.hasLocalChanges():this.syncMode!==Ei.Manual&&(this.doc.hasLocalChanges()||this.remoteChangeEventReceived)}async runWatchLoop(e){const t=async()=>{if(this.watchStream)return Promise.resolve();this.watchLoopTimerID&&(clearTimeout(this.watchLoopTimerID),this.watchLoopTimerID=void 0);try{[this.watchStream,this.watchAbortController]=await e(()=>{this.watchStream=void 0,this.watchAbortController=void 0,this.watchLoopTimerID=setTimeout(t,this.reconnectStreamDelay)})}catch{}};await t()}cancelWatchStream(){this.watchStream&&this.watchAbortController&&(this.watchAbortController.abort(),this.watchStream=void 0,this.watchAbortController=void 0),clearTimeout(this.watchLoopTimerID),this.watchLoopTimerID=void 0}}const Jo=()=>{};class ty{constructor(e){c(this,"finalized",!1);c(this,"observers",[]);c(this,"finalError");try{e(this)}catch(t){this.error(t)}}next(e){this.forEachObserver(t=>{t.next(e)})}error(e){this.forEachObserver(t=>{t.error(e)}),this.close(e)}complete(){this.forEachObserver(e=>{e.complete()}),this.close()}subscribe(e,t,n){let s;if(!e)throw new w(y.ErrInvalidArgument,"missing observer");if(this.finalized)throw new w(y.ErrRefused,"observable is finalized due to previous error");typeof e=="object"?s=e:s={next:e,error:t,complete:n},s.next===void 0&&(s.next=Jo),s.error===void 0&&(s.error=Jo),s.complete===void 0&&(s.complete=Jo);const i=Kf(),o=this.unsubscribeOne.bind(this,i);if(this.observers.push({subscriptionID:i,observer:s}),this.finalized)try{this.finalError?s.error(this.finalError):s.complete()}catch(a){z.warn(a)}return o}unsubscribeOne(e){var t;this.observers=(t=this.observers)==null?void 0:t.filter(n=>n.subscriptionID!==e)}forEachObserver(e){if(!this.finalized)for(let t=0;te}}class Xn{constructor(e,t,n,s){c(this,"id");c(this,"delimiter");c(this,"message");c(this,"root");c(this,"operations");c(this,"presenceChange");c(this,"previousPresence");c(this,"reversePresenceKeys");this.id=e,this.delimiter=pf,this.root=t,this.operations=[],this.previousPresence=ht(n),this.presenceChange=void 0,this.reversePresenceKeys=new Set,this.message=s}static create(e,t,n,s){return new Xn(e,t,n,s)}push(e){this.operations.push(e)}registerElement(e,t){this.root.registerElement(e,t)}registerRemovedElement(e){this.root.registerRemovedElement(e)}registerGCPair(e){this.root.registerGCPair(e)}getChange(){return ds.create({id:this.id,operations:this.operations,presenceChange:this.presenceChange,message:this.message})}hasChange(){return this.operations.length>0||this.presenceChange!==void 0}setPresenceChange(e){this.presenceChange=e}setReversePresence(e,t){for(const n of Object.keys(e))t!=null&&t.addToHistory?this.reversePresenceKeys.add(n):this.reversePresenceKeys.delete(n)}getReversePresence(){if(this.reversePresenceKeys.size===0)return;const e={};for(const t of this.reversePresenceKeys)e[t]=this.previousPresence[t];return e}issueTimeTicket(){return this.delimiter+=1,this.id.createTimeTicket(this.delimiter)}getLastTimeTicket(){return this.id.createTimeTicket(this.delimiter)}}class Ws{constructor(e){c(this,"rootObject");c(this,"elementPairMapByCreatedAt");c(this,"gcElementSetByCreatedAt");c(this,"gcPairMap");this.rootObject=e,this.elementPairMapByCreatedAt=new Map,this.gcElementSetByCreatedAt=new Set,this.gcPairMap=new Map,this.registerElement(e,void 0),e.getDescendants(t=>{if(t.getRemovedAt()&&this.registerRemovedElement(t),t instanceof at||t instanceof ct)for(const n of t.getGCPairs())this.registerGCPair(n);return!1})}static create(){return new Ws(Me.create(wt))}findByCreatedAt(e){const t=this.elementPairMapByCreatedAt.get(e.toIDString());if(t)return t.element}findElementPairByCreatedAt(e){return this.elementPairMapByCreatedAt.get(e.toIDString())}createSubPaths(e){let t=this.elementPairMapByCreatedAt.get(e.toIDString());if(!t)return[];const n=[];for(;t.parent;){const s=t.element.getCreatedAt(),i=t.parent.subPathOf(s);if(i===void 0)throw new w(y.ErrInvalidArgument,`cant find the given element: ${s.toIDString()}`);n.unshift(i),t=this.elementPairMapByCreatedAt.get(t.parent.getCreatedAt().toIDString())}return n.unshift("$"),n}createPath(e){return this.createSubPaths(e).join(".")}registerElement(e,t){this.elementPairMapByCreatedAt.set(e.getCreatedAt().toIDString(),{parent:t,element:e}),e instanceof pn&&e.getDescendants((n,s)=>(this.registerElement(n,s),!1))}deregisterElement(e){let t=0;const n=s=>{const i=s.getCreatedAt().toIDString();this.elementPairMapByCreatedAt.delete(i),this.gcElementSetByCreatedAt.delete(i),t++};return n(e),e instanceof pn&&e.getDescendants(s=>(n(s),!1)),t}registerRemovedElement(e){this.gcElementSetByCreatedAt.add(e.getCreatedAt().toIDString())}registerGCPair(e){if(this.gcPairMap.get(e.child.toIDString())){this.gcPairMap.delete(e.child.toIDString());return}this.gcPairMap.set(e.child.toIDString(),e)}getElementMapSize(){return this.elementPairMapByCreatedAt.size}getGarbageElementSetSize(){const e=new Set;for(const t of this.gcElementSetByCreatedAt){e.add(t);const n=this.elementPairMapByCreatedAt.get(t);n.element instanceof pn&&n.element.getDescendants(s=>(e.add(s.getCreatedAt().toIDString()),!1))}return e.size}getObject(){return this.rootObject}getGarbageLen(){return this.getGarbageElementSetSize()+this.gcPairMap.size}deepcopy(){return new Ws(this.rootObject.deepcopy())}garbageCollect(e){let t=0;for(const n of this.gcElementSetByCreatedAt){const s=this.elementPairMapByCreatedAt.get(n),i=s.element.getRemovedAt();i&&(e!=null&&e.afterOrEqual(i))&&(s.parent.purge(s.element),t+=this.deregisterElement(s.element))}for(const[,n]of this.gcPairMap){const s=n.child.getRemovedAt();s&&(e!=null&&e.afterOrEqual(s))&&(n.parent.purge(n.child),this.gcPairMap.delete(n.child.toIDString()),t+=1)}return t}toJSON(){return this.rootObject.toJSON()}toSortedJSON(){return this.rootObject.toSortedJSON()}getStats(){return{elements:this.getElementMapSize(),gcPairs:this.gcPairMap.size,gcElements:this.getGarbageElementSetSize()}}}function jf(r,e){const t=new Hs(r);return new Proxy(e,t.getHandlers())}class Hs{constructor(e){c(this,"context");c(this,"handlers");this.context=e,this.handlers={set:(t,n,s)=>(z.isEnabled(Be.Trivial)&&z.trivial(`obj[${n}]=${JSON.stringify(s)}`),Hs.setInternal(e,t,n,s),!0),get:(t,n)=>(z.isEnabled(Be.Trivial)&&z.trivial(`obj[${n}]`),n==="getID"?()=>t.getCreatedAt():n==="toJSON"||n==="toString"?()=>t.toJSON():n==="toJS"?()=>t.toJS():n==="toJSForTest"?()=>t.toJSForTest():Cn(e,t.get(n))),ownKeys:t=>t.getKeys(),getOwnPropertyDescriptor:()=>({enumerable:!0,configurable:!0}),deleteProperty:(t,n)=>(z.isEnabled(Be.Trivial)&&z.trivial(`obj[${n}]`),Hs.deleteInternal(e,t,n),!0)}}static setInternal(e,t,n,s){if(n.includes("."))throw new w(y.ErrInvalidObjectKey,"key must not contain the '.'.");const i=e.issueTimeTicket(),o=ro(e,s,i),a=t.set(n,o,i);e.registerElement(o,t),a&&e.registerRemovedElement(a),e.push(qn.create(n,o.deepcopy(),t.getCreatedAt(),i))}static buildObjectMembers(e,t){const n={};for(const[s,i]of Object.entries(t)){if(s.includes("."))throw new w(y.ErrInvalidObjectKey,"key must not contain the '.'.");const o=e.issueTimeTicket(),a=ro(e,i,o);n[s]=a}return n}static deleteInternal(e,t,n){const s=e.issueTimeTicket(),i=t.deleteByKey(n,s);i&&(e.push(Tn.create(t.getCreatedAt(),i.getCreatedAt(),s)),e.registerRemovedElement(i))}getHandlers(){return this.handlers}}function ny(r,e){const t=new de(r,e);return new Proxy(e,t.getHandlers())}function sy(r){return typeof r=="string"||r instanceof String?!isNaN(r):!1}function iy(r){return["concat","entries","every","filter","find","findIndex","forEach","join","keys","map","reduce","reduceRight","slice","some","toLocaleString","toString","values"].includes(r)}class de{constructor(e,t){c(this,"context");c(this,"handlers");c(this,"array");this.context=e,this.array=t,this.handlers={get:(n,s,i)=>s==="getID"?()=>n.getCreatedAt():s==="getElementByID"?o=>{const a=n.getByID(o);if(!(!a||a.isRemoved()))return un(e,a)}:s==="getElementByIndex"?o=>{const a=n.get(o);return un(e,a)}:s==="getLast"?()=>un(e,n.getLast()):s==="deleteByID"?o=>{const a=de.deleteInternalByID(e,n,o);return un(e,a)}:s==="insertAfter"?(o,a)=>{const u=de.insertAfterInternal(e,n,o,a);return un(e,u)}:s==="insertBefore"?(o,a)=>{const u=de.insertBeforeInternal(e,n,o,a);return un(e,u)}:s==="moveBefore"?(o,a)=>{de.moveBeforeInternal(e,n,o,a)}:s==="moveAfter"?(o,a)=>{de.moveAfterInternal(e,n,o,a)}:s==="moveFront"?o=>{de.moveFrontInternal(e,n,o)}:s==="moveLast"?o=>{de.moveLastInternal(e,n,o)}:sy(s)?Cn(e,n.get(Number(s))):s==="push"?o=>de.pushInternal(e,n,o):s==="splice"?(o,a,...u)=>de.splice(e,n,o,a,...u):s==="length"?n.length:typeof s=="symbol"&&s===Symbol.iterator?de.iteratorInternal.bind(this,e,n):s==="includes"?(o,a)=>de.includes(e,n,o,a):s==="indexOf"?(o,a)=>de.indexOf(e,n,o,a):s==="lastIndexOf"?(o,a)=>de.lastIndexOf(e,n,o,a):s==="toJSForTest"?()=>n.toJSForTest():s==="toTestString"?()=>de.toTestString(n):typeof s=="string"&&iy(s)?(...o)=>{const a=Array.from(n).map(u=>Cn(e,u));return Array.prototype[s].apply(a,o)}:Reflect.get(n,s,i),deleteProperty:(n,s)=>(z.isEnabled(Be.Trivial)&&z.trivial(`array[${s}]`),de.deleteInternalByIndex(e,n,Number.parseInt(s)),!0)}}static*iteratorInternal(e,t){for(const n of t)yield un(e,n)}static buildArrayElements(e,t){const n=[];for(const s of t){const i=e.issueTimeTicket(),o=ro(e,s,i);n.push(o)}return n}static pushInternal(e,t,n){return de.insertAfterInternal(e,t,t.getLastCreatedAt(),n),t.length}static moveBeforeInternal(e,t,n,s){const i=e.issueTimeTicket(),o=t.getPrevCreatedAt(n);t.moveAfter(o,s,i),e.push(hn.create(t.getCreatedAt(),o,s,i))}static moveAfterInternal(e,t,n,s){const i=e.issueTimeTicket();t.moveAfter(n,s,i),e.push(hn.create(t.getCreatedAt(),n,s,i))}static moveFrontInternal(e,t,n){const s=e.issueTimeTicket(),i=t.getHead();t.moveAfter(i.getCreatedAt(),n,s),e.push(hn.create(t.getCreatedAt(),i.getCreatedAt(),n,s))}static moveLastInternal(e,t,n){const s=e.issueTimeTicket(),i=t.getLastCreatedAt();t.moveAfter(i,n,s),e.push(hn.create(t.getCreatedAt(),i,n,s))}static insertAfterInternal(e,t,n,s){const i=e.issueTimeTicket(),o=ro(e,s,i);return t.insertAfter(n,o),e.registerElement(o,t),e.push(Ys.create(t.getCreatedAt(),n,o.deepcopy(),i)),o}static insertBeforeInternal(e,t,n,s){return de.insertAfterInternal(e,t,t.getPrevCreatedAt(n),s)}static deleteInternalByIndex(e,t,n){const s=e.issueTimeTicket(),i=t.deleteByIndex(n,s);if(i)return e.push(Tn.create(t.getCreatedAt(),i.getCreatedAt(),s)),e.registerRemovedElement(i),i}static deleteInternalByID(e,t,n){const s=e.issueTimeTicket(),i=t.delete(n,s);return e.push(Tn.create(t.getCreatedAt(),i.getCreatedAt(),s)),e.registerRemovedElement(i),i}static splice(e,t,n,s,...i){const o=t.length,a=n>=0?Math.min(n,o):Math.max(o+n,0),u=s===void 0?o:s<0?a:Math.min(a+s,o),l=[];for(let h=a;h=i)return!1;if(le.isSupport(n))return Array.from(t).map(l=>Cn(e,l)).includes(n,o);for(let u=o;u=i)return-1;if(le.isSupport(n))return Array.from(t).map(l=>Cn(e,l)).indexOf(n,o);for(let u=o;u=i?i-1:s<0?s+i:s;if(o<0)return-1;if(le.isSupport(n))return Array.from(t).map(l=>Cn(e,l)).lastIndexOf(n,o);for(let u=o;u>0;u--)if(((a=t.get(u))==null?void 0:a.getID())===n.getID())return u;return-1}static toTestString(e){return e.toTestString()}getHandlers(){return this.handlers}}class wo{constructor(e,t){c(this,"context");c(this,"text");this.context=e,this.text=t}initialize(e,t){this.context=e,this.text=t}getID(){return this.text.getID()}edit(e,t,n,s){if(!this.context||!this.text)throw new w(y.ErrNotInitialized,"Text is not initialized yet");if(e>t)throw new w(y.ErrInvalidArgument,"from should be less than or equal to to");const i=this.text.indexRangeToPosRange(e,t);z.isEnabled(Be.Debug)&&z.debug(`EDIT: f:${e}->${i[0].toTestString()}, t:${t}->${i[1].toTestString()} c:${n}`);const o=s?fs(s):void 0,a=this.context.issueTimeTicket(),[u,,l,h]=this.text.edit(i,n,a,o);for(const g of l)this.context.registerGCPair(g);return this.context.push(new _s(this.text.getCreatedAt(),i[0],i[1],u,n,o?new Map(Object.entries(o)):new Map,a)),this.text.findIndexesFromRange(h)}delete(e,t){return this.edit(e,t,"")}empty(){return this.edit(0,this.length,"")}setStyle(e,t,n){if(!this.context||!this.text)throw new w(y.ErrNotInitialized,"Text is not initialized yet");if(e>t)throw new w(y.ErrInvalidArgument,"from should be less than or equal to to");const s=this.text.indexRangeToPosRange(e,t);z.isEnabled(Be.Debug)&&z.debug(`STYL: f:${e}->${s[0].toTestString()}, t:${t}->${s[1].toTestString()} a:${JSON.stringify(n)}`);const i=fs(n),o=this.context.issueTimeTicket(),[a,u]=this.text.setStyle(s,i,o);for(const l of u)this.context.registerGCPair(l);return this.context.push(new Xs(this.text.getCreatedAt(),s[0],s[1],a,new Map(Object.entries(i)),o)),!0}indexRangeToPosRange(e){if(!this.context||!this.text)throw new w(y.ErrNotInitialized,"Text is not initialized yet");const t=this.text.indexRangeToPosRange(e[0],e[1]);return[t[0].toStruct(),t[1].toStruct()]}posRangeToIndexRange(e){if(!this.context||!this.text)throw new w(y.ErrNotInitialized,"Text is not initialized yet");const t=this.text.findIndexesFromRange([bt.fromStruct(e[0]),bt.fromStruct(e[1])]);return[t[0],t[1]]}toTestString(){if(!this.context||!this.text)throw new w(y.ErrNotInitialized,"Text is not initialized yet");return this.text.toTestString()}values(){if(!this.context||!this.text)throw new w(y.ErrNotInitialized,"Text is not initialized yet");return this.text.values()}get length(){return this.text.length}getTreeByIndex(){return this.text.getTreeByIndex()}getTreeByID(){return this.text.getTreeByID()}toString(){if(!this.context||!this.text)throw new w(y.ErrNotInitialized,"Text is not initialized yet");return this.text.toString()}toJSON(){if(!this.context||!this.text)throw new w(y.ErrNotInitialized,"Text is not initialized yet");return this.text.toJSON()}toJSForTest(){if(!this.context||!this.text)throw new w(y.ErrNotInitialized,"Text is not initialized yet");return this.text.toJSForTest()}createRangeForTest(e,t){if(!this.context||!this.text)throw new w(y.ErrNotInitialized,"Text is not initialized yet");return this.text.indexRangeToPosRange(e,t)}}class bo{constructor(e,t){c(this,"valueType");c(this,"value");c(this,"context");c(this,"counter");this.valueType=e,this.value=t}initialize(e,t){this.valueType=t.getValueType(),this.context=e,this.counter=t,this.value=t.getValue()}getID(){return this.counter.getID()}getValue(){return this.value}getValueType(){return this.valueType}increase(e){if(!this.context||!this.counter)throw new w(y.ErrNotInitialized,"Counter is not initialized yet");const t=this.context.issueTimeTicket(),n=le.of(e,t);if(!n.isNumericType())throw new TypeError(`Unsupported type of value: ${typeof n.getValue()}`);return this.counter.increase(n),this.context.push(ms.create(this.counter.getCreatedAt(),n,t)),this}toJSForTest(){if(!this.context||!this.counter)throw new w(y.ErrNotInitialized,"Counter is not initialized yet");return this.counter.toJSForTest()}}function mc(r,e,t){const{type:n}=r,s=t.issueTimeTicket();if(n===Zr){Wf(r);const{value:i}=r,o=ze.create(Ae.of(s,0),n,i);e.append(o)}else{const{children:i=[]}=r,{attributes:o}=r;let a;if(typeof o=="object"&&!mf(o)){const l=fs(o);a=new rn;for(const[h,g]of Object.entries(l))a.set(h,g,s)}const u=ze.create(Ae.of(s,0),n,void 0,a);e.append(u);for(const l of i)mc(l,u,t)}}function oy(r,e){const{type:t}=e,n=r.issueTimeTicket();let s;if(e.type===Zr){const{value:i}=e;s=ze.create(Ae.of(n,0),t,i)}else if(e){const{children:i=[]}=e,{attributes:o}=e;let a;if(typeof o=="object"&&!mf(o)){const u=fs(o);a=new rn;for(const[l,h]of Object.entries(u))a.set(l,h,n)}s=ze.create(Ae.of(r.issueTimeTicket(),0),t,void 0,a);for(const u of i)mc(u,s,r)}return s}function Wf(r){if(!r.value.length)throw new w(y.ErrInvalidArgument,"text node cannot have empty value");return!0}function Ku(r){if(!r.length)return!0;if(r[0].type===Zr)for(const t of r){const{type:n}=t;if(n!==Zr)throw new w(y.ErrInvalidArgument,"element node and text node cannot be passed together");Wf(t)}else for(const t of r){const{type:n}=t;if(n===Zr)throw new w(y.ErrInvalidArgument,"element node and text node cannot be passed together")}return!0}class To{constructor(e){c(this,"initialRoot");c(this,"context");c(this,"tree");this.initialRoot=e}initialize(e,t){this.context=e,this.tree=t}getID(){return this.tree.getID()}buildRoot(e){if(!this.initialRoot)return ze.create(Ae.of(e.issueTimeTicket(),0),sp);const t=ze.create(Ae.of(e.issueTimeTicket(),0),this.initialRoot.type);for(const n of this.initialRoot.children)mc(n,t,e);return t}getSize(){if(!this.context||!this.tree)throw new w(y.ErrNotInitialized,"Tree is not initialized yet");return this.tree.getSize()}getNodeSize(){if(!this.context||!this.tree)throw new w(y.ErrNotInitialized,"Tree is not initialized yet");return this.tree.getNodeSize()}getIndexTree(){if(!this.context||!this.tree)throw new w(y.ErrNotInitialized,"Tree is not initialized yet");return this.tree.getIndexTree()}styleByPath(e,t){if(!this.context||!this.tree)throw new w(y.ErrNotInitialized,"Tree is not initialized yet");if(!e.length)throw new w(y.ErrInvalidArgument,"path should not be empty");const[n,s]=this.tree.pathToPosRange(e),i=this.context.issueTimeTicket(),o=t?fs(t):void 0,[a]=this.tree.style([n,s],o,i);this.context.push(Qr.create(this.tree.getCreatedAt(),n,s,a,o?new Map(Object.entries(o)):new Map,i))}style(e,t,n){if(!this.context||!this.tree)throw new w(y.ErrNotInitialized,"Tree is not initialized yet");if(e>t)throw new w(y.ErrInvalidArgument,"from should be less than or equal to to");const s=this.tree.findPos(e),i=this.tree.findPos(t),o=this.context.issueTimeTicket(),a=n?fs(n):void 0,[u,l]=this.tree.style([s,i],a,o);for(const h of l)this.context.registerGCPair(h);this.context.push(Qr.create(this.tree.getCreatedAt(),s,i,u,a?new Map(Object.entries(a)):new Map,o))}removeStyle(e,t,n){if(!this.context||!this.tree)throw new w(y.ErrNotInitialized,"Tree is not initialized yet");if(e>t)throw new w(y.ErrInvalidArgument,"from should be less than or equal to to");const s=this.tree.findPos(e),i=this.tree.findPos(t),o=this.context.issueTimeTicket(),[a,u]=this.tree.removeStyle([s,i],n,o);for(const l of u)this.context.registerGCPair(l);this.context.push(Qr.createTreeRemoveStyleOperation(this.tree.getCreatedAt(),s,i,a,n,o))}editInternal(e,t,n,s=0){var l;if(n.length!==0&&n[0]&&(Ku(n),n[0].type!==Zr))for(const h of n){const{children:g=[]}=h;Ku(g)}const i=this.context.getLastTimeTicket();let o=new Array;if(((l=n[0])==null?void 0:l.type)===Zr){let h="";for(const g of n){const{value:v}=g;h+=v}o.push(ze.create(Ae.of(this.context.issueTimeTicket(),0),Zr,h))}else o=n.map(h=>h&&oy(this.context,h)).filter(h=>h);const[,a,u]=this.tree.edit([e,t],o.length?o.map(h=>h==null?void 0:h.deepcopy()):void 0,s,i,()=>this.context.issueTimeTicket());for(const h of a)this.context.registerGCPair(h);return this.context.push(Zs.create(this.tree.getCreatedAt(),e,t,o.length?o:void 0,s,u,i)),!0}editByPath(e,t,n,s=0){if(!this.context||!this.tree)throw new w(y.ErrNotInitialized,"Tree is not initialized yet");if(e.length!==t.length)throw new w(y.ErrInvalidArgument,"path length should be equal");if(!e.length||!t.length)throw new w(y.ErrInvalidArgument,"path should not be empty");const i=this.tree.pathToPos(e),o=this.tree.pathToPos(t);return this.editInternal(i,o,n?[n]:[],s)}editBulkByPath(e,t,n,s=0){if(!this.context||!this.tree)throw new w(y.ErrNotInitialized,"Tree is not initialized yet");if(e.length!==t.length)throw new w(y.ErrInvalidArgument,"path length should be equal");if(!e.length||!t.length)throw new w(y.ErrInvalidArgument,"path should not be empty");const i=this.tree.pathToPos(e),o=this.tree.pathToPos(t);return this.editInternal(i,o,n,s)}edit(e,t,n,s=0){if(!this.context||!this.tree)throw new w(y.ErrNotInitialized,"Tree is not initialized yet");if(e>t)throw new w(y.ErrInvalidArgument,"from should be less than or equal to to");const i=this.tree.findPos(e),o=this.tree.findPos(t);return this.editInternal(i,o,n?[n]:[],s)}editBulk(e,t,n,s=0){if(!this.context||!this.tree)throw new w(y.ErrNotInitialized,"Tree is not initialized yet");if(e>t)throw new w(y.ErrInvalidArgument,"from should be less than or equal to to");const i=this.tree.findPos(e),o=this.tree.findPos(t);return this.editInternal(i,o,n,s)}toXML(){if(!this.context||!this.tree)throw new w(y.ErrNotInitialized,"Tree is not initialized yet");return this.tree.toXML()}toJSON(){if(!this.context||!this.tree)throw new w(y.ErrNotInitialized,"Tree is not initialized yet");return this.tree.toJSON()}toJSForTest(){if(!this.context||!this.tree)throw new w(y.ErrNotInitialized,"Tree is not initialized yet");return this.tree.toJSForTest()}toJSInfoForTest(){if(!this.context||!this.tree)throw new w(y.ErrNotInitialized,"Tree is not initialized yet");return this.tree.toJSInfoForTest()}getRootTreeNode(){if(!this.context||!this.tree)throw new w(y.ErrNotInitialized,"Tree is not initialized yet");return this.tree.getRootTreeNode()}indexToPath(e){if(!this.context||!this.tree)throw new w(y.ErrNotInitialized,"Tree is not initialized yet");return this.tree.indexToPath(e)}pathToIndex(e){if(!this.context||!this.tree)throw new w(y.ErrNotInitialized,"Tree is not initialized yet");return this.tree.pathToIndex(e)}pathRangeToPosRange(e){if(!this.context||!this.tree)throw new w(y.ErrNotInitialized,"Tree is not initialized yet");const t=[this.tree.pathToIndex(e[0]),this.tree.pathToIndex(e[1])],n=this.tree.indexRangeToPosRange(t);return[n[0].toStruct(),n[1].toStruct()]}indexRangeToPosRange(e){if(!this.context||!this.tree)throw new w(y.ErrNotInitialized,"Tree is not initialized yet");return this.tree.indexRangeToPosStructRange(e)}posRangeToIndexRange(e){if(!this.context||!this.tree)throw new w(y.ErrNotInitialized,"Tree is not initialized yet");const t=[yt.fromStruct(e[0]),yt.fromStruct(e[1])];return this.tree.posRangeToIndexRange(t)}posRangeToPathRange(e){if(!this.context||!this.tree)throw new w(y.ErrNotInitialized,"Tree is not initialized yet");const t=[yt.fromStruct(e[0]),yt.fromStruct(e[1])];return this.tree.posRangeToPathRange(t)}}function ju(r,e){return jf(r,e)}function un(r,e){if(e){if(e instanceof le)return e;if(e instanceof Me)return jf(r,e);if(e instanceof je)return ny(r,e);if(e instanceof at)return new wo(r,e);if(e instanceof We){const t=new bo(Vt.IntegerCnt,0);return t.initialize(r,e),t}else if(e instanceof ct){const t=new To;return t.initialize(r,e),t}}else return;throw new TypeError(`Unsupported type of element: ${typeof e}`)}function Cn(r,e){const t=un(r,e);return t instanceof le?t.getValue():t}function ro(r,e,t){let n;if(le.isSupport(e))n=le.of(e,t);else if(Array.isArray(e))n=je.create(t,de.buildArrayElements(r,e));else if(typeof e=="object")e instanceof wo?(n=at.create(gs.create(),t),e.initialize(r,n)):e instanceof bo?(n=We.create(e.getValueType(),e.getValue(),t),e.initialize(r,n)):e instanceof To?(n=ct.create(e.buildRoot(r),t),e.initialize(r,n)):n=Me.create(t,Hs.buildObjectMembers(r,e));else throw new TypeError(`Unsupported type of value: ${typeof e}`);return n}const Wu=50;class ay{constructor(){c(this,"undoStack",[]);c(this,"redoStack",[])}hasUndo(){return this.undoStack.length>0}hasRedo(){return this.redoStack.length>0}pushUndo(e){this.undoStack.length>=Wu&&this.undoStack.shift(),this.undoStack.push(e)}popUndo(){return this.undoStack.pop()}pushRedo(e){this.redoStack.length>=Wu&&this.redoStack.shift(),this.redoStack.push(e)}popRedo(){return this.redoStack.pop()}clearRedo(){this.redoStack=[]}getUndoStackForTest(){return this.undoStack}getRedoStackForTest(){return this.redoStack}}const cy="yorkie-devtools-panel",uy="yorkie-devtools-sdk";let Yn="disconnected";const Hu=new Map,ki=new Map;typeof window<"u"&&(window.transactionEventsByDocKey=ki);function gi(r,e){(e!=null&&e.force||Yn!=="disconnected")&&window.postMessage({source:uy,...r},"*")}function ly(r){if(!r.isEnableDevtools()||typeof window>"u"||Hu.has(r.getKey()))return;ki.set(r.getKey(),[]);const e=r.subscribe("all",t=>{t.some(n=>n.type!==Le.StatusChanged&&n.type!==Le.Snapshot&&n.type!==Le.LocalChange&&n.type!==Le.RemoteChange&&n.type!==Le.Initialized&&n.type!==Le.Watched&&n.type!==Le.Unwatched&&n.type!==Le.PresenceChanged)||(ki.get(r.getKey()).push(t),Yn==="synced"&&gi({msg:"doc::sync::partial",docKey:r.getKey(),event:t}))});Hu.set(r.getKey(),[e]),gi({msg:"refresh-devtools"},{force:!0}),window.addEventListener("message",t=>{var s;if(((s=t.data)==null?void 0:s.source)!==cy)return;switch(t.data.msg){case"devtools::connect":if(Yn!=="disconnected")break;Yn="connected",gi({msg:"doc::available",docKey:r.getKey()}),z.info(`[YD] Devtools connected. Doc: ${r.getKey()}`);break;case"devtools::disconnect":Yn="disconnected",z.info(`[YD] Devtools disconnected. Doc: ${r.getKey()}`);break;case"devtools::subscribe":Yn="synced",gi({msg:"doc::sync::full",docKey:r.getKey(),events:ki.get(r.getKey())}),z.info(`[YD] Devtools subscribed. Doc: ${r.getKey()}`);break}})}var ln=(r=>(r.Detached="detached",r.Attached="attached",r.Removed="removed",r))(ln||{}),Le=(r=>(r.StatusChanged="status-changed",r.ConnectionChanged="connection-changed",r.SyncStatusChanged="sync-status-changed",r.Snapshot="snapshot",r.LocalChange="local-change",r.RemoteChange="remote-change",r.Initialized="initialized",r.Watched="watched",r.Unwatched="unwatched",r.PresenceChanged="presence-changed",r.Broadcast="broadcast",r.LocalBroadcast="local-broadcast",r))(Le||{}),ka=(r=>(r.Connected="connected",r.Disconnected="disconnected",r))(ka||{}),Ea=(r=>(r.Synced="synced",r.SyncFailed="sync-failed",r))(Ea||{});class Hf{constructor(e,t){c(this,"key");c(this,"status");c(this,"opts");c(this,"changeID");c(this,"checkpoint");c(this,"localChanges");c(this,"root");c(this,"clone");c(this,"eventStream");c(this,"eventStreamObserver");c(this,"onlineClients");c(this,"presences");c(this,"history");c(this,"internalHistory");c(this,"isUpdating");this.opts=t||{},this.key=e,this.status="detached",this.root=Ws.create(),this.changeID=dp,this.checkpoint=gp,this.localChanges=[],this.eventStream=ry(n=>{this.eventStreamObserver=n}),this.onlineClients=new Set,this.presences=new Map,this.isUpdating=!1,this.internalHistory=new ay,this.history={canUndo:this.canUndo.bind(this),canRedo:this.canRedo.bind(this),undo:this.undo.bind(this),redo:this.redo.bind(this)},ly(this)}update(e,t){if(this.getStatus()==="removed")throw new w(y.ErrDocumentRemoved,`${this.key} is removed`);this.ensureClone();const n=this.changeID.getActorID(),s=Xn.create(this.changeID.next(),this.clone.root,this.clone.presences.get(n)||{},t);try{const i=ju(s,this.clone.root.getObject());this.presences.has(n)||this.clone.presences.set(n,{}),this.isUpdating=!0,e(i,new Ro(s,this.clone.presences.get(n)))}catch(i){throw this.clone=void 0,i}finally{this.isUpdating=!1}if(s.hasChange()){z.isEnabled(Be.Trivial)&&z.trivial(`trying to update a local change: ${this.toJSON()}`);const i=s.getChange(),{opInfos:o,reverseOps:a}=i.execute(this.root,this.presences,se.Local),u=s.getReversePresence();u&&a.push({type:"presence",value:u}),this.localChanges.push(i),a.length>0&&this.internalHistory.pushUndo(a),o.length>0&&this.internalHistory.clearRedo(),this.changeID=i.getID();const l=[];o.length>0&&l.push({type:"local-change",source:se.Local,value:{message:i.getMessage()||"",operations:o,actor:n,clientSeq:i.getID().getClientSeq(),serverSeq:i.getID().getServerSeq()},rawChange:this.isEnableDevtools()?i.toStruct():void 0}),i.hasPresenceChange()&&l.push({type:"presence-changed",source:se.Local,value:{clientID:n,presence:this.getPresence(n)}}),this.publish(l),z.isEnabled(Be.Trivial)&&z.trivial(`after update a local change: ${this.toJSON()}`)}}subscribe(e,t,n,s){if(typeof e=="string"){if(typeof t!="function")throw new w(y.ErrInvalidArgument,"Second argument must be a callback function");if(e==="presence"){const a=t;return this.eventStream.subscribe(u=>{for(const l of u)l.type!=="initialized"&&l.type!=="watched"&&l.type!=="unwatched"&&l.type!=="presence-changed"||a(l)},n,s)}if(e==="my-presence"){const a=t;return this.eventStream.subscribe(u=>{for(const l of u)l.type!=="initialized"&&l.type!=="presence-changed"||l.type==="presence-changed"&&l.value.clientID!==this.changeID.getActorID()||a(l)},n,s)}if(e==="others"){const a=t;return this.eventStream.subscribe(u=>{for(const l of u)l.type!=="watched"&&l.type!=="unwatched"&&l.type!=="presence-changed"||l.value.clientID!==this.changeID.getActorID()&&a(l)},n,s)}if(e==="connection"){const a=t;return this.eventStream.subscribe(u=>{for(const l of u)l.type==="connection-changed"&&a(l)},n,s)}if(e==="status"){const a=t;return this.eventStream.subscribe(u=>{for(const l of u)l.type==="status-changed"&&a(l)},n,s)}if(e==="sync"){const a=t;return this.eventStream.subscribe(u=>{for(const l of u)l.type==="sync-status-changed"&&a(l)},n,s)}if(e==="local-broadcast"){const a=t;return this.eventStream.subscribe(u=>{for(const l of u)l.type==="local-broadcast"&&a(l)},n)}if(e==="broadcast"){const a=t;return this.eventStream.subscribe(u=>{for(const l of u)l.type==="broadcast"&&a(l)},n)}if(e==="all"){const a=t;return this.eventStream.subscribe(a,n,s)}const i=e,o=t;return this.eventStream.subscribe(a=>{for(const u of a){if(u.type!=="local-change"&&u.type!=="remote-change")continue;const l=[];for(const h of u.value.operations)this.isSameElementOrChildOf(h.path,i)&&l.push(h);l.length&&o({...u,value:{...u.value,operations:l}})}},n,s)}if(typeof e=="function"){const i=e,o=t,a=n;return this.eventStream.subscribe(u=>{for(const l of u)l.type!=="snapshot"&&l.type!=="local-change"&&l.type!=="remote-change"||i(l)},o,a)}throw new w(y.ErrInvalidArgument,`"${e}" is not a valid`)}publish(e){this.eventStreamObserver&&this.eventStreamObserver.next(e)}isSameElementOrChildOf(e,t){if(t===e)return!0;const n=e.split(".");return t.split(".").every((i,o)=>i===n[o])}applyChangePack(e){const t=e.hasSnapshot();for(t?this.applySnapshot(e.getCheckpoint().getServerSeq(),e.getVersionVector(),e.getSnapshot()):e.hasChanges()&&this.applyChanges(e.getChanges(),se.Remote);this.localChanges.length&&!(this.localChanges[0].getID().getClientSeq()>e.getCheckpoint().getClientSeq());)this.localChanges.shift();t&&this.applyChanges(this.localChanges,se.Remote),this.checkpoint=this.checkpoint.forward(e.getCheckpoint()),t||this.garbageCollect(e.getVersionVector()),t||this.filterVersionVector(e.getVersionVector()),e.getIsRemoved()&&this.applyStatus("removed"),z.isEnabled(Be.Trivial)&&z.trivial(`${this.root.toJSON()}`)}getCheckpoint(){return this.checkpoint}getChangeID(){return this.changeID}hasLocalChanges(){return this.localChanges.length>0}ensureClone(){this.clone||(this.clone={root:this.root.deepcopy(),presences:ht(this.presences)})}createChangePack(){const e=Array.from(this.localChanges),t=this.checkpoint.increaseClientSeq(e.length);return vo.create(this.key,t,!1,e,this.getVersionVector())}setActor(e){for(const t of this.localChanges)t.setActor(e);this.changeID=this.changeID.setActor(e)}isEnableDevtools(){return!!this.opts.enableDevtools}getKey(){return this.key}getStatus(){return this.status}getCloneRoot(){if(this.clone)return this.clone.root.getObject()}getRoot(){this.ensureClone();const e=Xn.create(this.changeID.next(),this.clone.root,this.clone.presences.get(this.changeID.getActorID())||{});return ju(e,this.clone.root.getObject())}garbageCollect(e){return this.opts.disableGC?0:(this.clone&&this.clone.root.garbageCollect(e),this.root.garbageCollect(e))}getRootObject(){return this.root.getObject()}getGarbageLen(){return this.root.getGarbageLen()}getGarbageLenFromClone(){return this.clone.root.getGarbageLen()}toJSON(){return this.root.toJSON()}toSortedJSON(){return this.root.toSortedJSON()}getStats(){return this.root.getStats()}toJSForTest(){return{...this.getRoot().toJSForTest(),key:"root"}}applySnapshot(e,t,n){const{root:s,presences:i}=me.bytesToSnapshot(n);this.root=new Ws(s),this.presences=i,this.changeID=this.changeID.setClocks(e,t),this.clone=void 0,this.publish([{type:"snapshot",source:se.Remote,value:{serverSeq:e.toString(),snapshot:this.isEnableDevtools()?me.bytesToHex(n):void 0,snapshotVector:me.versionVectorToHex(t)}}])}applyChanges(e,t){z.isEnabled(Be.Debug)&&z.debug(`trying to apply ${e.length} remote changes.elements:${this.root.getElementMapSize()}, removeds:${this.root.getGarbageElementSetSize()}`),z.isEnabled(Be.Trivial)&&z.trivial(e.map(n=>`${n.getID().toTestString()} ${n.toTestString()}`).join(` + */var it=null;try{it=new WebAssembly.Instance(new WebAssembly.Module(new Uint8Array([0,97,115,109,1,0,0,0,1,13,2,96,0,1,127,96,4,127,127,127,127,1,127,3,7,6,0,1,1,1,1,1,6,6,1,127,1,65,0,11,7,50,6,3,109,117,108,0,1,5,100,105,118,95,115,0,2,5,100,105,118,95,117,0,3,5,114,101,109,95,115,0,4,5,114,101,109,95,117,0,5,8,103,101,116,95,104,105,103,104,0,0,10,191,1,6,4,0,35,0,11,36,1,1,126,32,0,173,32,1,173,66,32,134,132,32,2,173,32,3,173,66,32,134,132,126,34,4,66,32,135,167,36,0,32,4,167,11,36,1,1,126,32,0,173,32,1,173,66,32,134,132,32,2,173,32,3,173,66,32,134,132,127,34,4,66,32,135,167,36,0,32,4,167,11,36,1,1,126,32,0,173,32,1,173,66,32,134,132,32,2,173,32,3,173,66,32,134,132,128,34,4,66,32,135,167,36,0,32,4,167,11,36,1,1,126,32,0,173,32,1,173,66,32,134,132,32,2,173,32,3,173,66,32,134,132,129,34,4,66,32,135,167,36,0,32,4,167,11,36,1,1,126,32,0,173,32,1,173,66,32,134,132,32,2,173,32,3,173,66,32,134,132,130,34,4,66,32,135,167,36,0,32,4,167,11])),{}).exports}catch{}function X(r,e,t){this.low=r|0,this.high=e|0,this.unsigned=!!t}X.prototype.__isLong__;Object.defineProperty(X.prototype,"__isLong__",{value:!0});function Ce(r){return(r&&r.__isLong__)===!0}function Lu(r){var e=Math.clz32(r&-r);return r?31-e:e}X.isLong=Ce;var Ju={},Mu={};function zn(r,e){var t,n,s;return e?(r>>>=0,(s=0<=r&&r<256)&&(n=Mu[r],n)?n:(t=Q(r,0,!0),s&&(Mu[r]=t),t)):(r|=0,(s=-128<=r&&r<128)&&(n=Ju[r],n)?n:(t=Q(r,r<0?-1:0,!1),s&&(Ju[r]=t),t))}X.fromInt=zn;function ot(r,e){if(isNaN(r))return e?Xr:pt;if(e){if(r<0)return Xr;if(r>=vf)return Tf}else{if(r<=-Uu)return Je;if(r+1>=Uu)return bf}return r<0?ot(-r,e).neg():Q(r%hs|0,r/hs|0,e)}X.fromNumber=ot;function Q(r,e,t){return new X(r,e,t)}X.fromBits=Q;var Qi=Math.pow;function rc(r,e,t){if(r.length===0)throw Error("empty string");if(typeof e=="number"?(t=e,e=!1):e=!!e,r==="NaN"||r==="Infinity"||r==="+Infinity"||r==="-Infinity")return e?Xr:pt;if(t=t||10,t<2||360)throw Error("interior hyphen");if(n===0)return rc(r.substring(1),e,t).neg();for(var s=ot(Qi(t,8)),i=pt,o=0;o>>0:this.low};k.toNumber=function(){return this.unsigned?(this.high>>>0)*hs+(this.low>>>0):this.high*hs+(this.low>>>0)};k.toString=function(e){if(e=e||10,e<2||36>>0,h=l.toString(e);if(o=u,o.isZero())return h+a;for(;h.length<6;)h="0"+h;a=""+h+a}};k.getHighBits=function(){return this.high};k.getHighBitsUnsigned=function(){return this.high>>>0};k.getLowBits=function(){return this.low};k.getLowBitsUnsigned=function(){return this.low>>>0};k.getNumBitsAbs=function(){if(this.isNegative())return this.eq(Je)?64:this.neg().getNumBitsAbs();for(var e=this.high!=0?this.high:this.low,t=31;t>0&&!(e&1<=0};k.isOdd=function(){return(this.low&1)===1};k.isEven=function(){return(this.low&1)===0};k.equals=function(e){return Ce(e)||(e=At(e)),this.unsigned!==e.unsigned&&this.high>>>31===1&&e.high>>>31===1?!1:this.high===e.high&&this.low===e.low};k.eq=k.equals;k.notEquals=function(e){return!this.eq(e)};k.neq=k.notEquals;k.ne=k.notEquals;k.lessThan=function(e){return this.comp(e)<0};k.lt=k.lessThan;k.lessThanOrEqual=function(e){return this.comp(e)<=0};k.lte=k.lessThanOrEqual;k.le=k.lessThanOrEqual;k.greaterThan=function(e){return this.comp(e)>0};k.gt=k.greaterThan;k.greaterThanOrEqual=function(e){return this.comp(e)>=0};k.gte=k.greaterThanOrEqual;k.ge=k.greaterThanOrEqual;k.compare=function(e){if(Ce(e)||(e=At(e)),this.eq(e))return 0;var t=this.isNegative(),n=e.isNegative();return t&&!n?-1:!t&&n?1:this.unsigned?e.high>>>0>this.high>>>0||e.high===this.high&&e.low>>>0>this.low>>>0?-1:1:this.sub(e).isNegative()?-1:1};k.comp=k.compare;k.negate=function(){return!this.unsigned&&this.eq(Je)?Je:this.not().add(_n)};k.neg=k.negate;k.add=function(e){Ce(e)||(e=At(e));var t=this.high>>>16,n=this.high&65535,s=this.low>>>16,i=this.low&65535,o=e.high>>>16,a=e.high&65535,u=e.low>>>16,l=e.low&65535,h=0,g=0,v=0,m=0;return m+=i+l,v+=m>>>16,m&=65535,v+=s+u,g+=v>>>16,v&=65535,g+=n+a,h+=g>>>16,g&=65535,h+=t+o,h&=65535,Q(v<<16|m,h<<16|g,this.unsigned)};k.subtract=function(e){return Ce(e)||(e=At(e)),this.add(e.neg())};k.sub=k.subtract;k.multiply=function(e){if(this.isZero())return this;if(Ce(e)||(e=At(e)),it){var t=it.mul(this.low,this.high,e.low,e.high);return Q(t,it.get_high(),this.unsigned)}if(e.isZero())return this.unsigned?Xr:pt;if(this.eq(Je))return e.isOdd()?Je:pt;if(e.eq(Je))return this.isOdd()?Je:pt;if(this.isNegative())return e.isNegative()?this.neg().mul(e.neg()):this.neg().mul(e).neg();if(e.isNegative())return this.mul(e.neg()).neg();if(this.lt(qu)&&e.lt(qu))return ot(this.toNumber()*e.toNumber(),this.unsigned);var n=this.high>>>16,s=this.high&65535,i=this.low>>>16,o=this.low&65535,a=e.high>>>16,u=e.high&65535,l=e.low>>>16,h=e.low&65535,g=0,v=0,m=0,A=0;return A+=o*h,m+=A>>>16,A&=65535,m+=i*h,v+=m>>>16,m&=65535,m+=o*l,v+=m>>>16,m&=65535,v+=s*h,g+=v>>>16,v&=65535,v+=i*l,g+=v>>>16,v&=65535,v+=o*u,g+=v>>>16,v&=65535,g+=n*h+s*l+i*u+o*a,g&=65535,Q(m<<16|A,g<<16|v,this.unsigned)};k.mul=k.multiply;k.divide=function(e){if(Ce(e)||(e=At(e)),e.isZero())throw Error("division by zero");if(it){if(!this.unsigned&&this.high===-2147483648&&e.low===-1&&e.high===-1)return this;var t=(this.unsigned?it.div_u:it.div_s)(this.low,this.high,e.low,e.high);return Q(t,it.get_high(),this.unsigned)}if(this.isZero())return this.unsigned?Xr:pt;var n,s,i;if(this.unsigned){if(e.unsigned||(e=e.toUnsigned()),e.gt(this))return Xr;if(e.gt(this.shru(1)))return wf;i=Xr}else{if(this.eq(Je)){if(e.eq(_n)||e.eq(Ia))return Je;if(e.eq(Je))return _n;var o=this.shr(1);return n=o.div(e).shl(1),n.eq(pt)?e.isNegative()?_n:Ia:(s=this.sub(e.mul(n)),i=n.add(s.div(e)),i)}else if(e.eq(Je))return this.unsigned?Xr:pt;if(this.isNegative())return e.isNegative()?this.neg().div(e.neg()):this.neg().div(e).neg();if(e.isNegative())return this.div(e.neg()).neg();i=pt}for(s=this;s.gte(e);){n=Math.max(1,Math.floor(s.toNumber()/e.toNumber()));for(var a=Math.ceil(Math.log(n)/Math.LN2),u=a<=48?1:Qi(2,a-48),l=ot(n),h=l.mul(e);h.isNegative()||h.gt(s);)n-=u,l=ot(n,this.unsigned),h=l.mul(e);l.isZero()&&(l=_n),i=i.add(l),s=s.sub(h)}return i};k.div=k.divide;k.modulo=function(e){if(Ce(e)||(e=At(e)),it){var t=(this.unsigned?it.rem_u:it.rem_s)(this.low,this.high,e.low,e.high);return Q(t,it.get_high(),this.unsigned)}return this.sub(this.div(e).mul(e))};k.mod=k.modulo;k.rem=k.modulo;k.not=function(){return Q(~this.low,~this.high,this.unsigned)};k.countLeadingZeros=function(){return this.high?Math.clz32(this.high):Math.clz32(this.low)+32};k.clz=k.countLeadingZeros;k.countTrailingZeros=function(){return this.low?Lu(this.low):Lu(this.high)+32};k.ctz=k.countTrailingZeros;k.and=function(e){return Ce(e)||(e=At(e)),Q(this.low&e.low,this.high&e.high,this.unsigned)};k.or=function(e){return Ce(e)||(e=At(e)),Q(this.low|e.low,this.high|e.high,this.unsigned)};k.xor=function(e){return Ce(e)||(e=At(e)),Q(this.low^e.low,this.high^e.high,this.unsigned)};k.shiftLeft=function(e){return Ce(e)&&(e=e.toInt()),(e&=63)===0?this:e<32?Q(this.low<>>32-e,this.unsigned):Q(0,this.low<>>e|this.high<<32-e,this.high>>e,this.unsigned):Q(this.high>>e-32,this.high>=0?0:-1,this.unsigned)};k.shr=k.shiftRight;k.shiftRightUnsigned=function(e){return Ce(e)&&(e=e.toInt()),(e&=63)===0?this:e<32?Q(this.low>>>e|this.high<<32-e,this.high>>>e,this.unsigned):e===32?Q(this.high,0,this.unsigned):Q(this.high>>>e-32,0,this.unsigned)};k.shru=k.shiftRightUnsigned;k.shr_u=k.shiftRightUnsigned;k.rotateLeft=function(e){var t;return Ce(e)&&(e=e.toInt()),(e&=63)===0?this:e===32?Q(this.high,this.low,this.unsigned):e<32?(t=32-e,Q(this.low<>>t,this.high<>>t,this.unsigned)):(e-=32,t=32-e,Q(this.high<>>t,this.low<>>t,this.unsigned))};k.rotl=k.rotateLeft;k.rotateRight=function(e){var t;return Ce(e)&&(e=e.toInt()),(e&=63)===0?this:e===32?Q(this.high,this.low,this.unsigned):e<32?(t=32-e,Q(this.high<>>e,this.low<>>e,this.unsigned)):(e-=32,t=32-e,Q(this.low<>>e,this.high<>>e,this.unsigned))};k.rotr=k.rotateRight;k.toSigned=function(){return this.unsigned?Q(this.low,this.high,!1):this};k.toUnsigned=function(){return this.unsigned?this:Q(this.low,this.high,!0)};k.toBytes=function(e){return e?this.toBytesLE():this.toBytesBE()};k.toBytesLE=function(){var e=this.high,t=this.low;return[t&255,t>>>8&255,t>>>16&255,t>>>24,e&255,e>>>8&255,e>>>16&255,e>>>24]};k.toBytesBE=function(){var e=this.high,t=this.low;return[e>>>24,e>>>16&255,e>>>8&255,e&255,t>>>24,t>>>16&255,t>>>8&255,t&255]};X.fromBytes=function(e,t,n){return n?X.fromBytesLE(e,t):X.fromBytesBE(e,t)};X.fromBytesLE=function(e,t){return new X(e[0]|e[1]<<8|e[2]<<16|e[3]<<24,e[4]|e[5]<<8|e[6]<<16|e[7]<<24,t)};X.fromBytesBE=function(e,t){return new X(e[4]<<24|e[5]<<16|e[6]<<8|e[7],e[0]<<24|e[1]<<16|e[2]<<8|e[3],t)};var be=(r=>(r[r.Null=0]="Null",r[r.Boolean=1]="Boolean",r[r.Integer=2]="Integer",r[r.Long=3]="Long",r[r.Double=4]="Double",r[r.String=5]="String",r[r.Bytes=6]="Bytes",r[r.Date=7]="Date",r))(be||{});class le extends Gs{constructor(t,n){super(n);c(this,"valueType");c(this,"value");this.valueType=le.getPrimitiveType(t),this.value=t===void 0?null:t}static of(t,n){return new le(t,n)}static valueFromBytes(t,n){switch(t){case 0:return null;case 1:return!!n[0];case 2:return n[0]|n[1]<<8|n[2]<<16|n[3]<<24;case 4:{const s=new DataView(n.buffer);return n.forEach(function(i,o){s.setUint8(o,i)}),s.getFloat64(0,!0)}case 5:return new TextDecoder("utf-8").decode(n);case 3:return X.fromBytesLE(Array.from(n));case 6:return n;case 7:return new Date(X.fromBytesLE(Array.from(n),!0).toNumber());default:throw new w(y.ErrUnimplemented,`unimplemented type: ${t}`)}}toJSON(){return this.valueType===5?`"${$t(this.value)}"`:`${this.value}`}toSortedJSON(){return this.toJSON()}toJSForTest(){return{createdAt:this.getCreatedAt().toTestString(),value:this.value,type:"YORKIE_PRIMITIVE"}}deepcopy(){const t=le.of(this.value,this.getCreatedAt());return t.setMovedAt(this.getMovedAt()),t.setRemovedAt(this.getRemovedAt()),t}getType(){return this.valueType}static getPrimitiveType(t){switch(typeof t){case"undefined":return 0;case"boolean":return 1;case"number":return this.isInteger(t)?2:4;case"string":return 5;case"object":if(t===null)return 0;if(t instanceof X)return 3;if(t instanceof Uint8Array)return 6;if(t instanceof Date)return 7}}static isSupport(t){return le.getPrimitiveType(t)!==void 0}static isInteger(t){return t%1===0}isNumericType(){const t=this.valueType;return t===2||t===3||t===4}getValue(){return this.value}toBytes(){switch(this.valueType){case 0:return new Uint8Array;case 1:return this.value?new Uint8Array([1]):new Uint8Array([0]);case 2:{const t=this.value;return new Uint8Array([t&255,t>>8&255,t>>16&255,t>>24&255])}case 4:{const t=this.value,n=new Uint8Array(8);return new DataView(n.buffer).setFloat64(0,t,!0),n}case 5:return new TextEncoder().encode(this.value);case 3:{const n=this.value.toBytesLE();return Uint8Array.from(n)}case 6:return this.value;case 7:{const t=this.value,n=X.fromNumber(t.getTime(),!0).toBytesLE();return Uint8Array.from(n)}default:throw new w(y.ErrUnimplemented,`unimplemented type: ${this.valueType}`)}}}class eo extends yf{constructor(t){super(t);c(this,"prev");c(this,"next");this.value=t}static createAfter(t,n){const s=new eo(n),i=t.next;return t.next=s,s.prev=t,s.next=i,i&&(i.prev=s),s}remove(t){return this.value.remove(t)}getCreatedAt(){return this.value.getCreatedAt()}getPositionedAt(){return this.value.getPositionedAt()}release(){this.prev&&(this.prev.next=this.next),this.next&&(this.next.prev=this.prev),this.prev=void 0,this.next=void 0}getLength(){return this.value.isRemoved()?0:1}getPrev(){return this.prev}getNext(){return this.next}getValue(){return this.value}isRemoved(){return this.value.isRemoved()}}class Ks{constructor(){c(this,"dummyHead");c(this,"last");c(this,"nodeMapByIndex");c(this,"nodeMapByCreatedAt");const e=le.of(0,wt);e.setRemovedAt(wt),this.dummyHead=new eo(e),this.last=this.dummyHead,this.nodeMapByIndex=new zs,this.nodeMapByCreatedAt=new Map,this.nodeMapByIndex.insert(this.dummyHead),this.nodeMapByCreatedAt.set(this.dummyHead.getCreatedAt().toIDString(),this.dummyHead)}static create(){return new Ks}get length(){return this.nodeMapByIndex.length}findNextBeforeExecutedAt(e,t){let n=this.nodeMapByCreatedAt.get(e.toIDString());if(!n)throw new w(y.ErrInvalidArgument,`cant find the given node: ${e.toIDString()}`);for(;n.getNext()&&n.getNext().getPositionedAt().after(t);)n=n.getNext();return n}release(e){this.last===e&&(this.last=e.getPrev()),e.release(),this.nodeMapByIndex.delete(e),this.nodeMapByCreatedAt.delete(e.getValue().getCreatedAt().toIDString())}insertAfter(e,t,n=t.getCreatedAt()){const s=this.findNextBeforeExecutedAt(e,n),i=eo.createAfter(s,t);s===this.last&&(this.last=i),this.nodeMapByIndex.insertAfter(s,i),this.nodeMapByCreatedAt.set(i.getCreatedAt().toIDString(),i)}moveAfter(e,t,n){const s=this.nodeMapByCreatedAt.get(e.toIDString());if(!s)throw new w(y.ErrInvalidArgument,`cant find the given node: ${e.toIDString()}`);const i=this.nodeMapByCreatedAt.get(t.toIDString());if(!i)throw new w(y.ErrInvalidArgument,`cant find the given node: ${t.toIDString()}`);s!==i&&(!i.getValue().getMovedAt()||n.after(i.getValue().getMovedAt()))&&(this.release(i),this.insertAfter(s.getCreatedAt(),i.getValue(),n),i.getValue().setMovedAt(n))}insert(e){this.insertAfter(this.last.getCreatedAt(),e)}getByID(e){return this.nodeMapByCreatedAt.get(e.toIDString())}subPathOf(e){const t=this.nodeMapByCreatedAt.get(e.toIDString());if(t)return String(this.nodeMapByIndex.indexOf(t))}purge(e){const t=this.nodeMapByCreatedAt.get(e.getCreatedAt().toIDString());if(!t)throw new w(y.ErrInvalidArgument,`fail to find the given createdAt: ${e.getCreatedAt().toIDString()}`);this.release(t)}getByIndex(e){if(e>=this.length)return;const[t,n]=this.nodeMapByIndex.find(e);let s=t;if(e===0&&t===this.dummyHead||n>0)do s&&(s=s.getNext());while(s&&s.isRemoved());return s}getPrevCreatedAt(e){let t=this.nodeMapByCreatedAt.get(e.toIDString());do t=t.getPrev();while(this.dummyHead!==t&&t.isRemoved());return t.getValue().getCreatedAt()}delete(e,t){const n=this.nodeMapByCreatedAt.get(e.toIDString()),s=n.isRemoved();return n.remove(t)&&!s&&this.nodeMapByIndex.splayNode(n),n.getValue()}deleteByIndex(e,t){const n=this.getByIndex(e);if(n)return n.remove(t)&&this.nodeMapByIndex.splayNode(n),n.getValue()}getHead(){return this.dummyHead.getValue()}getLast(){return this.last.getValue()}getLastCreatedAt(){return this.last.getCreatedAt()}toTestString(){const e=[];for(const t of this){const n=`${t.getCreatedAt().toIDString()}:${t.getValue().toJSON()}`;t.isRemoved()?e.push(`{${n}}`):e.push(`[${n}]`)}return e.join("")}*[Symbol.iterator](){let e=this.dummyHead.getNext();for(;e;)yield e,e=e.getNext()}}class je extends pn{constructor(t,n){super(t);c(this,"elements");this.elements=n}static create(t,n){if(!n)return new je(t,Ks.create());const s=Ks.create();for(const i of n)s.insertAfter(s.getLastCreatedAt(),i.deepcopy());return new je(t,s)}subPathOf(t){return this.elements.subPathOf(t)}purge(t){this.elements.purge(t)}insertAfter(t,n){this.elements.insertAfter(t,n)}moveAfter(t,n,s){this.elements.moveAfter(t,n,s)}get(t){const n=this.elements.getByIndex(t);return n==null?void 0:n.getValue()}getByID(t){const n=this.elements.getByID(t);return n==null?void 0:n.getValue()}getHead(){return this.elements.getHead()}getLast(){return this.elements.getLast()}getPrevCreatedAt(t){return this.elements.getPrevCreatedAt(t)}delete(t,n){return this.elements.delete(t,n)}deleteByIndex(t,n){return this.elements.deleteByIndex(t,n)}getLastCreatedAt(){return this.elements.getLastCreatedAt()}get length(){return this.elements.length}*[Symbol.iterator](){for(const t of this.elements)t.isRemoved()||(yield t.getValue())}toTestString(){return this.elements.toTestString()}getDescendants(t){for(const n of this.elements){const s=n.getValue();if(t(s,this))return;s instanceof pn&&s.getDescendants(t)}}toJSON(){const t=[];for(const n of this)t.push(n.toJSON());return`[${t.join(",")}]`}toJS(){return JSON.parse(this.toJSON())}toJSForTest(){const t={};for(let n=0;n({...m,value:m.value?{attributes:rs(m.value.getAttributes()),content:m.value.getContent()}:{attributes:void 0,content:""},type:"content"}));return[l,v,h,[u,u]]}setStyle(t,n,s,i){const[,o]=this.rgaTreeSplit.findNodeWithSplit(t[1],s),[,a]=this.rgaTreeSplit.findNodeWithSplit(t[0],s),u=[],l=this.rgaTreeSplit.findBetween(a,o),h=new Map,g=[];for(const m of l){const A=m.getCreatedAt().getActorID(),E=i!=null&&i.size?i.has(A)?i.get(A):wt:Ns;if(m.canStyle(s,E)){const R=h.get(A),$=m.getCreatedAt();(!R||$.after(R))&&h.set(A,$),g.push(m)}}const v=[];for(const m of g){if(m.isRemoved())continue;const[A,E]=this.rgaTreeSplit.findIndexesFromRange(m.createPosRange());u.push({type:"style",actor:s.getActorID(),from:A,to:E,value:{attributes:rs(n)}});for(const[R,$]of Object.entries(n)){const[U]=m.getValue().setAttr(R,$,s);U!==void 0&&v.push({parent:m.getValue(),child:U})}}return[h,v,u]}indexRangeToPosRange(t,n){const s=this.rgaTreeSplit.indexToPos(t);return t===n?[s,s]:[s,this.rgaTreeSplit.indexToPos(n)]}get length(){return this.rgaTreeSplit.length}getTreeByIndex(){return this.rgaTreeSplit.getTreeByIndex()}getTreeByID(){return this.rgaTreeSplit.getTreeByID()}toJSON(){const t=[];for(const n of this.rgaTreeSplit)n.isRemoved()||t.push(n.getValue().toJSON());return`[${t.join(",")}]`}toSortedJSON(){return this.toJSON()}toJSForTest(){return{createdAt:this.getCreatedAt().toTestString(),value:JSON.parse(this.toJSON()),type:"YORKIE_TEXT"}}toString(){return this.rgaTreeSplit.toString()}values(){const t=[];for(const n of this.rgaTreeSplit)if(!n.isRemoved()){const s=n.getValue();t.push({attributes:rs(s.getAttributes()),content:s.getContent()})}return t}getRGATreeSplit(){return this.rgaTreeSplit}toTestString(){return this.rgaTreeSplit.toTestString()}deepcopy(){const t=new at(this.rgaTreeSplit.deepcopy(),this.getCreatedAt());return t.remove(this.getRemovedAt()),t}findIndexesFromRange(t){return this.rgaTreeSplit.findIndexesFromRange(t)}getGCPairs(){const t=[];for(const n of this.rgaTreeSplit){n.getRemovedAt()&&t.push({parent:this.rgaTreeSplit,child:n});for(const s of n.getValue().getGCPairs())t.push(s)}return t}}class _s extends Tt{constructor(t,n,s,i,o,a,u){super(t,u);c(this,"fromPos");c(this,"toPos");c(this,"maxCreatedAtMapByActor");c(this,"content");c(this,"attributes");this.fromPos=n,this.toPos=s,this.maxCreatedAtMapByActor=i,this.content=o,this.attributes=a}static create(t,n,s,i,o,a,u){return new _s(t,n,s,i,o,a,u)}execute(t){const n=t.findByCreatedAt(this.getParentCreatedAt());if(!n)throw new w(y.ErrInvalidArgument,`fail to find ${this.getParentCreatedAt()}`);if(!(n instanceof at))throw new w(y.ErrInvalidArgument,"fail to execute, only Text can execute edit");const s=n,[,i,o]=s.edit([this.fromPos,this.toPos],this.content,this.getExecutedAt(),Object.fromEntries(this.attributes),this.maxCreatedAtMapByActor);for(const a of o)t.registerGCPair(a);return{opInfos:i.map(({from:a,to:u,value:l})=>({type:"edit",from:a,to:u,value:l,path:t.createPath(this.getParentCreatedAt())}))}}getEffectedCreatedAt(){return this.getParentCreatedAt()}toTestString(){const t=this.getParentCreatedAt().toTestString(),n=this.fromPos.toTestString(),s=this.toPos.toTestString(),i=this.content;return`${t}.EDIT(${n},${s},${i})`}getFromPos(){return this.fromPos}getToPos(){return this.toPos}getContent(){return this.content}getAttributes(){return this.attributes||new Map}getMaxCreatedAtMapByActor(){return this.maxCreatedAtMapByActor}}class Xs extends Tt{constructor(t,n,s,i,o,a){super(t,a);c(this,"fromPos");c(this,"toPos");c(this,"maxCreatedAtMapByActor");c(this,"attributes");this.fromPos=n,this.toPos=s,this.maxCreatedAtMapByActor=i,this.attributes=o}static create(t,n,s,i,o,a){return new Xs(t,n,s,i,o,a)}execute(t){const n=t.findByCreatedAt(this.getParentCreatedAt());if(!n)throw new w(y.ErrInvalidArgument,`fail to find ${this.getParentCreatedAt()}`);if(!(n instanceof at))throw new w(y.ErrInvalidArgument,"fail to execute, only Text can execute edit");const s=n,[,i,o]=s.setStyle([this.fromPos,this.toPos],this.attributes?Object.fromEntries(this.attributes):{},this.getExecutedAt(),this.maxCreatedAtMapByActor);for(const a of i)t.registerGCPair(a);return{opInfos:o.map(({from:a,to:u,value:l})=>({type:"style",from:a,to:u,value:l,path:t.createPath(this.getParentCreatedAt())}))}}getEffectedCreatedAt(){return this.getParentCreatedAt()}toTestString(){const t=this.getParentCreatedAt().toTestString(),n=this.fromPos.toTestString(),s=this.toPos.toTestString(),i=this.attributes;return`${t}.STYL(${n},${s},${JSON.stringify(i)})`}getFromPos(){return this.fromPos}getToPos(){return this.toPos}getAttributes(){return this.attributes}getMaxCreatedAtMapByActor(){return this.maxCreatedAtMapByActor}}const np=2,sp="root",Zr="text";function As(r,e){let t=0;const n=r.children;for(let s=0;s0)throw new w(y.ErrRefused,"Text node cannot have children")}updateAncestorsSize(){let e=this.parent;const t=this.isRemoved?-1:1;for(;e&&(e.size+=this.paddedSize*t,!e.isRemoved);)e=e.parent}updateDescendantsSize(){let e=0;for(const t of this._children){const n=t.updateDescendantsSize();t.isRemoved||(e+=n)}return this.size+=e,this.paddedSize}get isText(){return this.type===Zr}get paddedSize(){return this.size+(this.isText?0:np)}isAncestorOf(e){return op(this,e)}get nextSibling(){const e=this.parent.findOffset(this),t=this.parent.children[e+1];if(t)return t}get prevSibling(){const e=this.parent.findOffset(this),t=this.parent.children[e-1];if(t)return t}splitText(e,t){if(e===0||e===this.size)return;const n=this.value.slice(0,e),s=this.value.slice(e);if(!s.length)return;this.value=n;const i=this.cloneText(e+t);return i.value=s,this.parent.insertAfterInternal(i,this),i}get children(){return this._children.filter(e=>!e.isRemoved)}get allChildren(){return[...this._children]}hasTextChild(){return this.children.length>0&&this.children.every(e=>e.isText)}append(...e){if(this.isText)throw new w(y.ErrRefused,"Text node cannot have children");this._children.push(...e);for(const t of e)t.parent=this,t.updateAncestorsSize()}prepend(...e){if(this.isText)throw new w(y.ErrRefused,"Text node cannot have children");this._children.unshift(...e);for(const t of e)t.parent=this}insertBefore(e,t){if(this.isText)throw new w(y.ErrRefused,"Text node cannot have children");const n=this._children.indexOf(t);if(n===-1)throw new w(y.ErrInvalidArgument,"child not found");this.insertAtInternal(e,n),e.updateAncestorsSize()}insertAfter(e,t){if(this.isText)throw new w(y.ErrRefused,"Text node cannot have children");const n=this._children.indexOf(t);if(n===-1)throw new w(y.ErrInvalidArgument,"child not found");this.insertAtInternal(e,n+1),e.updateAncestorsSize()}insertAt(e,t){if(this.isText)throw new w(y.ErrRefused,"Text node cannot have children");this.insertAtInternal(e,t),e.updateAncestorsSize()}removeChild(e){if(this.isText)throw new w(y.ErrRefused,"Text node cannot have children");const t=this._children.indexOf(e);if(t===-1)throw new w(y.ErrInvalidArgument,"child not found");this._children.splice(t,1),e.parent=void 0}splitElement(e,t){const n=this.cloneElement(t);this.parent.insertAfterInternal(n,this),n.updateAncestorsSize();const s=this.children.slice(0,e),i=this.children.slice(e);this._children=s,n._children=i,this.size=this._children.reduce((o,a)=>o+a.paddedSize,0),n.size=n._children.reduce((o,a)=>o+a.paddedSize,0);for(const o of n._children)o.parent=n;return n}insertAfterInternal(e,t){if(this.isText)throw new w(y.ErrRefused,"Text node cannot have children");const n=this._children.indexOf(t);if(n===-1)throw new w(y.ErrInvalidArgument,"child not found");this.insertAtInternal(e,n+1)}insertAtInternal(e,t){if(this.isText)throw new w(y.ErrRefused,"Text node cannot have children");this._children.splice(t,0,e),e.parent=this}findOffset(e){if(this.isText)throw new w(y.ErrRefused,"Text node cannot have children");if(e.isRemoved){const t=this._children.indexOf(e);return this.allChildren.splice(0,t).filter(s=>!s.isRemoved).length}return this.children.indexOf(e)}findBranchOffset(e){if(this.isText)throw new w(y.ErrRefused,"Text node cannot have children");let t=e;for(;t;){const n=this._children.indexOf(t);if(n!==-1)return n;t=t.parent}return-1}}function op(r,e){if(r===e)return!1;for(;e.parent;){if(e.parent===r)return!0;e=e.parent}return!1}var ve=(r=>(r.Start="Start",r.End="End",r.Text="Text",r))(ve||{});function Af(r,e,t,n){if(e>t)throw new w(y.ErrInvalidArgument,`from is greater than to: ${e} > ${t}`);if(e>r.size)throw new w(y.ErrInvalidArgument,`from is out of range: ${e} > ${r.size}`);if(t>r.size)throw new w(y.ErrInvalidArgument,`to is out of range: ${t} > ${r.size}`);if(e===t)return;let s=0;for(const i of r.children){if(e-i.paddedSizei.size;(i.isText||u)&&n([i,i.isText?"Text":"Start"],l),Af(i,Math.max(0,o),Math.min(a,i.size),n),l&&n([i,"End"],l)}s+=i.paddedSize}}function If(r,e,t=0){for(const n of r.children)If(n,e,t+1);e(r,t)}function yo(r,e,t=0){for(const n of r._children)yo(n,e,t+1);e(r,t)}function Sa(r,e,t=!0){if(e>r.size)throw new w(y.ErrInvalidArgument,`index is out of range: ${e} > ${r.size}`);if(r.isText)return{node:r,offset:e};let n=0,s=0;for(const i of r.children){if(t&&i.isText&&i.size>=e-s)return Sa(i,e-s,t);if(e===s)return{node:r,offset:n};if(!t&&i.paddedSize===e-s)return{node:r,offset:n+1};if(i.paddedSize>e-s)return Sa(i,e-s-1,t);s+=i.paddedSize,n+=1}return{node:r,offset:n}}function Sf(r){return r.isText||r.children.length===0?r:Sf(r.children[0])}function ap(r,e){if(r.sizer===e?0:r0)if(t.right)t.right.parent=t,t=t.right;else return t;else if(n<0)if(t.left)t.left.parent=t,t=t.left;else{let s=t.parent,i=t;for(;s&&i===s.left;)i=s,s=s.parent;return s}else return t}}lastEntry(){if(!this.root)return this.root;let e=this.root;for(;e.right;)e=e.right;return e}size(){return this.counter}isEmpty(){return this.counter===0}getInternal(e,t){for(;t;){const n=this.comparator(e,t.key);if(n===0)return t;n<0?t=t.left:n>0&&(t=t.right)}}putInternal(e,t,n){if(!n)return this.counter+=1,new lp(e,t,!0);const s=this.comparator(e,n.key);return s<0?n.left=this.putInternal(e,t,n.left):s>0?n.right=this.putInternal(e,t,n.right):n.value=t,this.isRed(n.right)&&!this.isRed(n.left)&&(n=this.rotateLeft(n)),this.isRed(n.left)&&this.isRed(n.left.left)&&(n=this.rotateRight(n)),this.isRed(n.left)&&this.isRed(n.right)&&this.flipColors(n),n}removeInternal(e,t){if(this.comparator(t,e.key)<0)!this.isRed(e.left)&&!this.isRed(e.left.left)&&(e=this.moveRedLeft(e)),e.left=this.removeInternal(e.left,t);else{if(this.isRed(e.left)&&(e=this.rotateRight(e)),this.comparator(t,e.key)===0&&!e.right){this.counter-=1;return}if(!this.isRed(e.right)&&!this.isRed(e.right.left)&&(e=this.moveRedRight(e)),this.comparator(t,e.key)===0){this.counter-=1;const n=this.min(e.right);e.value=n.value,e.key=n.key,e.right=this.removeMin(e.right)}else e.right=this.removeInternal(e.right,t)}return this.fixUp(e)}min(e){return e.left?this.min(e.left):e}removeMin(e){if(e.left)return!this.isRed(e.left)&&!this.isRed(e.left.left)&&(e=this.moveRedLeft(e)),e.left=this.removeMin(e.left),this.fixUp(e)}fixUp(e){return this.isRed(e.right)&&(e=this.rotateLeft(e)),this.isRed(e.left)&&this.isRed(e.left.left)&&(e=this.rotateRight(e)),this.isRed(e.left)&&this.isRed(e.right)&&this.flipColors(e),e}moveRedLeft(e){return this.flipColors(e),this.isRed(e.right.left)&&(e.right=this.rotateRight(e.right),e=this.rotateLeft(e),this.flipColors(e)),e}moveRedRight(e){return this.flipColors(e),this.isRed(e.left.left)&&(e=this.rotateRight(e),this.flipColors(e)),e}isRed(e){return e&&e.isRed}rotateLeft(e){const t=e.right;return e.right=t.left,t.left=e,t.isRed=t.left.isRed,t.left.isRed=!0,t}rotateRight(e){const t=e.left;return e.left=t.right,t.right=e,t.isRed=t.right.isRed,t.right.isRed=!0,t}flipColors(e){e.isRed=!e.isRed,e.left.isRed=!e.left.isRed,e.right.isRed=!e.right.isRed}}class yt{constructor(e,t){c(this,"parentID");c(this,"leftSiblingID");this.parentID=e,this.leftSiblingID=t}static of(e,t){return new yt(e,t)}static fromTreePos(e){const{offset:t}=e;let{node:n}=e,s;return n.isText?(n.parent.children[0]===n&&t===0?s=n.parent:s=n,n=n.parent):t===0?s=n:s=n.children[t-1],yt.of(n.id,Ae.of(s.getCreatedAt(),s.getOffset()+t))}getParentID(){return this.parentID}static fromStruct(e){return yt.of(Ae.of(Ke.fromStruct(e.parentID.createdAt),e.parentID.offset),Ae.of(Ke.fromStruct(e.leftSiblingID.createdAt),e.leftSiblingID.offset))}toStruct(){return{parentID:{createdAt:this.getParentID().getCreatedAt().toStruct(),offset:this.getParentID().getOffset()},leftSiblingID:{createdAt:this.getLeftSiblingID().getCreatedAt().toStruct(),offset:this.getLeftSiblingID().getOffset()}}}toTreeNodePair(e){const t=this.getParentID(),n=this.getLeftSiblingID(),s=e.findFloorNode(t);let i=e.findFloorNode(n);if(!s||!i)throw new w(y.ErrRefused,`cannot find node of CRDTTreePos(${t.toTestString()}, ${n.toTestString()})`);return!n.equals(t)&&n.getOffset()>0&&n.getOffset()===i.id.getOffset()&&i.insPrevID&&(i=e.findFloorNode(i.insPrevID)),[s,i]}getLeftSiblingID(){return this.leftSiblingID}equals(e){return this.getParentID().getCreatedAt().equals(e.getParentID().getCreatedAt())&&this.getParentID().getOffset()===e.getParentID().getOffset()&&this.getLeftSiblingID().getCreatedAt().equals(e.getLeftSiblingID().getCreatedAt())&&this.getLeftSiblingID().getOffset()===e.getLeftSiblingID().getOffset()}}class Ae{constructor(e,t){c(this,"createdAt");c(this,"offset");this.createdAt=e,this.offset=t}static of(e,t){return new Ae(e,t)}static fromStruct(e){return Ae.of(Ke.fromStruct(e.createdAt),e.offset)}static createComparator(){return(e,t)=>{const n=e.getCreatedAt().compare(t.getCreatedAt());return n!==0?n:e.getOffset()>t.getOffset()?1:e.getOffset(){const i=s.deepcopy();return i.parent=t,i}),t.insPrevID=this.insPrevID,t.insNextID=this.insNextID,t}get value(){if(!this.isText)throw new w(y.ErrInvalidType,`cannot get value of element node: ${this.type}`);return this._value}set value(t){if(!this.isText)throw new w(y.ErrInvalidType,`cannot set value of element node: ${this.type}`);this._value=t,this.size=t.length}get isRemoved(){return!!this.removedAt}remove(t){const n=!this.removedAt;(!this.removedAt||this.removedAt.compare(t)>0)&&(this.removedAt=t),n&&this.updateAncestorsSize()}cloneText(t){return new ze(Ae.of(this.id.getCreatedAt(),t),this.type,void 0,void 0,this.removedAt)}cloneElement(t){return new ze(Ae.of(t(),0),this.type,void 0,void 0,this.removedAt)}split(t,n,s){const i=this.isText?this.splitText(n,this.id.getOffset()):this.splitElement(n,s);if(i){if(i.insPrevID=this.id,this.insNextID){const o=t.findFloorNode(this.insNextID);o.insPrevID=i.id,i.insNextID=this.insNextID}this.insNextID=i.id,t.registerNode(i)}return i}getCreatedAt(){return this.id.getCreatedAt()}getOffset(){return this.id.getOffset()}canDelete(t,n){return!this.getCreatedAt().after(n)&&(!this.removedAt||t.after(this.removedAt))}canStyle(t,n){return this.isText?!1:!this.getCreatedAt().after(n)&&(!this.removedAt||t.after(this.removedAt))}setAttrs(t,n){this.attrs||(this.attrs=new rn);const s=new Array;for(const[i,o]of Object.entries(t))s.push(this.attrs.set(i,o,n));return s}purge(t){this.attrs&&this.attrs.purge(t)}getGCPairs(){const t=[];if(!this.attrs)return t;for(const n of this.attrs)n.getRemovedAt()&&t.push({parent:this,child:n});return t}}function xa(r){var t;if(r.isText){const n=r;return{type:n.type,value:n.value}}const e={type:r.type,children:r.children.map(xa)};return r.attrs&&(e.attributes=rs((t=r.attrs)==null?void 0:t.toObject())),e}function nc(r){if(r.isText)return r.value;let e="";return r.attrs&&r.attrs.size()&&(e=" "+Array.from(r.attrs).filter(t=>!t.isRemoved()).sort((t,n)=>t.getKey().localeCompare(n.getKey())).map(t=>{const n=JSON.parse(t.getValue());return typeof n=="string"?`${t.getKey()}="${n}"`:`${t.getKey()}="${$t(t.getValue())}"`}).join(" ")),`<${r.type}${e}>${r.children.map(t=>nc(t)).join("")}`}function kf(r){if(r.isText){const e=r;return{type:e.type,value:e.value,size:e.size,isRemoved:e.isRemoved}}return{type:r.type,children:r.children.map(kf),size:r.size,isRemoved:r.isRemoved}}class ct extends Gs{constructor(t,n){super(n);c(this,"indexTree");c(this,"nodeMapByID");this.indexTree=new cp(t),this.nodeMapByID=new xf(Ae.createComparator()),this.indexTree.traverseAll(s=>{this.nodeMapByID.put(s.id,s)})}static create(t,n){return new ct(t,n)}findFloorNode(t){const n=this.nodeMapByID.floorEntry(t);if(!(!n||!n.key.getCreatedAt().equals(t.getCreatedAt())))return n.value}registerNode(t){this.nodeMapByID.put(t.id,t)}findNodesAndSplitText(t,n){const[s,i]=t.toTreeNodePair(this);let o=i;const a=s===o,u=o.parent&&!a?o.parent:s;if(o.isText&&o.split(this,t.getLeftSiblingID().getOffset()-o.id.getOffset()),n){const l=u.allChildren,h=a?0:l.indexOf(o)+1;for(let g=h;g{const E=A.getCreatedAt().getActorID(),R=i?i.has(E)?i.get(E):wt:Ns;if(A.canStyle(s,R)&&n){const $=v.get(E),U=A.getCreatedAt();(!$||U.after($))&&v.set(E,U);const _=A.setAttrs(n,s),D=_.reduce((ae,[,Se])=>(Se&&(ae[Se.getKey()]=g[Se.getKey()]),ae),{}),G=A.parent,ee=A.prevSibling||A.parent;Object.keys(D).length>0&&h.push({type:"style",from:this.toIndex(G,ee),to:this.toIndex(A,A),fromPath:this.toPath(G,ee),toPath:this.toPath(A,A),actor:s.getActorID(),value:D});for(const[ae]of _)ae&&m.push({parent:A,child:ae})}}),[v,m,h]}removeStyle(t,n,s,i){const[o,a]=this.findNodesAndSplitText(t[0],s),[u,l]=this.findNodesAndSplitText(t[1],s),h=[],g=new Map,v=[];return this.traverseInPosRange(o,a,u,l,([m])=>{const A=m.getCreatedAt().getActorID(),E=i?i.has(A)?i.get(A):wt:Ns;if(m.canStyle(s,E)&&n){const R=g.get(A),$=m.getCreatedAt();(!R||$.after(R))&&g.set(A,$),m.attrs||(m.attrs=new rn);for(const D of n){const G=m.attrs.remove(D,s);for(const ee of G)v.push({parent:m,child:ee})}const U=m.parent,_=m.prevSibling||m.parent;h.push({actor:s.getActorID(),type:"removeStyle",from:this.toIndex(U,_),to:this.toIndex(m,m),fromPath:this.toPath(U,_),toPath:this.toPath(m,m),value:n})}}),[g,v,h]}edit(t,n,s,i,o,a){const[u,l]=this.findNodesAndSplitText(t[0],i),[h,g]=this.findNodesAndSplitText(t[1],i),v=this.toIndex(u,l),m=this.toPath(u,l),A=[],E=[],R=[],$=new Map;this.traverseInPosRange(u,l,h,g,([D,G],ee)=>{if(G===ve.Start&&!ee)for(const ut of D.children)R.push(ut);const ae=D.getCreatedAt().getActorID(),Se=a?a.has(ae)?a.get(ae):wt:Ns;if(D.canDelete(i,Se)||A.includes(D.parent)){const ut=$.get(ae),He=D.getCreatedAt();(!ut||He.after(ut))&&$.set(ae,He),(G===ve.Text||G===ve.Start)&&A.push(D),E.push([D,G])}});const U=this.makeDeletionChanges(E,i),_=[];for(const D of A)D.remove(i),D.isRemoved&&_.push({parent:this,child:D});for(const D of R)D.removedAt||u.append(D);if(s>0){let D=0,G=u,ee=l;for(;D{u.isRemoved&&(ae.remove(i),_.push({parent:this,child:ae})),this.nodeMapByID.put(ae.id,ae)}),ee.isRemoved||D.push(ee);if(D.length){const ee=D.map(ae=>xa(ae));U.length&&U[U.length-1].from===v?U[U.length-1].value=ee:U.push({type:"content",from:v,to:v,fromPath:m,toPath:m,actor:i.getActorID(),value:ee})}}return[U,_,$]}editT(t,n,s,i,o){const a=this.findPos(t[0]),u=this.findPos(t[1]);this.edit([a,u],n,s,i,o)}move(t,n,s){throw new w(y.ErrUnimplemented,`not implemented: ${t}, ${n}, ${s}`)}purge(t){var i;(i=t.parent)==null||i.removeChild(t),this.nodeMapByID.remove(t.id);const n=t.insPrevID,s=t.insNextID;if(n){const o=this.findFloorNode(n);o.insNextID=s}if(s){const o=this.findFloorNode(s);o.insPrevID=n}t.insPrevID=void 0,t.insNextID=void 0}getGCPairs(){const t=[];return this.indexTree.traverse(n=>{n.getRemovedAt()&&t.push({parent:this,child:n});for(const s of n.getGCPairs())t.push(s)}),t}findPos(t,n=!0){const s=this.indexTree.findTreePos(t,n);return yt.fromTreePos(s)}pathToPosRange(t){const n=this.pathToIndex(t);return[this.findPos(n),this.findPos(n+1)]}pathToPos(t){const n=this.indexTree.pathToIndex(t);return this.findPos(n)}getRoot(){return this.indexTree.getRoot()}getSize(){return this.indexTree.size}getNodeSize(){return this.nodeMapByID.size()}getIndexTree(){return this.indexTree}toXML(){return nc(this.indexTree.getRoot())}toJSON(){return JSON.stringify(this.getRootTreeNode())}toJSForTest(){return{createdAt:this.getCreatedAt().toTestString(),value:JSON.parse(this.toJSON()),type:"YORKIE_TREE"}}toJSInfoForTest(){const t=this.indexTree.getRoot(),n=(s,i=void 0,o=void 0,a=0)=>{var m,A,E,R;let u,l,h;const g=s.isText?{node:s,offset:0}:i&&o?this.toTreePos(i,o):null;g&&(u=this.indexTree.indexOf(g),l=this.indexTree.treePosToPath(g),h=yt.fromTreePos(g).toStruct());const v={type:s.type,parent:i==null?void 0:i.id.toTestString(),size:s.size,id:s.id.toTestString(),removedAt:(m=s.removedAt)==null?void 0:m.toTestString(),insPrev:(A=s.insPrevID)==null?void 0:A.toTestString(),insNext:(E=s.insNextID)==null?void 0:E.toTestString(),value:s.isText?s.value:void 0,isRemoved:s.isRemoved,children:[],depth:a,attributes:s.attrs?rs((R=s.attrs)==null?void 0:R.toObject()):void 0,index:u,path:l,pos:h};for(let $=0;$0&&$===s[s.length-1].to?(s[s.length-1].to=U,s[s.length-1].toPath=this.toPath(R,m)):s.push({type:"content",from:$,to:U,fromPath:this.toPath(E,g),toPath:this.toPath(R,m),actor:n.getActorID()}))}return s.reverse()}findRightToken([t,n]){if(n===ve.Start){const u=t.allChildren;return u.length>0?[u[0],u[0].isText?ve.Text:ve.Start]:[t,ve.End]}const s=t.parent,i=s.allChildren,o=i.indexOf(t);if(s&&o===i.length-1)return[s,ve.End];const a=i[o+1];return[a,a.isText?ve.Text:ve.Start]}findLeftToken([t,n]){if(n===ve.End){const u=t.allChildren;if(u.length>0){const l=u[u.length-1];return[l,l.isText?ve.Text:ve.End]}return[t,ve.Start]}const s=t.parent,i=s.allChildren,o=i.indexOf(t);if(s&&o===0)return[s,ve.Start];const a=i[o-1];return[a,a.isText?ve.Text:ve.End]}}class Zs extends Tt{constructor(t,n,s,i,o,a,u){super(t,u);c(this,"fromPos");c(this,"toPos");c(this,"contents");c(this,"splitLevel");c(this,"maxCreatedAtMapByActor");this.fromPos=n,this.toPos=s,this.contents=i,this.splitLevel=o,this.maxCreatedAtMapByActor=a}static create(t,n,s,i,o,a,u){return new Zs(t,n,s,i,o,a,u)}execute(t){var u;const n=t.findByCreatedAt(this.getParentCreatedAt());if(!n)throw new w(y.ErrInvalidArgument,`fail to find ${this.getParentCreatedAt()}`);if(!(n instanceof ct))throw new w(y.ErrInvalidArgument,"fail to execute, only Tree can execute edit");const s=this.getExecutedAt(),i=n,[o,a]=i.edit([this.fromPos,this.toPos],(u=this.contents)==null?void 0:u.map(l=>l.deepcopy()),this.splitLevel,s,(()=>{let l=s.getDelimiter();return this.contents!==void 0&&(l+=this.contents.length),()=>Ke.of(s.getLamport(),++l,s.getActorID())})(),this.maxCreatedAtMapByActor);for(const l of a)t.registerGCPair(l);return{opInfos:o.map(({from:l,to:h,value:g,splitLevel:v,fromPath:m,toPath:A})=>({type:"tree-edit",path:t.createPath(this.getParentCreatedAt()),from:l,to:h,value:g,splitLevel:v,fromPath:m,toPath:A}))}}getEffectedCreatedAt(){return this.getParentCreatedAt()}toTestString(){const t=this.getParentCreatedAt().toTestString(),n=`${this.fromPos.getLeftSiblingID().getCreatedAt().toTestString()}/${this.fromPos.getLeftSiblingID().getOffset()}`,s=`${this.toPos.getLeftSiblingID().getCreatedAt().toTestString()}/${this.toPos.getLeftSiblingID().getOffset()}`,i=this.contents||[];return`${t}.EDIT(${n},${s},${i.map(o=>nc(o)).join("")})`}getFromPos(){return this.fromPos}getToPos(){return this.toPos}getContents(){return this.contents}getSplitLevel(){return this.splitLevel}getMaxCreatedAtMapByActor(){return this.maxCreatedAtMapByActor}}class ns{constructor(e){c(this,"vector");this.vector=e||new Map}set(e,t){this.vector.set(e,t)}get(e){return this.vector.get(e)}maxLamport(){let e=BigInt(0);for(const[,t]of this)t>e&&(e=t);return e}max(e){const t=new Map;for(const[n,s]of e){const i=this.vector.get(n),o=i&&i>s?i:s;t.set(n,o)}for(const[n,s]of this){const i=e.get(n),o=i&&i>s?i:s;t.set(n,o)}return new ns(t)}afterOrEqual(e){const t=this.vector.get(e.getActorID());return t===void 0?!1:t>=e.getLamport()}deepcopy(){const e=new Map;for(const[t,n]of this.vector)e.set(t,n);return new ns(e)}filter(e){const t=new Map;for(const[n]of e){const s=this.vector.get(n);s!==void 0&&t.set(n,s)}return new ns(t)}size(){return this.vector.size}*[Symbol.iterator](){for(const[e,t]of this.vector)yield[e,t]}}const hp=new ns(new Map);class Hr{constructor(e,t,n,s,i){c(this,"clientSeq");c(this,"serverSeq");c(this,"lamport");c(this,"actor");c(this,"versionVector");this.clientSeq=e,this.serverSeq=i,this.lamport=t,this.versionVector=s,this.actor=n}static of(e,t,n,s,i){return new Hr(e,t,n,s,i)}next(){const e=this.versionVector.deepcopy();return e.set(this.actor,this.lamport+1n),new Hr(this.clientSeq+1,this.lamport+1n,this.actor,e)}syncClocks(e){const t=e.lamport>this.lamport?e.lamport+1n:this.lamport+1n,n=this.versionVector.max(e.versionVector),s=new Hr(this.clientSeq,t,this.actor,n);return s.versionVector.set(this.actor,t),s}setClocks(e,t){const n=e>this.lamport?e:this.lamport+1n,s=this.versionVector.max(t);return s.set(this.actor,n),Hr.of(this.clientSeq,n,this.actor,s)}createTimeTicket(e){return Ke.of(this.lamport,e,this.actor)}setActor(e){return new Hr(this.clientSeq,this.lamport,e,this.versionVector,this.serverSeq)}setVersionVector(e){return new Hr(this.clientSeq,this.lamport,this.actor,e,this.serverSeq)}getClientSeq(){return this.clientSeq}getServerSeq(){return this.serverSeq?this.serverSeq.toString():""}getLamport(){return this.lamport}getLamportAsString(){return this.lamport.toString()}getActorID(){return this.actor}getVersionVector(){return this.versionVector}toTestString(){return`${this.lamport.toString()}:${this.actor.slice(-2)}:${this.clientSeq}`}}const dp=new Hr(0,0n,ec,hp);class ds{constructor({id:e,operations:t,presenceChange:n,message:s}){c(this,"id");c(this,"operations");c(this,"presenceChange");c(this,"message");this.id=e,this.operations=t||[],this.presenceChange=n,this.message=s}static create({id:e,operations:t,presenceChange:n,message:s}){return new ds({id:e,operations:t,presenceChange:n,message:s})}getID(){return this.id}getMessage(){return this.message}hasOperations(){return this.operations.length>0}getOperations(){return this.operations}setActor(e){for(const t of this.operations)t.setActor(e);this.id=this.id.setActor(e)}hasPresenceChange(){return this.presenceChange!==void 0}getPresenceChange(){return this.presenceChange}execute(e,t,n){const s=[],i=[];for(const o of this.operations){const a=o.execute(e,n);if(!a)continue;const{opInfos:u,reverseOp:l}=a;s.push(...u),l&&i.unshift(l)}return this.presenceChange&&(this.presenceChange.type===bn.Put?t.set(this.id.getActorID(),ht(this.presenceChange.presence)):t.delete(this.id.getActorID())),{opInfos:s,reverseOps:i}}toTestString(){return`${this.operations.map(e=>e.toTestString()).join(",")}`}toStruct(){return{changeID:me.bytesToHex(me.toChangeID(this.getID()).toBinary()),message:this.getMessage(),operations:this.getOperations().map(e=>me.bytesToHex(me.toOperation(e).toBinary())),presenceChange:this.getPresenceChange()}}static fromStruct(e){const{changeID:t,operations:n,presenceChange:s,message:i}=e;return ds.create({id:me.bytesToChangeID(me.hexToBytes(t)),operations:n==null?void 0:n.map(o=>me.bytesToOperation(me.hexToBytes(o))),presenceChange:s,message:i})}}class vo{constructor(e,t,n,s,i,o,a){c(this,"documentKey");c(this,"checkpoint");c(this,"isRemoved");c(this,"changes");c(this,"snapshot");c(this,"minSyncedTicket");c(this,"versionVector");this.documentKey=e,this.checkpoint=t,this.isRemoved=n,this.changes=s,this.snapshot=o,this.minSyncedTicket=a,this.versionVector=i}static create(e,t,n,s,i,o,a){return new vo(e,t,n,s,i,o,a)}getDocumentKey(){return this.documentKey}getCheckpoint(){return this.checkpoint}getIsRemoved(){return this.isRemoved}getChanges(){return this.changes}hasChanges(){return this.changes.length>0}getChangeSize(){return this.changes.length}hasSnapshot(){return!!this.snapshot&&!!this.snapshot.length}getSnapshot(){return this.snapshot}getMinSyncedTicket(){return this.minSyncedTicket}getVersionVector(){return this.versionVector}}class ss{constructor(e,t){c(this,"serverSeq");c(this,"clientSeq");this.serverSeq=e,this.clientSeq=t}static of(e,t){return new ss(e,t)}increaseClientSeq(e){return e===0?this:new ss(this.serverSeq,this.clientSeq+e)}forward(e){if(this.equals(e))return this;const t=this.serverSeq>e.serverSeq?this.serverSeq:e.serverSeq,n=Math.max(this.clientSeq,e.clientSeq);return ss.of(t,n)}getServerSeqAsString(){return this.serverSeq.toString()}getClientSeq(){return this.clientSeq}getServerSeq(){return this.serverSeq}equals(e){return this.clientSeq===e.clientSeq&&this.serverSeq==e.serverSeq}toTestString(){return`serverSeq=${this.serverSeq}, clientSeq=${this.clientSeq}`}}const gp=new ss(0n,0);class qt{constructor(e,t){c(this,"createdAt");c(this,"offset");this.createdAt=e,this.offset=t}static of(e,t){return new qt(e,t)}static fromStruct(e){return qt.of(Ke.fromStruct(e.createdAt),e.offset)}getCreatedAt(){return this.createdAt}getOffset(){return this.offset}equals(e){return this.createdAt.compare(e.createdAt)===0&&this.offset===e.offset}hasSameCreatedAt(e){return this.createdAt.compare(e.createdAt)===0}split(e){return new qt(this.createdAt,this.offset+e)}toStruct(){return{createdAt:this.createdAt.toStruct(),offset:this.offset}}toTestString(){return`${this.createdAt.toTestString()}:${this.offset}`}toIDString(){return`${this.createdAt.toIDString()}:${this.offset}`}}const mp=qt.of(wt,0);class bt{constructor(e,t){c(this,"id");c(this,"relativeOffset");this.id=e,this.relativeOffset=t}static of(e,t){return new bt(e,t)}static fromStruct(e){const t=qt.fromStruct(e.id);return bt.of(t,e.relativeOffset)}getID(){return this.id}getRelativeOffset(){return this.relativeOffset}getAbsoluteID(){return qt.of(this.id.getCreatedAt(),this.id.getOffset()+this.relativeOffset)}toTestString(){return`${this.id.toTestString()}:${this.relativeOffset}`}toStruct(){return{id:this.id.toStruct(),relativeOffset:this.relativeOffset}}equals(e){return this.id.equals(e.id)?this.relativeOffset===e.relativeOffset:!1}}class yn extends yf{constructor(t,n,s){super(n);c(this,"id");c(this,"removedAt");c(this,"prev");c(this,"next");c(this,"insPrev");c(this,"insNext");this.id=t,this.removedAt=s}static create(t,n){return new yn(t,n)}static createComparator(){return(t,n)=>{const s=t.getCreatedAt().compare(n.getCreatedAt());return s!==0?s:t.getOffset()>n.getOffset()?1:t.getOffset()0&&t.getID().getOffset()==e.getOffset()){if(!t.hasInsPrev())return t;t=t.getInsPrev()}return t}findFloorNode(e){const t=this.treeByID.floorEntry(e);if(t&&!(!t.key.equals(e)&&!t.key.hasSameCreatedAt(e)))return t.value}findBetween(e,t){const n=[];let s=e;for(;s&&s!==t;)n.push(s),s=s.getNext();return n}splitNode(e,t){if(t>e.getContentLength())throw new w(y.ErrInvalidArgument,"offset should be less than or equal to length");if(t===0)return e;if(t===e.getContentLength())return e.getNext();const n=e.split(t);this.treeByIndex.updateWeight(n),this.insertAfter(e,n);const s=e.getInsNext();return s&&s.setInsPrev(n),n.setInsPrev(e),n}deleteNodes(e,t,n){if(!e.length)return[[],new Map,new Map];const[s,i]=this.filterNodes(e,t,n),o=new Map,a=new Map,u=this.makeChanges(i,t);for(const l of s){const h=l.getCreatedAt().getActorID();(!o.has(h)||l.getID().getCreatedAt().after(o.get(h)))&&o.set(h,l.getID().getCreatedAt()),a.set(l.getID().toIDString(),l),l.remove(t)}return this.deleteIndexNodes(i),[u,o,a]}filterNodes(e,t,n){const s=!!n,i=[],o=[],[a,u]=this.findEdgesOfCandidates(e);o.push(a);for(const l of e){const h=l.getCreatedAt().getActorID(),g=s?n.has(h)?n.get(h):wt:Ns;l.canDelete(t,g)?i.push(l):o.push(l)}return o.push(u),[i,o]}findEdgesOfCandidates(e){return[e[0].getPrev(),e[e.length-1].getNext()]}makeChanges(e,t){const n=[];let s,i;for(let o=0;or<0?Math.ceil(r):Math.floor(r);var Vt=(r=>(r[r.IntegerCnt=0]="IntegerCnt",r[r.LongCnt=1]="LongCnt",r))(Vt||{});class We extends Gs{constructor(t,n,s){super(s);c(this,"valueType");c(this,"value");switch(this.valueType=t,t){case 0:typeof n=="number"?n>Math.pow(2,31)-1||n<-Math.pow(2,31)?this.value=X.fromNumber(n).toInt():this.value=Vu(n):this.value=n.toInt();break;case 1:typeof n=="number"?this.value=X.fromNumber(n):this.value=n;break;default:throw new w(y.ErrUnimplemented,`unimplemented type: ${t}`)}}static create(t,n,s){return new We(t,n,s)}static valueFromBytes(t,n){switch(t){case 0:return n[0]|n[1]<<8|n[2]<<16|n[3]<<24;case 1:return X.fromBytesLE(Array.from(n));default:throw new w(y.ErrUnimplemented,`unimplemented type: ${t}`)}}toJSON(){return`${this.value}`}toSortedJSON(){return this.toJSON()}toJSForTest(){return{createdAt:this.getCreatedAt().toTestString(),value:this.value,type:"YORKIE_COUNTER"}}deepcopy(){const t=We.create(this.valueType,this.value,this.getCreatedAt());return t.setMovedAt(this.getMovedAt()),t}getType(){return this.valueType}static getCounterType(t){switch(typeof t){case"object":return t instanceof X?1:void 0;case"number":return t>Math.pow(2,31)-1||t<-Math.pow(2,31)?1:0;default:return}}static isSupport(t){return!!We.getCounterType(t)}static isInteger(t){return t%1===0}isNumericType(){const t=this.valueType;return t===0||t===1}getValueType(){return this.valueType}getValue(){return this.value}toBytes(){switch(this.valueType){case 0:{const t=this.value;return new Uint8Array([t&255,t>>8&255,t>>16&255,t>>24&255])}case 1:{const n=this.value.toBytesLE();return Uint8Array.from(n)}default:throw new w(y.ErrUnimplemented,`unimplemented type: ${this.valueType}`)}}increase(t){function n(s){if(!s.isNumericType())throw new TypeError(`Unsupported type of value: ${typeof s.getValue()}`)}return n(this),n(t),this.valueType===1?this.value=this.value.add(t.getValue()):t.getType()===be.Long?this.value=this.value+t.getValue().toInt():this.value=X.fromNumber(this.value+Vu(t.getValue())).toInt(),this}}class ms extends Tt{constructor(t,n,s){super(t,s);c(this,"value");this.value=n}static create(t,n,s){return new ms(t,n,s)}execute(t){const n=t.findByCreatedAt(this.getParentCreatedAt());if(!n)throw new w(y.ErrInvalidArgument,`fail to find ${this.getParentCreatedAt()}`);if(!(n instanceof We))throw new w(y.ErrInvalidArgument,"fail to execute, only Counter can execute increase");const s=n,i=this.value.deepcopy();return s.increase(i),{opInfos:[{type:"increase",path:t.createPath(this.getParentCreatedAt()),value:i.getValue()}],reverseOp:this.toReverseOperation()}}toReverseOperation(){const t=this.value.deepcopy(),s=t.getType()===be.Long?t.getValue().multiply(-1):t.getValue()*-1;return ms.create(this.getParentCreatedAt(),le.of(s,t.getCreatedAt()))}getEffectedCreatedAt(){return this.getParentCreatedAt()}toTestString(){return`${this.getParentCreatedAt().toTestString()}.INCREASE.${this.value.toJSON()}`}getValue(){return this.value}}class Qr extends Tt{constructor(t,n,s,i,o,a,u){super(t,u);c(this,"fromPos");c(this,"toPos");c(this,"maxCreatedAtMapByActor");c(this,"attributes");c(this,"attributesToRemove");this.fromPos=n,this.toPos=s,this.maxCreatedAtMapByActor=i,this.attributes=o,this.attributesToRemove=a}static create(t,n,s,i,o,a){return new Qr(t,n,s,i,o,new Array,a)}static createTreeRemoveStyleOperation(t,n,s,i,o,a){return new Qr(t,n,s,i,new Map,o,a)}execute(t){const n=t.findByCreatedAt(this.getParentCreatedAt());if(!n)throw new w(y.ErrInvalidArgument,`fail to find ${this.getParentCreatedAt()}`);if(!(n instanceof ct))throw new w(y.ErrInvalidArgument,"fail to execute, only Tree can execute edit");const s=n;let i,o;if(this.attributes.size){const a={};[...this.attributes].forEach(([u,l])=>a[u]=l),[,o,i]=s.style([this.fromPos,this.toPos],a,this.getExecutedAt(),this.maxCreatedAtMapByActor)}else{const a=this.attributesToRemove;[,o,i]=s.removeStyle([this.fromPos,this.toPos],a,this.getExecutedAt(),this.maxCreatedAtMapByActor)}for(const a of o)t.registerGCPair(a);return{opInfos:i.map(({from:a,to:u,value:l,fromPath:h,toPath:g})=>({type:"tree-style",from:a,to:u,value:this.attributes.size?{attributes:l}:{attributesToRemove:l},fromPath:h,toPath:g,path:t.createPath(this.getParentCreatedAt())}))}}getEffectedCreatedAt(){return this.getParentCreatedAt()}toTestString(){const t=this.getParentCreatedAt().toTestString(),n=`${this.fromPos.getLeftSiblingID().getCreatedAt().toTestString()}:${this.fromPos.getLeftSiblingID().getOffset()}`,s=`${this.toPos.getLeftSiblingID().getCreatedAt().toTestString()}:${this.toPos.getLeftSiblingID().getOffset()}`;return`${t}.STYLE(${n},${s},${Object.entries(this.attributes||{}).map(([i,o])=>`${i}:"${o}"`).join(" ")})`}getFromPos(){return this.fromPos}getToPos(){return this.toPos}getAttributes(){return this.attributes}getAttributesToRemove(){return this.attributesToRemove}getMaxCreatedAtMapByActor(){return this.maxCreatedAtMapByActor}}function pp(r){const e=new Qa,t=e.data;for(const[n,s]of Object.entries(r))t[n]=JSON.stringify(s);return e}function yp(r){if(r.type===bn.Put)return new qs({type:Un.PUT,presence:pp(r.presence)});if(r.type===bn.Clear)return new qs({type:Un.CLEAR});throw new w(y.ErrUnimplemented,"unimplemented type")}function vp(r){return new gf({serverSeq:r.getServerSeq(),clientSeq:r.getClientSeq()})}function Ef(r){return new mo({clientSeq:r.getClientSeq(),lamport:r.getLamport(),actorId:gc(r.getActorID()),versionVector:sc(r.getVersionVector())})}function J(r){if(r)return new L({lamport:r.getLamport(),delimiter:r.getDelimiter(),actorId:gc(r.getActorID())})}function sc(r){if(!r)return;const e=new po;for(const[t,n]of r)e.vector[t]=BigInt(n.toString());return e}function Cf(r){switch(r){case be.Null:return W.NULL;case be.Boolean:return W.BOOLEAN;case be.Integer:return W.INTEGER;case be.Long:return W.LONG;case be.Double:return W.DOUBLE;case be.String:return W.STRING;case be.Bytes:return W.BYTES;case be.Date:return W.DATE;default:throw new w(y.ErrInvalidType,`unsupported type: ${r}`)}}function Nf(r){switch(r){case Vt.IntegerCnt:return W.INTEGER_CNT;case Vt.LongCnt:return W.LONG_CNT;default:throw new w(y.ErrInvalidType,`unsupported type: ${r}`)}}function Fo(r){if(r instanceof Me)return new Ye({type:W.JSON_OBJECT,createdAt:J(r.getCreatedAt()),value:Vf(r)});if(r instanceof je)return new Ye({type:W.JSON_ARRAY,createdAt:J(r.getCreatedAt()),value:Yp(r)});if(r instanceof at)return new Ye({type:W.TEXT,createdAt:J(r.getCreatedAt())});if(r instanceof le)return new Ye({type:Cf(r.getType()),createdAt:J(r.getCreatedAt()),value:r.toBytes()});if(r instanceof We)return new Ye({type:Nf(r.getType()),createdAt:J(r.getCreatedAt()),value:r.toBytes()});if(r instanceof ct)return new Ye({type:W.TREE,createdAt:J(r.getCreatedAt()),value:Xp(r)});throw new w(y.ErrUnimplemented,"unimplemented element")}function wp(r){return new $s({createdAt:J(r.getCreatedAt()),offset:r.getOffset()})}function fi(r){return new tn({createdAt:J(r.getID().getCreatedAt()),offset:r.getID().getOffset(),relativeOffset:r.getRelativeOffset()})}function hi(r){return new $n({parentId:Ps(r.getParentID()),leftSiblingId:Ps(r.getLeftSiblingID())})}function Ps(r){return new mn({createdAt:J(r.getCreatedAt()),offset:r.getOffset()})}function Pf(r){const e=new Za;if(r instanceof qn){const t=r,n=new Fi;n.parentCreatedAt=J(t.getParentCreatedAt()),n.key=t.getKey(),n.value=Fo(t.getValue()),n.executedAt=J(t.getExecutedAt()),e.body.case="set",e.body.value=n}else if(r instanceof Ys){const t=r,n=new Li;n.parentCreatedAt=J(t.getParentCreatedAt()),n.prevCreatedAt=J(t.getPrevCreatedAt()),n.value=Fo(t.getValue()),n.executedAt=J(t.getExecutedAt()),e.body.case="add",e.body.value=n}else if(r instanceof hn){const t=r,n=new Ji;n.parentCreatedAt=J(t.getParentCreatedAt()),n.prevCreatedAt=J(t.getPrevCreatedAt()),n.createdAt=J(t.getCreatedAt()),n.executedAt=J(t.getExecutedAt()),e.body.case="move",e.body.value=n}else if(r instanceof Tn){const t=r,n=new Mi;n.parentCreatedAt=J(t.getParentCreatedAt()),n.createdAt=J(t.getCreatedAt()),n.executedAt=J(t.getExecutedAt()),e.body.case="remove",e.body.value=n}else if(r instanceof _s){const t=r,n=new $i;n.parentCreatedAt=J(t.getParentCreatedAt()),n.from=fi(t.getFromPos()),n.to=fi(t.getToPos());const s=n.createdAtMapByActor;for(const[o,a]of t.getMaxCreatedAtMapByActor())s[o]=J(a);n.content=t.getContent();const i=n.attributes;for(const[o,a]of t.getAttributes())i[o]=a;n.executedAt=J(t.getExecutedAt()),e.body.case="edit",e.body.value=n}else if(r instanceof Xs){const t=r,n=new Ui;n.parentCreatedAt=J(t.getParentCreatedAt()),n.from=fi(t.getFromPos()),n.to=fi(t.getToPos());const s=n.createdAtMapByActor;for(const[o,a]of t.getMaxCreatedAtMapByActor())s[o]=J(a);const i=n.attributes;for(const[o,a]of t.getAttributes())i[o]=a;n.executedAt=J(t.getExecutedAt()),e.body.case="style",e.body.value=n}else if(r instanceof ms){const t=r,n=new qi;n.parentCreatedAt=J(t.getParentCreatedAt()),n.value=Fo(t.getValue()),n.executedAt=J(t.getExecutedAt()),e.body.case="increase",e.body.value=n}else if(r instanceof Zs){const t=r,n=new Vi,s=n.createdAtMapByActor;for(const[i,o]of t.getMaxCreatedAtMapByActor())s[i]=J(o);n.parentCreatedAt=J(t.getParentCreatedAt()),n.from=hi(t.getFromPos()),n.to=hi(t.getToPos()),n.contents=kp(t.getContents()),n.splitLevel=t.getSplitLevel(),n.executedAt=J(t.getExecutedAt()),e.body.case="treeEdit",e.body.value=n}else if(r instanceof Qr){const t=r,n=new zi;n.parentCreatedAt=J(t.getParentCreatedAt()),n.from=hi(t.getFromPos()),n.to=hi(t.getToPos());const s=n.createdAtMapByActor;for(const[o,a]of t.getMaxCreatedAtMapByActor())s[o]=J(a);const i=t.getAttributesToRemove();if(i.length>0)n.attributesToRemove=i;else{const o=n.attributes;for(const[a,u]of t.getAttributes())o[a]=u}n.executedAt=J(t.getExecutedAt()),e.body.case="treeStyle",e.body.value=n}else throw new w(y.ErrUnimplemented,"unimplemented operation");return e}function bp(r){const e=[];for(const t of r)e.push(Pf(t));return e}function Tp(r){const e=new hf({id:Ef(r.getID()),message:r.getMessage()});return r.hasOperations()&&(e.operations=bp(r.getOperations())),r.hasPresenceChange()&&(e.presenceChange=yp(r.getPresenceChange())),e}function Ap(r){const e=[];for(const t of r)e.push(Tp(t));return e}function Ip(r){const e=[];for(const t of r)e.push(new df({key:t.getStrKey(),element:oc(t.getValue())}));return e}function Sp(r){const e=[];for(const t of r)e.push(new _i({element:oc(t.getValue())}));return e}function xp(r){const e=[];for(const t of r){const n=new Xi;n.id=wp(t.getID()),n.value=t.getValue().getContent(),n.removedAt=J(t.getRemovedAt());const s=n.attributes,i=t.getValue().getAttrs();for(const o of i){const a=new ls;a.value=o.getValue(),a.updatedAt=J(o.getUpdatedAt()),s[o.getKey()]=a}e.push(n)}return e}function kp(r){const e=[];if(!r||!r.length)return e;for(const t of r)e.push(new Zi({content:ic(t)}));return e}function Ep(r){const e={};for(const t of r)e[t.getKey()]=new ls({value:t.getValue(),updatedAt:J(t.getUpdatedAt()),isRemoved:t.isRemoved()});return e}function ic(r){if(!r)return[];const e=[];return yo(r,(t,n)=>{const s=new Us({id:Ps(t.id),type:t.type,removedAt:J(t.removedAt),depth:n});t.isText&&(s.value=t.value),t.insPrevID&&(s.insPrevId=Ps(t.insPrevID)),t.insNextID&&(s.insNextId=Ps(t.insNextID)),t.attrs&&(s.attributes=Ep(t.attrs)),e.push(s)}),e}function Cp(r){const e=new Ue;return e.body.case="jsonObject",e.body.value=new Ki({nodes:Ip(r.getRHT()),createdAt:J(r.getCreatedAt()),movedAt:J(r.getMovedAt()),removedAt:J(r.getRemovedAt())}),e}function Of(r){const e=new Ue;return e.body.case="jsonArray",e.body.value=new ji({nodes:Sp(r.getElements()),createdAt:J(r.getCreatedAt()),movedAt:J(r.getMovedAt()),removedAt:J(r.getRemovedAt())}),e}function Np(r){const e=new Ue;return e.body.case="primitive",e.body.value=new Wi({type:Cf(r.getType()),value:r.toBytes(),createdAt:J(r.getCreatedAt()),movedAt:J(r.getMovedAt()),removedAt:J(r.getRemovedAt())}),e}function Pp(r){const e=new Ue;return e.body.case="text",e.body.value=new Hi({nodes:xp(r.getRGATreeSplit()),createdAt:J(r.getCreatedAt()),movedAt:J(r.getMovedAt()),removedAt:J(r.getRemovedAt())}),e}function Op(r){const e=new Ue;return e.body.case="counter",e.body.value=new Gi({type:Nf(r.getType()),value:r.toBytes(),createdAt:J(r.getCreatedAt()),movedAt:J(r.getMovedAt()),removedAt:J(r.getRemovedAt())}),e}function Df(r){const e=new Ue;return e.body.case="tree",e.body.value=new Yi({nodes:ic(r.getRoot()),createdAt:J(r.getCreatedAt()),movedAt:J(r.getMovedAt()),removedAt:J(r.getRemovedAt())}),e}function oc(r){if(r instanceof Me)return Cp(r);if(r instanceof je)return Of(r);if(r instanceof le)return Np(r);if(r instanceof at)return Pp(r);if(r instanceof We)return Op(r);if(r instanceof ct)return Df(r);throw new w(y.ErrUnimplemented,"unimplemented element")}function Dp(r){return new sn({documentKey:r.getDocumentKey(),checkpoint:vp(r.getCheckpoint()),isRemoved:r.getIsRemoved(),changes:Ap(r.getChanges()),snapshot:r.getSnapshot(),versionVector:sc(r.getVersionVector()),minSyncedTicket:J(r.getMinSyncedTicket())})}function zu(r){const e=r.findDetails(Gm);for(const t of e)if(t.metadata.code)return t.metadata.code;return""}function Bf(r){return Hr.of(r.clientSeq,BigInt(r.lamport),hc(r.actorId),ac(r.versionVector),BigInt(r.serverSeq))}function ac(r){if(!r)return;const e=new ns;return Object.entries(r.vector).forEach(([t,n])=>{e.set(t,BigInt(n.toString()))}),e}function M(r){if(r)return Ke.of(BigInt(r.lamport),r.delimiter,hc(r.actorId))}function cc(r){const e={};return Object.entries(r.data).forEach(([t,n])=>{e[t]=JSON.parse(n)}),e}function Bp(r){const e=r.type;if(e===Un.PUT){const t=cc(r.presence);return{type:bn.Put,presence:t}}if(e===Un.CLEAR)return{type:bn.Clear};throw new w(y.ErrInvalidType,`unsupported type: ${e}`)}function Rp(r){const e=new Map;return Object.entries(r).forEach(([t,n])=>{e.set(t,cc(n))}),e}function Rf(r){switch(r){case W.NULL:return be.Null;case W.BOOLEAN:return be.Boolean;case W.INTEGER:return be.Integer;case W.LONG:return be.Long;case W.DOUBLE:return be.Double;case W.STRING:return be.String;case W.BYTES:return be.Bytes;case W.DATE:return be.Date}throw new w(y.ErrUnimplemented,`unimplemented value type: ${r}`)}function to(r){switch(r){case W.INTEGER_CNT:return Vt.IntegerCnt;case W.LONG_CNT:return Vt.LongCnt}throw new w(y.ErrUnimplemented,`unimplemented value type: ${r}`)}function Lo(r){switch(r.type){case W.JSON_OBJECT:return r.value?qf(r.value):Me.create(M(r.createdAt));case W.JSON_ARRAY:return r.value?Gp(r.value):je.create(M(r.createdAt));case W.TEXT:return at.create(gs.create(),M(r.createdAt));case W.TREE:return _p(r.value);case W.NULL:case W.BOOLEAN:case W.INTEGER:case W.LONG:case W.DOUBLE:case W.STRING:case W.BYTES:case W.DATE:return le.of(le.valueFromBytes(Rf(r.type),r.value),M(r.createdAt));case W.INTEGER_CNT:case W.LONG_CNT:return We.create(to(r.type),We.valueFromBytes(to(r.type),r.value),M(r.createdAt))}}function di(r){return bt.of(qt.of(M(r.createdAt),r.offset),r.relativeOffset)}function Ff(r){return qt.of(M(r.createdAt),r.offset)}function Fp(r){const e=js.create(r.value);Object.entries(r.attributes).forEach(([n,s])=>{e.setAttr(n,s.value,M(s.updatedAt))});const t=yn.create(Ff(r.id),e);return t.remove(M(r.removedAt)),t}function Hn(r){return yt.of(Os(r.parentId),Os(r.leftSiblingId))}function Os(r){return Ae.of(M(r.createdAt),r.offset)}function Lp(r){if(!r.length)return;const e=[];return r.forEach(t=>{const n=uc(t.content);e.push(n)}),e}function uc(r){if(r.length===0)return;const e=[];for(const s of r)e.push(Mp(s));const t=e[e.length-1],n=new Map;n.set(r[e.length-1].depth,e[e.length-1]);for(let s=e.length-2;s>=0;s--)n.get(r[s].depth-1).prepend(e[s]),n.set(r[s].depth,e[s]);return t.updateDescendantsSize(),ct.create(t,wt).getRoot()}function Jp(r){const e=rn.create();for(const[t,n]of Object.entries(r))e.setInternal(t,n.value,M(n.updatedAt),n.isRemoved);return e}function Mp(r){const e=Os(r.id),t=ze.create(e,r.type),n=Object.entries(r.attributes);return t.isText?t.value=r.value:n.length&&(t.attrs=Jp(r.attributes)),r.insPrevId&&(t.insPrevID=Os(r.insPrevId)),r.insNextId&&(t.insNextID=Os(r.insNextId)),t.removedAt=M(r.removedAt),t}function Lf(r){if(r.body.case==="set"){const e=r.body.value;return qn.create(e.key,Lo(e.value),M(e.parentCreatedAt),M(e.executedAt))}else if(r.body.case==="add"){const e=r.body.value;return Ys.create(M(e.parentCreatedAt),M(e.prevCreatedAt),Lo(e.value),M(e.executedAt))}else if(r.body.case==="move"){const e=r.body.value;return hn.create(M(e.parentCreatedAt),M(e.prevCreatedAt),M(e.createdAt),M(e.executedAt))}else if(r.body.case==="remove"){const e=r.body.value;return Tn.create(M(e.parentCreatedAt),M(e.createdAt),M(e.executedAt))}else if(r.body.case==="edit"){const e=r.body.value,t=new Map;Object.entries(e.createdAtMapByActor).forEach(([s,i])=>{t.set(s,M(i))});const n=new Map;return Object.entries(e.attributes).forEach(([s,i])=>{n.set(s,i)}),_s.create(M(e.parentCreatedAt),di(e.from),di(e.to),t,e.content,n,M(e.executedAt))}else if(r.body.case==="style"){const e=r.body.value,t=new Map;Object.entries(e.createdAtMapByActor).forEach(([s,i])=>{t.set(s,M(i))});const n=new Map;return Object.entries(e.attributes).forEach(([s,i])=>{n.set(s,i)}),Xs.create(M(e.parentCreatedAt),di(e.from),di(e.to),t,n,M(e.executedAt))}else{if(r.body.case==="select")return;if(r.body.case==="increase"){const e=r.body.value;return ms.create(M(e.parentCreatedAt),Lo(e.value),M(e.executedAt))}else if(r.body.case==="treeEdit"){const e=r.body.value,t=new Map;return Object.entries(e.createdAtMapByActor).forEach(([n,s])=>{t.set(n,M(s))}),Zs.create(M(e.parentCreatedAt),Hn(e.from),Hn(e.to),Lp(e.contents),e.splitLevel,t,M(e.executedAt))}else if(r.body.case==="treeStyle"){const e=r.body.value,t=new Map,n=e.attributesToRemove,s=new Map;return e!=null&&e.createdAtMapByActor&&Object.entries(e.createdAtMapByActor).forEach(([i,o])=>{s.set(i,M(o))}),(n==null?void 0:n.length)>0?Qr.createTreeRemoveStyleOperation(M(e.parentCreatedAt),Hn(e.from),Hn(e.to),s,n,M(e.executedAt)):(Object.entries(e.attributes).forEach(([i,o])=>{t.set(i,o)}),Qr.create(M(e.parentCreatedAt),Hn(e.from),Hn(e.to),s,t,M(e.executedAt)))}else throw new w(y.ErrUnimplemented,"unimplemented operation")}}function $p(r){const e=[];for(const t of r){const n=Lf(t);n&&e.push(n)}return e}function Jf(r){const e=[];for(const t of r)e.push(ds.create({id:Bf(t.id),operations:$p(t.operations),presenceChange:t.presenceChange?Bp(t.presenceChange):void 0,message:t.message}));return e}function Up(r){return ss.of(BigInt(r.serverSeq),r.clientSeq)}function qp(r){return vo.create(r.documentKey,Up(r.checkpoint),r.isRemoved,Jf(r.changes),ac(r.versionVector),r.snapshot,M(r.minSyncedTicket))}function Mf(r){const e=new Vs;for(const n of r.nodes){const s=lc(n.element);e.set(n.key,s,s.getPositionedAt())}const t=new Me(M(r.createdAt),e);return t.setMovedAt(M(r.movedAt)),t.setRemovedAt(M(r.removedAt)),t}function $f(r){const e=new Ks;for(const n of r.nodes)e.insert(lc(n.element));const t=new je(M(r.createdAt),e);return t.setMovedAt(M(r.movedAt)),t.setRemovedAt(M(r.removedAt)),t}function Vp(r){const e=le.of(le.valueFromBytes(Rf(r.type),r.value),M(r.createdAt));return e.setMovedAt(M(r.movedAt)),e.setRemovedAt(M(r.removedAt)),e}function zp(r){const e=new gs;let t=e.getHead();for(const s of r.nodes){const i=e.insertAfter(t,Fp(s));s.insPrevId&&i.setInsPrev(e.findNode(Ff(s.insPrevId))),t=i}const n=new at(e,M(r.createdAt));return n.setMovedAt(M(r.movedAt)),n.setRemovedAt(M(r.removedAt)),n}function Kp(r){const e=We.create(to(r.type),We.valueFromBytes(to(r.type),r.value),M(r.createdAt));return e.setMovedAt(M(r.movedAt)),e.setRemovedAt(M(r.removedAt)),e}function Uf(r){const e=uc(r.nodes);return ct.create(e,M(r.createdAt))}function lc(r){if(r.body.case==="jsonObject")return Mf(r.body.value);if(r.body.case==="jsonArray")return $f(r.body.value);if(r.body.case==="primitive")return Vp(r.body.value);if(r.body.case==="text")return zp(r.body.value);if(r.body.case==="counter")return Kp(r.body.value);if(r.body.case==="tree")return Uf(r.body.value);throw new w(y.ErrUnimplemented,"unimplemented element")}function jp(r){if(!r)return{root:Me.create(wt),presences:new Map};const e=ea.fromBinary(r);return{root:lc(e.root),presences:Rp(e.presences)}}function Wp(r){const e=sc(r);return fc(e.toBinary())}function Hp(r){const e=dc(r),t=po.fromBinary(e);return ac(t)}function qf(r){if(!r)throw new w(y.ErrInvalidArgument,"bytes is empty");const e=Ue.fromBinary(r);return Mf(e.body.value)}function Vf(r){return oc(r).toBinary()}function Gp(r){if(!r)throw new w(y.ErrInvalidArgument,"bytes is empty");const e=Ue.fromBinary(r);return $f(e.body.value)}function Yp(r){return Of(r).toBinary()}function _p(r){if(!r)throw new w(y.ErrInvalidArgument,"bytes is empty");const e=Ue.fromBinary(r);return Uf(e.body.value)}function Xp(r){return Df(r).toBinary()}function fc(r){return r?Array.from(r).map(e=>e.toString(16).padStart(2,"0")).join(""):""}function hc(r){return fc(r)}function dc(r){return new Uint8Array(r.match(/.{1,2}/g).map(e=>parseInt(e,16)))}function gc(r){return dc(r)}function Zp(r){const e=mo.fromBinary(r);return Bf(e)}function Qp(r){const e=Za.fromBinary(r);return Lf(e)}const me={fromPresence:cc,toChangePack:Dp,fromChangePack:qp,fromChanges:Jf,toTreeNodes:ic,fromTreeNodes:uc,objectToBytes:Vf,bytesToObject:qf,bytesToSnapshot:jp,bytesToHex:fc,hexToBytes:dc,toHexString:hc,toUint8Array:gc,toOperation:Pf,toChangeID:Ef,PbChangeID:mo,bytesToChangeID:Zp,bytesToOperation:Qp,versionVectorToHex:Wp,hexToVersionVector:Hp};var Be=(r=>(r[r.Trivial=0]="Trivial",r[r.Debug=1]="Debug",r[r.Info=2]="Info",r[r.Warn=3]="Warn",r[r.Error=4]="Error",r[r.Fatal=5]="Fatal",r))(Be||{});let En=3;function zf(r){En=r}const z={trivial:(...r)=>{En>0||typeof console<"u"&&console.log("YORKIE T:",...r)},debug:(...r)=>{En>1||typeof console<"u"&&console.log("YORKIE D:",...r)},info:(...r)=>{En>2||typeof console<"u"&&console.log("YORKIE I:",...r)},warn:(...r)=>{En>3||typeof console<"u"&&(typeof console.warn<"u"?console.warn("YORKIE W:",...r):console.log("YORKIE W:",...r))},error:(...r)=>{En>4||typeof console<"u"&&(typeof console.error<"u"?console.error("YORKIE E:",...r):console.log("YORKIE E:",...r))},fatal:(...r)=>{typeof console<"u"&&(typeof console.error<"u"?console.error("YORKIE F:",...r):console.log("YORKIE F:",...r))},isEnabled:r=>En<=r};function Kf(){return"xxxxxxxx-xxxx-4xxxy-xxxx-xxxxxxxxxxx".replace(/[xy]/g,r=>{const e=Math.random()*16|0;return(r==="x"?e:e&3|8).toString(16)})}class ey{constructor(e,t,n,s,i){c(this,"reconnectStreamDelay");c(this,"doc");c(this,"docID");c(this,"syncMode");c(this,"remoteChangeEventReceived");c(this,"watchStream");c(this,"watchLoopTimerID");c(this,"watchAbortController");c(this,"unsubscribeBroadcastEvent");this.reconnectStreamDelay=e,this.doc=t,this.docID=n,this.syncMode=s,this.remoteChangeEventReceived=!1,this.unsubscribeBroadcastEvent=i}changeSyncMode(e){this.syncMode=e}needRealtimeSync(){return this.syncMode===Ei.RealtimeSyncOff?!1:this.syncMode===Ei.RealtimePushOnly?this.doc.hasLocalChanges():this.syncMode!==Ei.Manual&&(this.doc.hasLocalChanges()||this.remoteChangeEventReceived)}async runWatchLoop(e){const t=async()=>{if(this.watchStream)return Promise.resolve();this.watchLoopTimerID&&(clearTimeout(this.watchLoopTimerID),this.watchLoopTimerID=void 0);try{[this.watchStream,this.watchAbortController]=await e(()=>{this.watchStream=void 0,this.watchAbortController=void 0,this.watchLoopTimerID=setTimeout(t,this.reconnectStreamDelay)})}catch{}};await t()}cancelWatchStream(){this.watchStream&&this.watchAbortController&&(this.watchAbortController.abort(),this.watchStream=void 0,this.watchAbortController=void 0),clearTimeout(this.watchLoopTimerID),this.watchLoopTimerID=void 0}}const Jo=()=>{};class ty{constructor(e){c(this,"finalized",!1);c(this,"observers",[]);c(this,"finalError");try{e(this)}catch(t){this.error(t)}}next(e){this.forEachObserver(t=>{t.next(e)})}error(e){this.forEachObserver(t=>{t.error(e)}),this.close(e)}complete(){this.forEachObserver(e=>{e.complete()}),this.close()}subscribe(e,t,n){let s;if(!e)throw new w(y.ErrInvalidArgument,"missing observer");if(this.finalized)throw new w(y.ErrRefused,"observable is finalized due to previous error");typeof e=="object"?s=e:s={next:e,error:t,complete:n},s.next===void 0&&(s.next=Jo),s.error===void 0&&(s.error=Jo),s.complete===void 0&&(s.complete=Jo);const i=Kf(),o=this.unsubscribeOne.bind(this,i);if(this.observers.push({subscriptionID:i,observer:s}),this.finalized)try{this.finalError?s.error(this.finalError):s.complete()}catch(a){z.warn(a)}return o}unsubscribeOne(e){var t;this.observers=(t=this.observers)==null?void 0:t.filter(n=>n.subscriptionID!==e)}forEachObserver(e){if(!this.finalized)for(let t=0;te}}class Xn{constructor(e,t,n,s){c(this,"id");c(this,"delimiter");c(this,"message");c(this,"root");c(this,"operations");c(this,"presenceChange");c(this,"previousPresence");c(this,"reversePresenceKeys");this.id=e,this.delimiter=pf,this.root=t,this.operations=[],this.previousPresence=ht(n),this.presenceChange=void 0,this.reversePresenceKeys=new Set,this.message=s}static create(e,t,n,s){return new Xn(e,t,n,s)}push(e){this.operations.push(e)}registerElement(e,t){this.root.registerElement(e,t)}registerRemovedElement(e){this.root.registerRemovedElement(e)}registerGCPair(e){this.root.registerGCPair(e)}getChange(){return ds.create({id:this.id,operations:this.operations,presenceChange:this.presenceChange,message:this.message})}hasChange(){return this.operations.length>0||this.presenceChange!==void 0}setPresenceChange(e){this.presenceChange=e}setReversePresence(e,t){for(const n of Object.keys(e))t!=null&&t.addToHistory?this.reversePresenceKeys.add(n):this.reversePresenceKeys.delete(n)}getReversePresence(){if(this.reversePresenceKeys.size===0)return;const e={};for(const t of this.reversePresenceKeys)e[t]=this.previousPresence[t];return e}issueTimeTicket(){return this.delimiter+=1,this.id.createTimeTicket(this.delimiter)}getLastTimeTicket(){return this.id.createTimeTicket(this.delimiter)}}class Ws{constructor(e){c(this,"rootObject");c(this,"elementPairMapByCreatedAt");c(this,"gcElementSetByCreatedAt");c(this,"gcPairMap");this.rootObject=e,this.elementPairMapByCreatedAt=new Map,this.gcElementSetByCreatedAt=new Set,this.gcPairMap=new Map,this.registerElement(e,void 0),e.getDescendants(t=>{if(t.getRemovedAt()&&this.registerRemovedElement(t),t instanceof at||t instanceof ct)for(const n of t.getGCPairs())this.registerGCPair(n);return!1})}static create(){return new Ws(Me.create(wt))}findByCreatedAt(e){const t=this.elementPairMapByCreatedAt.get(e.toIDString());if(t)return t.element}findElementPairByCreatedAt(e){return this.elementPairMapByCreatedAt.get(e.toIDString())}createSubPaths(e){let t=this.elementPairMapByCreatedAt.get(e.toIDString());if(!t)return[];const n=[];for(;t.parent;){const s=t.element.getCreatedAt(),i=t.parent.subPathOf(s);if(i===void 0)throw new w(y.ErrInvalidArgument,`cant find the given element: ${s.toIDString()}`);n.unshift(i),t=this.elementPairMapByCreatedAt.get(t.parent.getCreatedAt().toIDString())}return n.unshift("$"),n}createPath(e){return this.createSubPaths(e).join(".")}registerElement(e,t){this.elementPairMapByCreatedAt.set(e.getCreatedAt().toIDString(),{parent:t,element:e}),e instanceof pn&&e.getDescendants((n,s)=>(this.registerElement(n,s),!1))}deregisterElement(e){let t=0;const n=s=>{const i=s.getCreatedAt().toIDString();this.elementPairMapByCreatedAt.delete(i),this.gcElementSetByCreatedAt.delete(i),t++};return n(e),e instanceof pn&&e.getDescendants(s=>(n(s),!1)),t}registerRemovedElement(e){this.gcElementSetByCreatedAt.add(e.getCreatedAt().toIDString())}registerGCPair(e){if(this.gcPairMap.get(e.child.toIDString())){this.gcPairMap.delete(e.child.toIDString());return}this.gcPairMap.set(e.child.toIDString(),e)}getElementMapSize(){return this.elementPairMapByCreatedAt.size}getGarbageElementSetSize(){const e=new Set;for(const t of this.gcElementSetByCreatedAt){e.add(t);const n=this.elementPairMapByCreatedAt.get(t);n.element instanceof pn&&n.element.getDescendants(s=>(e.add(s.getCreatedAt().toIDString()),!1))}return e.size}getObject(){return this.rootObject}getGarbageLen(){return this.getGarbageElementSetSize()+this.gcPairMap.size}deepcopy(){return new Ws(this.rootObject.deepcopy())}garbageCollect(e){let t=0;for(const n of this.gcElementSetByCreatedAt){const s=this.elementPairMapByCreatedAt.get(n),i=s.element.getRemovedAt();i&&(e!=null&&e.afterOrEqual(i))&&(s.parent.purge(s.element),t+=this.deregisterElement(s.element))}for(const[,n]of this.gcPairMap){const s=n.child.getRemovedAt();s&&(e!=null&&e.afterOrEqual(s))&&(n.parent.purge(n.child),this.gcPairMap.delete(n.child.toIDString()),t+=1)}return t}toJSON(){return this.rootObject.toJSON()}toSortedJSON(){return this.rootObject.toSortedJSON()}getStats(){return{elements:this.getElementMapSize(),gcPairs:this.gcPairMap.size,gcElements:this.getGarbageElementSetSize()}}}function jf(r,e){const t=new Hs(r);return new Proxy(e,t.getHandlers())}class Hs{constructor(e){c(this,"context");c(this,"handlers");this.context=e,this.handlers={set:(t,n,s)=>(z.isEnabled(Be.Trivial)&&z.trivial(`obj[${n}]=${JSON.stringify(s)}`),Hs.setInternal(e,t,n,s),!0),get:(t,n)=>(z.isEnabled(Be.Trivial)&&z.trivial(`obj[${n}]`),n==="getID"?()=>t.getCreatedAt():n==="toJSON"||n==="toString"?()=>t.toJSON():n==="toJS"?()=>t.toJS():n==="toJSForTest"?()=>t.toJSForTest():Cn(e,t.get(n))),ownKeys:t=>t.getKeys(),getOwnPropertyDescriptor:()=>({enumerable:!0,configurable:!0}),deleteProperty:(t,n)=>(z.isEnabled(Be.Trivial)&&z.trivial(`obj[${n}]`),Hs.deleteInternal(e,t,n),!0)}}static setInternal(e,t,n,s){if(n.includes("."))throw new w(y.ErrInvalidObjectKey,"key must not contain the '.'.");const i=e.issueTimeTicket(),o=ro(e,s,i),a=t.set(n,o,i);e.registerElement(o,t),a&&e.registerRemovedElement(a),e.push(qn.create(n,o.deepcopy(),t.getCreatedAt(),i))}static buildObjectMembers(e,t){const n={};for(const[s,i]of Object.entries(t)){if(s.includes("."))throw new w(y.ErrInvalidObjectKey,"key must not contain the '.'.");const o=e.issueTimeTicket(),a=ro(e,i,o);n[s]=a}return n}static deleteInternal(e,t,n){const s=e.issueTimeTicket(),i=t.deleteByKey(n,s);i&&(e.push(Tn.create(t.getCreatedAt(),i.getCreatedAt(),s)),e.registerRemovedElement(i))}getHandlers(){return this.handlers}}function ny(r,e){const t=new de(r,e);return new Proxy(e,t.getHandlers())}function sy(r){return typeof r=="string"||r instanceof String?!isNaN(r):!1}function iy(r){return["concat","entries","every","filter","find","findIndex","forEach","join","keys","map","reduce","reduceRight","slice","some","toLocaleString","toString","values"].includes(r)}class de{constructor(e,t){c(this,"context");c(this,"handlers");c(this,"array");this.context=e,this.array=t,this.handlers={get:(n,s,i)=>s==="getID"?()=>n.getCreatedAt():s==="getElementByID"?o=>{const a=n.getByID(o);if(!(!a||a.isRemoved()))return un(e,a)}:s==="getElementByIndex"?o=>{const a=n.get(o);return un(e,a)}:s==="getLast"?()=>un(e,n.getLast()):s==="deleteByID"?o=>{const a=de.deleteInternalByID(e,n,o);return un(e,a)}:s==="insertAfter"?(o,a)=>{const u=de.insertAfterInternal(e,n,o,a);return un(e,u)}:s==="insertBefore"?(o,a)=>{const u=de.insertBeforeInternal(e,n,o,a);return un(e,u)}:s==="moveBefore"?(o,a)=>{de.moveBeforeInternal(e,n,o,a)}:s==="moveAfter"?(o,a)=>{de.moveAfterInternal(e,n,o,a)}:s==="moveFront"?o=>{de.moveFrontInternal(e,n,o)}:s==="moveLast"?o=>{de.moveLastInternal(e,n,o)}:sy(s)?Cn(e,n.get(Number(s))):s==="push"?o=>de.pushInternal(e,n,o):s==="splice"?(o,a,...u)=>de.splice(e,n,o,a,...u):s==="length"?n.length:typeof s=="symbol"&&s===Symbol.iterator?de.iteratorInternal.bind(this,e,n):s==="includes"?(o,a)=>de.includes(e,n,o,a):s==="indexOf"?(o,a)=>de.indexOf(e,n,o,a):s==="lastIndexOf"?(o,a)=>de.lastIndexOf(e,n,o,a):s==="toJSForTest"?()=>n.toJSForTest():s==="toTestString"?()=>de.toTestString(n):typeof s=="string"&&iy(s)?(...o)=>{const a=Array.from(n).map(u=>Cn(e,u));return Array.prototype[s].apply(a,o)}:Reflect.get(n,s,i),deleteProperty:(n,s)=>(z.isEnabled(Be.Trivial)&&z.trivial(`array[${s}]`),de.deleteInternalByIndex(e,n,Number.parseInt(s)),!0)}}static*iteratorInternal(e,t){for(const n of t)yield un(e,n)}static buildArrayElements(e,t){const n=[];for(const s of t){const i=e.issueTimeTicket(),o=ro(e,s,i);n.push(o)}return n}static pushInternal(e,t,n){return de.insertAfterInternal(e,t,t.getLastCreatedAt(),n),t.length}static moveBeforeInternal(e,t,n,s){const i=e.issueTimeTicket(),o=t.getPrevCreatedAt(n);t.moveAfter(o,s,i),e.push(hn.create(t.getCreatedAt(),o,s,i))}static moveAfterInternal(e,t,n,s){const i=e.issueTimeTicket();t.moveAfter(n,s,i),e.push(hn.create(t.getCreatedAt(),n,s,i))}static moveFrontInternal(e,t,n){const s=e.issueTimeTicket(),i=t.getHead();t.moveAfter(i.getCreatedAt(),n,s),e.push(hn.create(t.getCreatedAt(),i.getCreatedAt(),n,s))}static moveLastInternal(e,t,n){const s=e.issueTimeTicket(),i=t.getLastCreatedAt();t.moveAfter(i,n,s),e.push(hn.create(t.getCreatedAt(),i,n,s))}static insertAfterInternal(e,t,n,s){const i=e.issueTimeTicket(),o=ro(e,s,i);return t.insertAfter(n,o),e.registerElement(o,t),e.push(Ys.create(t.getCreatedAt(),n,o.deepcopy(),i)),o}static insertBeforeInternal(e,t,n,s){return de.insertAfterInternal(e,t,t.getPrevCreatedAt(n),s)}static deleteInternalByIndex(e,t,n){const s=e.issueTimeTicket(),i=t.deleteByIndex(n,s);if(i)return e.push(Tn.create(t.getCreatedAt(),i.getCreatedAt(),s)),e.registerRemovedElement(i),i}static deleteInternalByID(e,t,n){const s=e.issueTimeTicket(),i=t.delete(n,s);return e.push(Tn.create(t.getCreatedAt(),i.getCreatedAt(),s)),e.registerRemovedElement(i),i}static splice(e,t,n,s,...i){const o=t.length,a=n>=0?Math.min(n,o):Math.max(o+n,0),u=s===void 0?o:s<0?a:Math.min(a+s,o),l=[];for(let h=a;h=i)return!1;if(le.isSupport(n))return Array.from(t).map(l=>Cn(e,l)).includes(n,o);for(let u=o;u=i)return-1;if(le.isSupport(n))return Array.from(t).map(l=>Cn(e,l)).indexOf(n,o);for(let u=o;u=i?i-1:s<0?s+i:s;if(o<0)return-1;if(le.isSupport(n))return Array.from(t).map(l=>Cn(e,l)).lastIndexOf(n,o);for(let u=o;u>0;u--)if(((a=t.get(u))==null?void 0:a.getID())===n.getID())return u;return-1}static toTestString(e){return e.toTestString()}getHandlers(){return this.handlers}}class wo{constructor(e,t){c(this,"context");c(this,"text");this.context=e,this.text=t}initialize(e,t){this.context=e,this.text=t}getID(){return this.text.getID()}edit(e,t,n,s){if(!this.context||!this.text)throw new w(y.ErrNotInitialized,"Text is not initialized yet");if(e>t)throw new w(y.ErrInvalidArgument,"from should be less than or equal to to");const i=this.text.indexRangeToPosRange(e,t);z.isEnabled(Be.Debug)&&z.debug(`EDIT: f:${e}->${i[0].toTestString()}, t:${t}->${i[1].toTestString()} c:${n}`);const o=s?fs(s):void 0,a=this.context.issueTimeTicket(),[u,,l,h]=this.text.edit(i,n,a,o);for(const g of l)this.context.registerGCPair(g);return this.context.push(new _s(this.text.getCreatedAt(),i[0],i[1],u,n,o?new Map(Object.entries(o)):new Map,a)),this.text.findIndexesFromRange(h)}delete(e,t){return this.edit(e,t,"")}empty(){return this.edit(0,this.length,"")}setStyle(e,t,n){if(!this.context||!this.text)throw new w(y.ErrNotInitialized,"Text is not initialized yet");if(e>t)throw new w(y.ErrInvalidArgument,"from should be less than or equal to to");const s=this.text.indexRangeToPosRange(e,t);z.isEnabled(Be.Debug)&&z.debug(`STYL: f:${e}->${s[0].toTestString()}, t:${t}->${s[1].toTestString()} a:${JSON.stringify(n)}`);const i=fs(n),o=this.context.issueTimeTicket(),[a,u]=this.text.setStyle(s,i,o);for(const l of u)this.context.registerGCPair(l);return this.context.push(new Xs(this.text.getCreatedAt(),s[0],s[1],a,new Map(Object.entries(i)),o)),!0}indexRangeToPosRange(e){if(!this.context||!this.text)throw new w(y.ErrNotInitialized,"Text is not initialized yet");const t=this.text.indexRangeToPosRange(e[0],e[1]);return[t[0].toStruct(),t[1].toStruct()]}posRangeToIndexRange(e){if(!this.context||!this.text)throw new w(y.ErrNotInitialized,"Text is not initialized yet");const t=this.text.findIndexesFromRange([bt.fromStruct(e[0]),bt.fromStruct(e[1])]);return[t[0],t[1]]}toTestString(){if(!this.context||!this.text)throw new w(y.ErrNotInitialized,"Text is not initialized yet");return this.text.toTestString()}values(){if(!this.context||!this.text)throw new w(y.ErrNotInitialized,"Text is not initialized yet");return this.text.values()}get length(){return this.text.length}getTreeByIndex(){return this.text.getTreeByIndex()}getTreeByID(){return this.text.getTreeByID()}toString(){if(!this.context||!this.text)throw new w(y.ErrNotInitialized,"Text is not initialized yet");return this.text.toString()}toJSON(){if(!this.context||!this.text)throw new w(y.ErrNotInitialized,"Text is not initialized yet");return this.text.toJSON()}toJSForTest(){if(!this.context||!this.text)throw new w(y.ErrNotInitialized,"Text is not initialized yet");return this.text.toJSForTest()}createRangeForTest(e,t){if(!this.context||!this.text)throw new w(y.ErrNotInitialized,"Text is not initialized yet");return this.text.indexRangeToPosRange(e,t)}}class bo{constructor(e,t){c(this,"valueType");c(this,"value");c(this,"context");c(this,"counter");this.valueType=e,this.value=t}initialize(e,t){this.valueType=t.getValueType(),this.context=e,this.counter=t,this.value=t.getValue()}getID(){return this.counter.getID()}getValue(){return this.value}getValueType(){return this.valueType}increase(e){if(!this.context||!this.counter)throw new w(y.ErrNotInitialized,"Counter is not initialized yet");const t=this.context.issueTimeTicket(),n=le.of(e,t);if(!n.isNumericType())throw new TypeError(`Unsupported type of value: ${typeof n.getValue()}`);return this.counter.increase(n),this.context.push(ms.create(this.counter.getCreatedAt(),n,t)),this}toJSForTest(){if(!this.context||!this.counter)throw new w(y.ErrNotInitialized,"Counter is not initialized yet");return this.counter.toJSForTest()}}function mc(r,e,t){const{type:n}=r,s=t.issueTimeTicket();if(n===Zr){Wf(r);const{value:i}=r,o=ze.create(Ae.of(s,0),n,i);e.append(o)}else{const{children:i=[]}=r,{attributes:o}=r;let a;if(typeof o=="object"&&!mf(o)){const l=fs(o);a=new rn;for(const[h,g]of Object.entries(l))a.set(h,g,s)}const u=ze.create(Ae.of(s,0),n,void 0,a);e.append(u);for(const l of i)mc(l,u,t)}}function oy(r,e){const{type:t}=e,n=r.issueTimeTicket();let s;if(e.type===Zr){const{value:i}=e;s=ze.create(Ae.of(n,0),t,i)}else if(e){const{children:i=[]}=e,{attributes:o}=e;let a;if(typeof o=="object"&&!mf(o)){const u=fs(o);a=new rn;for(const[l,h]of Object.entries(u))a.set(l,h,n)}s=ze.create(Ae.of(r.issueTimeTicket(),0),t,void 0,a);for(const u of i)mc(u,s,r)}return s}function Wf(r){if(!r.value.length)throw new w(y.ErrInvalidArgument,"text node cannot have empty value");return!0}function Ku(r){if(!r.length)return!0;if(r[0].type===Zr)for(const t of r){const{type:n}=t;if(n!==Zr)throw new w(y.ErrInvalidArgument,"element node and text node cannot be passed together");Wf(t)}else for(const t of r){const{type:n}=t;if(n===Zr)throw new w(y.ErrInvalidArgument,"element node and text node cannot be passed together")}return!0}class To{constructor(e){c(this,"initialRoot");c(this,"context");c(this,"tree");this.initialRoot=e}initialize(e,t){this.context=e,this.tree=t}getID(){return this.tree.getID()}buildRoot(e){if(!this.initialRoot)return ze.create(Ae.of(e.issueTimeTicket(),0),sp);const t=ze.create(Ae.of(e.issueTimeTicket(),0),this.initialRoot.type);for(const n of this.initialRoot.children)mc(n,t,e);return t}getSize(){if(!this.context||!this.tree)throw new w(y.ErrNotInitialized,"Tree is not initialized yet");return this.tree.getSize()}getNodeSize(){if(!this.context||!this.tree)throw new w(y.ErrNotInitialized,"Tree is not initialized yet");return this.tree.getNodeSize()}getIndexTree(){if(!this.context||!this.tree)throw new w(y.ErrNotInitialized,"Tree is not initialized yet");return this.tree.getIndexTree()}styleByPath(e,t){if(!this.context||!this.tree)throw new w(y.ErrNotInitialized,"Tree is not initialized yet");if(!e.length)throw new w(y.ErrInvalidArgument,"path should not be empty");const[n,s]=this.tree.pathToPosRange(e),i=this.context.issueTimeTicket(),o=t?fs(t):void 0,[a]=this.tree.style([n,s],o,i);this.context.push(Qr.create(this.tree.getCreatedAt(),n,s,a,o?new Map(Object.entries(o)):new Map,i))}style(e,t,n){if(!this.context||!this.tree)throw new w(y.ErrNotInitialized,"Tree is not initialized yet");if(e>t)throw new w(y.ErrInvalidArgument,"from should be less than or equal to to");const s=this.tree.findPos(e),i=this.tree.findPos(t),o=this.context.issueTimeTicket(),a=n?fs(n):void 0,[u,l]=this.tree.style([s,i],a,o);for(const h of l)this.context.registerGCPair(h);this.context.push(Qr.create(this.tree.getCreatedAt(),s,i,u,a?new Map(Object.entries(a)):new Map,o))}removeStyle(e,t,n){if(!this.context||!this.tree)throw new w(y.ErrNotInitialized,"Tree is not initialized yet");if(e>t)throw new w(y.ErrInvalidArgument,"from should be less than or equal to to");const s=this.tree.findPos(e),i=this.tree.findPos(t),o=this.context.issueTimeTicket(),[a,u]=this.tree.removeStyle([s,i],n,o);for(const l of u)this.context.registerGCPair(l);this.context.push(Qr.createTreeRemoveStyleOperation(this.tree.getCreatedAt(),s,i,a,n,o))}editInternal(e,t,n,s=0){var l;if(n.length!==0&&n[0]&&(Ku(n),n[0].type!==Zr))for(const h of n){const{children:g=[]}=h;Ku(g)}const i=this.context.getLastTimeTicket();let o=new Array;if(((l=n[0])==null?void 0:l.type)===Zr){let h="";for(const g of n){const{value:v}=g;h+=v}o.push(ze.create(Ae.of(this.context.issueTimeTicket(),0),Zr,h))}else o=n.map(h=>h&&oy(this.context,h)).filter(h=>h);const[,a,u]=this.tree.edit([e,t],o.length?o.map(h=>h==null?void 0:h.deepcopy()):void 0,s,i,()=>this.context.issueTimeTicket());for(const h of a)this.context.registerGCPair(h);return this.context.push(Zs.create(this.tree.getCreatedAt(),e,t,o.length?o:void 0,s,u,i)),!0}editByPath(e,t,n,s=0){if(!this.context||!this.tree)throw new w(y.ErrNotInitialized,"Tree is not initialized yet");if(e.length!==t.length)throw new w(y.ErrInvalidArgument,"path length should be equal");if(!e.length||!t.length)throw new w(y.ErrInvalidArgument,"path should not be empty");const i=this.tree.pathToPos(e),o=this.tree.pathToPos(t);return this.editInternal(i,o,n?[n]:[],s)}editBulkByPath(e,t,n,s=0){if(!this.context||!this.tree)throw new w(y.ErrNotInitialized,"Tree is not initialized yet");if(e.length!==t.length)throw new w(y.ErrInvalidArgument,"path length should be equal");if(!e.length||!t.length)throw new w(y.ErrInvalidArgument,"path should not be empty");const i=this.tree.pathToPos(e),o=this.tree.pathToPos(t);return this.editInternal(i,o,n,s)}edit(e,t,n,s=0){if(!this.context||!this.tree)throw new w(y.ErrNotInitialized,"Tree is not initialized yet");if(e>t)throw new w(y.ErrInvalidArgument,"from should be less than or equal to to");const i=this.tree.findPos(e),o=this.tree.findPos(t);return this.editInternal(i,o,n?[n]:[],s)}editBulk(e,t,n,s=0){if(!this.context||!this.tree)throw new w(y.ErrNotInitialized,"Tree is not initialized yet");if(e>t)throw new w(y.ErrInvalidArgument,"from should be less than or equal to to");const i=this.tree.findPos(e),o=this.tree.findPos(t);return this.editInternal(i,o,n,s)}toXML(){if(!this.context||!this.tree)throw new w(y.ErrNotInitialized,"Tree is not initialized yet");return this.tree.toXML()}toJSON(){if(!this.context||!this.tree)throw new w(y.ErrNotInitialized,"Tree is not initialized yet");return this.tree.toJSON()}toJSForTest(){if(!this.context||!this.tree)throw new w(y.ErrNotInitialized,"Tree is not initialized yet");return this.tree.toJSForTest()}toJSInfoForTest(){if(!this.context||!this.tree)throw new w(y.ErrNotInitialized,"Tree is not initialized yet");return this.tree.toJSInfoForTest()}getRootTreeNode(){if(!this.context||!this.tree)throw new w(y.ErrNotInitialized,"Tree is not initialized yet");return this.tree.getRootTreeNode()}indexToPath(e){if(!this.context||!this.tree)throw new w(y.ErrNotInitialized,"Tree is not initialized yet");return this.tree.indexToPath(e)}pathToIndex(e){if(!this.context||!this.tree)throw new w(y.ErrNotInitialized,"Tree is not initialized yet");return this.tree.pathToIndex(e)}pathRangeToPosRange(e){if(!this.context||!this.tree)throw new w(y.ErrNotInitialized,"Tree is not initialized yet");const t=[this.tree.pathToIndex(e[0]),this.tree.pathToIndex(e[1])],n=this.tree.indexRangeToPosRange(t);return[n[0].toStruct(),n[1].toStruct()]}indexRangeToPosRange(e){if(!this.context||!this.tree)throw new w(y.ErrNotInitialized,"Tree is not initialized yet");return this.tree.indexRangeToPosStructRange(e)}posRangeToIndexRange(e){if(!this.context||!this.tree)throw new w(y.ErrNotInitialized,"Tree is not initialized yet");const t=[yt.fromStruct(e[0]),yt.fromStruct(e[1])];return this.tree.posRangeToIndexRange(t)}posRangeToPathRange(e){if(!this.context||!this.tree)throw new w(y.ErrNotInitialized,"Tree is not initialized yet");const t=[yt.fromStruct(e[0]),yt.fromStruct(e[1])];return this.tree.posRangeToPathRange(t)}}function ju(r,e){return jf(r,e)}function un(r,e){if(e){if(e instanceof le)return e;if(e instanceof Me)return jf(r,e);if(e instanceof je)return ny(r,e);if(e instanceof at)return new wo(r,e);if(e instanceof We){const t=new bo(Vt.IntegerCnt,0);return t.initialize(r,e),t}else if(e instanceof ct){const t=new To;return t.initialize(r,e),t}}else return;throw new TypeError(`Unsupported type of element: ${typeof e}`)}function Cn(r,e){const t=un(r,e);return t instanceof le?t.getValue():t}function ro(r,e,t){let n;if(le.isSupport(e))n=le.of(e,t);else if(Array.isArray(e))n=je.create(t,de.buildArrayElements(r,e));else if(typeof e=="object")e instanceof wo?(n=at.create(gs.create(),t),e.initialize(r,n)):e instanceof bo?(n=We.create(e.getValueType(),e.getValue(),t),e.initialize(r,n)):e instanceof To?(n=ct.create(e.buildRoot(r),t),e.initialize(r,n)):n=Me.create(t,Hs.buildObjectMembers(r,e));else throw new TypeError(`Unsupported type of value: ${typeof e}`);return n}const Wu=50;class ay{constructor(){c(this,"undoStack",[]);c(this,"redoStack",[])}hasUndo(){return this.undoStack.length>0}hasRedo(){return this.redoStack.length>0}pushUndo(e){this.undoStack.length>=Wu&&this.undoStack.shift(),this.undoStack.push(e)}popUndo(){return this.undoStack.pop()}pushRedo(e){this.redoStack.length>=Wu&&this.redoStack.shift(),this.redoStack.push(e)}popRedo(){return this.redoStack.pop()}clearRedo(){this.redoStack=[]}getUndoStackForTest(){return this.undoStack}getRedoStackForTest(){return this.redoStack}}const cy="yorkie-devtools-panel",uy="yorkie-devtools-sdk";let Yn="disconnected";const Hu=new Map,ki=new Map;typeof window<"u"&&(window.transactionEventsByDocKey=ki);function gi(r,e){(e!=null&&e.force||Yn!=="disconnected")&&window.postMessage({source:uy,...r},"*")}function ly(r){if(!r.isEnableDevtools()||typeof window>"u"||Hu.has(r.getKey()))return;ki.set(r.getKey(),[]);const e=r.subscribe("all",t=>{t.some(n=>n.type!==Le.StatusChanged&&n.type!==Le.Snapshot&&n.type!==Le.LocalChange&&n.type!==Le.RemoteChange&&n.type!==Le.Initialized&&n.type!==Le.Watched&&n.type!==Le.Unwatched&&n.type!==Le.PresenceChanged)||(ki.get(r.getKey()).push(t),Yn==="synced"&&gi({msg:"doc::sync::partial",docKey:r.getKey(),event:t}))});Hu.set(r.getKey(),[e]),gi({msg:"refresh-devtools"},{force:!0}),window.addEventListener("message",t=>{var s;if(((s=t.data)==null?void 0:s.source)!==cy)return;switch(t.data.msg){case"devtools::connect":if(Yn!=="disconnected")break;Yn="connected",gi({msg:"doc::available",docKey:r.getKey()}),z.info(`[YD] Devtools connected. Doc: ${r.getKey()}`);break;case"devtools::disconnect":Yn="disconnected",z.info(`[YD] Devtools disconnected. Doc: ${r.getKey()}`);break;case"devtools::subscribe":Yn="synced",gi({msg:"doc::sync::full",docKey:r.getKey(),events:ki.get(r.getKey())}),z.info(`[YD] Devtools subscribed. Doc: ${r.getKey()}`);break}})}var ln=(r=>(r.Detached="detached",r.Attached="attached",r.Removed="removed",r))(ln||{}),Le=(r=>(r.StatusChanged="status-changed",r.ConnectionChanged="connection-changed",r.SyncStatusChanged="sync-status-changed",r.Snapshot="snapshot",r.LocalChange="local-change",r.RemoteChange="remote-change",r.Initialized="initialized",r.Watched="watched",r.Unwatched="unwatched",r.PresenceChanged="presence-changed",r.Broadcast="broadcast",r.LocalBroadcast="local-broadcast",r))(Le||{}),ka=(r=>(r.Connected="connected",r.Disconnected="disconnected",r))(ka||{}),Ea=(r=>(r.Synced="synced",r.SyncFailed="sync-failed",r))(Ea||{});class Hf{constructor(e,t){c(this,"key");c(this,"status");c(this,"opts");c(this,"changeID");c(this,"checkpoint");c(this,"localChanges");c(this,"root");c(this,"clone");c(this,"eventStream");c(this,"eventStreamObserver");c(this,"onlineClients");c(this,"presences");c(this,"history");c(this,"internalHistory");c(this,"isUpdating");this.opts=t||{},this.key=e,this.status="detached",this.root=Ws.create(),this.changeID=dp,this.checkpoint=gp,this.localChanges=[],this.eventStream=ry(n=>{this.eventStreamObserver=n}),this.onlineClients=new Set,this.presences=new Map,this.isUpdating=!1,this.internalHistory=new ay,this.history={canUndo:this.canUndo.bind(this),canRedo:this.canRedo.bind(this),undo:this.undo.bind(this),redo:this.redo.bind(this)},ly(this)}update(e,t){if(this.getStatus()==="removed")throw new w(y.ErrDocumentRemoved,`${this.key} is removed`);this.ensureClone();const n=this.changeID.getActorID(),s=Xn.create(this.changeID.next(),this.clone.root,this.clone.presences.get(n)||{},t);try{const i=ju(s,this.clone.root.getObject());this.presences.has(n)||this.clone.presences.set(n,{}),this.isUpdating=!0,e(i,new Ro(s,this.clone.presences.get(n)))}catch(i){throw this.clone=void 0,i}finally{this.isUpdating=!1}if(s.hasChange()){z.isEnabled(Be.Trivial)&&z.trivial(`trying to update a local change: ${this.toJSON()}`);const i=s.getChange(),{opInfos:o,reverseOps:a}=i.execute(this.root,this.presences,se.Local),u=s.getReversePresence();u&&a.push({type:"presence",value:u}),this.localChanges.push(i),a.length>0&&this.internalHistory.pushUndo(a),o.length>0&&this.internalHistory.clearRedo(),this.changeID=i.getID();const l=[];o.length>0&&l.push({type:"local-change",source:se.Local,value:{message:i.getMessage()||"",operations:o,actor:n,clientSeq:i.getID().getClientSeq(),serverSeq:i.getID().getServerSeq()},rawChange:this.isEnableDevtools()?i.toStruct():void 0}),i.hasPresenceChange()&&l.push({type:"presence-changed",source:se.Local,value:{clientID:n,presence:this.getPresence(n)}}),this.publish(l),z.isEnabled(Be.Trivial)&&z.trivial(`after update a local change: ${this.toJSON()}`)}}subscribe(e,t,n,s){if(typeof e=="string"){if(typeof t!="function")throw new w(y.ErrInvalidArgument,"Second argument must be a callback function");if(e==="presence"){const a=t;return this.eventStream.subscribe(u=>{for(const l of u)l.type!=="initialized"&&l.type!=="watched"&&l.type!=="unwatched"&&l.type!=="presence-changed"||a(l)},n,s)}if(e==="my-presence"){const a=t;return this.eventStream.subscribe(u=>{for(const l of u)l.type!=="initialized"&&l.type!=="presence-changed"||l.type==="presence-changed"&&l.value.clientID!==this.changeID.getActorID()||a(l)},n,s)}if(e==="others"){const a=t;return this.eventStream.subscribe(u=>{for(const l of u)l.type!=="watched"&&l.type!=="unwatched"&&l.type!=="presence-changed"||l.value.clientID!==this.changeID.getActorID()&&a(l)},n,s)}if(e==="connection"){const a=t;return this.eventStream.subscribe(u=>{for(const l of u)l.type==="connection-changed"&&a(l)},n,s)}if(e==="status"){const a=t;return this.eventStream.subscribe(u=>{for(const l of u)l.type==="status-changed"&&a(l)},n,s)}if(e==="sync"){const a=t;return this.eventStream.subscribe(u=>{for(const l of u)l.type==="sync-status-changed"&&a(l)},n,s)}if(e==="local-broadcast"){const a=t;return this.eventStream.subscribe(u=>{for(const l of u)l.type==="local-broadcast"&&a(l)},n)}if(e==="broadcast"){const a=t;return this.eventStream.subscribe(u=>{for(const l of u)l.type==="broadcast"&&a(l)},n)}if(e==="all"){const a=t;return this.eventStream.subscribe(a,n,s)}const i=e,o=t;return this.eventStream.subscribe(a=>{for(const u of a){if(u.type!=="local-change"&&u.type!=="remote-change")continue;const l=[];for(const h of u.value.operations)this.isSameElementOrChildOf(h.path,i)&&l.push(h);l.length&&o({...u,value:{...u.value,operations:l}})}},n,s)}if(typeof e=="function"){const i=e,o=t,a=n;return this.eventStream.subscribe(u=>{for(const l of u)l.type!=="snapshot"&&l.type!=="local-change"&&l.type!=="remote-change"||i(l)},o,a)}throw new w(y.ErrInvalidArgument,`"${e}" is not a valid`)}publish(e){this.eventStreamObserver&&this.eventStreamObserver.next(e)}isSameElementOrChildOf(e,t){if(t===e)return!0;const n=e.split(".");return t.split(".").every((i,o)=>i===n[o])}removePushedLocalChanges(e){for(;this.localChanges.length&&!(this.localChanges[0].getID().getClientSeq()>e);)this.localChanges.shift()}applyChangePack(e){const t=e.hasSnapshot();t?this.applySnapshot(e.getCheckpoint().getServerSeq(),e.getVersionVector(),e.getSnapshot(),e.getCheckpoint().getClientSeq()):(this.applyChanges(e.getChanges(),se.Remote),this.removePushedLocalChanges(e.getCheckpoint().getClientSeq())),this.checkpoint=this.checkpoint.forward(e.getCheckpoint()),t||this.garbageCollect(e.getVersionVector()),t||this.filterVersionVector(e.getVersionVector()),e.getIsRemoved()&&this.applyStatus("removed"),z.isEnabled(Be.Trivial)&&z.trivial(`${this.root.toJSON()}`)}getCheckpoint(){return this.checkpoint}getChangeID(){return this.changeID}hasLocalChanges(){return this.localChanges.length>0}ensureClone(){this.clone||(this.clone={root:this.root.deepcopy(),presences:ht(this.presences)})}createChangePack(){const e=Array.from(this.localChanges),t=this.checkpoint.increaseClientSeq(e.length);return vo.create(this.key,t,!1,e,this.getVersionVector())}setActor(e){for(const t of this.localChanges)t.setActor(e);this.changeID=this.changeID.setActor(e)}isEnableDevtools(){return!!this.opts.enableDevtools}getKey(){return this.key}getStatus(){return this.status}getCloneRoot(){if(this.clone)return this.clone.root.getObject()}getRoot(){this.ensureClone();const e=Xn.create(this.changeID.next(),this.clone.root,this.clone.presences.get(this.changeID.getActorID())||{});return ju(e,this.clone.root.getObject())}garbageCollect(e){return this.opts.disableGC?0:(this.clone&&this.clone.root.garbageCollect(e),this.root.garbageCollect(e))}getRootObject(){return this.root.getObject()}getGarbageLen(){return this.root.getGarbageLen()}getGarbageLenFromClone(){return this.clone.root.getGarbageLen()}toJSON(){return this.root.toJSON()}toSortedJSON(){return this.root.toSortedJSON()}getStats(){return this.root.getStats()}toJSForTest(){return{...this.getRoot().toJSForTest(),key:"root"}}applySnapshot(e,t,n,s=-1){const{root:i,presences:o}=me.bytesToSnapshot(n);this.root=new Ws(i),this.presences=o,this.changeID=this.changeID.setClocks(e,t),this.clone=void 0,this.removePushedLocalChanges(s),this.applyChanges(this.localChanges,se.Local),this.publish([{type:"snapshot",source:se.Remote,value:{serverSeq:e.toString(),snapshot:this.isEnableDevtools()?me.bytesToHex(n):void 0,snapshotVector:me.versionVectorToHex(t)}}])}applyChanges(e,t){z.isEnabled(Be.Debug)&&z.debug(`trying to apply ${e.length} remote changes.elements:${this.root.getElementMapSize()}, removeds:${this.root.getGarbageElementSetSize()}`),z.isEnabled(Be.Trivial)&&z.trivial(e.map(n=>`${n.getID().toTestString()} ${n.toTestString()}`).join(` `));for(const n of e)this.applyChange(n,t);z.isEnabled(Be.Debug)&&z.debug(`after appling ${e.length} remote changes.elements:${this.root.getElementMapSize()}, removeds:${this.root.getGarbageElementSetSize()}`)}applyChange(e,t){this.ensureClone(),e.execute(this.clone.root,this.clone.presences,t);const n=[],s=e.getID().getActorID();if(e.hasPresenceChange()&&this.onlineClients.has(s)){const o=e.getPresenceChange();switch(o.type){case bn.Put:n.push(this.presences.has(s)?{type:"presence-changed",source:t,value:{clientID:s,presence:o.presence}}:{type:"watched",source:se.Remote,value:{clientID:s,presence:o.presence}});break;case bn.Clear:n.push({type:"unwatched",source:se.Remote,value:{clientID:s,presence:this.getPresence(s)}}),this.removeOnlineClient(s);break}}const{opInfos:i}=e.execute(this.root,this.presences,t);if(this.changeID=this.changeID.syncClocks(e.getID()),i.length>0){const o=this.isEnableDevtools()?e.toStruct():void 0;n.push(t===se.Remote?{type:"remote-change",source:t,value:{actor:s,clientSeq:e.getID().getClientSeq(),serverSeq:e.getID().getServerSeq(),message:e.getMessage()||"",operations:i},rawChange:o}:{type:"local-change",source:t,value:{actor:s,clientSeq:e.getID().getClientSeq(),serverSeq:e.getID().getServerSeq(),message:e.getMessage()||"",operations:i},rawChange:o})}n.length>0&&this.publish(n)}applyWatchStream(e){if(e.body.case==="initialization"){const t=e.body.value.clientIds,n=new Set;for(const s of t)s!==this.changeID.getActorID()&&n.add(s);this.setOnlineClients(n),this.publish([{type:"initialized",source:se.Local,value:this.getPresences()}]);return}if(e.body.case==="event"){const{type:t,publisher:n}=e.body.value,s=[];if(t===Mn.DOCUMENT_WATCHED){if(this.onlineClients.has(n)&&this.hasPresence(n))return;this.addOnlineClient(n),this.hasPresence(n)&&s.push({type:"watched",source:se.Remote,value:{clientID:n,presence:this.getPresence(n)}})}else if(t===Mn.DOCUMENT_UNWATCHED){const i=this.getPresence(n);this.removeOnlineClient(n),i&&s.push({type:"unwatched",source:se.Remote,value:{clientID:n,presence:i}})}else if(t===Mn.DOCUMENT_BROADCAST&&e.body.value.body){const{topic:i,payload:o}=e.body.value.body,a=new TextDecoder;s.push({type:"broadcast",value:{clientID:n,topic:i,payload:JSON.parse(a.decode(o))}})}s.length>0&&this.publish(s)}}applyStatus(e){this.status=e,e==="detached"&&this.setActor(ec),this.publish([{source:e==="removed"?se.Remote:se.Local,type:"status-changed",value:e==="attached"?{status:e,actorID:this.changeID.getActorID()}:{status:e}}])}applyDocEvent(e){if(e.type==="status-changed"){this.applyStatus(e.value.status),e.value.status==="attached"&&this.setActor(e.value.actorID);return}if(e.type==="snapshot"){const{snapshot:t,serverSeq:n,snapshotVector:s}=e.value;if(!t)return;this.applySnapshot(BigInt(n),me.hexToVersionVector(s),me.hexToBytes(t));return}if(e.type==="local-change"||e.type==="remote-change"){if(!e.rawChange)return;const t=ds.fromStruct(e.rawChange);this.applyChange(t,e.source)}if(e.type==="initialized"){const t=new Set;for(const{clientID:n,presence:s}of e.value)t.add(n),this.presences.set(n,s);this.setOnlineClients(t);return}if(e.type==="watched"){const{clientID:t,presence:n}=e.value;this.addOnlineClient(t),this.presences.set(t,n);return}if(e.type==="unwatched"){const{clientID:t}=e.value;this.removeOnlineClient(t),this.presences.delete(t)}if(e.type==="presence-changed"){const{clientID:t,presence:n}=e.value;this.presences.set(t,n)}}applyTransactionEvent(e){for(const t of e)this.applyDocEvent(t)}getValueByPath(e){if(!e.startsWith("$"))throw new w(y.ErrInvalidArgument,'path must start with "$"');const t=e.split(".");t.shift();let n=this.getRoot();for(const s of t)if(n=n[s],n===void 0)return;return n}setOnlineClients(e){this.onlineClients=e}resetOnlineClients(){this.onlineClients=new Set}addOnlineClient(e){this.onlineClients.add(e)}removeOnlineClient(e){this.onlineClients.delete(e)}hasPresence(e){return this.presences.has(e)}getMyPresence(){if(this.status!=="attached")return{};const e=this.presences.get(this.changeID.getActorID());return e?ht(e):{}}getPresence(e){if(e===this.changeID.getActorID())return this.getMyPresence();if(!this.onlineClients.has(e))return;const t=this.presences.get(e);return t?ht(t):void 0}getPresenceForTest(e){const t=this.presences.get(e);return t?ht(t):void 0}getPresences(){const e=[];e.push({clientID:this.changeID.getActorID(),presence:ht(this.getMyPresence())});for(const t of this.onlineClients)this.presences.has(t)&&e.push({clientID:t,presence:ht(this.presences.get(t))});return e}getSelfForTest(){return{clientID:this.getChangeID().getActorID(),presence:this.getMyPresence()}}getOthersForTest(){const e=this.getChangeID().getActorID();return this.getPresences().filter(t=>t.clientID!==e).sort((t,n)=>t.clientID>n.clientID?1:-1)}canUndo(){return this.internalHistory.hasUndo()&&!this.isUpdating}filterVersionVector(e){const n=this.changeID.getVersionVector().filter(e);this.changeID=this.changeID.setVersionVector(n)}canRedo(){return this.internalHistory.hasRedo()&&!this.isUpdating}undo(){if(this.isUpdating)throw new w(y.ErrRefused,"Undo is not allowed during an update");const e=this.internalHistory.popUndo();if(e===void 0)throw new w(y.ErrRefused,"There is no operation to be undone");this.ensureClone();const t=Xn.create(this.changeID.next(),this.clone.root,this.clone.presences.get(this.changeID.getActorID())||{});for(const l of e){if(!(l instanceof Tt)){new Ro(t,ht(this.clone.presences.get(this.changeID.getActorID()))).set(l.value,{addToHistory:!0});continue}const h=t.issueTimeTicket();l.setExecutedAt(h),t.push(l)}const n=t.getChange();n.execute(this.clone.root,this.clone.presences,se.UndoRedo);const{opInfos:s,reverseOps:i}=n.execute(this.root,this.presences,se.UndoRedo),o=t.getReversePresence();if(o&&i.push({type:"presence",value:o}),i.length>0&&this.internalHistory.pushRedo(i),!n.hasPresenceChange()&&s.length===0)return;this.localChanges.push(n),this.changeID=n.getID();const a=this.changeID.getActorID(),u=[];s.length>0&&u.push({type:"local-change",source:se.UndoRedo,value:{message:n.getMessage()||"",operations:s,actor:a,clientSeq:n.getID().getClientSeq(),serverSeq:n.getID().getServerSeq()},rawChange:this.isEnableDevtools()?n.toStruct():void 0}),n.hasPresenceChange()&&u.push({type:"presence-changed",source:se.UndoRedo,value:{clientID:a,presence:this.getPresence(a)}}),this.publish(u)}redo(){if(this.isUpdating)throw new w(y.ErrRefused,"Redo is not allowed during an update");const e=this.internalHistory.popRedo();if(e===void 0)throw new w(y.ErrRefused,"There is no operation to be redone");this.ensureClone();const t=Xn.create(this.changeID.next(),this.clone.root,this.clone.presences.get(this.changeID.getActorID())||{});for(const l of e){if(!(l instanceof Tt)){new Ro(t,ht(this.clone.presences.get(this.changeID.getActorID()))).set(l.value,{addToHistory:!0});continue}const h=t.issueTimeTicket();l.setExecutedAt(h),t.push(l)}const n=t.getChange();n.execute(this.clone.root,this.clone.presences,se.UndoRedo);const{opInfos:s,reverseOps:i}=n.execute(this.root,this.presences,se.UndoRedo),o=t.getReversePresence();if(o&&i.push({type:"presence",value:o}),i.length>0&&this.internalHistory.pushUndo(i),!n.hasPresenceChange()&&s.length===0)return;this.localChanges.push(n),this.changeID=n.getID();const a=this.changeID.getActorID(),u=[];s.length>0&&u.push({type:"local-change",source:se.UndoRedo,value:{message:n.getMessage()||"",operations:s,actor:a,clientSeq:n.getID().getClientSeq(),serverSeq:n.getID().getServerSeq()},rawChange:this.isEnableDevtools()?n.toStruct():void 0}),n.hasPresenceChange()&&u.push({type:"presence-changed",source:se.UndoRedo,value:{clientID:a,presence:this.getPresence(a)}}),this.publish(u)}getUndoStackForTest(){return this.internalHistory.getUndoStackForTest()}getRedoStackForTest(){return this.internalHistory.getRedoStackForTest()}broadcast(e,t,n){const s={type:"local-broadcast",value:{topic:e,payload:t},options:n};this.publish([s])}getVersionVector(){return this.changeID.getVersionVector()}}function fy(r,e){return t=>async n=>(r&&n.header.set("x-api-key",r),e&&n.header.set("authorization",e),await t(n))}const hy="yorkie-js-sdk",dy="0.5.4",gy="Yorkie JS SDK",my="./src/yorkie.ts",py={access:"public",main:"./dist/yorkie-js-sdk.js",typings:"./dist/yorkie-js-sdk.d.ts"},yy=["dist"],vy={build:"tsc && vite build","build:proto":"npx buf generate","build:docs":"typedoc","build:ghpages":"mkdir -p ghpages/examples && cp -r docs ghpages/api-reference && find ../../examples -name 'dist' -type d -exec sh -c 'cp -r {} ghpages/examples/$(basename $(dirname {}))' \\;",dev:"vite build -c vite.preview.ts && vite preview",test:"vitest run","test:watch":"vitest","test:bench":"vitest bench","test:ci":"vitest run --coverage","test:yorkie.dev":"TEST_RPC_ADDR=https://api.yorkie.dev vitest run --coverage",prepare:"pnpm build"},wy={node:">=18.0.0",npm:">=7.1.0"},by={type:"git",url:"git+https://github.com/yorkie-team/yorkie-js-sdk.git"},Ty={name:"hackerwins",email:"susukang98@gmail.com"},Ay="Apache-2.0",Iy={url:"https://github.com/yorkie-team/yorkie-js-sdk/issues"},Sy="https://github.com/yorkie-team/yorkie-js-sdk#readme",xy={"@buf/googleapis_googleapis.bufbuild_es":"^1.4.0-20240524201209-f0e53af8f2fc.3","@bufbuild/buf":"^1.28.1","@bufbuild/protoc-gen-es":"^1.6.0","@connectrpc/protoc-gen-connect-es":"^1.4.0","@types/google-protobuf":"^3.15.5","@types/long":"^4.0.1","@typescript-eslint/eslint-plugin":"^6.21.0","@typescript-eslint/parser":"^6.21.0","@vitest/coverage-istanbul":"^0.34.5","@vitest/coverage-v8":"^0.34.5","eslint-plugin-tsdoc":"^0.2.16",prettier:"^2.7.1","ts-node":"^10.9.1",typedoc:"^0.25.13",typescript:"^5.3.3","typescript-transform-paths":"^3.3.1",vite:"^5.0.12","vite-plugin-commonjs":"^0.10.1","vite-plugin-dts":"^3.9.1","vite-tsconfig-paths":"^4.2.1",vitest:"^0.34.5"},ky={"@bufbuild/protobuf":"^1.6.0","@connectrpc/connect":"^1.4.0","@connectrpc/connect-web":"^1.4.0",long:"^5.2.0"},Gu={name:hy,version:dy,description:gy,main:my,publishConfig:py,files:yy,scripts:vy,engines:wy,repository:by,author:Ty,license:Ay,bugs:Iy,homepage:Sy,devDependencies:xy,dependencies:ky};function Ey(){return r=>async e=>(e.header.set("x-yorkie-user-agent",Gu.name+"/"+Gu.version),await r(e))}const Cy=r=>{try{if(JSON.stringify(r)===void 0)return!1}catch{return!1}return!0};var Ei=(r=>(r.Manual="manual",r.Realtime="realtime",r.RealtimePushOnly="realtime-pushonly",r.RealtimeSyncOff="realtime-syncoff",r))(Ei||{});const mi={syncLoopDuration:50,retrySyncLoopDelay:1e3,reconnectStreamDelay:1e3},Mo={maxRetries:1/0,initialRetryInterval:1e3,maxBackoff:2e4};class Gf{constructor(e,t){c(this,"id");c(this,"key");c(this,"status");c(this,"attachmentMap");c(this,"apiKey");c(this,"conditions");c(this,"syncLoopDuration");c(this,"reconnectStreamDelay");c(this,"retrySyncLoopDelay");c(this,"rpcClient");c(this,"taskQueue");c(this,"processing",!1);t=t||mi,this.key=t.key?t.key:Kf(),this.status="deactivated",this.attachmentMap=new Map,this.apiKey=t.apiKey||"",this.conditions={SyncLoop:!1,WatchLoop:!1},this.syncLoopDuration=t.syncLoopDuration||mi.syncLoopDuration,this.reconnectStreamDelay=t.reconnectStreamDelay||mi.reconnectStreamDelay,this.retrySyncLoopDelay=t.retrySyncLoopDelay||mi.retrySyncLoopDelay,this.rpcClient=Sm(Hm,Wm({baseUrl:e,interceptors:[fy(t.apiKey,t.token),Ey()]})),this.taskQueue=[]}activate(){return this.isActive()?Promise.resolve():this.enqueueTask(async()=>this.rpcClient.activateClient({clientKey:this.key},{headers:{"x-shard-key":this.apiKey}}).then(e=>{this.id=e.clientId,this.status="activated",this.runSyncLoop(),z.info(`[AC] c:"${this.getKey()}" activated, id:"${this.id}"`)}).catch(e=>{throw z.error(`[AC] c:"${this.getKey()}" err :`,e),this.handleConnectError(e),e}))}deactivate(){return this.status==="deactivated"?Promise.resolve():this.enqueueTask(async()=>this.rpcClient.deactivateClient({clientId:this.id},{headers:{"x-shard-key":this.apiKey}}).then(()=>{this.deactivateInternal(),z.info(`[DC] c"${this.getKey()}" deactivated`)}).catch(e=>{throw z.error(`[DC] c:"${this.getKey()}" err :`,e),this.handleConnectError(e),e}))}attach(e,t={}){if(!this.isActive())throw new w(y.ErrClientNotActivated,`${this.key} is not active`);if(e.getStatus()!==ln.Detached)throw new w(y.ErrDocumentNotDetached,`${e.getKey()} is not detached`);e.setActor(this.id),e.update((i,o)=>o.set(t.initialPresence||{}));const n=e.subscribe("local-broadcast",async i=>{var h;const{topic:o,payload:a}=i.value,u=(h=i.options)==null?void 0:h.error,l=i.options;try{await this.broadcast(e.getKey(),o,a,l)}catch(g){g instanceof Error&&(u==null||u(g))}}),s=t.syncMode??"realtime";return this.enqueueTask(async()=>this.rpcClient.attachDocument({clientId:this.id,changePack:me.toChangePack(e.createChangePack())},{headers:{"x-shard-key":`${this.apiKey}/${e.getKey()}`}}).then(async i=>{const o=me.fromChangePack(i.changePack);if(e.applyChangePack(o),e.getStatus()===ln.Removed)return e;e.applyStatus(ln.Attached),this.attachmentMap.set(e.getKey(),new ey(this.reconnectStreamDelay,e,i.documentId,s,n)),s!=="manual"&&await this.runWatchLoop(e.getKey()),z.info(`[AD] c:"${this.getKey()}" attaches d:"${e.getKey()}"`);const a=e.getRootObject();if(t.initialRoot){const u=t.initialRoot;e.update(l=>{for(const[h,g]of Object.entries(u))if(!a.has(h)){const v=h;l[v]=g}})}return e}).catch(i=>{throw z.error(`[AD] c:"${this.getKey()}" err :`,i),this.handleConnectError(i),i}))}detach(e,t={}){if(!this.isActive())throw new w(y.ErrClientNotActivated,`${this.key} is not active`);const n=this.attachmentMap.get(e.getKey());if(!n)throw new w(y.ErrDocumentNotAttached,`${e.getKey()} is not attached`);return e.update((s,i)=>i.clear()),this.enqueueTask(async()=>this.rpcClient.detachDocument({clientId:this.id,documentId:n.docID,changePack:me.toChangePack(e.createChangePack()),removeIfNotAttached:t.removeIfNotAttached??!1},{headers:{"x-shard-key":`${this.apiKey}/${e.getKey()}`}}).then(s=>{const i=me.fromChangePack(s.changePack);return e.applyChangePack(i),e.getStatus()!==ln.Removed&&e.applyStatus(ln.Detached),this.detachInternal(e.getKey()),z.info(`[DD] c:"${this.getKey()}" detaches d:"${e.getKey()}"`),e}).catch(s=>{throw z.error(`[DD] c:"${this.getKey()}" err :`,s),this.handleConnectError(s),s}))}async changeSyncMode(e,t){if(!this.isActive())throw new w(y.ErrClientNotActivated,`${this.key} is not active`);const n=this.attachmentMap.get(e.getKey());if(!n)throw new w(y.ErrDocumentNotAttached,`${e.getKey()} is not attached`);const s=n.syncMode;return s===t?e:(n.changeSyncMode(t),t==="manual"?(n.cancelWatchStream(),e):(t==="realtime"&&(n.remoteChangeEventReceived=!0),s==="manual"&&await this.runWatchLoop(e.getKey()),e))}sync(e){if(!this.isActive())throw new w(y.ErrClientNotActivated,`${this.key} is not active`);if(e){const t=this.attachmentMap.get(e.getKey());if(!t)throw new w(y.ErrDocumentNotAttached,`${e.getKey()} is not attached`);return this.enqueueTask(async()=>this.syncInternal(t,"realtime").catch(n=>{throw z.error(`[SY] c:"${this.getKey()}" err :`,n),this.handleConnectError(n),n}))}return this.enqueueTask(async()=>{const t=[];for(const[,n]of this.attachmentMap)t.push(this.syncInternal(n,n.syncMode));return Promise.all(t).catch(n=>{throw z.error(`[SY] c:"${this.getKey()}" err :`,n),this.handleConnectError(n),n})})}remove(e){if(!this.isActive())throw new w(y.ErrClientNotActivated,`${this.key} is not active`);const t=this.attachmentMap.get(e.getKey());if(!t)throw new w(y.ErrDocumentNotAttached,`${e.getKey()} is not attached`);e.setActor(this.id);const n=me.toChangePack(e.createChangePack());return n.isRemoved=!0,this.enqueueTask(async()=>this.rpcClient.removeDocument({clientId:this.id,documentId:t.docID,changePack:n},{headers:{"x-shard-key":`${this.apiKey}/${e.getKey()}`}}).then(s=>{const i=me.fromChangePack(s.changePack);e.applyChangePack(i),this.detachInternal(e.getKey()),z.info(`[RD] c:"${this.getKey()}" removes d:"${e.getKey()}"`)}).catch(s=>{throw z.error(`[RD] c:"${this.getKey()}" err :`,s),this.handleConnectError(s),s}))}getID(){return this.id}getKey(){return this.key}isActive(){return this.status==="activated"}getStatus(){return this.status}getCondition(e){return this.conditions[e]}broadcast(e,t,n,s){if(!this.isActive())throw new w(y.ErrClientNotActivated,`${this.key} is not active`);const i=this.attachmentMap.get(e);if(!i)throw new w(y.ErrDocumentNotAttached,`${e} is not attached`);if(!Cy(n))throw new w(y.ErrInvalidArgument,"payload is not serializable");const o=(s==null?void 0:s.maxRetries)??Mo.maxRetries,a=Mo.maxBackoff;let u=0;const l=g=>Math.min(Mo.initialRetryInterval*2**g,a),h=async()=>this.enqueueTask(async()=>this.rpcClient.broadcast({clientId:this.id,documentId:i.docID,topic:t,payload:new TextEncoder().encode(JSON.stringify(n))},{headers:{"x-shard-key":`${this.apiKey}/${e}`}}).then(()=>{z.info(`[BC] c:"${this.getKey()}" broadcasts d:"${e}" t:"${t}"`)}).catch(g=>{if(z.error(`[BC] c:"${this.getKey()}" err:`,g),this.handleConnectError(g))if(uh(),l(u-1)),z.info(`[BC] c:"${this.getKey()}" retry attempt ${u}/${o}`);else throw z.error(`[BC] c:"${this.getKey()}" exceeded maximum retry attempts`),g;else throw g}));return h()}runSyncLoop(){const e=()=>{if(!this.isActive()){z.debug(`[SL] c:"${this.getKey()}" exit sync loop`),this.conditions.SyncLoop=!1;return}const t=[];for(const[,n]of this.attachmentMap)n.needRealtimeSync()&&(n.remoteChangeEventReceived=!1,t.push(this.syncInternal(n,n.syncMode)));Promise.all(t).then(()=>setTimeout(e,this.syncLoopDuration)).catch(n=>{z.error(`[SL] c:"${this.getKey()}" sync failed:`,n),this.handleConnectError(n)?setTimeout(e,this.retrySyncLoopDelay):this.conditions.SyncLoop=!1})};z.debug(`[SL] c:"${this.getKey()}" run sync loop`),this.conditions.SyncLoop=!0,e()}async runWatchLoop(e){const t=this.attachmentMap.get(e);if(!t)throw new w(y.ErrDocumentNotAttached,`${e} is not attached`);return this.conditions.WatchLoop=!0,t.runWatchLoop(n=>{if(!this.isActive())return this.conditions.WatchLoop=!1,Promise.reject(new w(y.ErrClientNotActivated,`${this.key} is not active`));const s=new AbortController,i=this.rpcClient.watchDocument({clientId:this.id,documentId:t.docID},{headers:{"x-shard-key":`${this.apiKey}/${e}`},signal:s.signal});return t.doc.publish([{type:Le.ConnectionChanged,value:ka.Connected}]),z.info(`[WD] c:"${this.getKey()}" watches d:"${e}"`),new Promise((o,a)=>{(async()=>{try{for await(const l of i)this.handleWatchDocumentsResponse(t,l),l.body.case==="initialization"&&o([i,s])}catch(l){t.doc.resetOnlineClients(),t.doc.publish([{type:Le.Initialized,source:se.Local,value:t.doc.getPresences()}]),t.doc.publish([{type:Le.ConnectionChanged,value:ka.Disconnected}]),z.debug(`[WD] c:"${this.getKey()}" unwatches`),this.handleConnectError(l)?n():this.conditions.WatchLoop=!1,a(l)}})()})})}handleWatchDocumentsResponse(e,t){if(t.body.case==="event"&&t.body.value.type===Mn.DOCUMENT_CHANGED){e.remoteChangeEventReceived=!0;return}e.doc.applyWatchStream(t)}deactivateInternal(){this.status="deactivated";for(const[e,t]of this.attachmentMap)this.detachInternal(e),t.doc.applyStatus(ln.Detached)}detachInternal(e){const t=this.attachmentMap.get(e);t&&(t.cancelWatchStream(),t.unsubscribeBroadcastEvent(),this.attachmentMap.delete(e))}syncInternal(e,t){const{doc:n,docID:s}=e,i=n.createChangePack();return this.rpcClient.pushPullChanges({clientId:this.id,documentId:s,changePack:me.toChangePack(i),pushOnly:t==="realtime-pushonly"},{headers:{"x-shard-key":`${this.apiKey}/${n.getKey()}`}}).then(o=>{const a=me.fromChangePack(o.changePack);if(a.hasChanges()&&(e.syncMode==="realtime-pushonly"||e.syncMode==="realtime-syncoff"))return n;n.applyChangePack(a),e.doc.publish([{type:Le.SyncStatusChanged,value:Ea.Synced}]),n.getStatus()===ln.Removed&&this.detachInternal(n.getKey());const u=n.getKey(),l=a.getChangeSize();return z.info(`[PP] c:"${this.getKey()}" sync d:"${u}", push:${i.getChangeSize()} pull:${l} cp:${a.getCheckpoint().toTestString()}`),n}).catch(o=>{throw n.publish([{type:Le.SyncStatusChanged,value:Ea.SyncFailed}]),z.error(`[PP] c:"${this.getKey()}" err :`,o),o})}handleConnectError(e){return e instanceof we?e.code===te.Canceled||e.code===te.Unknown||e.code===te.ResourceExhausted||e.code===te.Unavailable?!0:((zu(e)===y.ErrClientNotActivated||zu(e)===y.ErrClientNotFound)&&this.deactivateInternal(),!1):!1}enqueueTask(e){return new Promise((t,n)=>{this.taskQueue.push(()=>e().then(t).catch(n)),this.processing||this.processNext()})}async processNext(){if(this.taskQueue.length===0){this.processing=!1;return}try{this.processing=!0,await this.taskQueue.shift()()}catch{z.error(`[TQ] c:"${this.getKey()}" process failed, id:"${this.id}"`)}this.processNext()}}const Yf={Client:Gf,Document:Hf,Primitive:le,Text:wo,Counter:bo,Tree:To,LogLevel:Be,setLogLevel:zf,IntType:Vt.IntegerCnt,LongType:Vt.LongCnt};typeof globalThis<"u"&&(globalThis.yorkie={Client:Gf,Document:Hf,Primitive:le,Text:wo,Counter:bo,Tree:To,LogLevel:Be,setLogLevel:zf,IntType:Vt.IntegerCnt,LongType:Vt.LongCnt});const Ny=(r,e)=>{const t=r.__vccOpts||r;for(const[n,s]of e)t[n]=s;return t},Py=[{title:"Todo",cards:[{title:"Pruning document"},{title:"Clean up codes"}]},{title:"Doing",cards:[{title:"Array operations"}]},{title:"Done",cards:[{title:"Create a sample page"},{title:"Launch demo site"}]}],cn=new Yf.Client("https://api.yorkie.dev",{apiKey:"cedaovjuioqlk4pjqn6g"}),Wt=new Yf.Document(`vuejs-kanban-${new Date().toISOString().substring(0,10).replace(/-/g,"")}`,{enableDevtools:!0}),Oy={data(){return{lists:[],title:"",opened:null}},created(){this.fetchDoc()},beforeUnmount(){this.disconnect()},watch:{opened(r){this.$nextTick(function(){r===0?this.$refs.addListForm.querySelector("input").focus():r&&this.$refs.addCardForm[r-1].querySelector("input").focus(),this.title=""})}},methods:{async fetchDoc(){await cn.activate(),await cn.attach(Wt),Wt.update(r=>{r.lists||(r.lists=Py)},"create default list if not exists"),Wt.subscribe(r=>{this.lists=Wt.getRoot().lists}),await cn.sync(),this.lists=Wt.getRoot().lists},async disconnect(){await cn.deactivate()},isOpened(r){return this.opened===r},openForm(r){this.opened=r},closeForm(){this.opened=null},addCard(r){this.title!==""&&Wt.update(e=>{e.lists.getElementByID(r.getID()).cards.push({title:this.title}),this.title=""},`add new card by ${cn.getID()}`)},deleteCard(r,e){Wt.update(t=>{t.lists.getElementByID(r.getID()).cards.deleteByID(e.getID())},`delete a card by ${cn.getID()}`)},addList(){this.title!==""&&Wt.update(r=>{r.lists.push({title:this.title,cards:[]}),this.title=""},`add new list by ${cn.getID()}`)},deleteList(r){Wt.update(e=>{e.lists.deleteByID(r.getID())},`delete a list by ${cn.getID()}`)}}},Dy={class:"list"},By=["onClick"],Ry={class:"title"},Fy={class:"card"},Ly=["onClick"],Jy={key:0,class:"add-form"},My=["onKeyup"],$y={class:"buttons"},Uy=["onClick"],qy=["onClick"],Vy={class:"add-list",ref:"addListForm"},zy={key:0,class:"add-form"},Ky={class:"buttons"};function jy(r,e,t,n,s,i){return Kt(),jt(Ge,null,[(Kt(!0),jt(Ge,null,Lc(s.lists,(o,a)=>(Kt(),jt("div",Dy,[Oe("span",{class:"delete",onClick:u=>i.deleteList(o)},"❌",8,By),Oe("div",Ry,xc(o.title),1),(Kt(!0),jt(Ge,null,Lc(o.cards,u=>(Kt(),jt("div",Fy,[Oe("span",{class:"delete",onClick:l=>i.deleteCard(o,u)},"❌",8,Ly),Ll(" "+xc(u.title),1)]))),256)),Oe("div",{class:"add-card",ref_for:!0,ref:"addCardForm"},[i.isOpened(a+1)?(Kt(),jt("div",Jy,[Fc(Oe("input",{type:"text",placeholder:"Enter card title","onUpdate:modelValue":e[0]||(e[0]=u=>s.title=u),onKeyup:[ui(u=>i.addCard(o),["enter"]),e[1]||(e[1]=ui(u=>i.closeForm(),["esc"]))]},null,40,My),[[nu,s.title]]),Oe("div",$y,[Oe("input",{type:"button",value:"Add",onClick:u=>i.addCard(o)},null,8,Uy),Oe("input",{type:"button",value:"Close",class:"pull-right",onClick:e[2]||(e[2]=u=>i.closeForm())})])])):(Kt(),jt("div",{key:1,class:"add-card-opener",onClick:u=>i.openForm(a+1)}," Add another card ",8,qy))],512)]))),256)),Oe("div",Vy,[i.isOpened(0)?(Kt(),jt("div",zy,[Fc(Oe("input",{type:"text",placeholder:"Enter list title","onUpdate:modelValue":e[3]||(e[3]=o=>s.title=o),onKeyup:[e[4]||(e[4]=ui(o=>i.addList(),["enter"])),e[5]||(e[5]=ui(o=>i.closeForm(),["esc"]))]},null,544),[[nu,s.title]]),Oe("div",Ky,[Oe("input",{type:"button",value:"Add",onClick:e[6]||(e[6]=o=>i.addList())}),Oe("input",{type:"button",value:"Close",class:"pull-right",onClick:e[7]||(e[7]=o=>i.closeForm())})])])):(Kt(),jt("div",{key:1,class:"add-list-opener",onClick:e[8]||(e[8]=o=>i.openForm(0))}," Add another list "))],512)],64)}const Wy=Ny(Oy,[["render",jy]]);Sg(Wy).mount("#app"); diff --git a/examples/vuejs-kanban/index.html b/examples/vuejs-kanban/index.html index 2c44af08a..cc6386330 100644 --- a/examples/vuejs-kanban/index.html +++ b/examples/vuejs-kanban/index.html @@ -6,7 +6,7 @@ Vite App - +