@jant/core 0.3.38 → 0.3.40

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (1181) hide show
  1. package/LICENSE +189 -189
  2. package/README.md +6 -4
  3. package/bin/commands/assets/prepare.js +55 -0
  4. package/bin/commands/db/execute-file.js +113 -0
  5. package/bin/commands/db/export.js +5 -0
  6. package/bin/commands/db/rehearse.js +65 -0
  7. package/bin/commands/deploy.js +162 -0
  8. package/bin/commands/export.js +73 -75
  9. package/bin/commands/import-site.js +1531 -267
  10. package/bin/commands/migrate.js +79 -0
  11. package/bin/commands/reset-password.js +80 -7
  12. package/bin/commands/site/export.js +415 -0
  13. package/bin/commands/site/import.js +5 -0
  14. package/bin/commands/site/localize-media.js +118 -0
  15. package/bin/commands/site/snapshot/export.js +357 -0
  16. package/bin/commands/site/snapshot/import.js +363 -0
  17. package/bin/commands/start.js +46 -0
  18. package/bin/commands/uploads/cleanup.js +119 -0
  19. package/bin/jant.js +55 -15
  20. package/bin/lib/cli-api-token.js +6 -0
  21. package/bin/lib/d1-query.js +194 -0
  22. package/bin/lib/load-node-runtime.js +10 -0
  23. package/bin/lib/migration-artifacts.js +99 -0
  24. package/bin/lib/migration-rehearsal.js +438 -0
  25. package/bin/lib/migration-runner.js +311 -0
  26. package/bin/lib/node-database.js +48 -0
  27. package/bin/lib/node-sqlite.js +158 -0
  28. package/bin/lib/public-assets.js +66 -0
  29. package/bin/lib/r2-query.js +170 -0
  30. package/bin/lib/runtime-target.js +33 -0
  31. package/bin/lib/site-localize-media.js +427 -0
  32. package/bin/lib/site-media-parser.js +1150 -0
  33. package/bin/lib/site-selection.js +222 -0
  34. package/bin/lib/site-snapshot.js +484 -0
  35. package/bin/lib/site-url.js +84 -0
  36. package/bin/lib/sql-export.js +194 -0
  37. package/bin/lib/wrangler-cli.js +41 -0
  38. package/bin/lib/wrangler-config.js +86 -0
  39. package/dist/app-CAtsuLLh.js +30644 -0
  40. package/dist/client/_assets/chunks/0041f681602cc834bb5c55ced0155b8e-BNpHLJgt.woff2 +0 -0
  41. package/dist/client/_assets/chunks/008ea9091e332c639ceb18874eacd60c-CygB704Q.woff2 +0 -0
  42. package/dist/client/_assets/chunks/00c9ac960d866ffaf8a866e5939024e2-CqRrlxSi.woff2 +0 -0
  43. package/dist/client/_assets/chunks/02629e5d0a9860b7fe32ec1f0563213a-YvgSIv_V.woff2 +0 -0
  44. package/dist/client/_assets/chunks/02e48e353415a00e0f556608cab33a43-YFgu4zi3.woff2 +0 -0
  45. package/dist/client/_assets/chunks/02faf6bb0ab4d56ada037c0bbaf9b9f7-DUuUM2eo.woff2 +0 -0
  46. package/dist/client/_assets/chunks/031089da45fbfb7dc18ac827bef4c56e-D4ahCOTO.woff2 +0 -0
  47. package/dist/client/_assets/chunks/03ac785139320b7b13bac9c150bf72bf-BG7zubxs.woff2 +0 -0
  48. package/dist/client/_assets/chunks/053bd3d7aec0040d0cc50c261a1f4e3e-BdG4yI0n.woff2 +0 -0
  49. package/dist/client/_assets/chunks/057a3d44d7fc606f113d863376d0ecf0-BsEMbuKV.woff2 +0 -0
  50. package/dist/client/_assets/chunks/0713613227cc4c686c45a279f8bdc166-BzLoJcLo.woff2 +0 -0
  51. package/dist/client/_assets/chunks/0b1f83a3c7e715560a55ad9eb0fb1c94-asGrAhxW.woff2 +0 -0
  52. package/dist/client/_assets/chunks/0c055db157e7a13f3103cc2a6b67fec3-1T6huY_I.woff2 +0 -0
  53. package/dist/client/_assets/chunks/0d3f5cc265cb6c439c517f2c4cebbddf-CmkfpVHX.woff2 +0 -0
  54. package/dist/client/_assets/chunks/0e97f44ebc65384c346fe19bcc52fa20-BJTzmZzt.woff2 +0 -0
  55. package/dist/client/_assets/chunks/10f2b44b3711d3f5bdcc30d373b543d1-BRTxD_6-.woff2 +0 -0
  56. package/dist/client/_assets/chunks/1139d32ae2bdeb26c0c8f31330aa9a9f-B7k4Da0E.woff2 +0 -0
  57. package/dist/client/_assets/chunks/1259e5825b314fe2b8bb96d6e8069ee5-Ba8VoZCg.woff2 +0 -0
  58. package/dist/client/_assets/chunks/12c518ebfe62818af550c08947e359e7-B7eDp07N.woff2 +0 -0
  59. package/dist/client/_assets/chunks/145831a59caa06d894022fe60212ed21-B3xSIk4b.woff2 +0 -0
  60. package/dist/client/_assets/chunks/14b040a2dda256936bc7b3470e548394-CF7zgNWs.woff2 +0 -0
  61. package/dist/client/_assets/chunks/14c1506106d92621bafb11016735194e-cbk_paoP.woff2 +0 -0
  62. package/dist/client/_assets/chunks/154a2c266902003bd8b7449386b10776-CYgd0apt.woff2 +0 -0
  63. package/dist/client/_assets/chunks/15f8c0df47fd639d1b0d9bd5cf507c9b-B11bYwtn.woff2 +0 -0
  64. package/dist/client/_assets/chunks/1668bd859ffe15bed7d5563117d8d5fb-DJotYU-j.woff2 +0 -0
  65. package/dist/client/_assets/chunks/169a096e61d38a773216f51d1ec2cc06-CzS4CZjy.woff2 +0 -0
  66. package/dist/client/_assets/chunks/1884a2b22d314c7d57707f03aec348e0-BdBJ4_JO.woff2 +0 -0
  67. package/dist/client/_assets/chunks/189f272ea2600c74d576b7b15c014922-CylwUmhO.woff2 +0 -0
  68. package/dist/client/_assets/chunks/190e3f8632494e7c095117f26b1c811e-DT09KhZe.woff2 +0 -0
  69. package/dist/client/_assets/chunks/19ad151c22ce1befe0a9ea643fbee570-BOjbPzxL.woff2 +0 -0
  70. package/dist/client/_assets/chunks/19e39850472250bfdbce654d30859879-Db8MVQ-5.woff2 +0 -0
  71. package/dist/client/_assets/chunks/1b5d0d740450fb996749464c9b882025-BG0yepI2.woff2 +0 -0
  72. package/dist/client/_assets/chunks/1bca0a2a8840ad0ee9414940593db144-CfiRZ0Fs.woff2 +0 -0
  73. package/dist/client/_assets/chunks/1c820b5295868008ca7c78afa5b7655d-rGkaVY0Z.woff2 +0 -0
  74. package/dist/client/_assets/chunks/1cda27dcaab977ae4ef5d5ab2a10ae03-3n1CbajX.woff2 +0 -0
  75. package/dist/client/_assets/chunks/1e2640116bbba817f43c43cc69371cf1-BLnekPNy.woff2 +0 -0
  76. package/dist/client/_assets/chunks/1f4bc38a1c50f55f335f5411cae47696-3J1JFXeu.woff2 +0 -0
  77. package/dist/client/_assets/chunks/1fbccc182322b513f57cd156a9a491b0-bRVH28a5.woff2 +0 -0
  78. package/dist/client/_assets/chunks/1fbe225742c69f4ba9ea5f74922f0ca1-BHRIiKDB.woff2 +0 -0
  79. package/dist/client/_assets/chunks/2022cf097cb952d9fe75b53b4587d2c3-Btdq5ZEB.woff2 +0 -0
  80. package/dist/client/_assets/chunks/21e0a71d86be7b8a9e812e7af09dd061-SSZaQU5Z.woff2 +0 -0
  81. package/dist/client/_assets/chunks/2240a3c43ca5ef59ae3c348c7884792f-DQgT8QLe.woff2 +0 -0
  82. package/dist/client/_assets/chunks/2573703213da30d3ba18925b100b2c2b-D61uHyrJ.woff2 +0 -0
  83. package/dist/client/_assets/chunks/265e048cc9f2f8a711ba585a534d5351-geHDzSNf.woff2 +0 -0
  84. package/dist/client/_assets/chunks/26839c0e47c73514b8d8f660d24d6b19-D2gmzZl-.woff2 +0 -0
  85. package/dist/client/_assets/chunks/280e3d2b58e9ad3501816072e01b0c13-Dx5yDwjz.woff2 +0 -0
  86. package/dist/client/_assets/chunks/2874d07e228da9583b0e73646dacd498-26mUURU-.woff2 +0 -0
  87. package/dist/client/_assets/chunks/29d49891713a2785a3a383001cf58c59-DVb6JpZh.woff2 +0 -0
  88. package/dist/client/_assets/chunks/2a22e14a9ad53f2abb3c7e85017b7d12-CU_4APNf.woff2 +0 -0
  89. package/dist/client/_assets/chunks/2a7cedfcd6e4c7cec36f4fd7b0f329c2-BUp7BYdq.woff2 +0 -0
  90. package/dist/client/_assets/chunks/2acea04a920f6af31e7db97052f563c6-KdL2n7-Y.woff2 +0 -0
  91. package/dist/client/_assets/chunks/2ae2ca951489c9d50cde5b36a2a5515b-CWV12jwD.woff2 +0 -0
  92. package/dist/client/_assets/chunks/2b3e8c5703b91f39f6027f43f0da6f4b-FHYDvFqX.woff2 +0 -0
  93. package/dist/client/_assets/chunks/2ba802b14f21a58fc61606c88fa93373-BmrW6szo.woff2 +0 -0
  94. package/dist/client/_assets/chunks/2d81eb6ab0ebbc0cabfb3a3341ba8800-Ds2YcMj0.woff2 +0 -0
  95. package/dist/client/_assets/chunks/2deb444546774c3a3ab38c75eb69cdfb-Dm9USQXk.woff2 +0 -0
  96. package/dist/client/_assets/chunks/2e98b666924b8e0a09d1aeeefd24bdd2-Cmh3DrKG.woff2 +0 -0
  97. package/dist/client/_assets/chunks/2f27ee4fb2cf6a280e110e09c18ef73e-D_yYWYMZ.woff2 +0 -0
  98. package/dist/client/_assets/chunks/2fbccf9a3853eb59db1a825e044515fd-CiShE3Wo.woff2 +0 -0
  99. package/dist/client/_assets/chunks/2fd3fceb6faed5e3db768e88d7614dca-D74stxc-.woff2 +0 -0
  100. package/dist/client/_assets/chunks/2ff009fa8701505d7f3dc6c83763f019-nkOuUfA-.woff2 +0 -0
  101. package/dist/client/_assets/chunks/31342cebfa5ea7fac06b4ea372d96bc5-DdIH_TkU.woff2 +0 -0
  102. package/dist/client/_assets/chunks/31424fe5d54692e7c8b38021ccb8597c-CfNu45zJ.woff2 +0 -0
  103. package/dist/client/_assets/chunks/3179006d1c7ebfa50d27482a2859d9a0-e7PNUH9y.woff2 +0 -0
  104. package/dist/client/_assets/chunks/34c2edb3c37f71258f5c4a31091f0c6c-Cyr8VjPf.woff2 +0 -0
  105. package/dist/client/_assets/chunks/35cf5dd04315e0b906e1a413d7905a2f-A-QPUrVX.woff2 +0 -0
  106. package/dist/client/_assets/chunks/360c190344c26278bbc50e2f4d6a2b3f-B7OhzvgR.woff2 +0 -0
  107. package/dist/client/_assets/chunks/375329ba0b50b94b35006498e555867c-CDc5XB7_.woff2 +0 -0
  108. package/dist/client/_assets/chunks/387c811226f303af62f1e21aae6f5c83-BmPYUAdb.woff2 +0 -0
  109. package/dist/client/_assets/chunks/389a950f2a1211946d294716e679e381-Diuxk8JN.woff2 +0 -0
  110. package/dist/client/_assets/chunks/39b0bbc910af9d2d6dcd8bd4abd6387d-NhvZf71d.woff2 +0 -0
  111. package/dist/client/_assets/chunks/3adc8f6350cf5067bcb6dc5e44c45d41-DIO3oy0b.woff2 +0 -0
  112. package/dist/client/_assets/chunks/3b41385fc27419c19822060daa0b5cb3-Dh5JVnsu.woff2 +0 -0
  113. package/dist/client/_assets/chunks/3bed5bd57de8f738e53cddaea88983d9-BAGVbLtM.woff2 +0 -0
  114. package/dist/client/_assets/chunks/3c201fd8d1bb20abe7d06b940e83a4d9-Bz0dCLvM.woff2 +0 -0
  115. package/dist/client/_assets/chunks/3cbe4a697fd595ef42c899de7d3e5445-zWwFRRI_.woff2 +0 -0
  116. package/dist/client/_assets/chunks/3d385ea0880df7204258e290648ec012-BQqoFH8R.woff2 +0 -0
  117. package/dist/client/_assets/chunks/3d83dacbbec3d8532ae9afede21f3aab-BH06SEJj.woff2 +0 -0
  118. package/dist/client/_assets/chunks/3dc1a4f0d7af59e16b5162a2b077a442-CkXZW3CY.woff2 +0 -0
  119. package/dist/client/_assets/chunks/3dc68e473fe23bd076dd46785cd23583-Cv6HZ0Dr.woff2 +0 -0
  120. package/dist/client/_assets/chunks/427577dcb707d1d35eebd155b4222aa7-D7-mHA6o.woff2 +0 -0
  121. package/dist/client/_assets/chunks/42a74b6a625bbf0a9616ed4db3152c88-CQ58KTMS.woff2 +0 -0
  122. package/dist/client/_assets/chunks/435b7dca567809813fcb395a27ed83a0-C6E3YXBr.woff2 +0 -0
  123. package/dist/client/_assets/chunks/43693195e775d515689fa035394067fd-DLMrklI6.woff2 +0 -0
  124. package/dist/client/_assets/chunks/43fb49e5b79ee7e553869d84e6e08b1e-BgOVrd59.woff2 +0 -0
  125. package/dist/client/_assets/chunks/44dcbbc3cc8f22e613b342d691511ab6-dRyYwGGi.woff2 +0 -0
  126. package/dist/client/_assets/chunks/450a5b53be0a8a778bb0b623e86b652f-qwII2gXW.woff2 +0 -0
  127. package/dist/client/_assets/chunks/457485e72835364662dfead6281638c1-Mv279UyL.woff2 +0 -0
  128. package/dist/client/_assets/chunks/47479c470fae70f10b7c964a7ecbf274-D9VNBclD.woff2 +0 -0
  129. package/dist/client/_assets/chunks/474fac21b12b7efd71f7c321578878b0-BJRz_Yd3.woff2 +0 -0
  130. package/dist/client/_assets/chunks/477866c8396474a17317dcac3e7a014f-e90LWIFy.woff2 +0 -0
  131. package/dist/client/_assets/chunks/478ebdaadda7775c391c5dcab4e697df-RfXJJ1gl.woff2 +0 -0
  132. package/dist/client/_assets/chunks/488846410760fe128dae939836ca5423-D0YbXQOX.woff2 +0 -0
  133. package/dist/client/_assets/chunks/48d6a97a185c799be4fe67aaf7edf213-CqLkiJik.woff2 +0 -0
  134. package/dist/client/_assets/chunks/48eb0a91e50c7f026e248c64145e72af-D8LB2Dye.woff2 +0 -0
  135. package/dist/client/_assets/chunks/490edb9fc8a4356aea556eed32287464-Bxk-XtyT.woff2 +0 -0
  136. package/dist/client/_assets/chunks/4a23fe6e82fd496b5eb20401b6164efe-CfhsfLd6.woff2 +0 -0
  137. package/dist/client/_assets/chunks/4b0e79ba18b2ce424fa93e84996d7cba-B0dS4UvF.woff2 +0 -0
  138. package/dist/client/_assets/chunks/4bc743968cf1c3ce5711de67ef1ccc4d-Dmn20LlT.woff2 +0 -0
  139. package/dist/client/_assets/chunks/4c4bdd0b3f3a52e28f3b643c1c5d43be-BLqyuzyK.woff2 +0 -0
  140. package/dist/client/_assets/chunks/4c96411f3693a9a8657a9c1190f82bce-BhP7AS2j.woff2 +0 -0
  141. package/dist/client/_assets/chunks/4c9aa12aba2a6a57410eacaff7427916-CLDZgzM7.woff2 +0 -0
  142. package/dist/client/_assets/chunks/4cca7233bf8ce5dec2e5d146b993d626-Bf7OgJe6.woff2 +0 -0
  143. package/dist/client/_assets/chunks/4cf0f292f3358bd2f73b1cf4ec1476f3-CIfjw85D.woff2 +0 -0
  144. package/dist/client/_assets/chunks/4d0a9128d06ea857f203bf5d007b1ab9-BZ-BuqS9.woff2 +0 -0
  145. package/dist/client/_assets/chunks/4dc0728df0f2ba70796f45f05654c7ba-DGd3NDaT.woff2 +0 -0
  146. package/dist/client/_assets/chunks/4dc2bc2c55b47f57d13b63aa6b1c8bd4-g3WbclK2.woff2 +0 -0
  147. package/dist/client/_assets/chunks/4e1cc6aafb411b572c8d3511e925ecf1-BUf15jYj.woff2 +0 -0
  148. package/dist/client/_assets/chunks/4e5384920bbb155d9d8d74887b09ea5b-2KLteQXT.woff2 +0 -0
  149. package/dist/client/_assets/chunks/501f66f24bce8234441954de1b568403-CIe4N6pO.woff2 +0 -0
  150. package/dist/client/_assets/chunks/50cfd672bfa62512ba090420acf35c87-CibXrwCT.woff2 +0 -0
  151. package/dist/client/_assets/chunks/5227dbe9933760a48baff21ebd13fc98-v8CBITMX.woff2 +0 -0
  152. package/dist/client/_assets/chunks/526b263e72c189f4b065738aaa6d423a-Dj5Ns6Ev.woff2 +0 -0
  153. package/dist/client/_assets/chunks/53a88404451448cd2e620a0ca0e45a20-CI0P5NCv.woff2 +0 -0
  154. package/dist/client/_assets/chunks/54da934819a917f561b439bfd10f88b6-CpoNRhz7.woff2 +0 -0
  155. package/dist/client/_assets/chunks/54e301f412730f391225db59dae1c8d5-CxTAz9F1.woff2 +0 -0
  156. package/dist/client/_assets/chunks/551b1d7a0b80c8d42af09863cdca7f01-BIGKH8GS.woff2 +0 -0
  157. package/dist/client/_assets/chunks/555d990ab3fd7d3d66c6d1fa9a82fec5-BndAe6f2.woff2 +0 -0
  158. package/dist/client/_assets/chunks/557cd00c5d6827e13d72a0c71b23587b-C6gpr-g-.woff2 +0 -0
  159. package/dist/client/_assets/chunks/563fa31542d553f25abab65cf7f81e1d-Cl_1me5X.woff2 +0 -0
  160. package/dist/client/_assets/chunks/56e1c4734bbbb38af2fbc262bf6e98f2-DZ32amUx.woff2 +0 -0
  161. package/dist/client/_assets/chunks/5947f5da5da9a352a2b534ee64bfc29a-DT0Fj-SL.woff2 +0 -0
  162. package/dist/client/_assets/chunks/5979c33a7eb5963bf8e83e46931b5fb5--4f9yv1z.woff2 +0 -0
  163. package/dist/client/_assets/chunks/597d69d0710e0178b162afb0a0c20401-CpThXFdo.woff2 +0 -0
  164. package/dist/client/_assets/chunks/59966ee0b069b577510fe68c350da0ee-Bs_HDvyP.woff2 +0 -0
  165. package/dist/client/_assets/chunks/5a10741e41259e235841440394c0763d-uCZGOg0A.woff2 +0 -0
  166. package/dist/client/_assets/chunks/5bfc7a121c35ae42623ef804fb525e0e-mS7vyFFz.woff2 +0 -0
  167. package/dist/client/_assets/chunks/5cc23a76e122d0ad2f7cede41bc35b27-4T1ZVQJu.woff2 +0 -0
  168. package/dist/client/_assets/chunks/5d48855bed5f3554eff91b573d7376ac-CPzsdNDF.woff2 +0 -0
  169. package/dist/client/_assets/chunks/5ddcbe564b29ef08632e1aeb33455435-CQzDKa-z.woff2 +0 -0
  170. package/dist/client/_assets/chunks/5f90024544c2907c6c0203c6210c50be-C_1uxIky.woff2 +0 -0
  171. package/dist/client/_assets/chunks/605667a998e91e2b6a4a3cd7c31fe5a9-Co2lOjER.woff2 +0 -0
  172. package/dist/client/_assets/chunks/60a14064ed334f0155795d795e926abe-C2HuVyw5.woff2 +0 -0
  173. package/dist/client/_assets/chunks/60d8b0805a0a8c54a6cca216004beff5-CV1GX5br.woff2 +0 -0
  174. package/dist/client/_assets/chunks/611b62d5fd9698d9b5ce495ba6f14c93-CPi2xRKF.woff2 +0 -0
  175. package/dist/client/_assets/chunks/61bf4287453da4025d03fa6b2dba66ca-CMh4XzzB.woff2 +0 -0
  176. package/dist/client/_assets/chunks/638369541268ed5a10af97ad77498c73-DrpvGu-L.woff2 +0 -0
  177. package/dist/client/_assets/chunks/649b12d7cee7bb981842946e4547e6ca-EACt8KkC.woff2 +0 -0
  178. package/dist/client/_assets/chunks/653bef2ed891ae48d8ed712283080649-C3d1ZTAc.woff2 +0 -0
  179. package/dist/client/_assets/chunks/67d2a81f06ba352f17fbdc3a5e6ea59e-DC8Iostn.woff2 +0 -0
  180. package/dist/client/_assets/chunks/67f32ceea9e78e5109f87724ad886010-C_3-9sSn.woff2 +0 -0
  181. package/dist/client/_assets/chunks/68304f3229cf763465f044fccb5892c0-CTvPlN8c.woff2 +0 -0
  182. package/dist/client/_assets/chunks/687d0f0f90a9b23e40102e16ad8e9836-Bzlx1W-7.woff2 +0 -0
  183. package/dist/client/_assets/chunks/688a88911e4da17b609196a959b8b930-BgwP4zIQ.woff2 +0 -0
  184. package/dist/client/_assets/chunks/68f2fab82ec8e9291f08c3145111549c-CXqagiiH.woff2 +0 -0
  185. package/dist/client/_assets/chunks/69519ada3f3f74ca20aacb8af48ab6b4-DncDOElk.woff2 +0 -0
  186. package/dist/client/_assets/chunks/6a6e884fb2b65ec5b4a3d5ecd0d01a6a-DBNJo4jq.woff2 +0 -0
  187. package/dist/client/_assets/chunks/6db6ddf72c38a78ce44c1327701152e1-CFUWMaQQ.woff2 +0 -0
  188. package/dist/client/_assets/chunks/6e1a8b45b01939088c3a8cfcf8c10681-BemqZSaI.woff2 +0 -0
  189. package/dist/client/_assets/chunks/6e2164fad867d166de2e5b274f04a563-_YD_QMym.woff2 +0 -0
  190. package/dist/client/_assets/chunks/6e83fe0b6e708eaf1c3003d6dee11488-CRqY8z2g.woff2 +0 -0
  191. package/dist/client/_assets/chunks/6eefc9d430171c1e1e4034ecadee31c8-d3VCnQ01.woff2 +0 -0
  192. package/dist/client/_assets/chunks/70861376e5d4f92f8aa7aa1b2749b617-BqwxmSo2.woff2 +0 -0
  193. package/dist/client/_assets/chunks/70adaf50c56d5ff859c64d35e0f1e34e-BCmTRExx.woff2 +0 -0
  194. package/dist/client/_assets/chunks/7124d150570d39ced8d45507dc11ca1e-Co_mUkqP.woff2 +0 -0
  195. package/dist/client/_assets/chunks/71eafb8fbe3a734283517e230ad8b6db-CFmZ-qAS.woff2 +0 -0
  196. package/dist/client/_assets/chunks/72ee453ac0e19bd2c631c8921c44e3de-CEidyyfI.woff2 +0 -0
  197. package/dist/client/_assets/chunks/751f54dbb115140d5b645a6ba4aff5d3-DY-S96zI.woff2 +0 -0
  198. package/dist/client/_assets/chunks/753b5f6fb254bacb6618ace25af3df60-uBG6c32o.woff2 +0 -0
  199. package/dist/client/_assets/chunks/7609e7e74dd4d916a7abc7ecc7d95f7e-CzrNhght.woff2 +0 -0
  200. package/dist/client/_assets/chunks/76b9d6fe838ae4151d95ce7200aa2bf6-BfQWDykU.woff2 +0 -0
  201. package/dist/client/_assets/chunks/76d4244186d118eea245d1385a4de2ec-CEoql1pw.woff2 +0 -0
  202. package/dist/client/_assets/chunks/77a7533bd21ccd33192d142a93555aa8-BzSb8ker.woff2 +0 -0
  203. package/dist/client/_assets/chunks/78ce29fed872e44fc9014d94875d2aac-D1BDuJXp.woff2 +0 -0
  204. package/dist/client/_assets/chunks/79a7fdf7d9c722b5723ae25e6ff8e203-5rPAnIr7.woff2 +0 -0
  205. package/dist/client/_assets/chunks/79a85a253e9b3f12d2e2cb15e16b3003-DTjWGv2X.woff2 +0 -0
  206. package/dist/client/_assets/chunks/7a86b155111ba20f3e87306ff6beac77-DchSNxJ1.woff2 +0 -0
  207. package/dist/client/_assets/chunks/7b1e76975b0984e6f83e3f9f8069e784-OB_rGzsR.woff2 +0 -0
  208. package/dist/client/_assets/chunks/7b6c60131822a0e4d36d980d52509d4e-8dQVuUiW.woff2 +0 -0
  209. package/dist/client/_assets/chunks/7caa14a095a6bc313aab780fe4ff7999-BJ-80Ois.woff2 +0 -0
  210. package/dist/client/_assets/chunks/7cbda564cb2dd4799ab9e89d51286aa7-MlT7YRSz.woff2 +0 -0
  211. package/dist/client/_assets/chunks/7d138084cf03c14116b11297fce0e3e3-CdWCcyam.woff2 +0 -0
  212. package/dist/client/_assets/chunks/7d65a3d6a65050eb5e6eca43398aeba4-CYB359u-.woff2 +0 -0
  213. package/dist/client/_assets/chunks/7dfc711962c8771f97e7c8898a6bcb65-Yv69yrg4.woff2 +0 -0
  214. package/dist/client/_assets/chunks/7ef123b62d530fcba73974fa265e0aae-CD7IMlBc.woff2 +0 -0
  215. package/dist/client/_assets/chunks/7f60eefa15956d6f06dd92404887d58c-LqioDjlc.woff2 +0 -0
  216. package/dist/client/_assets/chunks/7f8c15e0ecb102738981d9fa4cb6b921-8qiw7Fmn.woff2 +0 -0
  217. package/dist/client/_assets/chunks/80466082a896fd328f30a78593c7c568-BMAVDyAy.woff2 +0 -0
  218. package/dist/client/_assets/chunks/812b5a4b87f3a7b4afc1cfebc864f413-B4_mWnLK.woff2 +0 -0
  219. package/dist/client/_assets/chunks/812dfb7f8144d01b3cc9d5ce0b472f40-DxhfKDhh.woff2 +0 -0
  220. package/dist/client/_assets/chunks/84742b1ede4f0bb6d27131298eba21b4-4_QYQ-wj.woff2 +0 -0
  221. package/dist/client/_assets/chunks/8555f0285e3d28e95e2fc0ccccd9caff-CEnfoaRy.woff2 +0 -0
  222. package/dist/client/_assets/chunks/880162ae92cd9e120eb4e4e11fae459d-Cj61LKOn.woff2 +0 -0
  223. package/dist/client/_assets/chunks/8a3c84b0df36f851f5fea75ee8757951-CfHrA-x8.woff2 +0 -0
  224. package/dist/client/_assets/chunks/8b0c8c9f8cfa9fa090d97c5a5efb1f4c-DZc3EGF4.woff2 +0 -0
  225. package/dist/client/_assets/chunks/8c8393bc875f1ee36697a2113f4421ea-CnBugeCf.woff2 +0 -0
  226. package/dist/client/_assets/chunks/8dc035a34c76e6515ca203e2df182588-B1reQPCB.woff2 +0 -0
  227. package/dist/client/_assets/chunks/8e04e64c8f68d292a18d4160fbde8671-DkT7v-sd.woff2 +0 -0
  228. package/dist/client/_assets/chunks/8e6c9bb43afb8cbbff7cf1055e67c9bd-c7wzPI7v.woff2 +0 -0
  229. package/dist/client/_assets/chunks/8eb06109812cb80be44f47b8179c2709-DOaU0xD8.woff2 +0 -0
  230. package/dist/client/_assets/chunks/8f2b960c2823670e94f5b08aa65657e6-CHT-Gunr.woff2 +0 -0
  231. package/dist/client/_assets/chunks/8f89f57230d184f92a36e241874229d7-D6P0FMCn.woff2 +0 -0
  232. package/dist/client/_assets/chunks/904324af375d5fd370af1054355a050e-CHiXmgO7.woff2 +0 -0
  233. package/dist/client/_assets/chunks/90ac4f9d2aa02afdace2843b49fc18bb-CWArmWzF.woff2 +0 -0
  234. package/dist/client/_assets/chunks/90b6f57d77847f512fd11db74fa912f1-DzYbq8hW.woff2 +0 -0
  235. package/dist/client/_assets/chunks/911a2092d64d6d6494b254d819af2b91-C0xmZ-Cu.woff2 +0 -0
  236. package/dist/client/_assets/chunks/913759e6690f9fc0746a20b96f4bdcb4-B0k9hqx0.woff2 +0 -0
  237. package/dist/client/_assets/chunks/9154e26efe532a85a27d80902f5a2d6c-DJQmzPmB.woff2 +0 -0
  238. package/dist/client/_assets/chunks/9180de34b48b325200a97e267befff32-ClJx20hD.woff2 +0 -0
  239. package/dist/client/_assets/chunks/94e7ed67f1557b76fead6b6e456a0415-CjAhhvRn.woff2 +0 -0
  240. package/dist/client/_assets/chunks/95127a92346c04fec1fa81d6295b0a28-DNbeXPGm.woff2 +0 -0
  241. package/dist/client/_assets/chunks/958efb9b2fa2ea0008ffef009885f9f8-CNOwBDS1.woff2 +0 -0
  242. package/dist/client/_assets/chunks/95df3b9f681d9df411c30aea5b24f2e0-Dv7GHFVj.woff2 +0 -0
  243. package/dist/client/_assets/chunks/975af5a496e8d87d821910aa9fe4d598-CG5KDMOI.woff2 +0 -0
  244. package/dist/client/_assets/chunks/97a874bbf55ce89a4ab7cd27c7e938b1-fhost-bL.woff2 +0 -0
  245. package/dist/client/_assets/chunks/9ca9b71010a5faeee7047ef97aeee13b-K6NP7P3o.woff2 +0 -0
  246. package/dist/client/_assets/chunks/9cd0b77920b9d6c64eb686493123fc76-Db6wX5BE.woff2 +0 -0
  247. package/dist/client/_assets/chunks/9de02d745b8e25c6411fb152fb067748-CGxZtq8G.woff2 +0 -0
  248. package/dist/client/_assets/chunks/9eb33a430058d839ebbe2af4b2e0daa9-Cjd-WSds.woff2 +0 -0
  249. package/dist/client/_assets/chunks/9ebd27835ffcbd794e67151ab046ce68-DmxtZVr5.woff2 +0 -0
  250. package/dist/client/_assets/chunks/9f5a73aa8ba417688019d628f334db07-P03uxox_.woff2 +0 -0
  251. package/dist/client/_assets/chunks/9fbc06b2e3ff16b9d705c76db563ef17-XDHSv5Te.woff2 +0 -0
  252. package/dist/client/_assets/chunks/9fd53607094e329fa8e5c785b3ff0f1a-B-9qgOdM.woff2 +0 -0
  253. package/dist/client/_assets/chunks/a077f51cfb5cffb4ff4d8e229c0e9e79-BaPgyZ5H.woff2 +0 -0
  254. package/dist/client/_assets/chunks/a0f0c06d5c7a3ffa97706178cce212a8-DN_NE4Ic.woff2 +0 -0
  255. package/dist/client/_assets/chunks/a38c1830367f784181b6f544b0b11bbd-BmPGDXn1.woff2 +0 -0
  256. package/dist/client/_assets/chunks/a397997b579d3945c9c70a979c17a8ad-DXa54wGz.woff2 +0 -0
  257. package/dist/client/_assets/chunks/a3b929542e6c5a0644b73a7c8a8b6c03-B5i2p-Hj.woff2 +0 -0
  258. package/dist/client/_assets/chunks/a578742770fcd2226e3c45b5b6efdcb0-C1QhQdHg.woff2 +0 -0
  259. package/dist/client/_assets/chunks/a68d9d5027803832bb28e78cdcd04949-D_bwWhwg.woff2 +0 -0
  260. package/dist/client/_assets/chunks/a8857f5d478f101c053ba02d2f223e90-CHOaRPpq.woff2 +0 -0
  261. package/dist/client/_assets/chunks/a904b05966368bcf90b632c7c2e5f76b-BbTXYQVh.woff2 +0 -0
  262. package/dist/client/_assets/chunks/a9cf85e27428c14351d30eac8cbc8d91-DMaVc3-8.woff2 +0 -0
  263. package/dist/client/_assets/chunks/aa0ce6740f301351761a0615cc8b2e99-4RL3pitV.woff2 +0 -0
  264. package/dist/client/_assets/chunks/aa218a2c45f3749537ce876201e5152b-DndHqA-p.woff2 +0 -0
  265. package/dist/client/_assets/chunks/aa28db16818f9eaa8c817f289e1c3270-Drm1Jwhe.woff2 +0 -0
  266. package/dist/client/_assets/chunks/aa64c9953af43ca65832f413895bb433-CR32RteD.woff2 +0 -0
  267. package/dist/client/_assets/chunks/aa96d698491c2540e2dcf7009c65c456-BXlPVR0v.woff2 +0 -0
  268. package/dist/client/_assets/chunks/ada8f0241244c60ec8d3d59ad37f20a5-BFQsznEm.woff2 +0 -0
  269. package/dist/client/_assets/chunks/ae25c41034ddc1a9e0b41f5034c9aa4b-COQJkHOc.woff2 +0 -0
  270. package/dist/client/_assets/chunks/ae289ae3f8cdb54a3a6c07174517afec-DFGIoTY6.woff2 +0 -0
  271. package/dist/client/_assets/chunks/ae401fb4db80d5ff5cd3f8d9bc811070-Byt9AwoT.woff2 +0 -0
  272. package/dist/client/_assets/chunks/b02dfa2aa52cbdb1b2f11a9f44335469-DVWsuPSL.woff2 +0 -0
  273. package/dist/client/_assets/chunks/b0ab3a7f319ce6dd3c9a4de2674e7c72-CksmA6Hr.woff2 +0 -0
  274. package/dist/client/_assets/chunks/b159deb135e9946eea0572d52778170b-BZrtOTn0.woff2 +0 -0
  275. package/dist/client/_assets/chunks/b2e326f7f9b807451bf9c745df747efe-BvlONCPB.woff2 +0 -0
  276. package/dist/client/_assets/chunks/b341de0bc0bfe194a6c28dcfb566029e-DJAj3r6U.woff2 +0 -0
  277. package/dist/client/_assets/chunks/b846c293981ca5429eabaa967f222f26-GS-TAaO6.woff2 +0 -0
  278. package/dist/client/_assets/chunks/b91450304d9ac44f5c6e0da0792e055d-vS0S7kl0.woff2 +0 -0
  279. package/dist/client/_assets/chunks/baa325551b381c5e035ef143e56d4abe-DJg3GhKJ.woff2 +0 -0
  280. package/dist/client/_assets/chunks/bc3f0cb8b55ee11d32b94ca488976f8d-Dp5KZMSD.woff2 +0 -0
  281. package/dist/client/_assets/chunks/bcb3307527d6d0033bf0f17660b91e71-BMgRW_eW.woff2 +0 -0
  282. package/dist/client/_assets/chunks/be64f9379412876e00fd3a0bfa6b6fe9-BJ3FMWFM.woff2 +0 -0
  283. package/dist/client/_assets/chunks/befed8a4fa817773fa7109db6fe07f56-3sAmDsOO.woff2 +0 -0
  284. package/dist/client/_assets/chunks/bf1acc86e17b4229c548828a9d6f455d-JNuPCGDM.woff2 +0 -0
  285. package/dist/client/_assets/chunks/c09ee2b219982f8d46ad9968b7e6e0ba-qVb8yJHb.woff2 +0 -0
  286. package/dist/client/_assets/chunks/c0c7836749e585cee24ab2f8457c5b01-Ds0003oT.woff2 +0 -0
  287. package/dist/client/_assets/chunks/c2ac4ef1860812036ca2b8c4e4089bdc-DsziO8Du.woff2 +0 -0
  288. package/dist/client/_assets/chunks/c31019c08bd22464f7a88f090281404c-CUC0jMW1.woff2 +0 -0
  289. package/dist/client/_assets/chunks/c33c59feccf391f0c5f1f5d24e36d1fe-BXTVggad.woff2 +0 -0
  290. package/dist/client/_assets/chunks/c39ec937c6a8d124e8b68cf829ea5ad4-CarrkdmQ.woff2 +0 -0
  291. package/dist/client/_assets/chunks/c3fbc1f2557c343863a10698f8c966a2-BiOC1yo2.woff2 +0 -0
  292. package/dist/client/_assets/chunks/c3fd21315345ae541f6e98067059fa19-rHtO7vK5.woff2 +0 -0
  293. package/dist/client/_assets/chunks/c568a16e3168ceb1f191b70022c492ea-BpAiyU80.woff2 +0 -0
  294. package/dist/client/_assets/chunks/c57ee3b49b7e45b995539a6b2c51f138-IHDXeVRU.woff2 +0 -0
  295. package/dist/client/_assets/chunks/c5c1c0be944ea39a3f50a02d32f5b759-DAwbrvTL.woff2 +0 -0
  296. package/dist/client/_assets/chunks/c5e66d60be3375835bbd8d6b797f6eac-DWp4tpvN.woff2 +0 -0
  297. package/dist/client/_assets/chunks/c5f1075caf6d1344ee720de85114a521-DTTbeLhd.woff2 +0 -0
  298. package/dist/client/_assets/chunks/c82fd9456d7465b5e5bd3659e9b14c55-Cs6h6hE6.woff2 +0 -0
  299. package/dist/client/_assets/chunks/c90b7b65d2b9696fbf3a506738f94d68-DsvgiuQQ.woff2 +0 -0
  300. package/dist/client/_assets/chunks/cae29b3f8951eaf20d2f61c2206e28d9-CoHXmhmG.woff2 +0 -0
  301. package/dist/client/_assets/chunks/cba6ad3981cb7861428d4be169ee8124-CBdFsPAF.woff2 +0 -0
  302. package/dist/client/_assets/chunks/cc26525aa2af1f0b929af32ce50a7fba-D55LVtW9.woff2 +0 -0
  303. package/dist/client/_assets/chunks/cd0e7b51eddb22a77a09b025c0281434-ByI_TSTq.woff2 +0 -0
  304. package/dist/client/_assets/chunks/cd10a3af2133805d8c92104d1ee6ff18-Dtr5mBXe.woff2 +0 -0
  305. package/dist/client/_assets/chunks/cd6d074f3957d58bac58437fc97e5e33-CrVZuSbw.woff2 +0 -0
  306. package/dist/client/_assets/chunks/cd75ca47da9ae4c0899e37d4c543319b-DXU1s4Ja.woff2 +0 -0
  307. package/dist/client/_assets/chunks/cef249b6d013fb0cc0d574176bc23811-BL7WfNHA.woff2 +0 -0
  308. package/dist/client/_assets/chunks/d043b8d7a48bb0ac59ee1f1477d88eee-d5CwY2I8.woff2 +0 -0
  309. package/dist/client/_assets/chunks/d0bd387fda28e58d3c9b3efa2468dd8a-CjDFowFS.woff2 +0 -0
  310. package/dist/client/_assets/chunks/d12ce1d8445213317f9163283e58a05d-4RtGQnak.woff2 +0 -0
  311. package/dist/client/_assets/chunks/d15a3317942b7d31978a759fbf2222c8-DQ9QFQdS.woff2 +0 -0
  312. package/dist/client/_assets/chunks/d28fb13acf9ced9f0657fd4012c81cd2-D8Bgk6sd.woff2 +0 -0
  313. package/dist/client/_assets/chunks/d320b000b5978c7251148a6a154741b8-CcGZjeFx.woff2 +0 -0
  314. package/dist/client/_assets/chunks/d3714e6b90de8e2085dfb2514464dd6a-8LsVAcmb.woff2 +0 -0
  315. package/dist/client/_assets/chunks/d3beff96216c8af1aa79246476b6a323-hQysoMK3.woff2 +0 -0
  316. package/dist/client/_assets/chunks/d3e311f30c811dc339c262a79a51877e-CkUTbS74.woff2 +0 -0
  317. package/dist/client/_assets/chunks/d51f4cdc83711e510f5d25f03235597e-BY3VAGvr.woff2 +0 -0
  318. package/dist/client/_assets/chunks/d5df4a8dfd4328c67d933b3912c6ad0f-A2fccswC.woff2 +0 -0
  319. package/dist/client/_assets/chunks/d740dc2e854aaa7b3dcdd3ed25455eeb-Cw8LrB06.woff2 +0 -0
  320. package/dist/client/_assets/chunks/d8325ba7ae651bc30440905bd67b95f1-Dg8M_ijr.woff2 +0 -0
  321. package/dist/client/_assets/chunks/da13b136efb1d1e4c76575af8f79a698-BbfzLGVB.woff2 +0 -0
  322. package/dist/client/_assets/chunks/da2cf0ec56bf69374ee37764c7e3ea3d-fyVBKE2g.woff2 +0 -0
  323. package/dist/client/_assets/chunks/da93ae099ff3b7aae27b3f674d3fc721-BDG5ywtd.woff2 +0 -0
  324. package/dist/client/_assets/chunks/daf62255dd60679946f28c442ca62533-BnIjYSn3.woff2 +0 -0
  325. package/dist/client/_assets/chunks/dccda6a2e2db3b530788bdfa2acd1979-ByL7eZcn.woff2 +0 -0
  326. package/dist/client/_assets/chunks/dd01a1035345f6921a48525b8ce08f06-vkP6t4fC.woff2 +0 -0
  327. package/dist/client/_assets/chunks/e2204cf85edcb96c5de5c3dcf240da9d-Ch3zKjD-.woff2 +0 -0
  328. package/dist/client/_assets/chunks/e264213b9e102dabc603adb6e4fda5e6-CyxmQBHB.woff2 +0 -0
  329. package/dist/client/_assets/chunks/e3e913e145ddcd9323b2a0972967feb6-3sjEdzck.woff2 +0 -0
  330. package/dist/client/_assets/chunks/e4fb59479cedc87ba79785590bf861ca-sx7RZ8Vu.woff2 +0 -0
  331. package/dist/client/_assets/chunks/e5d00355f73293d40b61299459d17ca5-D8Vt3D-z.woff2 +0 -0
  332. package/dist/client/_assets/chunks/e647b8d2efc501c0cc0e407249cc7135-BrSW9DU4.woff2 +0 -0
  333. package/dist/client/_assets/chunks/e6e60ffb2ebd1828628764b507060aea-Dqyf48QC.woff2 +0 -0
  334. package/dist/client/_assets/chunks/e7c7ef3669ae48c0a736f06ca471e1d7-DNCebEB-.woff2 +0 -0
  335. package/dist/client/_assets/chunks/e81a742cacef744130c40de1b90837d8-DtAIFBk_.woff2 +0 -0
  336. package/dist/client/_assets/chunks/e8b755172122d1d0a5dd453e96b0ff24-BNTSyPYU.woff2 +0 -0
  337. package/dist/client/_assets/chunks/e99280299c305402eaa5271a3e36c49b-BpqXwl7U.woff2 +0 -0
  338. package/dist/client/_assets/chunks/e9c66b085052ece66bfadf45f711d3e1-DVza3Uob.woff2 +0 -0
  339. package/dist/client/_assets/chunks/ed7c6dafaa6d8bcf015ef0ca574837df-C7bcndJl.woff2 +0 -0
  340. package/dist/client/_assets/chunks/f00eb499abb94fa7b799d6d8c9b050e9-D_XvVTI9.woff2 +0 -0
  341. package/dist/client/_assets/chunks/f2900a1d30c3a33129f4e2225669bd0e-in84LilX.woff2 +0 -0
  342. package/dist/client/_assets/chunks/f2fb1f1fbf7e44afb53c672ec286a22e-tFk0sTQc.woff2 +0 -0
  343. package/dist/client/_assets/chunks/f372129c60aaece937cf7b91ee75c9b8-DiP_JYOt.woff2 +0 -0
  344. package/dist/client/_assets/chunks/f5237486197aeff59341a1ff38b8eff8-D_uuqrNZ.woff2 +0 -0
  345. package/dist/client/_assets/chunks/f553d54ef931066712d8f3f0ce018e1b-D8K983U5.woff2 +0 -0
  346. package/dist/client/_assets/chunks/f5d7487963d43c89da63aaf10f2e6fb7-B7GIrfPU.woff2 +0 -0
  347. package/dist/client/_assets/chunks/f649cba8e14c33d6bf2265483b14b895-Nm5wSov8.woff2 +0 -0
  348. package/dist/client/_assets/chunks/f6839df1bf7cb4dc8d27e5ea55bbe633-BIjWKN84.woff2 +0 -0
  349. package/dist/client/_assets/chunks/f6b7304e028980f77a7f7007bb540abd-CIlBt6sf.woff2 +0 -0
  350. package/dist/client/_assets/chunks/f75496953a40ff241178240209f56990-MOSKd67d.woff2 +0 -0
  351. package/dist/client/_assets/chunks/f7d36ffff7a75c9c6216d576a57dd00d-CaXQA5A8.woff2 +0 -0
  352. package/dist/client/_assets/chunks/f7f3f63e7a149cd89eccab3b52171d05-oNOOSdDV.woff2 +0 -0
  353. package/dist/client/_assets/chunks/f8db8bef0a6e1178835d350ae0d384a1-ZAiKM369.woff2 +0 -0
  354. package/dist/client/_assets/chunks/f92d74d1d217d21b39075ff23f79f7fd-BlTe0_IX.woff2 +0 -0
  355. package/dist/client/_assets/chunks/f9d6d981d8b87b3e469027277f585741-DQqIv77a.woff2 +0 -0
  356. package/dist/client/_assets/chunks/fa7d3b99744d7f2dc9e00864a97a62d6-Pfww07DK.woff2 +0 -0
  357. package/dist/client/_assets/chunks/fa8ed469ef290bfeb571418fe0abb628-D5v-Z7kY.woff2 +0 -0
  358. package/dist/client/_assets/chunks/fb0e90665980954719c2eb685b130bc0-CiWRvo58.woff2 +0 -0
  359. package/dist/client/_assets/chunks/fb4649a82c50620773d79820e2e5ff13-dw14czgx.woff2 +0 -0
  360. package/dist/client/_assets/chunks/fb61b690208eff56e6d8432951270901-CUAnVvWa.woff2 +0 -0
  361. package/dist/client/_assets/chunks/fb9402d6c6357a825affc402f14d5a7e-CIp4G53L.woff2 +0 -0
  362. package/dist/client/_assets/chunks/fcc41f6a067ddd658bba5c9dff234a32-BtZTNo2r.woff2 +0 -0
  363. package/dist/client/_assets/chunks/fd6ad889fcf3583bd9b0b6db53aad434-DqiKyYmz.woff2 +0 -0
  364. package/dist/client/_assets/chunks/ff0937ad63cda71ff420945ead55ab4d-CXGPdnOz.woff2 +0 -0
  365. package/dist/client/_assets/chunks/heic-to-XcUDQvtx.js +1 -0
  366. package/dist/client/_assets/chunks/literata-cyrillic-ext-wght-normal-CGKlZYBf.woff2 +0 -0
  367. package/dist/client/_assets/chunks/literata-cyrillic-wght-normal-DLqwHbi6.woff2 +0 -0
  368. package/dist/client/_assets/chunks/literata-greek-ext-wght-normal-e3e57Shi.woff2 +0 -0
  369. package/dist/client/_assets/chunks/literata-greek-wght-normal-CO1l-giJ.woff2 +0 -0
  370. package/dist/client/_assets/chunks/literata-latin-ext-wght-normal-BnEbWgdZ.woff2 +0 -0
  371. package/dist/client/_assets/chunks/literata-latin-wght-normal-DLxlUchJ.woff2 +0 -0
  372. package/dist/client/_assets/chunks/literata-vietnamese-wght-normal-LcSrhZ7T.woff2 +0 -0
  373. package/dist/client/_assets/chunks/module-ChVQstFd.js +716 -0
  374. package/dist/client/_assets/chunks/native-CR5HLOyf.js +1 -0
  375. package/dist/client/_assets/chunks/news-cycle-cyrillic-400-normal-9BSXki1I.woff +0 -0
  376. package/dist/client/_assets/chunks/news-cycle-cyrillic-400-normal-CUYmhJri.woff2 +0 -0
  377. package/dist/client/_assets/chunks/news-cycle-cyrillic-ext-400-normal-CKyb9yaQ.woff2 +0 -0
  378. package/dist/client/_assets/chunks/news-cycle-cyrillic-ext-400-normal-Llxpm7uO.woff +0 -0
  379. package/dist/client/_assets/chunks/news-cycle-greek-400-normal-BiAZ91Zl.woff2 +0 -0
  380. package/dist/client/_assets/chunks/news-cycle-greek-400-normal-D88oNngQ.woff +0 -0
  381. package/dist/client/_assets/chunks/news-cycle-greek-ext-400-normal-Ckclqjrc.woff2 +0 -0
  382. package/dist/client/_assets/chunks/news-cycle-greek-ext-400-normal-oz-bBDWj.woff +0 -0
  383. package/dist/client/_assets/chunks/news-cycle-latin-400-normal-BLgpQ3uo.woff +0 -0
  384. package/dist/client/_assets/chunks/news-cycle-latin-400-normal-BgW97ttO.woff2 +0 -0
  385. package/dist/client/_assets/chunks/news-cycle-latin-ext-400-normal-DmDltzLi.woff2 +0 -0
  386. package/dist/client/_assets/chunks/news-cycle-latin-ext-400-normal-lewDoXxP.woff +0 -0
  387. package/dist/client/_assets/chunks/news-cycle-vietnamese-400-normal-QPSuG-pc.woff +0 -0
  388. package/dist/client/_assets/chunks/news-cycle-vietnamese-400-normal-t2mxI9x9.woff2 +0 -0
  389. package/dist/client/_assets/chunks/newsreader-latin-ext-wght-normal-C-3rgBeH.woff2 +0 -0
  390. package/dist/client/_assets/chunks/newsreader-latin-wght-normal-CCVVNp6i.woff2 +0 -0
  391. package/dist/client/_assets/chunks/newsreader-vietnamese-wght-normal-Czsa-EzN.woff2 +0 -0
  392. package/dist/client/_assets/chunks/source-sans-3-cyrillic-ext-wght-normal-DzyfIafT.woff2 +0 -0
  393. package/dist/client/_assets/chunks/source-sans-3-cyrillic-wght-normal-BMDVbyM7.woff2 +0 -0
  394. package/dist/client/_assets/chunks/source-sans-3-greek-ext-wght-normal-BWSLJLk6.woff2 +0 -0
  395. package/dist/client/_assets/chunks/source-sans-3-greek-wght-normal-C9H9m1vD.woff2 +0 -0
  396. package/dist/client/_assets/chunks/source-sans-3-latin-ext-wght-normal-C8iNium2.woff2 +0 -0
  397. package/dist/client/_assets/chunks/source-sans-3-latin-wght-normal-BqRLTx4X.woff2 +0 -0
  398. package/dist/client/_assets/chunks/source-sans-3-vietnamese-wght-normal-C1uRvKPU.woff2 +0 -0
  399. package/dist/client/_assets/chunks/url-CG0eolsk.js +1 -0
  400. package/dist/client/_assets/client-auth.js +3260 -0
  401. package/dist/client/_assets/client-cjk-tc.css +1 -0
  402. package/dist/client/_assets/client-cjk.css +1 -0
  403. package/dist/client/_assets/client.css +2 -0
  404. package/dist/client/_assets/client.js +380 -0
  405. package/dist/index.js +2 -20359
  406. package/dist/node.js +479 -0
  407. package/package.json +67 -40
  408. package/src/__tests__/bin/uploads-cleanup.test.ts +77 -0
  409. package/src/__tests__/export-service.test.ts +550 -0
  410. package/src/__tests__/helpers/app.ts +60 -27
  411. package/src/__tests__/helpers/db.ts +14 -24
  412. package/src/__tests__/helpers/lingui-core-macro-mock.ts +15 -2
  413. package/src/__tests__/import-site-command.test.ts +406 -0
  414. package/src/__tests__/site-localize-media.test.ts +150 -0
  415. package/src/__tests__/site-media-parser.test.ts +216 -0
  416. package/src/app.tsx +277 -175
  417. package/src/assets/branding/generated/README.txt +15 -0
  418. package/src/assets/branding/generated/jant-apple-touch-icon.png +0 -0
  419. package/src/assets/branding/generated/jant-brand-assets.zip +0 -0
  420. package/src/assets/branding/generated/jant-brand-tile-512.png +0 -0
  421. package/src/assets/branding/generated/jant-brand-tile.svg +1 -0
  422. package/src/assets/branding/generated/jant-circle-tile-512.png +0 -0
  423. package/src/assets/branding/generated/jant-circle-tile.svg +1 -0
  424. package/src/assets/branding/generated/jant-favicon.ico +0 -0
  425. package/src/assets/branding/generated/jant-logo-negative.svg +1 -0
  426. package/src/assets/branding/generated/jant-logo-positive-512.png +0 -0
  427. package/src/assets/branding/generated/jant-logo-positive.svg +1 -0
  428. package/src/assets/branding/generated/jant-social-preview.png +0 -0
  429. package/src/assets/branding/generated/jant-square-tile-512.png +0 -0
  430. package/src/assets/branding/generated/jant-square-tile.svg +1 -0
  431. package/src/assets/branding/jant-logo-positive.svg +3 -0
  432. package/src/auth.ts +47 -6
  433. package/src/client/__tests__/avatar-upload.test.ts +186 -0
  434. package/src/client/__tests__/collection-form-bridge.test.ts +127 -0
  435. package/src/client/__tests__/collection-page-actions.test.ts +112 -0
  436. package/src/client/__tests__/collection-sort-menu.test.ts +78 -0
  437. package/src/client/__tests__/compose-bridge.test.ts +260 -0
  438. package/src/client/__tests__/compose-discovery.test.ts +155 -0
  439. package/src/client/__tests__/compose-shortcuts.test.ts +133 -0
  440. package/src/client/__tests__/confirm.test.ts +98 -0
  441. package/src/client/__tests__/custom-url-menu.test.ts +104 -0
  442. package/src/client/__tests__/form-enter-submit.test.ts +110 -0
  443. package/src/client/__tests__/post-form-bridge.test.ts +82 -0
  444. package/src/client/__tests__/sortable-list.test.ts +91 -0
  445. package/src/client/__tests__/toast.test.ts +46 -0
  446. package/src/client/archive-nav.js +1 -3
  447. package/src/client/avatar-upload.ts +66 -25
  448. package/src/client/collection-form-bridge.ts +32 -15
  449. package/src/client/collection-page-actions.ts +160 -0
  450. package/src/client/collection-sort-menu.ts +105 -0
  451. package/src/client/components/__tests__/jant-collection-form.test.ts +199 -51
  452. package/src/client/components/__tests__/jant-collection-sidebar.test.ts +306 -0
  453. package/src/client/components/__tests__/jant-compose-dialog.test.ts +2507 -342
  454. package/src/client/components/__tests__/jant-compose-editor.test.ts +484 -20
  455. package/src/client/components/__tests__/jant-compose-fullscreen.test.ts +298 -0
  456. package/src/client/components/__tests__/jant-post-form.test.ts +9 -8
  457. package/src/client/components/__tests__/jant-post-menu.test.ts +325 -0
  458. package/src/client/components/__tests__/jant-settings-avatar.test.ts +27 -3
  459. package/src/client/components/__tests__/jant-settings-general.test.ts +312 -84
  460. package/src/client/components/collection-manager-types.ts +51 -0
  461. package/src/client/components/collection-types.ts +12 -10
  462. package/src/client/components/compose-types.ts +80 -13
  463. package/src/client/components/jant-collection-form.ts +340 -509
  464. package/src/client/components/jant-collection-sidebar.ts +474 -463
  465. package/src/client/components/jant-compose-dialog.ts +1566 -479
  466. package/src/client/components/jant-compose-editor.ts +531 -276
  467. package/src/client/components/jant-compose-fullscreen.ts +184 -112
  468. package/src/client/components/jant-confirm-dialog.ts +249 -0
  469. package/src/client/components/jant-nav-manager.ts +79 -103
  470. package/src/client/components/jant-post-form.ts +4 -1
  471. package/src/client/components/jant-post-menu.ts +583 -306
  472. package/src/client/components/jant-settings-avatar.ts +15 -9
  473. package/src/client/components/jant-settings-general.ts +444 -137
  474. package/src/client/components/nav-manager-types.ts +6 -3
  475. package/src/client/components/post-form-template.ts +2 -9
  476. package/src/client/components/post-form-types.ts +2 -4
  477. package/src/client/components/settings-types.ts +34 -2
  478. package/src/client/compose-bridge.ts +297 -171
  479. package/src/client/compose-discovery-bridge.ts +9 -0
  480. package/src/client/compose-discovery.ts +254 -0
  481. package/src/client/compose-launch.ts +98 -0
  482. package/src/client/compose-shortcuts.ts +61 -0
  483. package/src/client/confirm.ts +40 -0
  484. package/src/client/custom-url-menu.ts +128 -0
  485. package/src/client/form-enter-submit.ts +87 -0
  486. package/src/client/json.ts +37 -0
  487. package/src/client/multipart-upload.ts +51 -18
  488. package/src/client/post-form-bridge.ts +20 -14
  489. package/src/client/runtime-paths.ts +72 -0
  490. package/src/client/settings-bridge.ts +54 -10
  491. package/src/client/site-header-nav.js +84 -0
  492. package/src/client/sortable-list.ts +152 -0
  493. package/src/client/thread-context.ts +11 -5
  494. package/src/client/tiptap/__tests__/floating-position.test.ts +74 -0
  495. package/src/client/tiptap/__tests__/link-toolbar.test.ts +94 -0
  496. package/src/client/tiptap/__tests__/paste-media.test.ts +39 -0
  497. package/src/client/tiptap/bubble-menu.ts +98 -13
  498. package/src/client/tiptap/create-editor.ts +6 -0
  499. package/src/client/tiptap/extensions.ts +15 -4
  500. package/src/client/tiptap/floating-position.ts +167 -0
  501. package/src/client/tiptap/inline-image-upload.ts +73 -0
  502. package/src/client/tiptap/link-input-rules.ts +56 -0
  503. package/src/client/tiptap/link-toolbar.ts +60 -14
  504. package/src/client/tiptap/paste-media.ts +120 -0
  505. package/src/client/tiptap/slash-commands.ts +205 -52
  506. package/src/client/tiptap/toolbar-mode.ts +31 -0
  507. package/src/client/toast.ts +136 -16
  508. package/src/client/types/sortablejs.d.ts +4 -4
  509. package/src/client/upload-session.ts +270 -0
  510. package/src/client/upload-with-metadata.ts +10 -17
  511. package/src/client-auth.ts +38 -0
  512. package/src/client.ts +10 -29
  513. package/src/db/__tests__/d1-query.test.ts +84 -0
  514. package/src/db/__tests__/demo-canonical-snapshot.test.ts +78 -0
  515. package/src/db/__tests__/demo-env-loader.test.ts +114 -0
  516. package/src/db/__tests__/dialect.test.ts +42 -0
  517. package/src/db/__tests__/migration-artifacts.test.ts +82 -0
  518. package/src/db/__tests__/migration-rehearsal.test.ts +73 -0
  519. package/src/db/__tests__/migration-runner.test.ts +72 -0
  520. package/src/db/__tests__/migrations.test.ts +293 -8
  521. package/src/db/__tests__/r2-query.test.ts +102 -0
  522. package/src/db/__tests__/wrangler-config.test.ts +86 -0
  523. package/src/db/backfills/0000_normalize_legacy_time_zone_values.sql +38 -0
  524. package/src/db/backfills/README.md +11 -0
  525. package/src/db/dialect.ts +71 -0
  526. package/src/db/index.ts +84 -2
  527. package/src/db/migrations/0000_baseline.sql +35 -57
  528. package/src/db/migrations/0002_site_aware_core.sql +354 -0
  529. package/src/db/migrations/0003_fts_site_aware.sql +38 -0
  530. package/src/db/migrations/0004_perpetual_eternity.sql +29 -0
  531. package/src/db/migrations/meta/0000_snapshot.json +134 -138
  532. package/src/db/migrations/meta/0001_snapshot.json +135 -139
  533. package/src/db/migrations/meta/0002_snapshot.json +1717 -0
  534. package/src/db/migrations/meta/0003_snapshot.json +1717 -0
  535. package/src/db/migrations/meta/0004_snapshot.json +1897 -0
  536. package/src/db/migrations/meta/_journal.json +23 -2
  537. package/src/db/migrations/pg/0000_pg_site_aware_baseline.sql +306 -0
  538. package/src/db/migrations/pg/0001_pg_search_support.sql +8 -0
  539. package/src/db/migrations/pg/0002_breezy_lockjaw.sql +29 -0
  540. package/src/db/migrations/pg/README.md +8 -0
  541. package/src/db/migrations/pg/meta/0000_snapshot.json +2195 -0
  542. package/src/db/migrations/pg/meta/0001_snapshot.json +2248 -0
  543. package/src/db/migrations/pg/meta/0002_snapshot.json +2476 -0
  544. package/src/db/migrations/pg/meta/_journal.json +27 -0
  545. package/src/db/pg/__tests__/node.test.ts +58 -0
  546. package/src/db/pg/node.ts +151 -0
  547. package/src/db/pg/schema.ts +739 -0
  548. package/src/db/raw-query.ts +15 -0
  549. package/src/db/rehearsal-fixtures/demo-current.json +25 -0
  550. package/src/db/rehearsal-fixtures/demo-current.sql +142 -0
  551. package/src/db/schema-bundle.ts +12 -0
  552. package/src/db/schema.ts +309 -128
  553. package/src/db/sqlite/schema.ts +1 -0
  554. package/src/i18n/__tests__/context.test.tsx +35 -0
  555. package/src/i18n/context.tsx +10 -2
  556. package/src/i18n/locales/en.po +1792 -231
  557. package/src/i18n/locales/en.ts +1 -1
  558. package/src/i18n/locales/glossary.zh-Hans.yml +116 -0
  559. package/src/i18n/locales/glossary.zh-Hant.yml +116 -0
  560. package/src/i18n/locales/zh-Hans.po +1831 -270
  561. package/src/i18n/locales/zh-Hans.ts +1 -1
  562. package/src/i18n/locales/zh-Hant.po +1835 -274
  563. package/src/i18n/locales/zh-Hant.ts +1 -1
  564. package/src/index.ts +4 -0
  565. package/src/lib/__tests__/asset-path.test.ts +54 -0
  566. package/src/lib/__tests__/blurhash-placeholder.test.ts +25 -1
  567. package/src/lib/__tests__/collection-groups.test.ts +63 -0
  568. package/src/lib/__tests__/collection-sort.test.ts +45 -0
  569. package/src/lib/__tests__/constants.test.ts +24 -1
  570. package/src/lib/__tests__/favicon.test.ts +1 -1
  571. package/src/lib/__tests__/feed.test.ts +147 -0
  572. package/src/lib/__tests__/hosted-control-plane.test.ts +106 -0
  573. package/src/lib/__tests__/hosted-domain.test.ts +78 -0
  574. package/src/lib/__tests__/hosted-signin.test.ts +103 -0
  575. package/src/lib/__tests__/icons.test.ts +14 -172
  576. package/src/lib/__tests__/image.test.ts +23 -4
  577. package/src/lib/__tests__/jant-branding.test.ts +160 -0
  578. package/src/lib/__tests__/markdown-to-tiptap.test.ts +27 -0
  579. package/src/lib/__tests__/page-title.test.ts +20 -0
  580. package/src/lib/__tests__/password.test.ts +60 -0
  581. package/src/lib/__tests__/post-display.test.ts +99 -0
  582. package/src/lib/__tests__/post-meta.test.ts +126 -0
  583. package/src/lib/__tests__/public-storage.test.ts +75 -0
  584. package/src/lib/__tests__/resolve-config.test.ts +156 -28
  585. package/src/lib/__tests__/schemas.test.ts +286 -22
  586. package/src/lib/__tests__/search-snippet.test.ts +43 -0
  587. package/src/lib/__tests__/site-resolution.test.ts +39 -0
  588. package/src/lib/__tests__/slug-format.test.ts +54 -0
  589. package/src/lib/__tests__/startup-config.test.ts +87 -0
  590. package/src/lib/__tests__/storage.test.ts +218 -1
  591. package/src/lib/__tests__/theme.test.ts +50 -13
  592. package/src/lib/__tests__/time.test.ts +44 -0
  593. package/src/lib/__tests__/timeline.test.ts +492 -4
  594. package/src/lib/__tests__/timezones.test.ts +51 -18
  595. package/src/lib/__tests__/tiptap-to-markdown.test.ts +23 -0
  596. package/src/lib/__tests__/url.test.ts +79 -1
  597. package/src/lib/__tests__/view.test.ts +74 -13
  598. package/src/lib/asset-path.ts +87 -0
  599. package/src/lib/blurhash-placeholder.ts +56 -1
  600. package/src/lib/collection-groups.ts +69 -0
  601. package/src/lib/collection-sort.ts +61 -0
  602. package/src/lib/confirm.ts +37 -0
  603. package/src/lib/constants.ts +20 -3
  604. package/src/lib/crypto.ts +47 -0
  605. package/src/lib/env.ts +245 -0
  606. package/src/lib/errors.ts +25 -9
  607. package/src/lib/favicon.ts +2 -1
  608. package/src/lib/featured-icons.ts +33 -0
  609. package/src/lib/feed.ts +73 -24
  610. package/src/lib/hosted-control-plane-sync.ts +27 -0
  611. package/src/lib/hosted-control-plane.ts +99 -0
  612. package/src/lib/hosted-domain-check.ts +98 -0
  613. package/src/lib/hosted-domain.ts +61 -0
  614. package/src/lib/hosted-signin.ts +115 -0
  615. package/src/lib/hosted-sso.ts +110 -0
  616. package/src/lib/icons.ts +10 -175
  617. package/src/lib/ids.ts +54 -0
  618. package/src/lib/image.ts +18 -7
  619. package/src/lib/jant-branding-generated.ts +947 -0
  620. package/src/lib/jant-branding.ts +520 -0
  621. package/src/lib/markdown-to-tiptap.ts +57 -0
  622. package/src/lib/media-helpers.ts +6 -2
  623. package/src/lib/navigation.ts +9 -2
  624. package/src/lib/page-title.ts +23 -0
  625. package/src/lib/pagination.ts +34 -0
  626. package/src/lib/password.ts +164 -0
  627. package/src/lib/post-display.ts +162 -0
  628. package/src/lib/post-meta.ts +95 -0
  629. package/src/lib/public-storage.ts +57 -0
  630. package/src/lib/render.tsx +22 -0
  631. package/src/lib/resolve-config.ts +78 -27
  632. package/src/lib/schemas.ts +271 -73
  633. package/src/lib/search-snippet.ts +110 -8
  634. package/src/lib/site-resolution.ts +28 -0
  635. package/src/lib/slug-format.ts +92 -0
  636. package/src/lib/slug.ts +1 -1
  637. package/src/lib/startup-config.ts +244 -0
  638. package/src/lib/storage.ts +722 -28
  639. package/src/lib/theme.ts +13 -6
  640. package/src/lib/time.ts +59 -15
  641. package/src/lib/timeline.ts +394 -63
  642. package/src/lib/timezones.ts +120 -50
  643. package/src/lib/tiptap-render.ts +1 -3
  644. package/src/lib/tiptap-to-markdown.ts +49 -0
  645. package/src/lib/upload.ts +216 -11
  646. package/src/lib/url.ts +210 -0
  647. package/src/lib/view.ts +87 -31
  648. package/src/middleware/__tests__/auth.test.ts +216 -14
  649. package/src/middleware/__tests__/error-handler.test.ts +37 -0
  650. package/src/middleware/__tests__/onboarding.test.ts +9 -0
  651. package/src/middleware/__tests__/secure-headers.test.ts +111 -0
  652. package/src/middleware/auth.ts +156 -28
  653. package/src/middleware/config.ts +29 -9
  654. package/src/middleware/error-handler.ts +16 -1
  655. package/src/middleware/onboarding.ts +15 -6
  656. package/src/middleware/secure-headers.ts +136 -25
  657. package/src/node/__tests__/cli-db-execute-file.test.ts +109 -0
  658. package/src/node/__tests__/cli-deploy.test.ts +124 -0
  659. package/src/node/__tests__/cli-export.test.ts +66 -0
  660. package/src/node/__tests__/cli-reset-password.test.ts +91 -0
  661. package/src/node/__tests__/cli-runtime-target.test.ts +37 -0
  662. package/src/node/__tests__/cli-site-selection.test.ts +133 -0
  663. package/src/node/__tests__/cli-site-snapshot.test.ts +636 -0
  664. package/src/node/__tests__/cli-site-token-env.test.ts +137 -0
  665. package/src/node/__tests__/runtime.test.ts +346 -0
  666. package/src/node/index.ts +18 -0
  667. package/src/node/request-handler.ts +668 -0
  668. package/src/node/runtime.ts +88 -0
  669. package/src/preset.css +73 -16
  670. package/src/routes/__tests__/compose.test.ts +77 -4
  671. package/src/routes/api/__tests__/attachments.test.ts +92 -0
  672. package/src/routes/api/__tests__/collections.test.ts +138 -24
  673. package/src/routes/api/__tests__/nav-items.test.ts +81 -20
  674. package/src/routes/api/__tests__/posts.test.ts +315 -57
  675. package/src/routes/api/__tests__/search.test.ts +25 -1
  676. package/src/routes/api/__tests__/settings.test.ts +380 -2
  677. package/src/routes/api/__tests__/upload-multipart.test.ts +216 -26
  678. package/src/routes/api/__tests__/uploads.test.ts +420 -0
  679. package/src/routes/api/attachments.ts +24 -0
  680. package/src/routes/api/collections.ts +59 -28
  681. package/src/routes/api/custom-urls.ts +6 -5
  682. package/src/routes/api/export.ts +37 -7
  683. package/src/routes/api/internal/__tests__/api-tokens.test.ts +55 -0
  684. package/src/routes/api/internal/__tests__/sites.test.ts +472 -0
  685. package/src/routes/api/internal/__tests__/uploads.test.ts +131 -0
  686. package/src/routes/api/internal/api-tokens.ts +17 -0
  687. package/src/routes/api/internal/sites.ts +241 -0
  688. package/src/routes/api/internal/uploads.ts +37 -0
  689. package/src/routes/api/nav-items.ts +24 -15
  690. package/src/routes/api/posts.ts +222 -74
  691. package/src/routes/api/search.ts +50 -9
  692. package/src/routes/api/settings.ts +141 -7
  693. package/src/routes/api/upload-multipart.ts +105 -16
  694. package/src/routes/api/upload.ts +90 -21
  695. package/src/routes/api/uploads.ts +247 -0
  696. package/src/routes/auth/__tests__/dev.test.ts +135 -0
  697. package/src/routes/auth/__tests__/hosted-sso.test.ts +136 -0
  698. package/src/routes/auth/__tests__/setup.test.ts +73 -49
  699. package/src/routes/auth/dev.ts +72 -0
  700. package/src/routes/auth/hosted-sso.ts +64 -0
  701. package/src/routes/auth/reset.tsx +41 -7
  702. package/src/routes/auth/setup.tsx +37 -38
  703. package/src/routes/auth/signin.tsx +36 -6
  704. package/src/routes/compose.tsx +25 -38
  705. package/src/routes/dash/__tests__/font-theme.test.ts +45 -34
  706. package/src/routes/dash/__tests__/settings-avatar.test.ts +24 -11
  707. package/src/routes/dash/custom-urls.tsx +245 -67
  708. package/src/routes/dash/settings.tsx +530 -139
  709. package/src/routes/feed/__tests__/rss.test.ts +200 -51
  710. package/src/routes/feed/__tests__/sitemap.test.ts +64 -0
  711. package/src/routes/feed/rss.ts +112 -48
  712. package/src/routes/feed/sitemap.ts +16 -6
  713. package/src/routes/hosted/__tests__/domain-check.test.ts +94 -0
  714. package/src/routes/hosted/domain-check.ts +39 -0
  715. package/src/routes/pages/__tests__/collections.test.ts +27 -21
  716. package/src/routes/pages/__tests__/featured.test.ts +9 -2
  717. package/src/routes/pages/archive.tsx +79 -33
  718. package/src/routes/pages/brand.tsx +119 -0
  719. package/src/routes/pages/collection.tsx +201 -65
  720. package/src/routes/pages/collections.tsx +46 -20
  721. package/src/routes/pages/featured.tsx +31 -39
  722. package/src/routes/pages/home.tsx +50 -25
  723. package/src/routes/pages/latest.tsx +20 -4
  724. package/src/routes/pages/new.tsx +10 -6
  725. package/src/routes/pages/page.tsx +27 -53
  726. package/src/routes/pages/partials.tsx +83 -0
  727. package/src/routes/pages/search.tsx +11 -9
  728. package/src/routes/pages/theme-sample.tsx +98 -0
  729. package/src/runtime/__tests__/node.test.ts +258 -0
  730. package/src/runtime/__tests__/readiness.test.ts +89 -0
  731. package/src/runtime/cloudflare.ts +102 -0
  732. package/src/runtime/index.ts +14 -0
  733. package/src/runtime/node.ts +187 -0
  734. package/src/runtime/readiness.ts +129 -0
  735. package/src/runtime/site.ts +169 -0
  736. package/src/services/__tests__/api-token.test.ts +5 -2
  737. package/src/services/__tests__/auth.test.ts +348 -0
  738. package/src/services/__tests__/collection.test.ts +199 -16
  739. package/src/services/__tests__/custom-url.test.ts +10 -3
  740. package/src/services/__tests__/hosted-handoff.test.ts +123 -0
  741. package/src/services/__tests__/media.test.ts +256 -33
  742. package/src/services/__tests__/navigation.test.ts +89 -4
  743. package/src/services/__tests__/post-timeline.test.ts +169 -2
  744. package/src/services/__tests__/post.test.ts +498 -39
  745. package/src/services/__tests__/search.test.ts +145 -14
  746. package/src/services/__tests__/settings.test.ts +162 -2
  747. package/src/services/__tests__/site-admin.test.ts +48 -0
  748. package/src/services/__tests__/site-profile.test.ts +175 -0
  749. package/src/services/api-token.ts +44 -11
  750. package/src/services/auth.ts +211 -9
  751. package/src/services/bootstrap.ts +68 -0
  752. package/src/services/collection.ts +556 -100
  753. package/src/services/custom-url.ts +42 -12
  754. package/src/services/export.ts +2269 -320
  755. package/src/services/hosted-handoff.ts +184 -0
  756. package/src/services/index.ts +110 -12
  757. package/src/services/media.ts +309 -39
  758. package/src/services/navigation.ts +141 -20
  759. package/src/services/path.ts +45 -9
  760. package/src/services/post.ts +1640 -248
  761. package/src/services/search.ts +222 -29
  762. package/src/services/settings.ts +202 -48
  763. package/src/services/site-admin.ts +825 -0
  764. package/src/services/site-member.ts +74 -0
  765. package/src/services/site-profile.ts +52 -0
  766. package/src/services/site.ts +250 -0
  767. package/src/services/upload-session.ts +707 -0
  768. package/src/style-cjk-tc.css +3 -0
  769. package/src/style-cjk.css +3 -0
  770. package/src/styles/components.css +647 -16
  771. package/src/styles/fonts/latin.css +4 -0
  772. package/src/styles/fonts/noto-serif-sc/400/02629e5d0a9860b7fe32ec1f0563213a.woff2 +0 -0
  773. package/src/styles/fonts/noto-serif-sc/400/031089da45fbfb7dc18ac827bef4c56e.woff2 +0 -0
  774. package/src/styles/fonts/noto-serif-sc/400/03ac785139320b7b13bac9c150bf72bf.woff2 +0 -0
  775. package/src/styles/fonts/noto-serif-sc/400/0b1f83a3c7e715560a55ad9eb0fb1c94.woff2 +0 -0
  776. package/src/styles/fonts/noto-serif-sc/400/14b040a2dda256936bc7b3470e548394.woff2 +0 -0
  777. package/src/styles/fonts/noto-serif-sc/400/189f272ea2600c74d576b7b15c014922.woff2 +0 -0
  778. package/src/styles/fonts/noto-serif-sc/400/1fbccc182322b513f57cd156a9a491b0.woff2 +0 -0
  779. package/src/styles/fonts/noto-serif-sc/400/21e0a71d86be7b8a9e812e7af09dd061.woff2 +0 -0
  780. package/src/styles/fonts/noto-serif-sc/400/265e048cc9f2f8a711ba585a534d5351.woff2 +0 -0
  781. package/src/styles/fonts/noto-serif-sc/400/2ae2ca951489c9d50cde5b36a2a5515b.woff2 +0 -0
  782. package/src/styles/fonts/noto-serif-sc/400/2ba802b14f21a58fc61606c88fa93373.woff2 +0 -0
  783. package/src/styles/fonts/noto-serif-sc/400/2deb444546774c3a3ab38c75eb69cdfb.woff2 +0 -0
  784. package/src/styles/fonts/noto-serif-sc/400/2fbccf9a3853eb59db1a825e044515fd.woff2 +0 -0
  785. package/src/styles/fonts/noto-serif-sc/400/2ff009fa8701505d7f3dc6c83763f019.woff2 +0 -0
  786. package/src/styles/fonts/noto-serif-sc/400/31424fe5d54692e7c8b38021ccb8597c.woff2 +0 -0
  787. package/src/styles/fonts/noto-serif-sc/400/360c190344c26278bbc50e2f4d6a2b3f.woff2 +0 -0
  788. package/src/styles/fonts/noto-serif-sc/400/39b0bbc910af9d2d6dcd8bd4abd6387d.woff2 +0 -0
  789. package/src/styles/fonts/noto-serif-sc/400/3adc8f6350cf5067bcb6dc5e44c45d41.woff2 +0 -0
  790. package/src/styles/fonts/noto-serif-sc/400/3bed5bd57de8f738e53cddaea88983d9.woff2 +0 -0
  791. package/src/styles/fonts/noto-serif-sc/400/3c201fd8d1bb20abe7d06b940e83a4d9.woff2 +0 -0
  792. package/src/styles/fonts/noto-serif-sc/400/3d385ea0880df7204258e290648ec012.woff2 +0 -0
  793. package/src/styles/fonts/noto-serif-sc/400/3dc1a4f0d7af59e16b5162a2b077a442.woff2 +0 -0
  794. package/src/styles/fonts/noto-serif-sc/400/3dc68e473fe23bd076dd46785cd23583.woff2 +0 -0
  795. package/src/styles/fonts/noto-serif-sc/400/435b7dca567809813fcb395a27ed83a0.woff2 +0 -0
  796. package/src/styles/fonts/noto-serif-sc/400/43693195e775d515689fa035394067fd.woff2 +0 -0
  797. package/src/styles/fonts/noto-serif-sc/400/43fb49e5b79ee7e553869d84e6e08b1e.woff2 +0 -0
  798. package/src/styles/fonts/noto-serif-sc/400/44dcbbc3cc8f22e613b342d691511ab6.woff2 +0 -0
  799. package/src/styles/fonts/noto-serif-sc/400/474fac21b12b7efd71f7c321578878b0.woff2 +0 -0
  800. package/src/styles/fonts/noto-serif-sc/400/4a23fe6e82fd496b5eb20401b6164efe.woff2 +0 -0
  801. package/src/styles/fonts/noto-serif-sc/400/4bc743968cf1c3ce5711de67ef1ccc4d.woff2 +0 -0
  802. package/src/styles/fonts/noto-serif-sc/400/4cf0f292f3358bd2f73b1cf4ec1476f3.woff2 +0 -0
  803. package/src/styles/fonts/noto-serif-sc/400/501f66f24bce8234441954de1b568403.woff2 +0 -0
  804. package/src/styles/fonts/noto-serif-sc/400/53a88404451448cd2e620a0ca0e45a20.woff2 +0 -0
  805. package/src/styles/fonts/noto-serif-sc/400/557cd00c5d6827e13d72a0c71b23587b.woff2 +0 -0
  806. package/src/styles/fonts/noto-serif-sc/400/563fa31542d553f25abab65cf7f81e1d.woff2 +0 -0
  807. package/src/styles/fonts/noto-serif-sc/400/56e1c4734bbbb38af2fbc262bf6e98f2.woff2 +0 -0
  808. package/src/styles/fonts/noto-serif-sc/400/5947f5da5da9a352a2b534ee64bfc29a.woff2 +0 -0
  809. package/src/styles/fonts/noto-serif-sc/400/5a10741e41259e235841440394c0763d.woff2 +0 -0
  810. package/src/styles/fonts/noto-serif-sc/400/60d8b0805a0a8c54a6cca216004beff5.woff2 +0 -0
  811. package/src/styles/fonts/noto-serif-sc/400/61bf4287453da4025d03fa6b2dba66ca.woff2 +0 -0
  812. package/src/styles/fonts/noto-serif-sc/400/638369541268ed5a10af97ad77498c73.woff2 +0 -0
  813. package/src/styles/fonts/noto-serif-sc/400/687d0f0f90a9b23e40102e16ad8e9836.woff2 +0 -0
  814. package/src/styles/fonts/noto-serif-sc/400/6e2164fad867d166de2e5b274f04a563.woff2 +0 -0
  815. package/src/styles/fonts/noto-serif-sc/400/6eefc9d430171c1e1e4034ecadee31c8.woff2 +0 -0
  816. package/src/styles/fonts/noto-serif-sc/400/71eafb8fbe3a734283517e230ad8b6db.woff2 +0 -0
  817. package/src/styles/fonts/noto-serif-sc/400/751f54dbb115140d5b645a6ba4aff5d3.woff2 +0 -0
  818. package/src/styles/fonts/noto-serif-sc/400/7609e7e74dd4d916a7abc7ecc7d95f7e.woff2 +0 -0
  819. package/src/styles/fonts/noto-serif-sc/400/76b9d6fe838ae4151d95ce7200aa2bf6.woff2 +0 -0
  820. package/src/styles/fonts/noto-serif-sc/400/78ce29fed872e44fc9014d94875d2aac.woff2 +0 -0
  821. package/src/styles/fonts/noto-serif-sc/400/79a85a253e9b3f12d2e2cb15e16b3003.woff2 +0 -0
  822. package/src/styles/fonts/noto-serif-sc/400/7caa14a095a6bc313aab780fe4ff7999.woff2 +0 -0
  823. package/src/styles/fonts/noto-serif-sc/400/7d138084cf03c14116b11297fce0e3e3.woff2 +0 -0
  824. package/src/styles/fonts/noto-serif-sc/400/880162ae92cd9e120eb4e4e11fae459d.woff2 +0 -0
  825. package/src/styles/fonts/noto-serif-sc/400/8f2b960c2823670e94f5b08aa65657e6.woff2 +0 -0
  826. package/src/styles/fonts/noto-serif-sc/400/8f89f57230d184f92a36e241874229d7.woff2 +0 -0
  827. package/src/styles/fonts/noto-serif-sc/400/9180de34b48b325200a97e267befff32.woff2 +0 -0
  828. package/src/styles/fonts/noto-serif-sc/400/95df3b9f681d9df411c30aea5b24f2e0.woff2 +0 -0
  829. package/src/styles/fonts/noto-serif-sc/400/975af5a496e8d87d821910aa9fe4d598.woff2 +0 -0
  830. package/src/styles/fonts/noto-serif-sc/400/97a874bbf55ce89a4ab7cd27c7e938b1.woff2 +0 -0
  831. package/src/styles/fonts/noto-serif-sc/400/9fd53607094e329fa8e5c785b3ff0f1a.woff2 +0 -0
  832. package/src/styles/fonts/noto-serif-sc/400/a578742770fcd2226e3c45b5b6efdcb0.woff2 +0 -0
  833. package/src/styles/fonts/noto-serif-sc/400/ae401fb4db80d5ff5cd3f8d9bc811070.woff2 +0 -0
  834. package/src/styles/fonts/noto-serif-sc/400/b0ab3a7f319ce6dd3c9a4de2674e7c72.woff2 +0 -0
  835. package/src/styles/fonts/noto-serif-sc/400/b159deb135e9946eea0572d52778170b.woff2 +0 -0
  836. package/src/styles/fonts/noto-serif-sc/400/b91450304d9ac44f5c6e0da0792e055d.woff2 +0 -0
  837. package/src/styles/fonts/noto-serif-sc/400/baa325551b381c5e035ef143e56d4abe.woff2 +0 -0
  838. package/src/styles/fonts/noto-serif-sc/400/c0c7836749e585cee24ab2f8457c5b01.woff2 +0 -0
  839. package/src/styles/fonts/noto-serif-sc/400/c2ac4ef1860812036ca2b8c4e4089bdc.woff2 +0 -0
  840. package/src/styles/fonts/noto-serif-sc/400/c31019c08bd22464f7a88f090281404c.woff2 +0 -0
  841. package/src/styles/fonts/noto-serif-sc/400/c57ee3b49b7e45b995539a6b2c51f138.woff2 +0 -0
  842. package/src/styles/fonts/noto-serif-sc/400/cd75ca47da9ae4c0899e37d4c543319b.woff2 +0 -0
  843. package/src/styles/fonts/noto-serif-sc/400/d12ce1d8445213317f9163283e58a05d.woff2 +0 -0
  844. package/src/styles/fonts/noto-serif-sc/400/d28fb13acf9ced9f0657fd4012c81cd2.woff2 +0 -0
  845. package/src/styles/fonts/noto-serif-sc/400/d3714e6b90de8e2085dfb2514464dd6a.woff2 +0 -0
  846. package/src/styles/fonts/noto-serif-sc/400/d3beff96216c8af1aa79246476b6a323.woff2 +0 -0
  847. package/src/styles/fonts/noto-serif-sc/400/d3e311f30c811dc339c262a79a51877e.woff2 +0 -0
  848. package/src/styles/fonts/noto-serif-sc/400/d51f4cdc83711e510f5d25f03235597e.woff2 +0 -0
  849. package/src/styles/fonts/noto-serif-sc/400/d5df4a8dfd4328c67d933b3912c6ad0f.woff2 +0 -0
  850. package/src/styles/fonts/noto-serif-sc/400/dccda6a2e2db3b530788bdfa2acd1979.woff2 +0 -0
  851. package/src/styles/fonts/noto-serif-sc/400/f5237486197aeff59341a1ff38b8eff8.woff2 +0 -0
  852. package/src/styles/fonts/noto-serif-sc/400/f553d54ef931066712d8f3f0ce018e1b.woff2 +0 -0
  853. package/src/styles/fonts/noto-serif-sc/400/f649cba8e14c33d6bf2265483b14b895.woff2 +0 -0
  854. package/src/styles/fonts/noto-serif-sc/400/f6839df1bf7cb4dc8d27e5ea55bbe633.woff2 +0 -0
  855. package/src/styles/fonts/noto-serif-sc/400/f6b7304e028980f77a7f7007bb540abd.woff2 +0 -0
  856. package/src/styles/fonts/noto-serif-sc/400/f8db8bef0a6e1178835d350ae0d384a1.woff2 +0 -0
  857. package/src/styles/fonts/noto-serif-sc/400/fb4649a82c50620773d79820e2e5ff13.woff2 +0 -0
  858. package/src/styles/fonts/noto-serif-sc/400/fb9402d6c6357a825affc402f14d5a7e.woff2 +0 -0
  859. package/src/styles/fonts/noto-serif-sc/700/0041f681602cc834bb5c55ced0155b8e.woff2 +0 -0
  860. package/src/styles/fonts/noto-serif-sc/700/00c9ac960d866ffaf8a866e5939024e2.woff2 +0 -0
  861. package/src/styles/fonts/noto-serif-sc/700/02e48e353415a00e0f556608cab33a43.woff2 +0 -0
  862. package/src/styles/fonts/noto-serif-sc/700/02faf6bb0ab4d56ada037c0bbaf9b9f7.woff2 +0 -0
  863. package/src/styles/fonts/noto-serif-sc/700/057a3d44d7fc606f113d863376d0ecf0.woff2 +0 -0
  864. package/src/styles/fonts/noto-serif-sc/700/10f2b44b3711d3f5bdcc30d373b543d1.woff2 +0 -0
  865. package/src/styles/fonts/noto-serif-sc/700/14c1506106d92621bafb11016735194e.woff2 +0 -0
  866. package/src/styles/fonts/noto-serif-sc/700/154a2c266902003bd8b7449386b10776.woff2 +0 -0
  867. package/src/styles/fonts/noto-serif-sc/700/19e39850472250bfdbce654d30859879.woff2 +0 -0
  868. package/src/styles/fonts/noto-serif-sc/700/1b5d0d740450fb996749464c9b882025.woff2 +0 -0
  869. package/src/styles/fonts/noto-serif-sc/700/1bca0a2a8840ad0ee9414940593db144.woff2 +0 -0
  870. package/src/styles/fonts/noto-serif-sc/700/1cda27dcaab977ae4ef5d5ab2a10ae03.woff2 +0 -0
  871. package/src/styles/fonts/noto-serif-sc/700/1f4bc38a1c50f55f335f5411cae47696.woff2 +0 -0
  872. package/src/styles/fonts/noto-serif-sc/700/2022cf097cb952d9fe75b53b4587d2c3.woff2 +0 -0
  873. package/src/styles/fonts/noto-serif-sc/700/2240a3c43ca5ef59ae3c348c7884792f.woff2 +0 -0
  874. package/src/styles/fonts/noto-serif-sc/700/280e3d2b58e9ad3501816072e01b0c13.woff2 +0 -0
  875. package/src/styles/fonts/noto-serif-sc/700/2874d07e228da9583b0e73646dacd498.woff2 +0 -0
  876. package/src/styles/fonts/noto-serif-sc/700/29d49891713a2785a3a383001cf58c59.woff2 +0 -0
  877. package/src/styles/fonts/noto-serif-sc/700/2d81eb6ab0ebbc0cabfb3a3341ba8800.woff2 +0 -0
  878. package/src/styles/fonts/noto-serif-sc/700/3179006d1c7ebfa50d27482a2859d9a0.woff2 +0 -0
  879. package/src/styles/fonts/noto-serif-sc/700/34c2edb3c37f71258f5c4a31091f0c6c.woff2 +0 -0
  880. package/src/styles/fonts/noto-serif-sc/700/389a950f2a1211946d294716e679e381.woff2 +0 -0
  881. package/src/styles/fonts/noto-serif-sc/700/42a74b6a625bbf0a9616ed4db3152c88.woff2 +0 -0
  882. package/src/styles/fonts/noto-serif-sc/700/457485e72835364662dfead6281638c1.woff2 +0 -0
  883. package/src/styles/fonts/noto-serif-sc/700/488846410760fe128dae939836ca5423.woff2 +0 -0
  884. package/src/styles/fonts/noto-serif-sc/700/48eb0a91e50c7f026e248c64145e72af.woff2 +0 -0
  885. package/src/styles/fonts/noto-serif-sc/700/4b0e79ba18b2ce424fa93e84996d7cba.woff2 +0 -0
  886. package/src/styles/fonts/noto-serif-sc/700/54e301f412730f391225db59dae1c8d5.woff2 +0 -0
  887. package/src/styles/fonts/noto-serif-sc/700/597d69d0710e0178b162afb0a0c20401.woff2 +0 -0
  888. package/src/styles/fonts/noto-serif-sc/700/5cc23a76e122d0ad2f7cede41bc35b27.woff2 +0 -0
  889. package/src/styles/fonts/noto-serif-sc/700/5d48855bed5f3554eff91b573d7376ac.woff2 +0 -0
  890. package/src/styles/fonts/noto-serif-sc/700/5ddcbe564b29ef08632e1aeb33455435.woff2 +0 -0
  891. package/src/styles/fonts/noto-serif-sc/700/605667a998e91e2b6a4a3cd7c31fe5a9.woff2 +0 -0
  892. package/src/styles/fonts/noto-serif-sc/700/67f32ceea9e78e5109f87724ad886010.woff2 +0 -0
  893. package/src/styles/fonts/noto-serif-sc/700/68f2fab82ec8e9291f08c3145111549c.woff2 +0 -0
  894. package/src/styles/fonts/noto-serif-sc/700/69519ada3f3f74ca20aacb8af48ab6b4.woff2 +0 -0
  895. package/src/styles/fonts/noto-serif-sc/700/6a6e884fb2b65ec5b4a3d5ecd0d01a6a.woff2 +0 -0
  896. package/src/styles/fonts/noto-serif-sc/700/6e1a8b45b01939088c3a8cfcf8c10681.woff2 +0 -0
  897. package/src/styles/fonts/noto-serif-sc/700/70adaf50c56d5ff859c64d35e0f1e34e.woff2 +0 -0
  898. package/src/styles/fonts/noto-serif-sc/700/72ee453ac0e19bd2c631c8921c44e3de.woff2 +0 -0
  899. package/src/styles/fonts/noto-serif-sc/700/753b5f6fb254bacb6618ace25af3df60.woff2 +0 -0
  900. package/src/styles/fonts/noto-serif-sc/700/76d4244186d118eea245d1385a4de2ec.woff2 +0 -0
  901. package/src/styles/fonts/noto-serif-sc/700/7a86b155111ba20f3e87306ff6beac77.woff2 +0 -0
  902. package/src/styles/fonts/noto-serif-sc/700/7b1e76975b0984e6f83e3f9f8069e784.woff2 +0 -0
  903. package/src/styles/fonts/noto-serif-sc/700/7b6c60131822a0e4d36d980d52509d4e.woff2 +0 -0
  904. package/src/styles/fonts/noto-serif-sc/700/7cbda564cb2dd4799ab9e89d51286aa7.woff2 +0 -0
  905. package/src/styles/fonts/noto-serif-sc/700/7f60eefa15956d6f06dd92404887d58c.woff2 +0 -0
  906. package/src/styles/fonts/noto-serif-sc/700/7f8c15e0ecb102738981d9fa4cb6b921.woff2 +0 -0
  907. package/src/styles/fonts/noto-serif-sc/700/812b5a4b87f3a7b4afc1cfebc864f413.woff2 +0 -0
  908. package/src/styles/fonts/noto-serif-sc/700/812dfb7f8144d01b3cc9d5ce0b472f40.woff2 +0 -0
  909. package/src/styles/fonts/noto-serif-sc/700/84742b1ede4f0bb6d27131298eba21b4.woff2 +0 -0
  910. package/src/styles/fonts/noto-serif-sc/700/8555f0285e3d28e95e2fc0ccccd9caff.woff2 +0 -0
  911. package/src/styles/fonts/noto-serif-sc/700/8e04e64c8f68d292a18d4160fbde8671.woff2 +0 -0
  912. package/src/styles/fonts/noto-serif-sc/700/958efb9b2fa2ea0008ffef009885f9f8.woff2 +0 -0
  913. package/src/styles/fonts/noto-serif-sc/700/9ca9b71010a5faeee7047ef97aeee13b.woff2 +0 -0
  914. package/src/styles/fonts/noto-serif-sc/700/9cd0b77920b9d6c64eb686493123fc76.woff2 +0 -0
  915. package/src/styles/fonts/noto-serif-sc/700/9ebd27835ffcbd794e67151ab046ce68.woff2 +0 -0
  916. package/src/styles/fonts/noto-serif-sc/700/a077f51cfb5cffb4ff4d8e229c0e9e79.woff2 +0 -0
  917. package/src/styles/fonts/noto-serif-sc/700/a397997b579d3945c9c70a979c17a8ad.woff2 +0 -0
  918. package/src/styles/fonts/noto-serif-sc/700/a68d9d5027803832bb28e78cdcd04949.woff2 +0 -0
  919. package/src/styles/fonts/noto-serif-sc/700/a904b05966368bcf90b632c7c2e5f76b.woff2 +0 -0
  920. package/src/styles/fonts/noto-serif-sc/700/aa218a2c45f3749537ce876201e5152b.woff2 +0 -0
  921. package/src/styles/fonts/noto-serif-sc/700/aa28db16818f9eaa8c817f289e1c3270.woff2 +0 -0
  922. package/src/styles/fonts/noto-serif-sc/700/aa96d698491c2540e2dcf7009c65c456.woff2 +0 -0
  923. package/src/styles/fonts/noto-serif-sc/700/ae25c41034ddc1a9e0b41f5034c9aa4b.woff2 +0 -0
  924. package/src/styles/fonts/noto-serif-sc/700/ae289ae3f8cdb54a3a6c07174517afec.woff2 +0 -0
  925. package/src/styles/fonts/noto-serif-sc/700/b02dfa2aa52cbdb1b2f11a9f44335469.woff2 +0 -0
  926. package/src/styles/fonts/noto-serif-sc/700/b2e326f7f9b807451bf9c745df747efe.woff2 +0 -0
  927. package/src/styles/fonts/noto-serif-sc/700/c33c59feccf391f0c5f1f5d24e36d1fe.woff2 +0 -0
  928. package/src/styles/fonts/noto-serif-sc/700/c82fd9456d7465b5e5bd3659e9b14c55.woff2 +0 -0
  929. package/src/styles/fonts/noto-serif-sc/700/c90b7b65d2b9696fbf3a506738f94d68.woff2 +0 -0
  930. package/src/styles/fonts/noto-serif-sc/700/cba6ad3981cb7861428d4be169ee8124.woff2 +0 -0
  931. package/src/styles/fonts/noto-serif-sc/700/cc26525aa2af1f0b929af32ce50a7fba.woff2 +0 -0
  932. package/src/styles/fonts/noto-serif-sc/700/cd0e7b51eddb22a77a09b025c0281434.woff2 +0 -0
  933. package/src/styles/fonts/noto-serif-sc/700/cd6d074f3957d58bac58437fc97e5e33.woff2 +0 -0
  934. package/src/styles/fonts/noto-serif-sc/700/cef249b6d013fb0cc0d574176bc23811.woff2 +0 -0
  935. package/src/styles/fonts/noto-serif-sc/700/d0bd387fda28e58d3c9b3efa2468dd8a.woff2 +0 -0
  936. package/src/styles/fonts/noto-serif-sc/700/da93ae099ff3b7aae27b3f674d3fc721.woff2 +0 -0
  937. package/src/styles/fonts/noto-serif-sc/700/e264213b9e102dabc603adb6e4fda5e6.woff2 +0 -0
  938. package/src/styles/fonts/noto-serif-sc/700/e7c7ef3669ae48c0a736f06ca471e1d7.woff2 +0 -0
  939. package/src/styles/fonts/noto-serif-sc/700/e81a742cacef744130c40de1b90837d8.woff2 +0 -0
  940. package/src/styles/fonts/noto-serif-sc/700/e8b755172122d1d0a5dd453e96b0ff24.woff2 +0 -0
  941. package/src/styles/fonts/noto-serif-sc/700/e99280299c305402eaa5271a3e36c49b.woff2 +0 -0
  942. package/src/styles/fonts/noto-serif-sc/700/e9c66b085052ece66bfadf45f711d3e1.woff2 +0 -0
  943. package/src/styles/fonts/noto-serif-sc/700/ed7c6dafaa6d8bcf015ef0ca574837df.woff2 +0 -0
  944. package/src/styles/fonts/noto-serif-sc/700/f2900a1d30c3a33129f4e2225669bd0e.woff2 +0 -0
  945. package/src/styles/fonts/noto-serif-sc/700/fa7d3b99744d7f2dc9e00864a97a62d6.woff2 +0 -0
  946. package/src/styles/fonts/noto-serif-sc/700/fb0e90665980954719c2eb685b130bc0.woff2 +0 -0
  947. package/src/styles/fonts/noto-serif-sc/noto-serif-sc.css +3615 -0
  948. package/src/styles/fonts/noto-serif-tc/400/008ea9091e332c639ceb18874eacd60c.woff2 +0 -0
  949. package/src/styles/fonts/noto-serif-tc/400/053bd3d7aec0040d0cc50c261a1f4e3e.woff2 +0 -0
  950. package/src/styles/fonts/noto-serif-tc/400/0713613227cc4c686c45a279f8bdc166.woff2 +0 -0
  951. package/src/styles/fonts/noto-serif-tc/400/0e97f44ebc65384c346fe19bcc52fa20.woff2 +0 -0
  952. package/src/styles/fonts/noto-serif-tc/400/1139d32ae2bdeb26c0c8f31330aa9a9f.woff2 +0 -0
  953. package/src/styles/fonts/noto-serif-tc/400/15f8c0df47fd639d1b0d9bd5cf507c9b.woff2 +0 -0
  954. package/src/styles/fonts/noto-serif-tc/400/1668bd859ffe15bed7d5563117d8d5fb.woff2 +0 -0
  955. package/src/styles/fonts/noto-serif-tc/400/190e3f8632494e7c095117f26b1c811e.woff2 +0 -0
  956. package/src/styles/fonts/noto-serif-tc/400/19ad151c22ce1befe0a9ea643fbee570.woff2 +0 -0
  957. package/src/styles/fonts/noto-serif-tc/400/1c820b5295868008ca7c78afa5b7655d.woff2 +0 -0
  958. package/src/styles/fonts/noto-serif-tc/400/1fbe225742c69f4ba9ea5f74922f0ca1.woff2 +0 -0
  959. package/src/styles/fonts/noto-serif-tc/400/2a7cedfcd6e4c7cec36f4fd7b0f329c2.woff2 +0 -0
  960. package/src/styles/fonts/noto-serif-tc/400/2acea04a920f6af31e7db97052f563c6.woff2 +0 -0
  961. package/src/styles/fonts/noto-serif-tc/400/2e98b666924b8e0a09d1aeeefd24bdd2.woff2 +0 -0
  962. package/src/styles/fonts/noto-serif-tc/400/2fd3fceb6faed5e3db768e88d7614dca.woff2 +0 -0
  963. package/src/styles/fonts/noto-serif-tc/400/35cf5dd04315e0b906e1a413d7905a2f.woff2 +0 -0
  964. package/src/styles/fonts/noto-serif-tc/400/387c811226f303af62f1e21aae6f5c83.woff2 +0 -0
  965. package/src/styles/fonts/noto-serif-tc/400/3b41385fc27419c19822060daa0b5cb3.woff2 +0 -0
  966. package/src/styles/fonts/noto-serif-tc/400/3cbe4a697fd595ef42c899de7d3e5445.woff2 +0 -0
  967. package/src/styles/fonts/noto-serif-tc/400/3d83dacbbec3d8532ae9afede21f3aab.woff2 +0 -0
  968. package/src/styles/fonts/noto-serif-tc/400/47479c470fae70f10b7c964a7ecbf274.woff2 +0 -0
  969. package/src/styles/fonts/noto-serif-tc/400/4dc0728df0f2ba70796f45f05654c7ba.woff2 +0 -0
  970. package/src/styles/fonts/noto-serif-tc/400/4dc2bc2c55b47f57d13b63aa6b1c8bd4.woff2 +0 -0
  971. package/src/styles/fonts/noto-serif-tc/400/4e1cc6aafb411b572c8d3511e925ecf1.woff2 +0 -0
  972. package/src/styles/fonts/noto-serif-tc/400/5227dbe9933760a48baff21ebd13fc98.woff2 +0 -0
  973. package/src/styles/fonts/noto-serif-tc/400/526b263e72c189f4b065738aaa6d423a.woff2 +0 -0
  974. package/src/styles/fonts/noto-serif-tc/400/54da934819a917f561b439bfd10f88b6.woff2 +0 -0
  975. package/src/styles/fonts/noto-serif-tc/400/5bfc7a121c35ae42623ef804fb525e0e.woff2 +0 -0
  976. package/src/styles/fonts/noto-serif-tc/400/5f90024544c2907c6c0203c6210c50be.woff2 +0 -0
  977. package/src/styles/fonts/noto-serif-tc/400/649b12d7cee7bb981842946e4547e6ca.woff2 +0 -0
  978. package/src/styles/fonts/noto-serif-tc/400/653bef2ed891ae48d8ed712283080649.woff2 +0 -0
  979. package/src/styles/fonts/noto-serif-tc/400/67d2a81f06ba352f17fbdc3a5e6ea59e.woff2 +0 -0
  980. package/src/styles/fonts/noto-serif-tc/400/68304f3229cf763465f044fccb5892c0.woff2 +0 -0
  981. package/src/styles/fonts/noto-serif-tc/400/688a88911e4da17b609196a959b8b930.woff2 +0 -0
  982. package/src/styles/fonts/noto-serif-tc/400/6db6ddf72c38a78ce44c1327701152e1.woff2 +0 -0
  983. package/src/styles/fonts/noto-serif-tc/400/77a7533bd21ccd33192d142a93555aa8.woff2 +0 -0
  984. package/src/styles/fonts/noto-serif-tc/400/7d65a3d6a65050eb5e6eca43398aeba4.woff2 +0 -0
  985. package/src/styles/fonts/noto-serif-tc/400/7dfc711962c8771f97e7c8898a6bcb65.woff2 +0 -0
  986. package/src/styles/fonts/noto-serif-tc/400/7ef123b62d530fcba73974fa265e0aae.woff2 +0 -0
  987. package/src/styles/fonts/noto-serif-tc/400/80466082a896fd328f30a78593c7c568.woff2 +0 -0
  988. package/src/styles/fonts/noto-serif-tc/400/8a3c84b0df36f851f5fea75ee8757951.woff2 +0 -0
  989. package/src/styles/fonts/noto-serif-tc/400/8b0c8c9f8cfa9fa090d97c5a5efb1f4c.woff2 +0 -0
  990. package/src/styles/fonts/noto-serif-tc/400/8dc035a34c76e6515ca203e2df182588.woff2 +0 -0
  991. package/src/styles/fonts/noto-serif-tc/400/8eb06109812cb80be44f47b8179c2709.woff2 +0 -0
  992. package/src/styles/fonts/noto-serif-tc/400/904324af375d5fd370af1054355a050e.woff2 +0 -0
  993. package/src/styles/fonts/noto-serif-tc/400/911a2092d64d6d6494b254d819af2b91.woff2 +0 -0
  994. package/src/styles/fonts/noto-serif-tc/400/9de02d745b8e25c6411fb152fb067748.woff2 +0 -0
  995. package/src/styles/fonts/noto-serif-tc/400/9eb33a430058d839ebbe2af4b2e0daa9.woff2 +0 -0
  996. package/src/styles/fonts/noto-serif-tc/400/9f5a73aa8ba417688019d628f334db07.woff2 +0 -0
  997. package/src/styles/fonts/noto-serif-tc/400/a0f0c06d5c7a3ffa97706178cce212a8.woff2 +0 -0
  998. package/src/styles/fonts/noto-serif-tc/400/a38c1830367f784181b6f544b0b11bbd.woff2 +0 -0
  999. package/src/styles/fonts/noto-serif-tc/400/a9cf85e27428c14351d30eac8cbc8d91.woff2 +0 -0
  1000. package/src/styles/fonts/noto-serif-tc/400/aa0ce6740f301351761a0615cc8b2e99.woff2 +0 -0
  1001. package/src/styles/fonts/noto-serif-tc/400/bc3f0cb8b55ee11d32b94ca488976f8d.woff2 +0 -0
  1002. package/src/styles/fonts/noto-serif-tc/400/bcb3307527d6d0033bf0f17660b91e71.woff2 +0 -0
  1003. package/src/styles/fonts/noto-serif-tc/400/bf1acc86e17b4229c548828a9d6f455d.woff2 +0 -0
  1004. package/src/styles/fonts/noto-serif-tc/400/c3fbc1f2557c343863a10698f8c966a2.woff2 +0 -0
  1005. package/src/styles/fonts/noto-serif-tc/400/c5c1c0be944ea39a3f50a02d32f5b759.woff2 +0 -0
  1006. package/src/styles/fonts/noto-serif-tc/400/c5f1075caf6d1344ee720de85114a521.woff2 +0 -0
  1007. package/src/styles/fonts/noto-serif-tc/400/cae29b3f8951eaf20d2f61c2206e28d9.woff2 +0 -0
  1008. package/src/styles/fonts/noto-serif-tc/400/d043b8d7a48bb0ac59ee1f1477d88eee.woff2 +0 -0
  1009. package/src/styles/fonts/noto-serif-tc/400/d320b000b5978c7251148a6a154741b8.woff2 +0 -0
  1010. package/src/styles/fonts/noto-serif-tc/400/da13b136efb1d1e4c76575af8f79a698.woff2 +0 -0
  1011. package/src/styles/fonts/noto-serif-tc/400/da2cf0ec56bf69374ee37764c7e3ea3d.woff2 +0 -0
  1012. package/src/styles/fonts/noto-serif-tc/400/daf62255dd60679946f28c442ca62533.woff2 +0 -0
  1013. package/src/styles/fonts/noto-serif-tc/400/dd01a1035345f6921a48525b8ce08f06.woff2 +0 -0
  1014. package/src/styles/fonts/noto-serif-tc/400/e4fb59479cedc87ba79785590bf861ca.woff2 +0 -0
  1015. package/src/styles/fonts/noto-serif-tc/400/e5d00355f73293d40b61299459d17ca5.woff2 +0 -0
  1016. package/src/styles/fonts/noto-serif-tc/400/e647b8d2efc501c0cc0e407249cc7135.woff2 +0 -0
  1017. package/src/styles/fonts/noto-serif-tc/400/e6e60ffb2ebd1828628764b507060aea.woff2 +0 -0
  1018. package/src/styles/fonts/noto-serif-tc/400/f00eb499abb94fa7b799d6d8c9b050e9.woff2 +0 -0
  1019. package/src/styles/fonts/noto-serif-tc/400/f7d36ffff7a75c9c6216d576a57dd00d.woff2 +0 -0
  1020. package/src/styles/fonts/noto-serif-tc/400/f7f3f63e7a149cd89eccab3b52171d05.woff2 +0 -0
  1021. package/src/styles/fonts/noto-serif-tc/400/fcc41f6a067ddd658bba5c9dff234a32.woff2 +0 -0
  1022. package/src/styles/fonts/noto-serif-tc/400/fd6ad889fcf3583bd9b0b6db53aad434.woff2 +0 -0
  1023. package/src/styles/fonts/noto-serif-tc/700/0c055db157e7a13f3103cc2a6b67fec3.woff2 +0 -0
  1024. package/src/styles/fonts/noto-serif-tc/700/0d3f5cc265cb6c439c517f2c4cebbddf.woff2 +0 -0
  1025. package/src/styles/fonts/noto-serif-tc/700/1259e5825b314fe2b8bb96d6e8069ee5.woff2 +0 -0
  1026. package/src/styles/fonts/noto-serif-tc/700/12c518ebfe62818af550c08947e359e7.woff2 +0 -0
  1027. package/src/styles/fonts/noto-serif-tc/700/145831a59caa06d894022fe60212ed21.woff2 +0 -0
  1028. package/src/styles/fonts/noto-serif-tc/700/169a096e61d38a773216f51d1ec2cc06.woff2 +0 -0
  1029. package/src/styles/fonts/noto-serif-tc/700/1884a2b22d314c7d57707f03aec348e0.woff2 +0 -0
  1030. package/src/styles/fonts/noto-serif-tc/700/1e2640116bbba817f43c43cc69371cf1.woff2 +0 -0
  1031. package/src/styles/fonts/noto-serif-tc/700/2573703213da30d3ba18925b100b2c2b.woff2 +0 -0
  1032. package/src/styles/fonts/noto-serif-tc/700/26839c0e47c73514b8d8f660d24d6b19.woff2 +0 -0
  1033. package/src/styles/fonts/noto-serif-tc/700/2a22e14a9ad53f2abb3c7e85017b7d12.woff2 +0 -0
  1034. package/src/styles/fonts/noto-serif-tc/700/2b3e8c5703b91f39f6027f43f0da6f4b.woff2 +0 -0
  1035. package/src/styles/fonts/noto-serif-tc/700/2f27ee4fb2cf6a280e110e09c18ef73e.woff2 +0 -0
  1036. package/src/styles/fonts/noto-serif-tc/700/31342cebfa5ea7fac06b4ea372d96bc5.woff2 +0 -0
  1037. package/src/styles/fonts/noto-serif-tc/700/375329ba0b50b94b35006498e555867c.woff2 +0 -0
  1038. package/src/styles/fonts/noto-serif-tc/700/427577dcb707d1d35eebd155b4222aa7.woff2 +0 -0
  1039. package/src/styles/fonts/noto-serif-tc/700/450a5b53be0a8a778bb0b623e86b652f.woff2 +0 -0
  1040. package/src/styles/fonts/noto-serif-tc/700/477866c8396474a17317dcac3e7a014f.woff2 +0 -0
  1041. package/src/styles/fonts/noto-serif-tc/700/478ebdaadda7775c391c5dcab4e697df.woff2 +0 -0
  1042. package/src/styles/fonts/noto-serif-tc/700/48d6a97a185c799be4fe67aaf7edf213.woff2 +0 -0
  1043. package/src/styles/fonts/noto-serif-tc/700/490edb9fc8a4356aea556eed32287464.woff2 +0 -0
  1044. package/src/styles/fonts/noto-serif-tc/700/4c4bdd0b3f3a52e28f3b643c1c5d43be.woff2 +0 -0
  1045. package/src/styles/fonts/noto-serif-tc/700/4c96411f3693a9a8657a9c1190f82bce.woff2 +0 -0
  1046. package/src/styles/fonts/noto-serif-tc/700/4c9aa12aba2a6a57410eacaff7427916.woff2 +0 -0
  1047. package/src/styles/fonts/noto-serif-tc/700/4cca7233bf8ce5dec2e5d146b993d626.woff2 +0 -0
  1048. package/src/styles/fonts/noto-serif-tc/700/4d0a9128d06ea857f203bf5d007b1ab9.woff2 +0 -0
  1049. package/src/styles/fonts/noto-serif-tc/700/4e5384920bbb155d9d8d74887b09ea5b.woff2 +0 -0
  1050. package/src/styles/fonts/noto-serif-tc/700/50cfd672bfa62512ba090420acf35c87.woff2 +0 -0
  1051. package/src/styles/fonts/noto-serif-tc/700/551b1d7a0b80c8d42af09863cdca7f01.woff2 +0 -0
  1052. package/src/styles/fonts/noto-serif-tc/700/555d990ab3fd7d3d66c6d1fa9a82fec5.woff2 +0 -0
  1053. package/src/styles/fonts/noto-serif-tc/700/5979c33a7eb5963bf8e83e46931b5fb5.woff2 +0 -0
  1054. package/src/styles/fonts/noto-serif-tc/700/59966ee0b069b577510fe68c350da0ee.woff2 +0 -0
  1055. package/src/styles/fonts/noto-serif-tc/700/60a14064ed334f0155795d795e926abe.woff2 +0 -0
  1056. package/src/styles/fonts/noto-serif-tc/700/611b62d5fd9698d9b5ce495ba6f14c93.woff2 +0 -0
  1057. package/src/styles/fonts/noto-serif-tc/700/6e83fe0b6e708eaf1c3003d6dee11488.woff2 +0 -0
  1058. package/src/styles/fonts/noto-serif-tc/700/70861376e5d4f92f8aa7aa1b2749b617.woff2 +0 -0
  1059. package/src/styles/fonts/noto-serif-tc/700/7124d150570d39ced8d45507dc11ca1e.woff2 +0 -0
  1060. package/src/styles/fonts/noto-serif-tc/700/79a7fdf7d9c722b5723ae25e6ff8e203.woff2 +0 -0
  1061. package/src/styles/fonts/noto-serif-tc/700/8c8393bc875f1ee36697a2113f4421ea.woff2 +0 -0
  1062. package/src/styles/fonts/noto-serif-tc/700/8e6c9bb43afb8cbbff7cf1055e67c9bd.woff2 +0 -0
  1063. package/src/styles/fonts/noto-serif-tc/700/90ac4f9d2aa02afdace2843b49fc18bb.woff2 +0 -0
  1064. package/src/styles/fonts/noto-serif-tc/700/90b6f57d77847f512fd11db74fa912f1.woff2 +0 -0
  1065. package/src/styles/fonts/noto-serif-tc/700/913759e6690f9fc0746a20b96f4bdcb4.woff2 +0 -0
  1066. package/src/styles/fonts/noto-serif-tc/700/9154e26efe532a85a27d80902f5a2d6c.woff2 +0 -0
  1067. package/src/styles/fonts/noto-serif-tc/700/94e7ed67f1557b76fead6b6e456a0415.woff2 +0 -0
  1068. package/src/styles/fonts/noto-serif-tc/700/95127a92346c04fec1fa81d6295b0a28.woff2 +0 -0
  1069. package/src/styles/fonts/noto-serif-tc/700/9fbc06b2e3ff16b9d705c76db563ef17.woff2 +0 -0
  1070. package/src/styles/fonts/noto-serif-tc/700/a3b929542e6c5a0644b73a7c8a8b6c03.woff2 +0 -0
  1071. package/src/styles/fonts/noto-serif-tc/700/a8857f5d478f101c053ba02d2f223e90.woff2 +0 -0
  1072. package/src/styles/fonts/noto-serif-tc/700/aa64c9953af43ca65832f413895bb433.woff2 +0 -0
  1073. package/src/styles/fonts/noto-serif-tc/700/ada8f0241244c60ec8d3d59ad37f20a5.woff2 +0 -0
  1074. package/src/styles/fonts/noto-serif-tc/700/b341de0bc0bfe194a6c28dcfb566029e.woff2 +0 -0
  1075. package/src/styles/fonts/noto-serif-tc/700/b846c293981ca5429eabaa967f222f26.woff2 +0 -0
  1076. package/src/styles/fonts/noto-serif-tc/700/be64f9379412876e00fd3a0bfa6b6fe9.woff2 +0 -0
  1077. package/src/styles/fonts/noto-serif-tc/700/befed8a4fa817773fa7109db6fe07f56.woff2 +0 -0
  1078. package/src/styles/fonts/noto-serif-tc/700/c09ee2b219982f8d46ad9968b7e6e0ba.woff2 +0 -0
  1079. package/src/styles/fonts/noto-serif-tc/700/c39ec937c6a8d124e8b68cf829ea5ad4.woff2 +0 -0
  1080. package/src/styles/fonts/noto-serif-tc/700/c3fd21315345ae541f6e98067059fa19.woff2 +0 -0
  1081. package/src/styles/fonts/noto-serif-tc/700/c568a16e3168ceb1f191b70022c492ea.woff2 +0 -0
  1082. package/src/styles/fonts/noto-serif-tc/700/c5e66d60be3375835bbd8d6b797f6eac.woff2 +0 -0
  1083. package/src/styles/fonts/noto-serif-tc/700/cd10a3af2133805d8c92104d1ee6ff18.woff2 +0 -0
  1084. package/src/styles/fonts/noto-serif-tc/700/d15a3317942b7d31978a759fbf2222c8.woff2 +0 -0
  1085. package/src/styles/fonts/noto-serif-tc/700/d740dc2e854aaa7b3dcdd3ed25455eeb.woff2 +0 -0
  1086. package/src/styles/fonts/noto-serif-tc/700/d8325ba7ae651bc30440905bd67b95f1.woff2 +0 -0
  1087. package/src/styles/fonts/noto-serif-tc/700/e2204cf85edcb96c5de5c3dcf240da9d.woff2 +0 -0
  1088. package/src/styles/fonts/noto-serif-tc/700/e3e913e145ddcd9323b2a0972967feb6.woff2 +0 -0
  1089. package/src/styles/fonts/noto-serif-tc/700/f2fb1f1fbf7e44afb53c672ec286a22e.woff2 +0 -0
  1090. package/src/styles/fonts/noto-serif-tc/700/f372129c60aaece937cf7b91ee75c9b8.woff2 +0 -0
  1091. package/src/styles/fonts/noto-serif-tc/700/f5d7487963d43c89da63aaf10f2e6fb7.woff2 +0 -0
  1092. package/src/styles/fonts/noto-serif-tc/700/f75496953a40ff241178240209f56990.woff2 +0 -0
  1093. package/src/styles/fonts/noto-serif-tc/700/f92d74d1d217d21b39075ff23f79f7fd.woff2 +0 -0
  1094. package/src/styles/fonts/noto-serif-tc/700/f9d6d981d8b87b3e469027277f585741.woff2 +0 -0
  1095. package/src/styles/fonts/noto-serif-tc/700/fa8ed469ef290bfeb571418fe0abb628.woff2 +0 -0
  1096. package/src/styles/fonts/noto-serif-tc/700/fb61b690208eff56e6d8432951270901.woff2 +0 -0
  1097. package/src/styles/fonts/noto-serif-tc/700/ff0937ad63cda71ff420945ead55ab4d.woff2 +0 -0
  1098. package/src/styles/fonts/noto-serif-tc/noto-serif-tc.css +3104 -0
  1099. package/src/styles/tokens.css +42 -7
  1100. package/src/styles/ui.css +7597 -3395
  1101. package/src/types/app-context.ts +7 -0
  1102. package/src/types/bindings.ts +77 -27
  1103. package/src/types/config.ts +104 -4
  1104. package/src/types/constants.ts +43 -4
  1105. package/src/types/entities.ts +63 -4
  1106. package/src/types/operations.ts +45 -15
  1107. package/src/types/props.ts +48 -10
  1108. package/src/types/views.ts +51 -8
  1109. package/src/ui/__tests__/color-themes.test.ts +81 -0
  1110. package/src/ui/__tests__/font-themes.test.ts +76 -7
  1111. package/src/ui/color-themes.ts +424 -238
  1112. package/src/ui/compose/ComposeDialog.tsx +149 -91
  1113. package/src/ui/compose/ComposePrompt.tsx +20 -3
  1114. package/src/ui/dash/ActionButtons.tsx +16 -2
  1115. package/src/ui/dash/DangerZone.tsx +10 -1
  1116. package/src/ui/dash/StatusBadge.tsx +3 -3
  1117. package/src/ui/dash/appearance/AdvancedContent.tsx +9 -2
  1118. package/src/ui/dash/appearance/ColorThemeContent.tsx +326 -63
  1119. package/src/ui/dash/appearance/FontThemeContent.tsx +75 -17
  1120. package/src/ui/dash/appearance/NavigationContent.tsx +48 -21
  1121. package/src/ui/dash/settings/AccountContent.tsx +7 -2
  1122. package/src/ui/dash/settings/AccountMenuContent.tsx +242 -111
  1123. package/src/ui/dash/settings/ApiTokensContent.tsx +38 -8
  1124. package/src/ui/dash/settings/AvatarContent.tsx +1 -1
  1125. package/src/ui/dash/settings/DeleteAccountContent.tsx +300 -0
  1126. package/src/ui/dash/settings/GeneralContent.tsx +120 -6
  1127. package/src/ui/dash/settings/SessionsContent.tsx +23 -5
  1128. package/src/ui/dash/settings/SettingsDirectory.tsx +99 -0
  1129. package/src/ui/dash/settings/SettingsRootContent.tsx +176 -221
  1130. package/src/ui/feed/CuratedThreadPreview.tsx +73 -0
  1131. package/src/ui/feed/LinkCard.tsx +52 -36
  1132. package/src/ui/feed/NoteCard.tsx +10 -4
  1133. package/src/ui/feed/PostStatusBadges.tsx +4 -21
  1134. package/src/ui/feed/QuoteCard.tsx +11 -3
  1135. package/src/ui/feed/ThreadPreview.tsx +11 -5
  1136. package/src/ui/feed/TimelineFeed.tsx +53 -15
  1137. package/src/ui/feed/__tests__/timeline-cards.test.ts +172 -0
  1138. package/src/ui/feed/thread-preview-state.ts +2 -4
  1139. package/src/ui/font-themes.ts +211 -43
  1140. package/src/ui/layouts/BaseLayout.tsx +161 -30
  1141. package/src/ui/layouts/SiteLayout.tsx +51 -18
  1142. package/src/ui/layouts/__tests__/BaseLayout.test.tsx +169 -0
  1143. package/src/ui/pages/ArchivePage.tsx +320 -120
  1144. package/src/ui/pages/BrandPage.tsx +927 -0
  1145. package/src/ui/pages/CollectionEditorPage.tsx +155 -0
  1146. package/src/ui/pages/CollectionPage.tsx +482 -23
  1147. package/src/ui/pages/CollectionsPage.tsx +57 -57
  1148. package/src/ui/pages/FeaturedPage.tsx +24 -3
  1149. package/src/ui/pages/HomePage.tsx +13 -0
  1150. package/src/ui/pages/PostPage.tsx +13 -4
  1151. package/src/ui/pages/SearchPage.tsx +12 -2
  1152. package/src/ui/pages/ThemeSamplePage.tsx +1160 -0
  1153. package/src/ui/shared/AdminBreadcrumb.tsx +22 -6
  1154. package/src/ui/shared/CollectionDirectory.tsx +131 -0
  1155. package/src/ui/shared/CollectionsManager.tsx +277 -0
  1156. package/src/ui/shared/DecorativeQuoteMark.tsx +32 -0
  1157. package/src/ui/shared/HomePageBranding.tsx +22 -0
  1158. package/src/ui/shared/JantBrandMark.tsx +35 -0
  1159. package/src/ui/shared/MediaGallery.tsx +106 -36
  1160. package/src/ui/shared/PaginatedPageHeader.tsx +49 -0
  1161. package/src/ui/shared/Pagination.tsx +2 -6
  1162. package/src/ui/shared/PostFooter.tsx +130 -67
  1163. package/src/ui/shared/__tests__/home-page-branding.test.tsx +14 -0
  1164. package/src/ui/shared/__tests__/media-gallery.test.ts +82 -0
  1165. package/src/ui/shared/__tests__/navigation-labels.test.ts +103 -0
  1166. package/src/ui/shared/__tests__/pagination.test.ts +18 -1
  1167. package/src/ui/shared/__tests__/post-footer.test.ts +122 -0
  1168. package/src/ui/shared/collection-management-labels.ts +161 -0
  1169. package/src/ui/shared/navigation-labels.ts +126 -0
  1170. package/src/vendor/datastar.js +1955 -7
  1171. package/dist/client/assets/heic-to-DIRPI3VF.js +0 -1
  1172. package/dist/client/assets/module-RjUF93sV.js +0 -716
  1173. package/dist/client/assets/native-48B9X9Wg.js +0 -1
  1174. package/dist/client/assets/url-FWFqPJPb.js +0 -1
  1175. package/dist/client/client.css +0 -1
  1176. package/dist/client/client.js +0 -33565
  1177. package/src/client/components/collection-sidebar-types.ts +0 -43
  1178. package/src/client/tiptap/paste-image.ts +0 -129
  1179. package/src/lib/emoji-catalog.ts +0 -963
  1180. package/src/lib/icon-catalog.ts +0 -5213
  1181. package/src/ui/shared/CollectionsSidebar.tsx +0 -294
@@ -0,0 +1,3260 @@
1
+ import{a as e,n as t,s as n,t as r}from"./chunks/url-CG0eolsk.js";import{C as i,E as a,S as o,T as s,_ as c,a as l,b as u,c as d,d as f,f as p,g as m,h,i as g,l as _,m as v,n as y,o as b,p as x,r as S,s as C,t as ee,u as te,v as ne,w as re,x as ie,y as ae}from"./client.js";var oe={ICO_16:16,ICO_32:32,APPLE_TOUCH:512};function se(e){let t=e.length*16,n=6+t,r=new ArrayBuffer(6+t),i=new DataView(r);i.setUint16(0,0,!0),i.setUint16(2,1,!0),i.setUint16(4,e.length,!0);let a=[];for(let t=0;t<e.length;t++){let r=e[t],o=6+t*16;i.setUint8(o+0,r.size<256?r.size:0),i.setUint8(o+1,r.size<256?r.size:0),i.setUint8(o+2,0),i.setUint8(o+3,0),i.setUint16(o+4,1,!0),i.setUint16(o+6,32,!0),i.setUint32(o+8,r.png.byteLength,!0),i.setUint32(o+12,n,!0),n+=r.png.byteLength,a.push(r.png)}return new Blob([r,...a],{type:`image/x-icon`})}var ce=180;function le(e){return new Promise((t,n)=>{let r=new Image;r.onload=()=>{URL.revokeObjectURL(r.src),t(r)},r.onerror=()=>n(Error(`Failed to load image`)),r.src=URL.createObjectURL(e)})}function ue(e,t){let n=document.createElement(`canvas`);n.width=t,n.height=t;let r=n.getContext(`2d`);if(!r)throw Error(`Failed to get canvas context`);r.imageSmoothingEnabled=!0,r.imageSmoothingQuality=`high`;let i=Math.max(t/e.width,t/e.height),a=t/i,o=t/i,s=(e.width-a)/2,c=(e.height-o)/2;return r.drawImage(e,s,c,a,o,0,0,t,t),new Promise((e,t)=>{n.toBlob(n=>{n?e(n):t(Error(`Failed to create PNG blob`))},`image/png`)})}function de(e,t){return e.type===`image/png`&&t.width===t.height&&t.width>=ce&&t.height>=ce}async function fe(e,t){let n=e.closest(`form`)?.querySelector(`label`),r=n?.textContent??``;try{n&&(n.textContent=e.dataset.textProcessing||`Processing...`);let r=await le(t),i=t,o=t.name;if(t.type!==`image/svg+xml`){let e=await ue(r,512);i=new File([e],t.name.replace(/\.[^.]+$/,`.png`),{type:`image/png`}),o=i.name}let s=de(t,r)?Promise.resolve(t):ue(r,oe.APPLE_TOUCH),[c,l,u]=await Promise.all([ue(r,16),ue(r,32),s]),[f,p]=await Promise.all([c.arrayBuffer(),l.arrayBuffer()]),m=se([{size:16,png:f},{size:32,png:p}]);n&&(n.textContent=e.dataset.textUploading||`Uploading...`);let h=new FormData;h.append(`file`,i,o),h.append(`favicon`,m,`favicon.ico`),h.append(`appleTouch`,u,`apple-touch-icon.png`);let g=await fetch(a(`/settings/avatar`),{method:`POST`,headers:{Accept:`application/json`},body:h});if(!g.ok){let t=e.dataset.textError||`Upload failed. Please try again.`;try{let e=await d(g);t=C(e,`error`)??C(e,`message`)??t}catch{}throw Error(t)}let _=await d(g),v=C(_,`status`),y=C(_,`url`);if(v===`redirect`&&y){window.location.href=y;return}window.location.href=a(`/settings/avatar?saved`)}catch(t){n&&(n.textContent=r),m(t instanceof Error&&t.message?t.message:e.dataset.textError||`Upload failed. Please try again.`,`error`)}e.value=``}function pe(){document.addEventListener(`change`,e=>{let t=e.target.closest(`[data-avatar-upload]`);t?.files?.[0]&&(e.stopPropagation(),fe(t,t.files[0]))})}pe();var me=`default`,he=class extends o{static properties={_open:{state:!0},_title:{state:!0},_message:{state:!0},_confirmLabel:{state:!0},_cancelLabel:{state:!0},_tone:{state:!0}};#e=[];#t=null;createRenderRoot(){return this.innerHTML=``,this}constructor(){super(),this._open=!1,this._title=``,this._message=``,this._confirmLabel=``,this._cancelLabel=``,this._tone=me}disconnectedCallback(){super.disconnectedCallback();let e=this.#t;this.#t=null,e?.resolve(!1);for(let e of this.#e.splice(0))e.resolve(!1)}async confirm(e){return await new Promise(t=>{this.#e.push({...e,tone:e.tone??me,resolve:t}),this.#t||this.#n()})}async#n(){if(this.#t||this.#e.length===0)return;let e=this.#e.shift();if(!e)return;this.#t=e,this._title=e.title??``,this._message=e.message,this._confirmLabel=e.confirmLabel,this._cancelLabel=e.cancelLabel,this._tone=e.tone??me,this._open=!0,await this.updateComplete;let t=this.querySelector(`.confirm-dialog`);t&&(t.open||t.showModal(),t.querySelector(`.confirm-dialog-panel`)?.focus())}#r(e){let t=this.#t;if(!t)return;this.#t=null;let n=this.querySelector(`.confirm-dialog`);n?.open&&n.close(),this._open=!1,this._title=``,this._message=``,this._confirmLabel=``,this._cancelLabel=``,this._tone=me,t.resolve(e),queueMicrotask(()=>void this.#n())}#i=e=>{e.preventDefault(),this.#r(!1)};#a=e=>{e.target===e.currentTarget&&this.#r(!1)};#o=e=>{if(e.key===`Escape`){e.preventDefault(),e.stopPropagation(),this.#r(!1);return}let t=e.target,n=t instanceof HTMLButtonElement||t instanceof HTMLInputElement||t instanceof HTMLSelectElement||t instanceof HTMLTextAreaElement||t instanceof HTMLAnchorElement;e.key===`Enter`&&!e.defaultPrevented&&!e.metaKey&&!e.ctrlKey&&!e.altKey&&!e.shiftKey&&!n&&(e.preventDefault(),this.#r(!0))};#s(){if(this._title)return{title:this._title,message:this._message};let e=this._message.match(/^(.+?[??])\s+(.+)$/u);return e?{title:e[1],message:e[2]}:{title:this._message,message:``}}render(){if(!this._open)return i;let{title:e,message:t}=this.#s(),n=this._tone===`danger`?`btn-destructive`:`btn`;return s`
2
+ <dialog
3
+ class="dialog confirm-dialog"
4
+ @cancel=${this.#i}
5
+ @click=${this.#a}
6
+ @keydown=${this.#o}
7
+ >
8
+ <div
9
+ class="confirm-dialog-panel"
10
+ data-tone=${this._tone}
11
+ tabindex="-1"
12
+ role="document"
13
+ aria-labelledby="confirm-dialog-title"
14
+ aria-describedby=${t?`confirm-dialog-message`:`confirm-dialog-title`}
15
+ >
16
+ <header class="confirm-dialog-header">
17
+ <h2 id="confirm-dialog-title" class="confirm-dialog-title">
18
+ ${e}
19
+ </h2>
20
+ ${t?s`<p
21
+ id="confirm-dialog-message"
22
+ class="confirm-dialog-message"
23
+ >
24
+ ${t}
25
+ </p>`:i}
26
+ </header>
27
+ <footer class="confirm-dialog-actions">
28
+ <button
29
+ type="button"
30
+ class="btn-outline"
31
+ @click=${()=>this.#r(!1)}
32
+ >
33
+ ${this._cancelLabel}
34
+ </button>
35
+ <button
36
+ type="button"
37
+ class=${n}
38
+ @click=${()=>this.#r(!0)}
39
+ >
40
+ ${this._confirmLabel}
41
+ </button>
42
+ </footer>
43
+ </div>
44
+ </dialog>
45
+ `}};customElements.get(`jant-confirm-dialog`)||customElements.define(`jant-confirm-dialog`,he);var ge=`jant-confirm-dialog`;function _e(){let e=document.querySelector(ge);if(e)return e;let t=document.createElement(ge);return document.body.appendChild(t),t}function ve(e){return _e().confirm(e)}globalThis.jantConfirm=ve;var w=ae(class extends u{constructor(e){if(super(e),e.type!==ie.ATTRIBUTE||e.name!==`class`||e.strings?.length>2)throw Error("`classMap()` can only be used in the `class` attribute and must be the only part in the attribute.")}render(e){return` `+Object.keys(e).filter(t=>e[t]).join(` `)+` `}update(e,[t]){if(this.st===void 0){this.st=new Set,e.strings!==void 0&&(this.nt=new Set(e.strings.join(` `).split(/\s/).filter(e=>e!==``)));for(let e in t)t[e]&&!this.nt?.has(e)&&this.st.add(e);return this.render(t)}let n=e.element.classList;for(let e of this.st)e in t||(n.remove(e),this.st.delete(e));for(let e in t){let r=!!t[e];r===this.st.has(e)||this.nt?.has(e)||(r?(n.add(e),this.st.add(e)):(n.remove(e),this.st.delete(e)))}return re}}),ye=class extends c{};ye.directiveName=`unsafeSVG`,ye.resultType=2;var be=ae(ye),xe={site:`sit`,siteDomain:`sdm`,post:`pst`,media:`med`,uploadSession:`upl`,collection:`col`,path:`pth`,collectionDirectoryItem:`cdi`,navItem:`nav`,apiToken:`api`,user:`usr`,session:`ses`,account:`acc`,verification:`vrf`};xe.user,xe.session,xe.account,xe.verification;var Se=[`image/jpeg`,`image/png`,`image/gif`,`image/webp`,`image/svg+xml`,`image/avif`,`image/bmp`,`image/x-icon`],Ce=[`video/mp4`,`video/webm`,`video/quicktime`,`video/x-msvideo`,`video/x-matroska`,`video/mpeg`,`video/3gpp`,`video/x-flv`,`video/ogg`],we=[`audio/mpeg`,`audio/ogg`,`audio/wav`,`audio/mp4`,`audio/x-m4a`,`audio/flac`,`audio/aac`,`audio/webm`,`audio/x-aiff`,`audio/opus`,`audio/3gpp`,`audio/midi`],Te=[`application/pdf`,`application/epub+zip`,`application/x-mobipocket-ebook`,`application/vnd.amazon.ebook`],Ee=[`application/msword`,`application/vnd.openxmlformats-officedocument.wordprocessingml.document`,`application/vnd.ms-excel`,`application/vnd.openxmlformats-officedocument.spreadsheetml.sheet`,`application/vnd.ms-powerpoint`,`application/vnd.openxmlformats-officedocument.presentationml.presentation`,`application/vnd.oasis.opendocument.text`,`application/vnd.oasis.opendocument.spreadsheet`,`application/vnd.oasis.opendocument.presentation`,`application/vnd.apple.pages`,`application/vnd.apple.numbers`,`application/vnd.apple.keynote`],De=[`text/plain`,`text/markdown`,`text/csv`,`text/x-tiptap+json`,`text/html`,`text/css`,`text/javascript`,`text/xml`,`text/rtf`,`text/tab-separated-values`,`text/calendar`,`application/json`,`application/xml`,`application/yaml`,`application/toml`],Oe=[`application/zip`,`application/x-tar`,`application/gzip`,`application/x-bzip2`,`application/x-7z-compressed`,`application/x-rar-compressed`,`application/zstd`],ke=[`font/ttf`,`font/otf`,`font/woff`,`font/woff2`],Ae=[`model/gltf+json`,`model/gltf-binary`,`model/obj`,`application/x-figma`,`image/vnd.dxf`],je=[`application/sql`,`application/wasm`,`application/x-ipynb+json`,`application/x-sh`,`application/x-python-code`],Me=new Map([...Se.map(e=>[e,`image`]),...Ce.map(e=>[e,`video`]),...we.map(e=>[e,`audio`]),...Te.map(e=>[e,`document`]),...Ee.map(e=>[e,`office`]),...De.map(e=>[e,`text`]),...Oe.map(e=>[e,`archive`]),...ke.map(e=>[e,`font`]),...Ae.map(e=>[e,`3d`]),...je.map(e=>[e,`code`])]);function Ne(e){return Me.get(e)||(e.startsWith(`image/`)?`image`:e.startsWith(`video/`)?`video`:e.startsWith(`audio/`)?`audio`:e.startsWith(`font/`)?`font`:e.startsWith(`model/`)?`3d`:e.startsWith(`text/`)?`text`:`archive`)}function Pe(e){return e.startsWith(`image/`)}function Fe(e,t){return Ie(e.type,e.size,t)}function Ie(e,t,n){if(n?.imagesOnly&&!Pe(e))return`File type not allowed.`;let r=n.maxFileSizeMB;return t>r*1024*1024?`File too large (max ${r}MB).`:null}var Le=5e3,Re={SITE_NAME:{defaultValue:`Jant`,envOnly:!1,envKeys:[`SITE_NAME`]},SITE_DESCRIPTION:{defaultValue:`Thoughts, links, and quotes — one post at a time`,envOnly:!1,envKeys:[`SITE_DESCRIPTION`]},SITE_LANGUAGE:{defaultValue:`en`,envOnly:!1,envKeys:[`SITE_LANGUAGE`]},HOME_DEFAULT_VIEW:{defaultValue:`latest`,envOnly:!1,envKeys:[`HOME_DEFAULT_VIEW`]},MAIN_RSS_FEED:{defaultValue:`featured`,envOnly:!1,envKeys:[`MAIN_RSS_FEED`]},HEADER_NAV_MAX_VISIBLE:{defaultValue:`2`,envOnly:!1,envKeys:[`HEADER_NAV_MAX_VISIBLE`]},DEFAULT_THEME:{defaultValue:`linen`,envOnly:!0,envKeys:[`DEFAULT_THEME`]},SITE_ORIGIN:{defaultValue:``,envOnly:!0,envKeys:[`SITE_ORIGIN`]},SITE_PATH_PREFIX:{defaultValue:``,envOnly:!0,envKeys:[`SITE_PATH_PREFIX`]},AUTH_SECRET:{defaultValue:``,envOnly:!0,envKeys:[`AUTH_SECRET`]},R2_PUBLIC_URL:{defaultValue:``,envOnly:!0,envKeys:[`R2_PUBLIC_URL`]},IMAGE_TRANSFORM_URL:{defaultValue:``,envOnly:!0,envKeys:[`IMAGE_TRANSFORM_URL`]},DEMO_EMAIL:{defaultValue:``,envOnly:!0,envKeys:[`DEMO_EMAIL`]},DEMO_PASSWORD:{defaultValue:``,envOnly:!0,envKeys:[`DEMO_PASSWORD`]},DEMO_MODE:{defaultValue:`false`,envOnly:!0,envKeys:[`DEMO_MODE`]},PAGE_SIZE:{defaultValue:`50`,envOnly:!0,envKeys:[`PAGE_SIZE`]},SEARCH_PAGE_SIZE:{defaultValue:``,envOnly:!0,envKeys:[`SEARCH_PAGE_SIZE`]},ARCHIVE_PAGE_SIZE:{defaultValue:``,envOnly:!0,envKeys:[`ARCHIVE_PAGE_SIZE`]},STORAGE_DRIVER:{defaultValue:`r2`,envOnly:!0,envKeys:[`STORAGE_DRIVER`]},S3_ENDPOINT:{defaultValue:``,envOnly:!0,envKeys:[`S3_ENDPOINT`]},S3_BUCKET:{defaultValue:``,envOnly:!0,envKeys:[`S3_BUCKET`]},S3_ACCESS_KEY_ID:{defaultValue:``,envOnly:!0,envKeys:[`S3_ACCESS_KEY_ID`]},S3_SECRET_ACCESS_KEY:{defaultValue:``,envOnly:!0,envKeys:[`S3_SECRET_ACCESS_KEY`]},S3_REGION:{defaultValue:`auto`,envOnly:!0,envKeys:[`S3_REGION`]},S3_PUBLIC_URL:{defaultValue:``,envOnly:!0,envKeys:[`S3_PUBLIC_URL`]},UPLOAD_MAX_FILE_SIZE_MB:{defaultValue:`500`,envOnly:!0,envKeys:[`UPLOAD_MAX_FILE_SIZE_MB`]},SUMMARY_MAX_PARAGRAPHS:{defaultValue:`5`,envOnly:!0,envKeys:[`SUMMARY_MAX_PARAGRAPHS`]},SUMMARY_MAX_CHARS:{defaultValue:`500`,envOnly:!0,envKeys:[`SUMMARY_MAX_CHARS`]},SLUG_ID_LENGTH:{defaultValue:`5`,envOnly:!0,envKeys:[`SLUG_ID_LENGTH`]},RSS_FEED_LIMIT:{defaultValue:`50`,envOnly:!0,envKeys:[`RSS_FEED_LIMIT`]},THEME:{defaultValue:``,envOnly:!1,internal:!0},CUSTOM_CSS:{defaultValue:``,envOnly:!1,internal:!0},SITE_AVATAR:{defaultValue:``,envOnly:!1,internal:!0},SHOW_HEADER_AVATAR:{defaultValue:``,envOnly:!1,internal:!0},SITE_FAVICON_ICO:{defaultValue:``,envOnly:!1,internal:!0},SITE_FAVICON_APPLE_TOUCH:{defaultValue:``,envOnly:!1,internal:!0},SITE_FAVICON_VERSION:{defaultValue:``,envOnly:!1,internal:!0},FONT_THEME:{defaultValue:``,envOnly:!1,internal:!0},THEME_MODE:{defaultValue:``,envOnly:!1,internal:!0},TIME_ZONE:{defaultValue:`UTC`,envOnly:!1,envKeys:[`TIME_ZONE`]},SITE_FOOTER:{defaultValue:``,envOnly:!1,envKeys:[`SITE_FOOTER`]},SHOW_JANT_BRANDING_ON_HOME:{defaultValue:``,envOnly:!1,envKeys:[`SHOW_JANT_BRANDING_ON_HOME`]},NOINDEX:{defaultValue:``,envOnly:!1,envKeys:[`NOINDEX`]},DISCOVERY_COMPOSE_OPEN_SHORTCUT_AT:{defaultValue:``,envOnly:!1,internal:!0},ONBOARDING_STATUS:{defaultValue:`pending`,envOnly:!1,internal:!0},PASSWORD_RESET_TOKEN:{defaultValue:``,envOnly:!1,internal:!0},DELETE_CSRF_TOKEN:{defaultValue:``,envOnly:!1,internal:!0}},ze=[`featured`,`latest`,`collections`,`signin`,`signout`,`setup`,`settings`,`posts`,`dash`,`api`,`feed`,`search`,`archive`,`media`,`pages`,`reset`,`c`,`compose`,`static`,`assets`,`_assets`,`health`],Be=[`new`];function Ve(e){let t=e.split(`/`)[0]?.toLowerCase();return ze.includes(t)}Object.fromEntries(Object.entries(Re).filter(([,e])=>!e.envOnly||`internal`in e).map(([e])=>[e,e]));var He=/^[a-z0-9]+(?:-[a-z0-9]+)*$/;function Ue(e){return e.toLowerCase().replace(/[^a-z0-9-]/g,`-`).replace(/-{2,}/g,`-`).replace(/^-|-$/g,``)}function We(e,t){return Ue(e.slice(0,t))}function Ge(e,t={}){let n=e.trim();return n?t.maxLength&&n.length>t.maxLength?`too_long`:He.test(n)?Ve(n)||t.additionalReservedValues?.some(e=>e.toLowerCase()===n.toLowerCase())?`reserved`:null:`invalid`:null}var Ke=`[data-editor-floating-ui]`,qe={drafts:`
46
+ <rect x="3.85" y="3.45" width="7.85" height="8.35" rx="2.35" />
47
+ <rect
48
+ x="6.15"
49
+ y="5.75"
50
+ width="7.85"
51
+ height="8.35"
52
+ rx="2.35"
53
+ fill="var(--compose-dialog-icon-paper-fill)"
54
+ stroke="none"
55
+ />
56
+ <rect x="6.15" y="5.75" width="7.85" height="8.35" rx="2.35" />
57
+ <path d="M8.55 8.55h3.2" stroke-width="1.2" />
58
+ <path d="M8.55 10.8h3.95" stroke-width="1.2" />
59
+ <path d="M8.55 13.05h2.45" stroke-width="1.2" />
60
+ `},Je={public:`
61
+ <circle cx="8" cy="8" r="5.15" />
62
+ <path d="M3.85 8h8.3" />
63
+ <path d="M8 2.85c1.22 1.32 1.95 3.08 1.95 5.15S9.22 11.83 8 13.15" />
64
+ <path d="M8 2.85C6.78 4.17 6.05 5.93 6.05 8S6.78 11.83 8 13.15" />
65
+ `,latest_hidden:`
66
+ <path
67
+ d="M2.55 8c1.38-2.18 3.44-3.4 5.45-3.4S12.07 5.82 13.45 8c-1.38 2.18-3.44 3.4-5.45 3.4S3.93 10.18 2.55 8Z"
68
+ />
69
+ <path d="M4.35 11.1 11.65 4.9" />
70
+ `,private:`
71
+ <rect x="4.05" y="7.05" width="7.9" height="5.4" rx="1.75" />
72
+ <path d="M5.95 7.05V5.9A2.05 2.05 0 0 1 8 3.85a2.05 2.05 0 0 1 2.05 2.05v1.15" />
73
+ `},Ye={check:`
74
+ <path d="M4.35 8.2 6.9 10.7 11.65 5.95" />
75
+ `,chevron:`
76
+ <path d="M5.1 6.45 8 9.3l2.9-2.85" />
77
+ `},Xe={collection:`
78
+ <rect x="3" y="5.05" width="10" height="8.15" rx="2.2" />
79
+ <path d="M5.1 5.05V4.2a1.1 1.1 0 0 1 1.1-1.1h3.6a1.1 1.1 0 0 1 1.1 1.1v.85" />
80
+ `,search:`
81
+ <circle cx="7.1" cy="7.1" r="3.65" />
82
+ <path d="m10.1 10.1 2.45 2.45" />
83
+ `,plus:`
84
+ <path d="M8 3.5v9" />
85
+ <path d="M3.5 8h9" />
86
+ `,plusCircle:`
87
+ <circle cx="8" cy="8" r="5.7" />
88
+ <path d="M8 5.55v4.9" />
89
+ <path d="M5.55 8h4.9" />
90
+ `,chevron:`
91
+ <path d="M5.1 6.45 8 9.3l2.9-2.85" />
92
+ `};function Ze(e){return s`<svg
93
+ class="compose-dialog-header-icon"
94
+ width="24"
95
+ height="24"
96
+ viewBox="0 0 18 18"
97
+ fill="none"
98
+ stroke="currentColor"
99
+ stroke-width="1.25"
100
+ stroke-linecap="round"
101
+ stroke-linejoin="round"
102
+ aria-hidden="true"
103
+ >
104
+ ${be(e)}
105
+ </svg>`}function Qe(e,t){return s`<span class=${t} aria-hidden="true">
106
+ <svg
107
+ class="compose-publish-visibility-svg"
108
+ width="16"
109
+ height="16"
110
+ viewBox="0 0 16 16"
111
+ fill="none"
112
+ stroke="currentColor"
113
+ stroke-width="1.35"
114
+ stroke-linecap="round"
115
+ stroke-linejoin="round"
116
+ >
117
+ ${be(e)}
118
+ </svg>
119
+ </span>`}function $e(e,t){return s`<svg
120
+ class=${t}
121
+ width="16"
122
+ height="16"
123
+ viewBox="0 0 16 16"
124
+ fill="none"
125
+ stroke="currentColor"
126
+ stroke-width="1.35"
127
+ stroke-linecap="round"
128
+ stroke-linejoin="round"
129
+ aria-hidden="true"
130
+ >
131
+ ${be(e)}
132
+ </svg>`}function et(e,t){return s`<svg
133
+ class=${t}
134
+ width="14"
135
+ height="14"
136
+ viewBox="0 0 16 16"
137
+ fill="none"
138
+ stroke="currentColor"
139
+ stroke-width="1.55"
140
+ stroke-linecap="round"
141
+ stroke-linejoin="round"
142
+ aria-hidden="true"
143
+ >
144
+ ${be(e)}
145
+ </svg>`}function tt(e){return Array.isArray(e)?e.flatMap(e=>{if(!e||typeof e!=`object`)return[];let t=Reflect.get(e,`id`),n=Reflect.get(e,`title`);return typeof t!=`string`||typeof n!=`string`?[]:[{id:t,title:n}]}):[]}function nt(e){return!e.content||e.content.length===0?!0:e.content.every(e=>e.type===`paragraph`&&(!e.content||e.content.length===0))}function rt(e){return e?nt(e)?null:e:null}var it=class e extends o{static _lastNewPostVisibility=`public`;static properties={collections:{type:Array},labels:{type:Object},uploadMaxFileSize:{type:Number,attribute:`upload-max-file-size`},pageMode:{type:Boolean,attribute:`page-mode`},closeHref:{type:String,attribute:`close-href`},autoRestoreDraft:{type:Boolean,attribute:`auto-restore-draft`},_format:{state:!0},_status:{state:!0},_loading:{state:!0},_collectionIds:{state:!0},_showCollection:{state:!0},_collectionSearch:{state:!0},_altPanelOpen:{state:!0},_altPanelIndex:{state:!0},_attachedPanelOpen:{state:!0},_attachedTextIndex:{state:!0},_confirmPanelOpen:{state:!0},_editPostId:{state:!0},_draftSourceId:{state:!0},_draftsPanelOpen:{state:!0},_drafts:{state:!0},_draftsLoading:{state:!0},_draftsError:{state:!0},_draftMenuOpenId:{state:!0},_addCollectionPanelOpen:{state:!0},_replyToId:{state:!0},_replyToData:{state:!0},_replyExpanded:{state:!0},_slug:{state:!0},_visibility:{state:!0},_showPublishPanel:{state:!0},_suggestedSlug:{state:!0},_suggestedSlugLoading:{state:!0},_slugCheckLoading:{state:!0},_slugTaken:{state:!0},_visibilityLocked:{state:!0}};_attachedEditor=null;_attachedTextSnapshot=null;_confirmForDrafts=!1;_confirmForAttachedText=!1;_draftSaveTimer=null;_draftRestored=!1;_initialSnapshot=null;_pageFocusApplied=!1;_pageLeaveRequested=!1;_replyThreadRootId=null;_replyRefreshKind=null;_replyRefreshId=null;_slugCheckTimer=null;_slugSuggestTimer=null;_slugSuggestRequestId=0;_slugCheckRequestId=0;_slugSuggestionKey=``;_suppressBeforeUnload=!1;_dialogEl=null;_filePickerActive=!1;_ignoreNextEscapeClose=!1;createRenderRoot(){return this.innerHTML=``,this}constructor(){super(),this.collections=[],this.labels={},this.uploadMaxFileSize=500,this.pageMode=!1,this.closeHref=`/`,this.autoRestoreDraft=!1,this._format=`note`,this._status=`published`,this._loading=!1,this._collectionIds=[],this._showCollection=!1,this._collectionSearch=``,this._altPanelOpen=!1,this._altPanelIndex=0,this._attachedPanelOpen=!1,this._attachedTextIndex=0,this._confirmPanelOpen=!1,this._editPostId=null,this._draftSourceId=null,this._draftsPanelOpen=!1,this._drafts=[],this._draftsLoading=!1,this._draftsError=null,this._draftMenuOpenId=null,this._addCollectionPanelOpen=!1,this._replyToId=null,this._replyToData=null,this._replyExpanded=!1,this._replyThreadRootId=null,this._replyRefreshKind=null,this._replyRefreshId=null,this._slug=``,this._visibility=e._lastNewPostVisibility,this._showPublishPanel=!1,this._suggestedSlug=``,this._suggestedSlugLoading=!1,this._slugCheckLoading=!1,this._slugTaken=!1,this._visibilityLocked=!1}get _editor(){return this.querySelector(`jant-compose-editor`)}updated(e){super.updated(e),this._initialSnapshot===null&&this._editor&&this._captureInitialSnapshot(),e.has(`_addCollectionPanelOpen`)&&this._addCollectionPanelOpen&&this.updateComplete.then(()=>{let e=this.querySelector(`[data-collection-quick-dialog] [data-collection-title-input]`);e?.focus(),e?.select()}),(e.has(`_format`)||e.has(`_collectionIds`)||e.has(`_slug`)||e.has(`_visibility`))&&!this._editPostId&&!this._draftSourceId&&this._scheduleDraftSave()}reset(){this._format=`note`,this._status=`published`,this._loading=!1,this._collectionIds=[],this._showCollection=!1,this._collectionSearch=``,this._altPanelOpen=!1,this._altPanelIndex=0,this._attachedPanelOpen=!1,this._attachedTextIndex=0,this._confirmPanelOpen=!1,this._editPostId=null,this._draftSourceId=null,this._draftsPanelOpen=!1,this._drafts=[],this._draftsLoading=!1,this._draftsError=null,this._draftMenuOpenId=null,this._addCollectionPanelOpen=!1,this._replyToId=null,this._replyToData=null,this._replyExpanded=!1,this._replyThreadRootId=null,this._replyRefreshKind=null,this._replyRefreshId=null,this._slug=``,this._visibility=e._lastNewPostVisibility,this._showPublishPanel=!1,this._suggestedSlug=``,this._suggestedSlugLoading=!1,this._slugCheckLoading=!1,this._slugTaken=!1,this._slugSuggestionKey=``,this._visibilityLocked=!1,this._confirmForDrafts=!1,this._confirmForAttachedText=!1,this._initialSnapshot=null,this._pageFocusApplied=!1,this._pageLeaveRequested=!1,this._slugSuggestRequestId+=1,this._slugCheckRequestId+=1,this._suppressBeforeUnload=!1,this._filePickerActive=!1,this._ignoreNextEscapeClose=!1,this._cancelSlugTimers(),this._destroyAttachedEditor(),this._editor?.reset(),this._captureInitialSnapshot()}async refreshCollections(){try{let e=await fetch(`/api/collections?view=compose`,{headers:{Accept:`application/json`}});if(!e.ok)return!1;let t=await e.json().catch(()=>null);return Array.isArray(t?.collections)?(this.collections=tt(t.collections),!0):!1}catch{return!1}}async openEdit(e){this.reset();let t=await fetch(`/api/posts/${e}`);if(!t.ok)return;let n=await t.json();this._editPostId=e,this._format=n.format,this._slug=n.slug??``,this._slugTaken=!1,this._slugCheckLoading=!1,this._suggestedSlug=``,this._suggestedSlugLoading=!1,this._slugSuggestionKey=``,this._visibility=n.visibility??`public`,this._visibilityLocked=!!n.replyToId,n.collectionIds?.length&&(this._collectionIds=n.collectionIds),await this.updateComplete;let r=n.mediaAttachments??[],i=r.filter(e=>!e.mimeType.startsWith(`text/`)),a=r.filter(e=>e.mimeType===`text/x-tiptap+json`),o=await Promise.all(a.map(async e=>{try{let t=await fetch(`/api/media/${e.id}/content`);if(t.ok){let n=await t.text(),r=JSON.parse(n);return{bodyJson:JSON.stringify(r.json??{}),bodyHtml:r.html??``,summary:e.summary??``,mediaId:e.id}}}catch{}return{bodyJson:`{}`,bodyHtml:``,summary:e.summary??``,mediaId:e.id}}));this._editor?.populate({format:n.format,title:n.format===`quote`?void 0:n.title??void 0,bodyJson:n.body??void 0,url:n.format===`quote`?n.sourceUrl??void 0:n.url??void 0,quoteText:n.quoteText??void 0,quoteAuthor:n.format===`quote`?n.sourceName??void 0:void 0,rating:n.rating??void 0,media:i.map(e=>({id:e.id,previewUrl:e.previewUrl,alt:e.alt,mimeType:e.mimeType})),textAttachments:o,attachmentOrder:r.map(e=>e.id)}),this.closest(`dialog`)?.showModal(),globalThis.requestAnimationFrame(()=>{this._editor?.focusInput(),this._captureInitialSnapshot()})}async openNew(e){this.reset(),e?.restoreDraft!==!1&&await this.restoreLocalDraft(),e?.collectionId&&!this._collectionIds.includes(e.collectionId)&&(this._collectionIds=[e.collectionId,...this._collectionIds]),this.closest(`dialog`)?.showModal(),await this.updateComplete,this._editor?.focusInput(),this._captureInitialSnapshot()}async openReply(e,t,n,r){this.reset(),this._replyToId=e,this._replyThreadRootId=n??e,this._replyRefreshKind=r?.kind??null,this._replyRefreshId=r?.id??null,this._replyToData=t??null,this._format=`note`,this.closest(`dialog`)?.showModal(),await this.updateComplete,this._editor?.focusInput(),this._captureInitialSnapshot()}async _fetchReplyContext(e){try{let t=await fetch(`/api/posts/${e}`);if(!t.ok)return;let n=await t.json();this._replyThreadRootId=n.replyToId?n.threadId:n.id;let r=n.publishedAt?new Date(n.publishedAt*1e3).toLocaleDateString(void 0,{month:`short`,day:`numeric`}):``;this._replyToData={contentHtml:n.bodyHtml??``,dateText:r}}catch{}}set loading(e){this._loading=e}_closeDialog(){let e=this.closest(`dialog`);if(e){e.close(),document.activeElement?.blur();return}this.pageMode&&(this._suppressBeforeUnload=!0,globalThis.location.assign(this.closeHref||a(`/`)))}requestCloseAndLeave(){this._pageLeaveRequested=!0,this.requestClose()}consumePageLeaveRequest(){let e=this._pageLeaveRequested;return this._pageLeaveRequested=!1,e}preparePageLeave(){this._suppressBeforeUnload=!0}_clearFilePickerEscapeState(){this._filePickerActive=!1,this._ignoreNextEscapeClose=!1}_shouldIgnoreEscapeClose(){return this._filePickerActive||this._ignoreNextEscapeClose?(this._clearFilePickerEscapeState(),!0):!1}_hasContent(){let e=this._editor;if(!e)return!1;let t=e.getData();return!!(t.body||t.title.trim()||t.url.trim()||t.quoteText.trim()||t.quoteAuthor.trim()||t.attachedTexts.length>0||t.rating>0||t.attachments.length>0)}_buildSnapshot(){let e=this._editor;if(!e)return null;let t=e.getData(),n=e.getEffectiveAttachedTexts(),r=this._format===`note`&&t.title.trim().length>0?e._showTitle:!1,i=t.rating>0?e._showRating:!1;return{format:this._format,collectionIds:[...this._collectionIds],slug:this._slug,visibility:this._visibility,title:t.title,bodyJson:e.getNormalizedBodyJson(),url:t.url,quoteText:t.quoteText,quoteAuthor:t.quoteAuthor,rating:t.rating,showTitle:r,showRating:i,attachments:e._attachments.map(e=>({clientId:e.clientId,mediaId:e.mediaId,previewUrl:e.previewUrl,mimeType:e.file.type,alt:e.alt,status:e.status,summary:e.summary,chars:e.chars})),attachedTexts:n.map(e=>({clientId:e.clientId,mediaId:e.mediaId??null,bodyJson:e.bodyJson,bodyHtml:e.bodyHtml,summary:e.summary})),attachmentOrder:e.getEffectiveAttachmentOrder()}}_serializeSnapshot(e){return e?JSON.stringify(e):null}_captureInitialSnapshot(){this._initialSnapshot=this._serializeSnapshot(this._buildSnapshot())}_hasUnsavedChanges(){let e=this._serializeSnapshot(this._buildSnapshot());return e===null||!this._editPostId&&!this._draftSourceId&&!this._hasContent()?!1:this._initialSnapshot===null?this._hasContent():e!==this._initialSnapshot}requestClose(){if(!this._loading){if(this._showCollection&&(this._showCollection=!1,this._collectionSearch=``),this._showPublishPanel&&=!1,this._confirmPanelOpen){let e=this._confirmForAttachedText;this._confirmPanelOpen=!1,this._confirmForDrafts=!1,this._confirmForAttachedText=!1,this._pageLeaveRequested=!1,this.updateComplete.then(()=>{if(e){this._attachedEditor?.commands.focus();return}this._editor?.focusInput()});return}if(this._editPostId){this._hasUnsavedChanges()?(this._confirmForDrafts=!1,this._confirmForAttachedText=!1,this._confirmPanelOpen=!0):(this._closeDialog(),this.reset());return}this._hasContent()?(this._confirmForDrafts=!1,this._confirmForAttachedText=!1,this._confirmPanelOpen=!0):(this._closeDialog(),this.reset())}}_discardAndClose(){if(this._draftSourceId){let e=this._draftSourceId;fetch(`/api/posts/${e}`,{method:`DELETE`}).catch(()=>{}),m(this.labels.draftDeleted)}this._clearDraftFromStorage(),this._confirmPanelOpen=!1,this._confirmForAttachedText=!1,this._closeDialog(),this.reset()}_discardAttachedPanel(){this._confirmForAttachedText=!1,this._destroyAttachedEditor(),this._attachedPanelOpen=!1,this._editor?.closeAttachedPanel(this._attachedTextIndex)}_handleConfirmSave(){this._confirmForAttachedText?(this._confirmPanelOpen=!1,this._confirmForAttachedText=!1,this._doneAttachedPanel()):this._confirmForDrafts?(this._dispatchSubmit(`draft`),this._confirmPanelOpen=!1,this.reset(),this._openDraftsPanel()):this._editPostId?(this._confirmPanelOpen=!1,this._submit(`published`)):(this._confirmPanelOpen=!1,this._submit(`draft`))}_handleConfirmDiscard(){if(this._confirmForAttachedText)this._confirmPanelOpen=!1,this._discardAttachedPanel();else if(this._confirmForDrafts){if(this._draftSourceId){let e=this._draftSourceId;fetch(`/api/posts/${e}`,{method:`DELETE`}).catch(()=>{}),m(this.labels.draftDeleted)}this._confirmPanelOpen=!1,this.reset(),this._openDraftsPanel()}else this._discardAndClose()}_buildSubmitDetail(e){let t=this._editor;if(!t)return null;let n=t.getData(),r=new Map((n.attachments??[]).map(e=>[e.clientId,e])),i=new Map(n.attachedTexts.map(e=>[e.clientId,e])),a=[];for(let e of n.attachmentOrder){let t=r.get(e);if(t){a.push({type:`media`,clientId:e,mediaId:t.mediaId,alt:t.alt||void 0});continue}let n=i.get(e);n?.bodyJson&&a.push({type:`text`,clientId:e,bodyJson:n.bodyJson,summary:n.summary,mediaId:n.mediaId,originalBodyJson:rt(n.originalBodyJson??null)})}return{format:this._format,title:n.title,body:n.body,url:n.url,quoteText:n.quoteText,quoteAuthor:n.quoteAuthor,slug:this._slug.trim()||void 0,status:e,visibility:this._visibilityLocked?void 0:this._visibility,rating:n.rating,collectionIds:[...this._collectionIds],attachments:a,editPostId:this._editPostId??this._draftSourceId??void 0,replyToId:this._replyToId??void 0,replyThreadRootId:this._replyThreadRootId??void 0,replyRefreshKind:this._replyRefreshKind??void 0,replyRefreshId:this._replyRefreshId??void 0}}_focusBlockedSubmitField(){if(this._getSlugValidationMessage())return this._revealSlugField(),!0;let e=this._editor;return e?e.getUrlValidationMessage()?(e.revealUrlValidation(),e.focusUrlInput(`end`),!0):e.getLinkTitleValidationMessage()?(e.revealLinkTitleValidation(),e.focusLinkTitleInput(`end`),!0):this._format===`quote`&&!e._quoteText.trim()?(e.focusInput(`end`),!0):!1:!1}_dispatchSubmit(e){if(this._loading)return!1;let t=this._editor;if(!t||this._focusBlockedSubmitField())return!1;let n=this._buildSubmitDetail(e);if(!n)return!1;let r=(t._attachments??[]).filter(e=>e.status===`pending`||e.status===`processing`||e.status===`uploading`);return this.dispatchEvent(new CustomEvent(`jant:compose-submit-deferred`,{bubbles:!0,detail:{...n,pendingAttachments:r}})),!0}_submit(e){if(this._showPublishPanel=!1,this._clearDraftFromStorage(),this._dispatchSubmit(e)){if(this.pageMode){this._loading=!0;return}this._closeDialog(),this.reset()}}_toggleCollection(e){this._collectionIds.includes(e)?this._collectionIds=this._collectionIds.filter(t=>t!==e):this._collectionIds=[...this._collectionIds,e]}_selectedCollectionLabel(e){let t=this._collectionIds,n=e.find(e=>e.id===t[0]);return n?t.length===1?n.title:this.labels.collectionCountLabel.replace(`%name%`,n.title).replace(`%count%`,String(t.length-1)):``}_cancelSlugTimers(){this._slugCheckTimer!==null&&(clearTimeout(this._slugCheckTimer),this._slugCheckTimer=null),this._slugSuggestTimer!==null&&(clearTimeout(this._slugSuggestTimer),this._slugSuggestTimer=null)}_currentSlugOwnerId(){return this._editPostId??this._draftSourceId??void 0}_hasManualSlug(){return this._slug.trim().length>0}_currentSuggestionTitle(){return this._editor?.getData().title.trim()??``}_canSuggestSlug(){return this._currentSuggestionTitle().length>0}_currentSuggestionKey(){return`${this._currentSlugOwnerId()??``}::${this._currentSuggestionTitle()}`}_scheduleSuggestedSlugRefresh(e=!1){if(!this._showPublishPanel||this._hasManualSlug())return;if(!this._canSuggestSlug()){this._slugSuggestRequestId+=1,this._suggestedSlug=``,this._suggestedSlugLoading=!1,this._slugSuggestionKey=``;return}let t=this._currentSuggestionKey();if(this._slugSuggestionKey!==t&&(this._suggestedSlug=``),!e&&!this._suggestedSlugLoading&&this._suggestedSlug&&this._slugSuggestionKey===t)return;this._slugSuggestTimer!==null&&(clearTimeout(this._slugSuggestTimer),this._slugSuggestTimer=null);let n=()=>void this._refreshSuggestedSlug(t);if(e){n();return}this._slugSuggestTimer=setTimeout(n,250)}async _refreshSuggestedSlug(e){if(this._slugSuggestTimer=null,this._hasManualSlug()||!this._canSuggestSlug())return;let t=++this._slugSuggestRequestId;this._suggestedSlugLoading=!0;let n=new URLSearchParams({mode:`suggest`}),r=this._currentSuggestionTitle();r&&n.set(`title`,r);let i=this._currentSlugOwnerId();i&&n.set(`postId`,i);try{let r=await fetch(`/api/posts/slug?${n.toString()}`);if(!r.ok)return;let i=await r.json();if(t!==this._slugSuggestRequestId||this._hasManualSlug()||!this._showPublishPanel)return;this._suggestedSlug=i.slug?.trim()??``,this._slugSuggestionKey=e}catch{}finally{t===this._slugSuggestRequestId&&(this._suggestedSlugLoading=!1)}}_scheduleSlugAvailabilityCheck(){if(!this._hasManualSlug()){this._slugTaken=!1,this._slugCheckLoading=!1;return}if(this._slugCheckTimer!==null&&(clearTimeout(this._slugCheckTimer),this._slugCheckTimer=null),this._getSlugSyncValidationMessage()){this._slugTaken=!1,this._slugCheckLoading=!1;return}this._slugCheckLoading=!0;let e=this._slug.trim();this._slugCheckTimer=setTimeout(()=>{this._checkSlugAvailability(e)},250)}async _checkSlugAvailability(e){this._slugCheckTimer=null;let t=++this._slugCheckRequestId,n=new URLSearchParams({mode:`check`,slug:e}),r=this._currentSlugOwnerId();r&&n.set(`postId`,r);try{let r=await fetch(`/api/posts/slug?${n.toString()}`);if(!r.ok)return;let i=await r.json();if(t!==this._slugCheckRequestId||this._slug.trim()!==e)return;this._slugTaken=i.available===!1}catch{}finally{t===this._slugCheckRequestId&&(this._slugCheckLoading=!1)}}_useSuggestedSlug(){this._suggestedSlug&&(this._slug=this._suggestedSlug,this._slugTaken=!1,this._slugCheckLoading=!1,this.updateComplete.then(()=>{this.querySelector(`.compose-publish-slug-input`)?.focus()}))}_resetCustomSlug(){this._slug=``,this._slugTaken=!1,this._slugCheckLoading=!1,this._scheduleSuggestedSlugRefresh(!0),this.updateComplete.then(()=>{this.querySelector(`.compose-publish-slug-input`)?.focus()})}connectedCallback(){super.connectedCallback(),this.addEventListener(`keydown`,this._handleKeydown),this.addEventListener(`jant:alt-panel-open`,this._handleAltPanelOpen),this.addEventListener(`jant:alt-panel-close`,this._handleAltPanelClose),this.addEventListener(`jant:attached-panel-open`,this._handleAttachedPanelOpen),this.addEventListener(`jant:compose-content-changed`,this._onContentChanged),this.addEventListener(`jant:file-picker-open`,this._handleFilePickerOpen),this.addEventListener(`jant:file-picker-close`,this._handleFilePickerClose),this.addEventListener(`jant:fullscreen-open`,this._handleFullscreenOpen),this.addEventListener(`pointerdown`,this._handlePointerDown),document.addEventListener(`jant:fullscreen-close`,this._handleFullscreenClose),window.addEventListener(`beforeunload`,this._onBeforeUnload),this._dialogEl=this.closest(`dialog`),this._dialogEl&&(this._dialogEl.addEventListener(`cancel`,this._handleDialogCancel),this._dialogEl.addEventListener(`click`,this._handleDialogClick)),this.pageMode&&this.updateComplete.then(()=>this._focusPageEditorOnMount())}disconnectedCallback(){super.disconnectedCallback(),this.removeEventListener(`keydown`,this._handleKeydown),this.removeEventListener(`jant:alt-panel-open`,this._handleAltPanelOpen),this.removeEventListener(`jant:alt-panel-close`,this._handleAltPanelClose),this.removeEventListener(`jant:attached-panel-open`,this._handleAttachedPanelOpen),this.removeEventListener(`jant:compose-content-changed`,this._onContentChanged),this.removeEventListener(`jant:file-picker-open`,this._handleFilePickerOpen),this.removeEventListener(`jant:file-picker-close`,this._handleFilePickerClose),this.removeEventListener(`jant:fullscreen-open`,this._handleFullscreenOpen),this.removeEventListener(`pointerdown`,this._handlePointerDown),document.removeEventListener(`jant:fullscreen-close`,this._handleFullscreenClose),window.removeEventListener(`beforeunload`,this._onBeforeUnload),this._cancelSlugTimers(),this._destroyAttachedEditor(),this._cancelDraftSaveTimer(),this._dialogEl&&=(this._dialogEl.removeEventListener(`cancel`,this._handleDialogCancel),this._dialogEl.removeEventListener(`click`,this._handleDialogClick),null)}_handleFilePickerOpen=()=>{this._filePickerActive=!0,this._ignoreNextEscapeClose=!1};_handleFilePickerClose=e=>{this._filePickerActive=!1,this._ignoreNextEscapeClose=!!e.detail?.cancelled};_handlePointerDown=()=>{this._clearFilePickerEscapeState()};_handleDialogCancel=e=>{e.preventDefault(),!this._shouldIgnoreEscapeClose()&&(this._dismissEscapeOverlay()||this.requestClose())};_handleDialogClick=e=>{if(!this._dialogEl||e.target!==this._dialogEl)return;let t=e,n=document.elementFromPoint(t.clientX,t.clientY);n instanceof globalThis.Element&&n.closest(Ke)||this.requestClose()};_focusPageEditorEnd(){this.updateComplete.then(()=>this._editor?.focusInput(`end`))}_dismissEscapeOverlay(){return this._confirmPanelOpen?(this.requestClose(),!0):this._addCollectionPanelOpen?(this._closeAddCollectionPanel(),!0):this._editor?.isEmojiPickerOpen()?(this._editor.closeEmojiPicker({restoreFocus:!0}),!0):this._showCollection?(this._showCollection=!1,this._collectionSearch=``,this._focusPageEditorEnd(),!0):this._showPublishPanel?(this._showPublishPanel=!1,this._focusPageEditorEnd(),!0):this._altPanelOpen?(this._closeAltPanel(),this._focusPageEditorEnd(),!0):this._draftMenuOpenId?(this._draftMenuOpenId=null,!0):this._draftsPanelOpen?(this._closeDraftsPanel(),!0):this._attachedPanelOpen?(this._cancelAttachedPanel(),!0):!1}_handleKeydown=e=>{let t=e;if(t.key!==`Escape`&&this._clearFilePickerEscapeState(),t.key===`Escape`){if(t.preventDefault(),t.stopPropagation(),this._shouldIgnoreEscapeClose()||this._dismissEscapeOverlay())return;this.requestClose()}else if(t.key===`Enter`&&this._confirmPanelOpen)t.preventDefault(),this._handleConfirmSave();else if((t.metaKey||t.ctrlKey)&&t.key===`Enter`){if(e.preventDefault(),this._attachedPanelOpen){this._doneAttachedPanel();return}if(!this._canPublish()){this._focusBlockedSubmitField();return}this._submit(`published`)}};_handleAltPanelOpen=e=>{this._altPanelIndex=e.detail.index,this._altPanelOpen=!0,this.updateComplete.then(()=>{this.querySelector(`.compose-alt-input`)?.focus()})};_handleAltPanelClose=()=>{this._altPanelOpen=!1};_getAltAttachment(){return this._editor?._attachments[this._altPanelIndex]??null}_onAltInput(e){let t=e.target.value;this._editor?.updateAlt(this._altPanelIndex,t)}_closeAltPanel(){this._altPanelOpen=!1}_handleFullscreenClose=e=>{let t=this._editor;t&&(t.setEditorState(e.detail.json,e.detail.title,e.detail.showTitle),this.updateComplete.then(()=>t.focusInput(`end`))),this._replyExpanded=e.detail.replyExpanded};_buildFullscreenReplyContext(){return!this._replyToId||!this._replyToData?null:{contentHtml:this._replyToData.contentHtml,dateText:this._replyToData.dateText,expanded:this._replyExpanded}}_handleFullscreenOpen=e=>{e.detail.replyContext=this._buildFullscreenReplyContext()};_handleAttachedPanelOpen=e=>{this._attachedTextIndex=e.detail.index,this._attachedPanelOpen=!0,this.updateComplete.then(()=>{let e=this.querySelector(`.compose-attached-tiptap`);if(!e)return;let t=this._editor?._attachedTexts[this._attachedTextIndex]?.bodyJson??null;this._attachedTextSnapshot=t?JSON.parse(JSON.stringify(t)):null,this._attachedEditor=y({element:e,placeholder:this.labels.attachedTextPlaceholder,content:t,toolbarMode:`compose`}),this._focusAttachedEditorBoundary(t)})};_focusAttachedEditorBoundary(e){if(!this._attachedEditor)return;let t=rt(e??this._attachedEditor.getJSON())?`end`:`start`;this._attachedEditor.commands.focus(t)}_isAttachedTextDirty(){return this._attachedEditor?JSON.stringify(rt(this._attachedEditor.getJSON()))!==JSON.stringify(rt(this._attachedTextSnapshot)):!1}_destroyAttachedEditor(){this._attachedEditor&&=(this._attachedEditor.destroy(),null),this._attachedTextSnapshot=null}_doneAttachedPanel(){if(this._attachedEditor){let e=this._attachedEditor.getJSON(),t=this._attachedEditor.getHTML();this._editor?.updateAttachedText(this._attachedTextIndex,e,t)}this._confirmForAttachedText=!1,this._destroyAttachedEditor(),this._attachedPanelOpen=!1,this._editor?.closeAttachedPanel(this._attachedTextIndex)}_cancelAttachedPanel(){if(this._isAttachedTextDirty()){this._confirmForDrafts=!1,this._confirmForAttachedText=!0,this._confirmPanelOpen=!0;return}this._discardAttachedPanel()}_handleAttachedEditorMouseDown(e){e.target===e.currentTarget&&(e.preventDefault(),this._focusAttachedEditorBoundary())}_handleDraftButtonClick(){this._loading||(this._hasContent()?(this._confirmForDrafts=!0,this._confirmPanelOpen=!0):this._openDraftsPanel())}async _openDraftsPanel(){this._draftsPanelOpen=!0,this._draftsLoading=!0,this._draftsError=null,this._draftMenuOpenId=null;try{let e=await fetch(`/api/posts?status=draft&limit=50`);if(!e.ok)throw Error(`Failed to load drafts`);let t=await e.json();this._drafts=(Array.isArray(t)?t:t.posts??[]).map(e=>({id:e.id,format:e.format,title:(e.format===`quote`?e.sourceName:e.title)??null,bodyText:e.bodyText??null,bodyHtml:e.bodyHtml??null,url:(e.format===`quote`?e.sourceUrl:e.url)??null,quoteText:e.quoteText??null,replyToId:e.replyToId??null,updatedAt:e.updatedAt,mediaAttachments:(e.mediaAttachments??[]).map(e=>({id:e.id,previewUrl:e.previewUrl,alt:e.alt,mimeType:e.mimeType}))}))}catch{this._draftsError=`Could not load drafts. Try again.`,this._drafts=[]}finally{this._draftsLoading=!1}}_closeDraftsPanel(){this._draftsPanelOpen=!1,this._draftMenuOpenId=null,this.updateComplete.then(()=>this._editor?.focusInput())}async _loadDraft(e){this._draftsPanelOpen=!1,this._draftMenuOpenId=null,this.reset();let t=await fetch(`/api/posts/${e}`);if(!t.ok)return;let n=await t.json();this._draftSourceId=e,this._format=n.format,this._slug=n.slug??``,this._slugTaken=!1,this._slugCheckLoading=!1,this._suggestedSlug=``,this._suggestedSlugLoading=!1,this._slugSuggestionKey=``,this._visibility=n.visibility??`public`,this._visibilityLocked=!!n.replyToId,n.collectionIds?.length&&(this._collectionIds=n.collectionIds),n.replyToId&&(this._replyToId=n.replyToId,await this._fetchReplyContext(n.replyToId)),await this.updateComplete;let r=n.mediaAttachments??[],i=r.filter(e=>!e.mimeType.startsWith(`text/`)),a=r.filter(e=>e.mimeType===`text/x-tiptap+json`),o=await Promise.all(a.map(async e=>{try{let t=await fetch(`/api/media/${e.id}/content`);if(t.ok){let n=await t.text(),r=JSON.parse(n);return{bodyJson:JSON.stringify(r.json??{}),bodyHtml:r.html??``,summary:e.summary??``,mediaId:e.id}}}catch{}return{bodyJson:`{}`,bodyHtml:``,summary:e.summary??``,mediaId:e.id}}));this._editor?.populate({format:n.format,title:n.format===`quote`?void 0:n.title??void 0,bodyJson:n.body??void 0,url:n.format===`quote`?n.sourceUrl??void 0:n.url??void 0,quoteText:n.quoteText??void 0,quoteAuthor:n.format===`quote`?n.sourceName??void 0:void 0,rating:n.rating??void 0,media:i.map(e=>({id:e.id,previewUrl:e.previewUrl,alt:e.alt,mimeType:e.mimeType})),textAttachments:o,attachmentOrder:r.map(e=>e.id)}),globalThis.requestAnimationFrame(()=>{this._editor?.focusInput(),this._captureInitialSnapshot()})}async _deleteDraft(e){this._draftMenuOpenId=null,this._drafts=this._drafts.filter(t=>t.id!==e);try{if(!(await fetch(`/api/posts/${e}`,{method:`DELETE`})).ok)throw Error();m(this.labels.draftDeleted)}catch{m(`Failed to delete draft. Try again.`,`error`),this._openDraftsPanel()}}_formatDraftDate(e){let t=Date.now()/1e3-e;return t<60?`now`:t<3600?`${Math.floor(t/60)}m`:t<86400?`${Math.floor(t/3600)}h`:t<604800?`${Math.floor(t/86400)}d`:new Date(e*1e3).toLocaleDateString(void 0,{month:`short`,day:`numeric`})}_getDraftPreview(e){return e.bodyText?e.bodyText:e.title?e.title:e.quoteText?e.quoteText:e.url?e.url:null}static _DRAFT_KEY=`jant:compose-draft`;static _DRAFT_MAX_AGE=10080*60*1e3;_onContentChanged=()=>{this.requestUpdate(),this._hasManualSlug()||this._scheduleSuggestedSlugRefresh(),!this._editPostId&&!this._draftSourceId&&this._scheduleDraftSave()};_cancelDraftSaveTimer(){this._draftSaveTimer!==null&&(clearTimeout(this._draftSaveTimer),this._draftSaveTimer=null)}_scheduleDraftSave(){this._cancelDraftSaveTimer(),this._draftSaveTimer=setTimeout(()=>this._saveDraftToStorage(),1e3)}_onBeforeUnload=e=>{if(this._suppressBeforeUnload)return;this._draftSaveTimer!==null&&(this._cancelDraftSaveTimer(),this._saveDraftToStorage());let t=this.closest(`dialog`);this._hasUnsavedChanges()&&(this.pageMode||t?.open===!0)&&(e.preventDefault(),e.returnValue=``)};_saveDraftToStorage(){let t=this._editor;if(!t)return;let n=t.getData();if(!(n.body||n.title.trim()||n.url.trim()||n.quoteText.trim()||n.quoteAuthor.trim()||n.rating>0||n.attachedTexts.length>0)){globalThis.localStorage.removeItem(e._DRAFT_KEY);return}let r={format:this._format,title:n.title,bodyJson:t.getNormalizedBodyJson(),url:n.url,quoteText:n.quoteText,quoteAuthor:n.quoteAuthor,slug:this._slug,visibility:this._visibility,rating:n.rating,showTitle:this._format===`note`&&n.title.trim().length>0?t._showTitle:!1,showRating:n.rating>0?t._showRating:!1,collectionIds:[...this._collectionIds],replyToId:this._replyToId,attachedTexts:n.attachedTexts.map(e=>({clientId:e.clientId,bodyJson:e.bodyJson,bodyHtml:e.bodyHtml,summary:e.summary})),attachmentOrder:[...n.attachmentOrder],savedAt:Date.now()};try{globalThis.localStorage.setItem(e._DRAFT_KEY,JSON.stringify(r))}catch{}}_clearDraftFromStorage(){this._cancelDraftSaveTimer(),globalThis.localStorage.removeItem(e._DRAFT_KEY)}async restoreLocalDraft(){if(this._editPostId||this._draftSourceId||this._hasContent())return;let t;try{t=globalThis.localStorage.getItem(e._DRAFT_KEY)}catch{return}if(!t)return;let n;try{n=JSON.parse(t)}catch{globalThis.localStorage.removeItem(e._DRAFT_KEY);return}if(Date.now()-n.savedAt>e._DRAFT_MAX_AGE){globalThis.localStorage.removeItem(e._DRAFT_KEY);return}this._format=n.format,this._collectionIds=[...n.collectionIds??[]],this._slug=n.slug??``,this._slugTaken=!1,this._slugCheckLoading=!1,this._suggestedSlug=``,this._suggestedSlugLoading=!1,this._slugSuggestionKey=``,this._visibility=n.visibility??`public`,n.replyToId&&(this._replyToId=n.replyToId,await this._fetchReplyContext(n.replyToId)),await this.updateComplete;let r=n.attachedTexts?.flatMap(e=>{let t=rt(e.bodyJson);return t?[{clientId:e.clientId,bodyJson:JSON.stringify(t),bodyHtml:e.bodyHtml,summary:e.summary}]:[]});this._editor?.populate({format:n.format,title:n.title||void 0,bodyJson:n.bodyJson?JSON.stringify(n.bodyJson):void 0,url:n.url||void 0,quoteText:n.quoteText||void 0,quoteAuthor:n.quoteAuthor||void 0,rating:n.rating||void 0,showTitle:n.showTitle,showRating:n.showRating,textAttachments:r?.length?r:void 0,attachmentOrder:n.attachmentOrder}),this._draftRestored=!0,m(this.labels.draftRestored),globalThis.requestAnimationFrame(()=>{this._captureInitialSnapshot()})}async _focusPageEditorOnMount(){this._pageFocusApplied||(this.autoRestoreDraft&&await this.restoreLocalDraft(),await this.updateComplete,globalThis.requestAnimationFrame(()=>{this._editor?.focusInput(),this._pageFocusApplied=!0}))}_renderDraftsPanel(){return this._draftsPanelOpen?s`
146
+ <div class="compose-drafts-panel">
147
+ <div class="compose-alt-header">
148
+ <button
149
+ type="button"
150
+ class="compose-attached-panel-back"
151
+ @click=${()=>this._closeDraftsPanel()}
152
+ >
153
+ <svg
154
+ class="icon-fine"
155
+ width="16"
156
+ height="16"
157
+ viewBox="0 0 16 16"
158
+ fill="none"
159
+ stroke="currentColor"
160
+ stroke-width="1.5"
161
+ stroke-linecap="round"
162
+ stroke-linejoin="round"
163
+ >
164
+ <path d="M11 3L6 8l5 5" />
165
+ </svg>
166
+ </button>
167
+ <span class="compose-alt-title">${this.labels.drafts}</span>
168
+ </div>
169
+ ${this._draftsLoading?s`<div class="compose-drafts-loading">
170
+ <svg
171
+ class="animate-spin size-5"
172
+ xmlns="http://www.w3.org/2000/svg"
173
+ viewBox="0 0 24 24"
174
+ fill="none"
175
+ stroke="currentColor"
176
+ stroke-width="2"
177
+ stroke-linecap="round"
178
+ stroke-linejoin="round"
179
+ >
180
+ <path d="M21 12a9 9 0 1 1-6.219-8.56" />
181
+ </svg>
182
+ </div>`:this._draftsError?s`<div class="compose-drafts-empty">${this._draftsError}</div>`:this._drafts.length===0?s`<div class="compose-drafts-empty">
183
+ ${this.labels.draftsEmpty}
184
+ </div>`:s`<div class="compose-drafts-list">
185
+ ${this._drafts.map((e,t)=>s`
186
+ ${t>0?s`<div class="compose-drafts-divider"></div>`:i}
187
+ ${this._renderDraftItem(e)}
188
+ `)}
189
+ </div>`}
190
+ </div>
191
+ `:i}_renderDraftItem(e){let t=this._getDraftPreview(e);return s`
192
+ <div class="compose-draft-item" @click=${()=>this._loadDraft(e.id)}>
193
+ <div class="compose-draft-content">
194
+ ${t?s`<div class="compose-draft-preview">${t}</div>`:s`<div
195
+ class="compose-draft-preview compose-draft-preview-empty"
196
+ >
197
+ Empty draft
198
+ </div>`}
199
+ <div class="compose-draft-meta">
200
+ ${this._formatDraftDate(e.updatedAt)}
201
+ </div>
202
+ </div>
203
+ <div class="relative">
204
+ ${this._draftMenuOpenId===e.id?s`<div
205
+ class="compose-dropdown-backdrop"
206
+ @click=${e=>{e.stopPropagation(),this._draftMenuOpenId=null}}
207
+ ></div>`:i}
208
+ <button
209
+ type="button"
210
+ class="compose-draft-more"
211
+ @click=${t=>{t.stopPropagation(),this._draftMenuOpenId=this._draftMenuOpenId===e.id?null:e.id}}
212
+ >
213
+ <svg width="16" height="16" viewBox="0 0 16 16" fill="currentColor">
214
+ <circle cx="4" cy="8" r="1.2" />
215
+ <circle cx="8" cy="8" r="1.2" />
216
+ <circle cx="12" cy="8" r="1.2" />
217
+ </svg>
218
+ </button>
219
+ ${this._draftMenuOpenId===e.id?s`
220
+ <div class="compose-dropdown compose-dropdown-right">
221
+ <button
222
+ type="button"
223
+ class="compose-dropdown-item compose-dropdown-item-danger"
224
+ @click=${t=>{t.stopPropagation(),this._deleteDraft(e.id)}}
225
+ >
226
+ ${this.labels.deleteDraft}
227
+ </button>
228
+ </div>
229
+ `:i}
230
+ </div>
231
+ </div>
232
+ `}_renderReplyContext(){if(!this._replyToId||!this._replyToData)return i;let{contentHtml:e,dateText:t}=this._replyToData,n=this._replyExpanded;return s`
233
+ <div class="compose-reply-row">
234
+ <div class="compose-thread-dot"></div>
235
+ <div
236
+ class=${w({"compose-reply-context":!0,expanded:n})}
237
+ >
238
+ <div class="compose-reply-context-body">
239
+ ${ne(e)}
240
+ </div>
241
+ ${n?i:s`<div class="compose-reply-fade"></div>`}
242
+ </div>
243
+ </div>
244
+ <div class="compose-reply-meta">
245
+ ${t?s`<span>${t}</span><span>·</span>`:i}
246
+ <button
247
+ type="button"
248
+ class="compose-reply-toggle"
249
+ @click=${()=>{this._replyExpanded=!this._replyExpanded}}
250
+ >
251
+ ${n?this.labels.showLess:this.labels.showMore}
252
+ </button>
253
+ </div>
254
+ `}_renderHeader(){let e=[`note`,`link`,`quote`],t={note:this.labels.note,link:this.labels.link,quote:this.labels.quote},n=this._hasContent()?this.labels.saveAsDraft:this.labels.drafts;return s`
255
+ <header class="compose-dialog-header">
256
+ <button
257
+ type="button"
258
+ class="compose-dialog-cancel"
259
+ @click=${()=>this.requestClose()}
260
+ >
261
+ ${this.labels.cancel}
262
+ </button>
263
+
264
+ <div class="compose-dialog-header-center">
265
+ ${this._editPostId?s`<span class="compose-dialog-title"
266
+ >${this.labels.editPost}</span
267
+ >`:s`
268
+ <div class="compose-segmented">
269
+ <div
270
+ class=${w({"compose-format-pill":!0,"compose-format-pill-link":this._format===`link`,"compose-format-pill-quote":this._format===`quote`})}
271
+ ></div>
272
+ ${e.map(e=>s`
273
+ <button
274
+ type="button"
275
+ class=${w({"compose-segmented-item":!0,"compose-segmented-item-active":this._format===e})}
276
+ @click=${()=>{this._format=e,this._showPublishPanel=!1,globalThis.requestAnimationFrame(()=>this._editor?.focusInput())}}
277
+ >
278
+ ${t[e]}
279
+ </button>
280
+ `)}
281
+ </div>
282
+ `}
283
+ </div>
284
+
285
+ <div class="compose-dialog-header-actions">
286
+ ${this._editPostId?i:s`<button
287
+ type="button"
288
+ class="compose-dialog-header-btn compose-dialog-draft-btn"
289
+ aria-label=${n}
290
+ title=${n}
291
+ ?disabled=${this._loading}
292
+ @click=${()=>this._handleDraftButtonClick()}
293
+ >
294
+ ${Ze(qe.drafts)}
295
+ </button>`}
296
+ </div>
297
+ </header>
298
+ `}_renderCollectionSelector(){let e=this.collections??[],t=this._collectionSearch.toLowerCase(),n=t?e.filter(e=>e.title.toLowerCase().includes(t)):e,r=this._collectionIds.length,a=r>0?this._selectedCollectionLabel(e):this.labels.collection,o=t?this.labels.noCollections:this.labels.emptyCollections;return s`
299
+ <div class="flex-1 min-w-0">
300
+ ${this._showCollection?s`<div
301
+ class="compose-dropdown-backdrop"
302
+ @click=${()=>{this._showCollection=!1,this._collectionSearch=``}}
303
+ ></div>`:i}
304
+ <div class="select compose-collection-select" data-select-initialized>
305
+ <button
306
+ type="button"
307
+ class="compose-collection-trigger"
308
+ aria-haspopup="listbox"
309
+ aria-expanded=${this._showCollection?`true`:`false`}
310
+ data-open=${this._showCollection?`true`:i}
311
+ data-selected=${r>0?`true`:i}
312
+ @click=${()=>{this._showPublishPanel=!1,this._showCollection=!this._showCollection,this._showCollection||(this._collectionSearch=``)}}
313
+ >
314
+ <span class="compose-collection-trigger-icon">
315
+ ${$e(Xe.collection,`compose-collection-trigger-svg`)}
316
+ </span>
317
+ <span class="compose-collection-label">${a}</span>
318
+ ${$e(Xe.chevron,`compose-collection-chevron`)}
319
+ </button>
320
+ <div
321
+ class="compose-collection-popover"
322
+ data-popover
323
+ data-side="bottom"
324
+ aria-hidden=${this._showCollection?`false`:`true`}
325
+ >
326
+ ${e.length>0?s`<div class="compose-collection-popover-header">
327
+ <label class="compose-collection-search-shell">
328
+ ${$e(Xe.search,`compose-collection-search-icon`)}
329
+ <input
330
+ type="text"
331
+ role="combobox"
332
+ class="compose-collection-search-input"
333
+ placeholder=${this.labels.searchCollections}
334
+ autocomplete="off"
335
+ autocorrect="off"
336
+ spellcheck="false"
337
+ .value=${this._collectionSearch}
338
+ @input=${e=>{this._collectionSearch=e.target.value}}
339
+ />
340
+ </label>
341
+ </div>`:i}
342
+ <div
343
+ role="listbox"
344
+ class="compose-collection-options"
345
+ aria-multiselectable="true"
346
+ >
347
+ ${n.length>0?n.map(e=>{let t=this._collectionIds.includes(e.id);return s`
348
+ <button
349
+ type="button"
350
+ class=${w({"compose-collection-option":!0,"compose-collection-option-selected":t})}
351
+ role="option"
352
+ data-value=${e.id}
353
+ aria-selected=${t?`true`:`false`}
354
+ @click=${()=>this._toggleCollection(e.id)}
355
+ >
356
+ <span class="compose-collection-option-label"
357
+ >${e.title}</span
358
+ >
359
+ <span
360
+ class=${w({"compose-collection-option-marker":!0,"compose-collection-option-marker-selected":t,"compose-collection-option-marker-add":!t})}
361
+ >
362
+ ${t?s`<svg
363
+ xmlns="http://www.w3.org/2000/svg"
364
+ class="compose-collection-option-check-circle"
365
+ viewBox="0 0 24 24"
366
+ fill="none"
367
+ aria-hidden="true"
368
+ >
369
+ <circle
370
+ cx="12"
371
+ cy="12"
372
+ r="10"
373
+ fill="currentColor"
374
+ />
375
+ <path
376
+ d="M8 12.5 10.7 15.2 16.4 9.5"
377
+ stroke="var(--site-page-bg)"
378
+ stroke-width="2.3"
379
+ stroke-linecap="round"
380
+ stroke-linejoin="round"
381
+ />
382
+ </svg>`:$e(Xe.plusCircle,`compose-collection-option-plus-circle`)}
383
+ </span>
384
+ </button>
385
+ `}):s`<div class="compose-collection-empty">
386
+ ${o}
387
+ </div>`}
388
+ </div>
389
+ <div class="compose-collection-footer">
390
+ <button
391
+ type="button"
392
+ class="compose-collection-add-action"
393
+ @click=${()=>{this._showCollection=!1,this._collectionSearch=``,this._addCollectionPanelOpen=!0}}
394
+ >
395
+ <span class="compose-collection-add-icon">
396
+ ${$e(Xe.plus,`compose-collection-add-svg`)}
397
+ </span>
398
+ ${this.labels.addCollection}
399
+ </button>
400
+ </div>
401
+ </div>
402
+ </div>
403
+ </div>
404
+ `}_closeAddCollectionPanel(){this._addCollectionPanelOpen=!1,this.updateComplete.then(()=>{this.querySelector(`.compose-collection-trigger`)?.focus()})}async _handleAddCollectionSubmit(e){let t=e;t.stopPropagation();let n=t.detail;if(!n)return;let r=this.querySelector(`jant-collection-form`);r&&(r.loading=!0);try{let e=await fetch(`/api/collections`,{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify(n.data)}),t=await e.json().catch(()=>null);if(!e.ok)throw Error(t?.error||`Couldn't create collection. Try again.`);if(!t?.id||!t.title)throw Error(`Couldn't create collection. Try again.`);let r={id:t.id,title:t.title};(!await this.refreshCollections()||!this.collections.some(e=>e.id===t.id))&&(this.collections=[...this.collections,r]),this._collectionIds=[...this._collectionIds,t.id],this._closeAddCollectionPanel(),m(this.labels.collectionFormLabels.createdLabel)}catch(e){m(e instanceof Error?e.message:`Couldn't create collection. Try again.`,`error`)}finally{r&&(r.loading=!1)}}_submitAddCollectionForm(){let e=this.querySelector(`[data-collection-quick-dialog] form`);e&&e.requestSubmit()}_renderAddCollectionPanel(){return this._addCollectionPanelOpen?s`
405
+ <div
406
+ class="collection-quick-dialog-backdrop"
407
+ @click=${()=>this._closeAddCollectionPanel()}
408
+ ></div>
409
+ <div
410
+ class="collection-quick-dialog"
411
+ data-collection-quick-dialog
412
+ role="dialog"
413
+ aria-modal="true"
414
+ aria-label=${this.labels.addCollection}
415
+ @click=${e=>e.stopPropagation()}
416
+ >
417
+ <div class="collection-quick-dialog-header">
418
+ <div class="collection-quick-dialog-title-block">
419
+ <h2 class="collection-quick-dialog-title">
420
+ ${this.labels.addCollection}
421
+ </h2>
422
+ <p class="collection-quick-dialog-note">
423
+ ${this.labels.collectionFormLabels.quickHint}
424
+ </p>
425
+ </div>
426
+ <button
427
+ type="button"
428
+ class="collection-quick-dialog-cancel"
429
+ @click=${()=>this._closeAddCollectionPanel()}
430
+ >
431
+ ${this.labels.collectionFormLabels.cancelLabel}
432
+ </button>
433
+ </div>
434
+ <div class="collection-quick-dialog-body">
435
+ <jant-collection-form
436
+ variant="quick"
437
+ .labels=${this.labels.collectionFormLabels}
438
+ .initial=${{title:``,slug:``,description:``,sortOrder:`newest`,icon:``}}
439
+ action=${a(`/api/collections`)}
440
+ cancel-href="javascript:void(0)"
441
+ @jant:collection-submit=${e=>this._handleAddCollectionSubmit(e)}
442
+ ></jant-collection-form>
443
+ </div>
444
+ <div class="collection-quick-dialog-footer">
445
+ <button
446
+ type="button"
447
+ class="compose-post-btn collection-quick-dialog-submit"
448
+ @click=${()=>this._submitAddCollectionForm()}
449
+ >
450
+ ${this.labels.collectionFormLabels.quickSubmitLabel}
451
+ </button>
452
+ </div>
453
+ </div>
454
+ `:i}_renderAttachedPanel(){return this._attachedPanelOpen?s`
455
+ <div class="compose-attached-panel">
456
+ <div class="compose-alt-header">
457
+ <button
458
+ type="button"
459
+ class="compose-attached-cancel"
460
+ @click=${()=>this._cancelAttachedPanel()}
461
+ >
462
+ ${this.labels.cancel}
463
+ </button>
464
+ <span class="compose-alt-title">${this.labels.attachedText}</span>
465
+ <button
466
+ type="button"
467
+ class="compose-post-btn ml-auto"
468
+ @click=${()=>this._doneAttachedPanel()}
469
+ >
470
+ ${this.labels.done}
471
+ </button>
472
+ </div>
473
+ <div class="flex-1 p-4 overflow-hidden flex flex-col">
474
+ <div
475
+ class="compose-attached-tiptap compose-tiptap-body"
476
+ @mousedown=${e=>this._handleAttachedEditorMouseDown(e)}
477
+ ></div>
478
+ </div>
479
+ </div>
480
+ `:i}_renderAltPanel(){if(!this._altPanelOpen)return i;let e=this._getAltAttachment();if(!e)return i;let t=Ne(e.file.type);return s`
481
+ <div class="compose-alt-panel">
482
+ <div class="compose-alt-header">
483
+ <button
484
+ type="button"
485
+ class="compose-attached-panel-back"
486
+ @click=${()=>this._closeAltPanel()}
487
+ >
488
+ <svg
489
+ class="icon-fine"
490
+ width="16"
491
+ height="16"
492
+ viewBox="0 0 16 16"
493
+ fill="none"
494
+ stroke="currentColor"
495
+ stroke-width="1.5"
496
+ stroke-linecap="round"
497
+ stroke-linejoin="round"
498
+ >
499
+ <path d="M11 3L6 8l5 5" />
500
+ </svg>
501
+ </button>
502
+ <span class="compose-alt-title">${this.labels.addAltTitle}</span>
503
+ </div>
504
+ <div class="compose-alt-preview">
505
+ ${t===`image`?s`<img
506
+ src=${e.previewUrl}
507
+ alt=""
508
+ class="compose-alt-preview-img"
509
+ />`:t===`video`?s`<video
510
+ src=${e.previewUrl}
511
+ class="compose-alt-preview-img"
512
+ preload="metadata"
513
+ muted
514
+ ></video>`:s`<span class="text-sm text-muted-foreground"
515
+ >${e.file.name}</span
516
+ >`}
517
+ </div>
518
+ <div class="compose-alt-input-row">
519
+ <input
520
+ type="text"
521
+ .value=${e.alt}
522
+ @input=${e=>this._onAltInput(e)}
523
+ class="compose-input compose-alt-input"
524
+ placeholder=${this.labels.altPlaceholder}
525
+ />
526
+ </div>
527
+ <div class="compose-alt-footer">
528
+ <span class="text-xs text-muted-foreground"
529
+ >${this.labels.altHint}</span
530
+ >
531
+ <button
532
+ type="button"
533
+ class="compose-post-btn"
534
+ @click=${()=>this._closeAltPanel()}
535
+ >
536
+ ${this.labels.done}
537
+ </button>
538
+ </div>
539
+ </div>
540
+ `}_renderConfirmPanel(){if(!this._confirmPanelOpen)return i;let e=!!this._editPostId;return s`
541
+ <div class="compose-confirm-panel">
542
+ <div class="compose-confirm-sheet">
543
+ <div class="compose-confirm-header">
544
+ <p class="compose-confirm-title">${this._confirmForAttachedText?this.labels.confirmAttachedTitle:e?this.labels.confirmEditTitle:this.labels.confirmCloseTitle}</p>
545
+ <p class="compose-confirm-subtitle">${this._confirmForAttachedText?this.labels.confirmAttachedSubtitle:e?this.labels.confirmEditSubtitle:this.labels.confirmCloseSubtitle}</p>
546
+ </div>
547
+ <button
548
+ type="button"
549
+ class="compose-confirm-action compose-confirm-save"
550
+ @click=${()=>this._handleConfirmSave()}
551
+ >
552
+ ${this._confirmForAttachedText?this.labels.confirmAttachedSave:e?this.labels.confirmEditPublish:this.labels.confirmCloseSave}
553
+ </button>
554
+ <button
555
+ type="button"
556
+ class="compose-confirm-action compose-confirm-discard"
557
+ @click=${()=>this._handleConfirmDiscard()}
558
+ >
559
+ ${this._confirmForAttachedText?this.labels.confirmAttachedDiscard:e?this.labels.confirmEditDiscard:this.labels.confirmCloseDiscard}
560
+ </button>
561
+ <button
562
+ type="button"
563
+ class="compose-confirm-action compose-confirm-cancel"
564
+ @click=${()=>this.requestClose()}
565
+ >
566
+ ${this.labels.confirmCloseCancel}
567
+ </button>
568
+ </div>
569
+ </div>
570
+ `}_getSubmitLabel(){return this._editPostId?this.labels.update:this._replyToId?this.labels.reply:this._visibility===`latest_hidden`?this.labels.postHiddenFromLatest:this._visibility===`private`?this.labels.postPrivately:this.labels.post}_getSlugSyncValidationMessage(){let e=Ge(this._slug);return e===`invalid`?this.labels.publishSlugInvalid:e===`reserved`?this.labels.publishSlugReserved:null}_getSlugValidationMessage(){return this._getSlugSyncValidationMessage()||(this._hasManualSlug()&&this._slugTaken?this.labels.publishSlugTaken:null)}_getSlugPreviewUrl(){if(!this._hasManualSlug()||this._getSlugValidationMessage())return null;let e=a(`/${this._slug.trim()}`),t=globalThis.location?.origin&&globalThis.location.origin!==`null`?globalThis.location.origin:`http://localhost`;return new URL(e,`${t}/`).toString()}_getSlugPreviewParts(){let e=this._getSlugPreviewUrl();if(!e)return null;let t=new URL(e);return{full:e,origin:t.origin,path:`${t.pathname}${t.search}${t.hash}`}}_getSlugStatusMessage(){return this._hasManualSlug()?this._getSlugValidationMessage()?this._getSlugValidationMessage():null:this._suggestedSlugLoading?this.labels.publishSlugGenerating:null}_revealSlugField(){this._showCollection=!1,this._collectionSearch=``,this._showPublishPanel=!0,this._confirmPanelOpen=!1,this._scheduleSuggestedSlugRefresh(!0),this.updateComplete.then(()=>{this.querySelector(`.compose-publish-slug-input`)?.focus()})}_canPublish(){if(this._loading)return!1;let e=this._editor;if(!e||this._getSlugValidationMessage()||e.getUrlValidationMessage()||e.getLinkTitleValidationMessage())return!1;let t=e.getData();return this._format===`link`?t.url.trim().length>0:this._format===`quote`?t.quoteText.trim().length>0:this._hasContent()}_togglePublishPanel(){this._showCollection=!1,this._collectionSearch=``;let e=!this._showPublishPanel;this._showPublishPanel=e,e&&this._scheduleSuggestedSlugRefresh(!0)}_setVisibility(t){this._visibilityLocked||(this._visibility=t,!this._editPostId&&!this._draftSourceId&&!this._replyToId&&(e._lastNewPostVisibility=t),this._showPublishPanel=!1)}_onSlugInput(e){if(this._slug=e.target.value.toLowerCase(),this._slugTaken=!1,this._slugCheckLoading=!1,this._hasManualSlug()){this._scheduleSlugAvailabilityCheck();return}this._scheduleSuggestedSlugRefresh()}_renderVisibilityIcon(e,t=`menu`){let n=w({"compose-publish-visibility-icon":!0,"compose-publish-visibility-icon-toggle":t===`toggle`,"compose-publish-visibility-icon-public":e===`public`,"compose-publish-visibility-icon-latest_hidden":e===`latest_hidden`,"compose-publish-visibility-icon-private":e===`private`});return Qe(Je[e],n)}_renderPublishVisibilityOption(e,t,n){let r=this._visibility===e;return s`
571
+ <button
572
+ type="button"
573
+ class=${w({"compose-publish-option":!0,"compose-publish-option-selected":r})}
574
+ role="radio"
575
+ aria-checked=${r?`true`:`false`}
576
+ ?disabled=${this._visibilityLocked}
577
+ @click=${()=>this._setVisibility(e)}
578
+ >
579
+ ${this._renderVisibilityIcon(e)}
580
+ <span class="compose-publish-copy">
581
+ <span class="compose-publish-row-label">${t}</span>
582
+ <span class="compose-publish-row-hint">${n}</span>
583
+ </span>
584
+ ${r?et(Ye.check,`compose-publish-row-check`):i}
585
+ </button>
586
+ `}_renderPublishSlugSection(){let e=this._getSlugValidationMessage(),t=this._getSlugStatusMessage(),n=this._getSlugPreviewParts(),r=!this._hasManualSlug()&&!this._suggestedSlugLoading&&!!this._suggestedSlug;return s`
587
+ <section class="compose-publish-section">
588
+ <div class="compose-publish-section-header">
589
+ <div class="compose-publish-section-copy">
590
+ <p class="compose-publish-section-label">
591
+ ${this.labels.publishSlugLabel}
592
+ </p>
593
+ <p class="compose-publish-section-hint">
594
+ ${this.labels.publishSlugHint}
595
+ </p>
596
+ </div>
597
+ ${this._hasManualSlug()?s`
598
+ <button
599
+ type="button"
600
+ class="compose-publish-section-action"
601
+ @click=${()=>this._resetCustomSlug()}
602
+ >
603
+ ${this.labels.publishSlugReset}
604
+ </button>
605
+ `:i}
606
+ </div>
607
+ <div class="compose-publish-slug-field">
608
+ <div class="compose-publish-slug-input-wrap">
609
+ <span class="compose-publish-slug-prefix">/</span>
610
+ <input
611
+ type="text"
612
+ class="compose-input compose-publish-slug-input"
613
+ .value=${this._slug}
614
+ placeholder=${this.labels.publishSlugPlaceholder}
615
+ aria-invalid=${e?`true`:`false`}
616
+ spellcheck="false"
617
+ autocapitalize="off"
618
+ autocomplete="off"
619
+ @input=${e=>this._onSlugInput(e)}
620
+ />
621
+ </div>
622
+ ${r?s`
623
+ <button
624
+ type="button"
625
+ class="compose-slug-suggestion"
626
+ @click=${()=>this._useSuggestedSlug()}
627
+ >
628
+ <span class="compose-slug-suggestion-copy">
629
+ <span class="compose-slug-suggestion-label"
630
+ >${this.labels.publishSlugSuggested}</span
631
+ >
632
+ <span class="compose-slug-suggestion-chip">
633
+ <span class="compose-slug-suggestion-value"
634
+ >/${this._suggestedSlug}</span
635
+ >
636
+ </span>
637
+ </span>
638
+ <span class="compose-slug-suggestion-icon" aria-hidden="true">
639
+ <svg
640
+ width="14"
641
+ height="14"
642
+ viewBox="0 0 14 14"
643
+ fill="none"
644
+ stroke="currentColor"
645
+ stroke-width="1.4"
646
+ stroke-linecap="round"
647
+ stroke-linejoin="round"
648
+ >
649
+ <path d="M3 7h8" />
650
+ <path d="m8 3 4 4-4 4" />
651
+ </svg>
652
+ </span>
653
+ </button>
654
+ `:i}
655
+ ${t?s`<p
656
+ class=${w({"compose-publish-slug-status":!0,"compose-publish-slug-status-error":!!e})}
657
+ data-compose-slug-error=${e?`true`:i}
658
+ >
659
+ ${t}
660
+ </p>`:i}
661
+ ${n?s`<p
662
+ class="compose-publish-slug-preview"
663
+ data-compose-slug-preview
664
+ title=${n.full}
665
+ >
666
+ <span class="compose-publish-slug-preview-origin"
667
+ >${n.origin}</span
668
+ ><span class="compose-publish-slug-preview-path"
669
+ >${n.path}</span
670
+ >
671
+ </p>`:i}
672
+ </div>
673
+ </section>
674
+ `}_renderPublishPanel(){return this._showPublishPanel?s`
675
+ <div
676
+ class="compose-publish-panel"
677
+ role="dialog"
678
+ aria-label=${this.labels.publishSettings}
679
+ data-compose-publish-panel
680
+ >
681
+ ${this._visibilityLocked?i:s`
682
+ <section class="compose-publish-section">
683
+ <div class="compose-publish-section-header">
684
+ <div class="compose-publish-section-copy">
685
+ <p class="compose-publish-section-label">
686
+ ${this.labels.publishVisibilityLabel}
687
+ </p>
688
+ </div>
689
+ </div>
690
+ <div class="compose-publish-list" role="radiogroup">
691
+ ${this._renderPublishVisibilityOption(`public`,this.labels.publishVisibilityPublic,this.labels.publishVisibilityPublicHint)}
692
+ ${this._renderPublishVisibilityOption(`latest_hidden`,this.labels.publishVisibilityHiddenFromLatest,this.labels.publishVisibilityHiddenFromLatestHint)}
693
+ ${this._renderPublishVisibilityOption(`private`,this.labels.publishVisibilityPrivate,this.labels.publishVisibilityPrivateHint)}
694
+ </div>
695
+ </section>
696
+ `}
697
+ ${this._visibilityLocked?i:s`<div
698
+ class="compose-publish-divider"
699
+ aria-hidden="true"
700
+ ></div>`}
701
+ ${this._renderPublishSlugSection()}
702
+ </div>
703
+ `:i}_renderPublishButton(){let e=s`<svg
704
+ class="animate-spin size-4"
705
+ xmlns="http://www.w3.org/2000/svg"
706
+ viewBox="0 0 24 24"
707
+ fill="none"
708
+ stroke="currentColor"
709
+ stroke-width="2"
710
+ stroke-linecap="round"
711
+ stroke-linejoin="round"
712
+ role="status"
713
+ >
714
+ <path d="M21 12a9 9 0 1 1-6.219-8.56" />
715
+ </svg>`,t=this._canPublish();return s`
716
+ <div class="compose-publish-group">
717
+ ${this._showPublishPanel?s`<div
718
+ class="compose-dropdown-backdrop"
719
+ @click=${()=>{this._showPublishPanel=!1}}
720
+ ></div>`:i}
721
+ <div
722
+ role="group"
723
+ class=${w({"compose-publish-buttons":!0,"compose-publish-buttons-inactive":!t&&!this._loading})}
724
+ >
725
+ <button
726
+ type="button"
727
+ class=${w({"compose-publish-main":!0,"compose-publish-main-loading":this._loading})}
728
+ ?disabled=${!t}
729
+ @click=${()=>this._submit(`published`)}
730
+ >
731
+ ${this._loading?e:i} ${this._getSubmitLabel()}
732
+ </button>
733
+ <button
734
+ type="button"
735
+ class=${w({"compose-publish-toggle":!0,"compose-publish-toggle-loading":this._loading})}
736
+ ?disabled=${this._loading}
737
+ aria-haspopup="dialog"
738
+ aria-expanded=${this._showPublishPanel?`true`:`false`}
739
+ aria-label=${this.labels.publishSettings}
740
+ title=${this.labels.publishSettings}
741
+ @click=${()=>this._togglePublishPanel()}
742
+ >
743
+ ${et(Ye.chevron,`compose-publish-toggle-chevron`)}
744
+ </button>
745
+ </div>
746
+ ${this._renderPublishPanel()}
747
+ </div>
748
+ `}render(){let e=!!(this._replyToId&&this._replyToData),t=s`<jant-compose-editor
749
+ .format=${this._format}
750
+ .labels=${this.labels}
751
+ .uploadMaxFileSize=${this.uploadMaxFileSize}
752
+ ></jant-compose-editor>`;return s`
753
+ <div
754
+ class=${w({"compose-dialog-inner":!0,"compose-dialog-inner-page":this.pageMode,"compose-dialog-inner-suspended":this._addCollectionPanelOpen})}
755
+ aria-hidden=${this._addCollectionPanelOpen?`true`:`false`}
756
+ ?inert=${this._addCollectionPanelOpen}
757
+ >
758
+ ${this._renderHeader()}
759
+ ${e?s`
760
+ <div class="compose-thread-layout">
761
+ ${this._renderReplyContext()}
762
+ <div class="compose-editor-row">
763
+ <div class="compose-thread-dot"></div>
764
+ ${t}
765
+ </div>
766
+ </div>
767
+ `:t}
768
+
769
+ <div class="compose-action-row">
770
+ ${this._renderCollectionSelector()} ${this._renderPublishButton()}
771
+ </div>
772
+ ${this._renderAttachedPanel()} ${this._renderAltPanel()}
773
+ ${this._renderDraftsPanel()} ${this._renderConfirmPanel()}
774
+ </div>
775
+ ${this._renderAddCollectionPanel()}
776
+ `}};customElements.define(`jant-compose-dialog`,it);var at=e=>e??i;function ot(e,t,n){return(t=pt(t))in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}function st(){return st=Object.assign?Object.assign.bind():function(e){for(var t=1;t<arguments.length;t++){var n=arguments[t];for(var r in n)({}).hasOwnProperty.call(n,r)&&(e[r]=n[r])}return e},st.apply(null,arguments)}function ct(e,t){var n=Object.keys(e);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(e);t&&(r=r.filter(function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable})),n.push.apply(n,r)}return n}function lt(e){for(var t=1;t<arguments.length;t++){var n=arguments[t]==null?{}:arguments[t];t%2?ct(Object(n),!0).forEach(function(t){ot(e,t,n[t])}):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(n)):ct(Object(n)).forEach(function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(n,t))})}return e}function ut(e,t){if(e==null)return{};var n,r,i=dt(e,t);if(Object.getOwnPropertySymbols){var a=Object.getOwnPropertySymbols(e);for(r=0;r<a.length;r++)n=a[r],t.indexOf(n)===-1&&{}.propertyIsEnumerable.call(e,n)&&(i[n]=e[n])}return i}function dt(e,t){if(e==null)return{};var n={};for(var r in e)if({}.hasOwnProperty.call(e,r)){if(t.indexOf(r)!==-1)continue;n[r]=e[r]}return n}function ft(e,t){if(typeof e!=`object`||!e)return e;var n=e[Symbol.toPrimitive];if(n!==void 0){var r=n.call(e,t||`default`);if(typeof r!=`object`)return r;throw TypeError(`@@toPrimitive must return a primitive value.`)}return(t===`string`?String:Number)(e)}function pt(e){var t=ft(e,`string`);return typeof t==`symbol`?t:t+``}function mt(e){"@babel/helpers - typeof";return mt=typeof Symbol==`function`&&typeof Symbol.iterator==`symbol`?function(e){return typeof e}:function(e){return e&&typeof Symbol==`function`&&e.constructor===Symbol&&e!==Symbol.prototype?`symbol`:typeof e},mt(e)}var ht=`1.15.7`;function gt(e){if(typeof window<`u`&&window.navigator)return!!navigator.userAgent.match(e)}var _t=gt(/(?:Trident.*rv[ :]?11\.|msie|iemobile|Windows Phone)/i),vt=gt(/Edge/i),yt=gt(/firefox/i),bt=gt(/safari/i)&&!gt(/chrome/i)&&!gt(/android/i),xt=gt(/iP(ad|od|hone)/i),St=gt(/chrome/i)&&gt(/android/i),Ct={capture:!1,passive:!1};function T(e,t,n){e.addEventListener(t,n,!_t&&Ct)}function E(e,t,n){e.removeEventListener(t,n,!_t&&Ct)}function wt(e,t){if(t){if(t[0]===`>`&&(t=t.substring(1)),e)try{if(e.matches)return e.matches(t);if(e.msMatchesSelector)return e.msMatchesSelector(t);if(e.webkitMatchesSelector)return e.webkitMatchesSelector(t)}catch{return!1}return!1}}function Tt(e){return e.host&&e!==document&&e.host.nodeType&&e.host!==e?e.host:e.parentNode}function Et(e,t,n,r){if(e){n||=document;do{if(t!=null&&(t[0]===`>`?e.parentNode===n&&wt(e,t):wt(e,t))||r&&e===n)return e;if(e===n)break}while(e=Tt(e))}return null}var Dt=/\s+/g;function Ot(e,t,n){e&&t&&(e.classList?e.classList[n?`add`:`remove`](t):e.className=((` `+e.className+` `).replace(Dt,` `).replace(` `+t+` `,` `)+(n?` `+t:``)).replace(Dt,` `))}function D(e,t,n){var r=e&&e.style;if(r){if(n===void 0)return document.defaultView&&document.defaultView.getComputedStyle?n=document.defaultView.getComputedStyle(e,``):e.currentStyle&&(n=e.currentStyle),t===void 0?n:n[t];!(t in r)&&t.indexOf(`webkit`)===-1&&(t=`-webkit-`+t),r[t]=n+(typeof n==`string`?``:`px`)}}function kt(e,t){var n=``;if(typeof e==`string`)n=e;else do{var r=D(e,`transform`);r&&r!==`none`&&(n=r+` `+n)}while(!t&&(e=e.parentNode));var i=window.DOMMatrix||window.WebKitCSSMatrix||window.CSSMatrix||window.MSCSSMatrix;return i&&new i(n)}function At(e,t,n){if(e){var r=e.getElementsByTagName(t),i=0,a=r.length;if(n)for(;i<a;i++)n(r[i],i);return r}return[]}function jt(){return document.scrollingElement||document.documentElement}function O(e,t,n,r,i){if(!(!e.getBoundingClientRect&&e!==window)){var a,o,s,c,l,u,d;if(e!==window&&e.parentNode&&e!==jt()?(a=e.getBoundingClientRect(),o=a.top,s=a.left,c=a.bottom,l=a.right,u=a.height,d=a.width):(o=0,s=0,c=window.innerHeight,l=window.innerWidth,u=window.innerHeight,d=window.innerWidth),(t||n)&&e!==window&&(i||=e.parentNode,!_t))do if(i&&i.getBoundingClientRect&&(D(i,`transform`)!==`none`||n&&D(i,`position`)!==`static`)){var f=i.getBoundingClientRect();o-=f.top+parseInt(D(i,`border-top-width`)),s-=f.left+parseInt(D(i,`border-left-width`)),c=o+a.height,l=s+a.width;break}while(i=i.parentNode);if(r&&e!==window){var p=kt(i||e),m=p&&p.a,h=p&&p.d;p&&(o/=h,s/=m,d/=m,u/=h,c=o+u,l=s+d)}return{top:o,left:s,bottom:c,right:l,width:d,height:u}}}function Mt(e,t,n){for(var r=Rt(e,!0),i=O(e)[t];r;){var a=O(r)[n],o=void 0;if(o=n===`top`||n===`left`?i>=a:i<=a,!o)return r;if(r===jt())break;r=Rt(r,!1)}return!1}function Nt(e,t,n,r){for(var i=0,a=0,o=e.children;a<o.length;){if(o[a].style.display!==`none`&&o[a]!==P.ghost&&(r||o[a]!==P.dragged)&&Et(o[a],n.draggable,e,!1)){if(i===t)return o[a];i++}a++}return null}function Pt(e,t){for(var n=e.lastElementChild;n&&(n===P.ghost||D(n,`display`)===`none`||t&&!wt(n,t));)n=n.previousElementSibling;return n||null}function Ft(e,t){var n=0;if(!e||!e.parentNode)return-1;for(;e=e.previousElementSibling;)e.nodeName.toUpperCase()!==`TEMPLATE`&&e!==P.clone&&(!t||wt(e,t))&&n++;return n}function It(e){var t=0,n=0,r=jt();if(e)do{var i=kt(e),a=i.a,o=i.d;t+=e.scrollLeft*a,n+=e.scrollTop*o}while(e!==r&&(e=e.parentNode));return[t,n]}function Lt(e,t){for(var n in e)if(e.hasOwnProperty(n)){for(var r in t)if(t.hasOwnProperty(r)&&t[r]===e[n][r])return Number(n)}return-1}function Rt(e,t){if(!e||!e.getBoundingClientRect)return jt();var n=e,r=!1;do if(n.clientWidth<n.scrollWidth||n.clientHeight<n.scrollHeight){var i=D(n);if(n.clientWidth<n.scrollWidth&&(i.overflowX==`auto`||i.overflowX==`scroll`)||n.clientHeight<n.scrollHeight&&(i.overflowY==`auto`||i.overflowY==`scroll`)){if(!n.getBoundingClientRect||n===document.body)return jt();if(r||t)return n;r=!0}}while(n=n.parentNode);return jt()}function zt(e,t){if(e&&t)for(var n in t)t.hasOwnProperty(n)&&(e[n]=t[n]);return e}function Bt(e,t){return Math.round(e.top)===Math.round(t.top)&&Math.round(e.left)===Math.round(t.left)&&Math.round(e.height)===Math.round(t.height)&&Math.round(e.width)===Math.round(t.width)}var Vt;function Ht(e,t){return function(){if(!Vt){var n=arguments,r=this;n.length===1?e.call(r,n[0]):e.apply(r,n),Vt=setTimeout(function(){Vt=void 0},t)}}}function Ut(){clearTimeout(Vt),Vt=void 0}function Wt(e,t,n){e.scrollLeft+=t,e.scrollTop+=n}function Gt(e){var t=window.Polymer,n=window.jQuery||window.Zepto;return t&&t.dom?t.dom(e).cloneNode(!0):n?n(e).clone(!0)[0]:e.cloneNode(!0)}function Kt(e,t,n){var r={};return Array.from(e.children).forEach(function(i){if(!(!Et(i,t.draggable,e,!1)||i.animated||i===n)){var a=O(i);r.left=Math.min(r.left??1/0,a.left),r.top=Math.min(r.top??1/0,a.top),r.right=Math.max(r.right??-1/0,a.right),r.bottom=Math.max(r.bottom??-1/0,a.bottom)}}),r.width=r.right-r.left,r.height=r.bottom-r.top,r.x=r.left,r.y=r.top,r}var qt=`Sortable`+new Date().getTime();function Jt(){var e=[],t;return{captureAnimationState:function(){e=[],this.options.animation&&[].slice.call(this.el.children).forEach(function(t){if(!(D(t,`display`)===`none`||t===P.ghost)){e.push({target:t,rect:O(t)});var n=lt({},e[e.length-1].rect);if(t.thisAnimationDuration){var r=kt(t,!0);r&&(n.top-=r.f,n.left-=r.e)}t.fromRect=n}})},addAnimationState:function(t){e.push(t)},removeAnimationState:function(t){e.splice(Lt(e,{target:t}),1)},animateAll:function(n){var r=this;if(!this.options.animation){clearTimeout(t),typeof n==`function`&&n();return}var i=!1,a=0;e.forEach(function(e){var t=0,n=e.target,o=n.fromRect,s=O(n),c=n.prevFromRect,l=n.prevToRect,u=e.rect,d=kt(n,!0);d&&(s.top-=d.f,s.left-=d.e),n.toRect=s,n.thisAnimationDuration&&Bt(c,s)&&!Bt(o,s)&&(u.top-s.top)/(u.left-s.left)===(o.top-s.top)/(o.left-s.left)&&(t=Xt(u,c,l,r.options)),Bt(s,o)||(n.prevFromRect=o,n.prevToRect=s,t||=r.options.animation,r.animate(n,u,s,t)),t&&(i=!0,a=Math.max(a,t),clearTimeout(n.animationResetTimer),n.animationResetTimer=setTimeout(function(){n.animationTime=0,n.prevFromRect=null,n.fromRect=null,n.prevToRect=null,n.thisAnimationDuration=null},t),n.thisAnimationDuration=t)}),clearTimeout(t),i?t=setTimeout(function(){typeof n==`function`&&n()},a):typeof n==`function`&&n(),e=[]},animate:function(e,t,n,r){if(r){D(e,`transition`,``),D(e,`transform`,``);var i=kt(this.el),a=i&&i.a,o=i&&i.d,s=(t.left-n.left)/(a||1),c=(t.top-n.top)/(o||1);e.animatingX=!!s,e.animatingY=!!c,D(e,`transform`,`translate3d(`+s+`px,`+c+`px,0)`),this.forRepaintDummy=Yt(e),D(e,`transition`,`transform `+r+`ms`+(this.options.easing?` `+this.options.easing:``)),D(e,`transform`,`translate3d(0,0,0)`),typeof e.animated==`number`&&clearTimeout(e.animated),e.animated=setTimeout(function(){D(e,`transition`,``),D(e,`transform`,``),e.animated=!1,e.animatingX=!1,e.animatingY=!1},r)}}}}function Yt(e){return e.offsetWidth}function Xt(e,t,n,r){return Math.sqrt((t.top-e.top)**2+(t.left-e.left)**2)/Math.sqrt((t.top-n.top)**2+(t.left-n.left)**2)*r.animation}var Zt=[],Qt={initializeByDefault:!0},$t={mount:function(e){for(var t in Qt)Qt.hasOwnProperty(t)&&!(t in e)&&(e[t]=Qt[t]);Zt.forEach(function(t){if(t.pluginName===e.pluginName)throw`Sortable: Cannot mount plugin ${e.pluginName} more than once`}),Zt.push(e)},pluginEvent:function(e,t,n){var r=this;this.eventCanceled=!1,n.cancel=function(){r.eventCanceled=!0};var i=e+`Global`;Zt.forEach(function(r){t[r.pluginName]&&(t[r.pluginName][i]&&t[r.pluginName][i](lt({sortable:t},n)),t.options[r.pluginName]&&t[r.pluginName][e]&&t[r.pluginName][e](lt({sortable:t},n)))})},initializePlugins:function(e,t,n,r){for(var i in Zt.forEach(function(r){var i=r.pluginName;if(!(!e.options[i]&&!r.initializeByDefault)){var a=new r(e,t,e.options);a.sortable=e,a.options=e.options,e[i]=a,st(n,a.defaults)}}),e.options)if(e.options.hasOwnProperty(i)){var a=this.modifyOption(e,i,e.options[i]);a!==void 0&&(e.options[i]=a)}},getEventProperties:function(e,t){var n={};return Zt.forEach(function(r){typeof r.eventProperties==`function`&&st(n,r.eventProperties.call(t[r.pluginName],e))}),n},modifyOption:function(e,t,n){var r;return Zt.forEach(function(i){e[i.pluginName]&&i.optionListeners&&typeof i.optionListeners[t]==`function`&&(r=i.optionListeners[t].call(e[i.pluginName],n))}),r}};function en(e){var t=e.sortable,n=e.rootEl,r=e.name,i=e.targetEl,a=e.cloneEl,o=e.toEl,s=e.fromEl,c=e.oldIndex,l=e.newIndex,u=e.oldDraggableIndex,d=e.newDraggableIndex,f=e.originalEvent,p=e.putSortable,m=e.extraEventProperties;if(t||=n&&n[qt],t){var h,g=t.options,_=`on`+r.charAt(0).toUpperCase()+r.substr(1);window.CustomEvent&&!_t&&!vt?h=new CustomEvent(r,{bubbles:!0,cancelable:!0}):(h=document.createEvent(`Event`),h.initEvent(r,!0,!0)),h.to=o||n,h.from=s||n,h.item=i||n,h.clone=a,h.oldIndex=c,h.newIndex=l,h.oldDraggableIndex=u,h.newDraggableIndex=d,h.originalEvent=f,h.pullMode=p?p.lastPutMode:void 0;var v=lt(lt({},m),$t.getEventProperties(r,t));for(var y in v)h[y]=v[y];n&&n.dispatchEvent(h),g[_]&&g[_].call(t,h)}}var tn=[`evt`],nn=function(e,t){var n=arguments.length>2&&arguments[2]!==void 0?arguments[2]:{},r=n.evt,i=ut(n,tn);$t.pluginEvent.bind(P)(e,t,lt({dragEl:k,parentEl:A,ghostEl:j,rootEl:M,nextEl:an,lastDownEl:on,cloneEl:N,cloneHidden:sn,dragStarted:Cn,putSortable:pn,activeSortable:P.active,originalEvent:r,oldIndex:cn,oldDraggableIndex:un,newIndex:ln,newDraggableIndex:dn,hideGhostForTarget:Hn,unhideGhostForTarget:Un,cloneNowHidden:function(){sn=!0},cloneNowShown:function(){sn=!1},dispatchSortableEvent:function(e){rn({sortable:t,name:e,originalEvent:r})}},i))};function rn(e){en(lt({putSortable:pn,cloneEl:N,targetEl:k,rootEl:M,oldIndex:cn,oldDraggableIndex:un,newIndex:ln,newDraggableIndex:dn},e))}var k,A,j,M,an,on,N,sn,cn,ln,un,dn,fn,pn,mn=!1,hn=!1,gn=[],_n,vn,yn,bn,xn,Sn,Cn,wn,Tn,En=!1,Dn=!1,On,kn,An=[],jn=!1,Mn=[],Nn=typeof document<`u`,Pn=xt,Fn=vt||_t?`cssFloat`:`float`,In=Nn&&!St&&!xt&&`draggable`in document.createElement(`div`),Ln=function(){if(Nn){if(_t)return!1;var e=document.createElement(`x`);return e.style.cssText=`pointer-events:auto`,e.style.pointerEvents===`auto`}}(),Rn=function(e,t){var n=D(e),r=parseInt(n.width)-parseInt(n.paddingLeft)-parseInt(n.paddingRight)-parseInt(n.borderLeftWidth)-parseInt(n.borderRightWidth),i=Nt(e,0,t),a=Nt(e,1,t),o=i&&D(i),s=a&&D(a),c=o&&parseInt(o.marginLeft)+parseInt(o.marginRight)+O(i).width,l=s&&parseInt(s.marginLeft)+parseInt(s.marginRight)+O(a).width;if(n.display===`flex`)return n.flexDirection===`column`||n.flexDirection===`column-reverse`?`vertical`:`horizontal`;if(n.display===`grid`)return n.gridTemplateColumns.split(` `).length<=1?`vertical`:`horizontal`;if(i&&o.float&&o.float!==`none`){var u=o.float===`left`?`left`:`right`;return a&&(s.clear===`both`||s.clear===u)?`vertical`:`horizontal`}return i&&(o.display===`block`||o.display===`flex`||o.display===`table`||o.display===`grid`||c>=r&&n[Fn]===`none`||a&&n[Fn]===`none`&&c+l>r)?`vertical`:`horizontal`},zn=function(e,t,n){var r=n?e.left:e.top,i=n?e.right:e.bottom,a=n?e.width:e.height,o=n?t.left:t.top,s=n?t.right:t.bottom,c=n?t.width:t.height;return r===o||i===s||r+a/2===o+c/2},Bn=function(e,t){var n;return gn.some(function(r){var i=r[qt].options.emptyInsertThreshold;if(!(!i||Pt(r))){var a=O(r),o=e>=a.left-i&&e<=a.right+i,s=t>=a.top-i&&t<=a.bottom+i;if(o&&s)return n=r}}),n},Vn=function(e){function t(e,n){return function(r,i,a,o){var s=r.options.group.name&&i.options.group.name&&r.options.group.name===i.options.group.name;if(e==null&&(n||s))return!0;if(e==null||e===!1)return!1;if(n&&e===`clone`)return e;if(typeof e==`function`)return t(e(r,i,a,o),n)(r,i,a,o);var c=(n?r:i).options.group.name;return e===!0||typeof e==`string`&&e===c||e.join&&e.indexOf(c)>-1}}var n={},r=e.group;(!r||mt(r)!=`object`)&&(r={name:r}),n.name=r.name,n.checkPull=t(r.pull,!0),n.checkPut=t(r.put),n.revertClone=r.revertClone,e.group=n},Hn=function(){!Ln&&j&&D(j,`display`,`none`)},Un=function(){!Ln&&j&&D(j,`display`,``)};Nn&&!St&&document.addEventListener(`click`,function(e){if(hn)return e.preventDefault(),e.stopPropagation&&e.stopPropagation(),e.stopImmediatePropagation&&e.stopImmediatePropagation(),hn=!1,!1},!0);var Wn=function(e){if(k){e=e.touches?e.touches[0]:e;var t=Bn(e.clientX,e.clientY);if(t){var n={};for(var r in e)e.hasOwnProperty(r)&&(n[r]=e[r]);n.target=n.rootEl=t,n.preventDefault=void 0,n.stopPropagation=void 0,t[qt]._onDragOver(n)}}},Gn=function(e){k&&k.parentNode[qt]._isOutsideThisEl(e.target)};function P(e,t){if(!(e&&e.nodeType&&e.nodeType===1))throw`Sortable: \`el\` must be an HTMLElement, not ${{}.toString.call(e)}`;this.el=e,this.options=t=st({},t),e[qt]=this;var n={group:null,sort:!0,disabled:!1,store:null,handle:null,draggable:/^[uo]l$/i.test(e.nodeName)?`>li`:`>*`,swapThreshold:1,invertSwap:!1,invertedSwapThreshold:null,removeCloneOnHide:!0,direction:function(){return Rn(e,this.options)},ghostClass:`sortable-ghost`,chosenClass:`sortable-chosen`,dragClass:`sortable-drag`,ignore:`a, img`,filter:null,preventOnFilter:!0,animation:0,easing:null,setData:function(e,t){e.setData(`Text`,t.textContent)},dropBubble:!1,dragoverBubble:!1,dataIdAttr:`data-id`,delay:0,delayOnTouchOnly:!1,touchStartThreshold:(Number.parseInt?Number:window).parseInt(window.devicePixelRatio,10)||1,forceFallback:!1,fallbackClass:`sortable-fallback`,fallbackOnBody:!1,fallbackTolerance:0,fallbackOffset:{x:0,y:0},supportPointer:P.supportPointer!==!1&&`PointerEvent`in window&&(!bt||xt),emptyInsertThreshold:5};for(var r in $t.initializePlugins(this,e,n),n)!(r in t)&&(t[r]=n[r]);for(var i in Vn(t),this)i.charAt(0)===`_`&&typeof this[i]==`function`&&(this[i]=this[i].bind(this));this.nativeDraggable=t.forceFallback?!1:In,this.nativeDraggable&&(this.options.touchStartThreshold=1),t.supportPointer?T(e,`pointerdown`,this._onTapStart):(T(e,`mousedown`,this._onTapStart),T(e,`touchstart`,this._onTapStart)),this.nativeDraggable&&(T(e,`dragover`,this),T(e,`dragenter`,this)),gn.push(this.el),t.store&&t.store.get&&this.sort(t.store.get(this)||[]),st(this,Jt())}P.prototype={constructor:P,_isOutsideThisEl:function(e){!this.el.contains(e)&&e!==this.el&&(wn=null)},_getDirection:function(e,t){return typeof this.options.direction==`function`?this.options.direction.call(this,e,t,k):this.options.direction},_onTapStart:function(e){if(e.cancelable){var t=this,n=this.el,r=this.options,i=r.preventOnFilter,a=e.type,o=e.touches&&e.touches[0]||e.pointerType&&e.pointerType===`touch`&&e,s=(o||e).target,c=e.target.shadowRoot&&(e.path&&e.path[0]||e.composedPath&&e.composedPath()[0])||s,l=r.filter;if(tr(n),!k&&!(/mousedown|pointerdown/.test(a)&&e.button!==0||r.disabled)&&!c.isContentEditable&&!(!this.nativeDraggable&&bt&&s&&s.tagName.toUpperCase()===`SELECT`)&&(s=Et(s,r.draggable,n,!1),!(s&&s.animated)&&on!==s)){if(cn=Ft(s),un=Ft(s,r.draggable),typeof l==`function`){if(l.call(this,e,s,this)){rn({sortable:t,rootEl:c,name:`filter`,targetEl:s,toEl:n,fromEl:n}),nn(`filter`,t,{evt:e}),i&&e.preventDefault();return}}else if(l&&(l=l.split(`,`).some(function(r){if(r=Et(c,r.trim(),n,!1),r)return rn({sortable:t,rootEl:r,name:`filter`,targetEl:s,fromEl:n,toEl:n}),nn(`filter`,t,{evt:e}),!0}),l)){i&&e.preventDefault();return}r.handle&&!Et(c,r.handle,n,!1)||this._prepareDragStart(e,o,s)}}},_prepareDragStart:function(e,t,n){var r=this,i=r.el,a=r.options,o=i.ownerDocument,s;if(n&&!k&&n.parentNode===i){var c=O(n);if(M=i,k=n,A=k.parentNode,an=k.nextSibling,on=n,fn=a.group,P.dragged=k,_n={target:k,clientX:(t||e).clientX,clientY:(t||e).clientY},xn=_n.clientX-c.left,Sn=_n.clientY-c.top,this._lastX=(t||e).clientX,this._lastY=(t||e).clientY,k.style[`will-change`]=`all`,s=function(){if(nn(`delayEnded`,r,{evt:e}),P.eventCanceled){r._onDrop();return}r._disableDelayedDragEvents(),!yt&&r.nativeDraggable&&(k.draggable=!0),r._triggerDragStart(e,t),rn({sortable:r,name:`choose`,originalEvent:e}),Ot(k,a.chosenClass,!0)},a.ignore.split(`,`).forEach(function(e){At(k,e.trim(),Jn)}),T(o,`dragover`,Wn),T(o,`mousemove`,Wn),T(o,`touchmove`,Wn),a.supportPointer?(T(o,`pointerup`,r._onDrop),!this.nativeDraggable&&T(o,`pointercancel`,r._onDrop)):(T(o,`mouseup`,r._onDrop),T(o,`touchend`,r._onDrop),T(o,`touchcancel`,r._onDrop)),yt&&this.nativeDraggable&&(this.options.touchStartThreshold=4,k.draggable=!0),nn(`delayStart`,this,{evt:e}),a.delay&&(!a.delayOnTouchOnly||t)&&(!this.nativeDraggable||!(vt||_t))){if(P.eventCanceled){this._onDrop();return}a.supportPointer?(T(o,`pointerup`,r._disableDelayedDrag),T(o,`pointercancel`,r._disableDelayedDrag)):(T(o,`mouseup`,r._disableDelayedDrag),T(o,`touchend`,r._disableDelayedDrag),T(o,`touchcancel`,r._disableDelayedDrag)),T(o,`mousemove`,r._delayedDragTouchMoveHandler),T(o,`touchmove`,r._delayedDragTouchMoveHandler),a.supportPointer&&T(o,`pointermove`,r._delayedDragTouchMoveHandler),r._dragStartTimer=setTimeout(s,a.delay)}else s()}},_delayedDragTouchMoveHandler:function(e){var t=e.touches?e.touches[0]:e;Math.max(Math.abs(t.clientX-this._lastX),Math.abs(t.clientY-this._lastY))>=Math.floor(this.options.touchStartThreshold/(this.nativeDraggable&&window.devicePixelRatio||1))&&this._disableDelayedDrag()},_disableDelayedDrag:function(){k&&Jn(k),clearTimeout(this._dragStartTimer),this._disableDelayedDragEvents()},_disableDelayedDragEvents:function(){var e=this.el.ownerDocument;E(e,`mouseup`,this._disableDelayedDrag),E(e,`touchend`,this._disableDelayedDrag),E(e,`touchcancel`,this._disableDelayedDrag),E(e,`pointerup`,this._disableDelayedDrag),E(e,`pointercancel`,this._disableDelayedDrag),E(e,`mousemove`,this._delayedDragTouchMoveHandler),E(e,`touchmove`,this._delayedDragTouchMoveHandler),E(e,`pointermove`,this._delayedDragTouchMoveHandler)},_triggerDragStart:function(e,t){t||=e.pointerType==`touch`&&e,!this.nativeDraggable||t?this.options.supportPointer?T(document,`pointermove`,this._onTouchMove):t?T(document,`touchmove`,this._onTouchMove):T(document,`mousemove`,this._onTouchMove):(T(k,`dragend`,this),T(M,`dragstart`,this._onDragStart));try{document.selection?nr(function(){document.selection.empty()}):window.getSelection().removeAllRanges()}catch{}},_dragStarted:function(e,t){if(mn=!1,M&&k){nn(`dragStarted`,this,{evt:t}),this.nativeDraggable&&T(document,`dragover`,Gn);var n=this.options;!e&&Ot(k,n.dragClass,!1),Ot(k,n.ghostClass,!0),P.active=this,e&&this._appendGhost(),rn({sortable:this,name:`start`,originalEvent:t})}else this._nulling()},_emulateDragOver:function(){if(vn){this._lastX=vn.clientX,this._lastY=vn.clientY,Hn();for(var e=document.elementFromPoint(vn.clientX,vn.clientY),t=e;e&&e.shadowRoot&&(e=e.shadowRoot.elementFromPoint(vn.clientX,vn.clientY),e!==t);)t=e;if(k.parentNode[qt]._isOutsideThisEl(e),t)do{if(t[qt]){var n=void 0;if(n=t[qt]._onDragOver({clientX:vn.clientX,clientY:vn.clientY,target:e,rootEl:t}),n&&!this.options.dragoverBubble)break}e=t}while(t=Tt(t));Un()}},_onTouchMove:function(e){if(_n){var t=this.options,n=t.fallbackTolerance,r=t.fallbackOffset,i=e.touches?e.touches[0]:e,a=j&&kt(j,!0),o=j&&a&&a.a,s=j&&a&&a.d,c=Pn&&kn&&It(kn),l=(i.clientX-_n.clientX+r.x)/(o||1)+(c?c[0]-An[0]:0)/(o||1),u=(i.clientY-_n.clientY+r.y)/(s||1)+(c?c[1]-An[1]:0)/(s||1);if(!P.active&&!mn){if(n&&Math.max(Math.abs(i.clientX-this._lastX),Math.abs(i.clientY-this._lastY))<n)return;this._onDragStart(e,!0)}if(j){a?(a.e+=l-(yn||0),a.f+=u-(bn||0)):a={a:1,b:0,c:0,d:1,e:l,f:u};var d=`matrix(${a.a},${a.b},${a.c},${a.d},${a.e},${a.f})`;D(j,`webkitTransform`,d),D(j,`mozTransform`,d),D(j,`msTransform`,d),D(j,`transform`,d),yn=l,bn=u,vn=i}e.cancelable&&e.preventDefault()}},_appendGhost:function(){if(!j){var e=this.options.fallbackOnBody?document.body:M,t=O(k,!0,Pn,!0,e),n=this.options;if(Pn){for(kn=e;D(kn,`position`)===`static`&&D(kn,`transform`)===`none`&&kn!==document;)kn=kn.parentNode;kn!==document.body&&kn!==document.documentElement?(kn===document&&(kn=jt()),t.top+=kn.scrollTop,t.left+=kn.scrollLeft):kn=jt(),An=It(kn)}j=k.cloneNode(!0),Ot(j,n.ghostClass,!1),Ot(j,n.fallbackClass,!0),Ot(j,n.dragClass,!0),D(j,`transition`,``),D(j,`transform`,``),D(j,`box-sizing`,`border-box`),D(j,`margin`,0),D(j,`top`,t.top),D(j,`left`,t.left),D(j,`width`,t.width),D(j,`height`,t.height),D(j,`opacity`,`0.8`),D(j,`position`,Pn?`absolute`:`fixed`),D(j,`zIndex`,`100000`),D(j,`pointerEvents`,`none`),P.ghost=j,e.appendChild(j),D(j,`transform-origin`,xn/parseInt(j.style.width)*100+`% `+Sn/parseInt(j.style.height)*100+`%`)}},_onDragStart:function(e,t){var n=this,r=e.dataTransfer,i=n.options;if(nn(`dragStart`,this,{evt:e}),P.eventCanceled){this._onDrop();return}nn(`setupClone`,this),P.eventCanceled||(N=Gt(k),N.removeAttribute(`id`),N.draggable=!1,N.style[`will-change`]=``,this._hideClone(),Ot(N,this.options.chosenClass,!1),P.clone=N),n.cloneId=nr(function(){nn(`clone`,n),!P.eventCanceled&&(n.options.removeCloneOnHide||M.insertBefore(N,k),n._hideClone(),rn({sortable:n,name:`clone`}))}),!t&&Ot(k,i.dragClass,!0),t?(hn=!0,n._loopId=setInterval(n._emulateDragOver,50)):(E(document,`mouseup`,n._onDrop),E(document,`touchend`,n._onDrop),E(document,`touchcancel`,n._onDrop),r&&(r.effectAllowed=`move`,i.setData&&i.setData.call(n,r,k)),T(document,`drop`,n),D(k,`transform`,`translateZ(0)`)),mn=!0,n._dragStartId=nr(n._dragStarted.bind(n,t,e)),T(document,`selectstart`,n),Cn=!0,window.getSelection().removeAllRanges(),bt&&D(document.body,`user-select`,`none`)},_onDragOver:function(e){var t=this.el,n=e.target,r,i,a,o=this.options,s=o.group,c=P.active,l=fn===s,u=o.sort,d=pn||c,f,p=this,m=!1;if(jn)return;function h(o,s){nn(o,p,lt({evt:e,isOwner:l,axis:f?`vertical`:`horizontal`,revert:a,dragRect:r,targetRect:i,canSort:u,fromSortable:d,target:n,completed:_,onMove:function(n,i){return qn(M,t,k,r,n,O(n),e,i)},changed:v},s))}function g(){h(`dragOverAnimationCapture`),p.captureAnimationState(),p!==d&&d.captureAnimationState()}function _(r){return h(`dragOverCompleted`,{insertion:r}),r&&(l?c._hideClone():c._showClone(p),p!==d&&(Ot(k,pn?pn.options.ghostClass:c.options.ghostClass,!1),Ot(k,o.ghostClass,!0)),pn!==p&&p!==P.active?pn=p:p===P.active&&pn&&(pn=null),d===p&&(p._ignoreWhileAnimating=n),p.animateAll(function(){h(`dragOverAnimationComplete`),p._ignoreWhileAnimating=null}),p!==d&&(d.animateAll(),d._ignoreWhileAnimating=null)),(n===k&&!k.animated||n===t&&!n.animated)&&(wn=null),!o.dragoverBubble&&!e.rootEl&&n!==document&&(k.parentNode[qt]._isOutsideThisEl(e.target),!r&&Wn(e)),!o.dragoverBubble&&e.stopPropagation&&e.stopPropagation(),m=!0}function v(){ln=Ft(k),dn=Ft(k,o.draggable),rn({sortable:p,name:`change`,toEl:t,newIndex:ln,newDraggableIndex:dn,originalEvent:e})}if(e.preventDefault!==void 0&&e.cancelable&&e.preventDefault(),n=Et(n,o.draggable,t,!0),h(`dragOver`),P.eventCanceled)return m;if(k.contains(e.target)||n.animated&&n.animatingX&&n.animatingY||p._ignoreWhileAnimating===n)return _(!1);if(hn=!1,c&&!o.disabled&&(l?u||(a=A!==M):pn===this||(this.lastPutMode=fn.checkPull(this,c,k,e))&&s.checkPut(this,c,k,e))){if(f=this._getDirection(e,n)===`vertical`,r=O(k),h(`dragOverValid`),P.eventCanceled)return m;if(a)return A=M,g(),this._hideClone(),h(`revert`),P.eventCanceled||(an?M.insertBefore(k,an):M.appendChild(k)),_(!0);var y=Pt(t,o.draggable);if(!y||Zn(e,f,this)&&!y.animated){if(y===k)return _(!1);if(y&&t===e.target&&(n=y),n&&(i=O(n)),qn(M,t,k,r,n,i,e,!!n)!==!1)return g(),y&&y.nextSibling?t.insertBefore(k,y.nextSibling):t.appendChild(k),A=t,v(),_(!0)}else if(y&&Xn(e,f,this)){var b=Nt(t,0,o,!0);if(b===k)return _(!1);if(n=b,i=O(n),qn(M,t,k,r,n,i,e,!1)!==!1)return g(),t.insertBefore(k,b),A=t,v(),_(!0)}else if(n.parentNode===t){i=O(n);var x=0,S,C=k.parentNode!==t,ee=!zn(k.animated&&k.toRect||r,n.animated&&n.toRect||i,f),te=f?`top`:`left`,ne=Mt(n,`top`,`top`)||Mt(k,`top`,`top`),re=ne?ne.scrollTop:void 0;wn!==n&&(S=i[te],En=!1,Dn=!ee&&o.invertSwap||C),x=Qn(e,n,i,f,ee?1:o.swapThreshold,o.invertedSwapThreshold==null?o.swapThreshold:o.invertedSwapThreshold,Dn,wn===n);var ie;if(x!==0){var ae=Ft(k);do ae-=x,ie=A.children[ae];while(ie&&(D(ie,`display`)===`none`||ie===j))}if(x===0||ie===n)return _(!1);wn=n,Tn=x;var oe=n.nextElementSibling,se=!1;se=x===1;var ce=qn(M,t,k,r,n,i,e,se);if(ce!==!1)return(ce===1||ce===-1)&&(se=ce===1),jn=!0,setTimeout(Yn,30),g(),se&&!oe?t.appendChild(k):n.parentNode.insertBefore(k,se?oe:n),ne&&Wt(ne,0,re-ne.scrollTop),A=k.parentNode,S!==void 0&&!Dn&&(On=Math.abs(S-O(n)[te])),v(),_(!0)}if(t.contains(k))return _(!1)}return!1},_ignoreWhileAnimating:null,_offMoveEvents:function(){E(document,`mousemove`,this._onTouchMove),E(document,`touchmove`,this._onTouchMove),E(document,`pointermove`,this._onTouchMove),E(document,`dragover`,Wn),E(document,`mousemove`,Wn),E(document,`touchmove`,Wn)},_offUpEvents:function(){var e=this.el.ownerDocument;E(e,`mouseup`,this._onDrop),E(e,`touchend`,this._onDrop),E(e,`pointerup`,this._onDrop),E(e,`pointercancel`,this._onDrop),E(e,`touchcancel`,this._onDrop),E(document,`selectstart`,this)},_onDrop:function(e){var t=this.el,n=this.options;if(ln=Ft(k),dn=Ft(k,n.draggable),nn(`drop`,this,{evt:e}),A=k&&k.parentNode,ln=Ft(k),dn=Ft(k,n.draggable),P.eventCanceled){this._nulling();return}mn=!1,Dn=!1,En=!1,clearInterval(this._loopId),clearTimeout(this._dragStartTimer),rr(this.cloneId),rr(this._dragStartId),this.nativeDraggable&&(E(document,`drop`,this),E(t,`dragstart`,this._onDragStart)),this._offMoveEvents(),this._offUpEvents(),bt&&D(document.body,`user-select`,``),D(k,`transform`,``),e&&(Cn&&(e.cancelable&&e.preventDefault(),!n.dropBubble&&e.stopPropagation()),j&&j.parentNode&&j.parentNode.removeChild(j),(M===A||pn&&pn.lastPutMode!==`clone`)&&N&&N.parentNode&&N.parentNode.removeChild(N),k&&(this.nativeDraggable&&E(k,`dragend`,this),Jn(k),k.style[`will-change`]=``,Cn&&!mn&&Ot(k,pn?pn.options.ghostClass:this.options.ghostClass,!1),Ot(k,this.options.chosenClass,!1),rn({sortable:this,name:`unchoose`,toEl:A,newIndex:null,newDraggableIndex:null,originalEvent:e}),M===A?ln!==cn&&ln>=0&&(rn({sortable:this,name:`update`,toEl:A,originalEvent:e}),rn({sortable:this,name:`sort`,toEl:A,originalEvent:e})):(ln>=0&&(rn({rootEl:A,name:`add`,toEl:A,fromEl:M,originalEvent:e}),rn({sortable:this,name:`remove`,toEl:A,originalEvent:e}),rn({rootEl:A,name:`sort`,toEl:A,fromEl:M,originalEvent:e}),rn({sortable:this,name:`sort`,toEl:A,originalEvent:e})),pn&&pn.save()),P.active&&((ln==null||ln===-1)&&(ln=cn,dn=un),rn({sortable:this,name:`end`,toEl:A,originalEvent:e}),this.save()))),this._nulling()},_nulling:function(){nn(`nulling`,this),M=k=A=j=an=N=on=sn=_n=vn=Cn=ln=dn=cn=un=wn=Tn=pn=fn=P.dragged=P.ghost=P.clone=P.active=null;var e=this.el;Mn.forEach(function(t){e.contains(t)&&(t.checked=!0)}),Mn.length=yn=bn=0},handleEvent:function(e){switch(e.type){case`drop`:case`dragend`:this._onDrop(e);break;case`dragenter`:case`dragover`:k&&(this._onDragOver(e),Kn(e));break;case`selectstart`:e.preventDefault();break}},toArray:function(){for(var e=[],t,n=this.el.children,r=0,i=n.length,a=this.options;r<i;r++)t=n[r],Et(t,a.draggable,this.el,!1)&&e.push(t.getAttribute(a.dataIdAttr)||er(t));return e},sort:function(e,t){var n={},r=this.el;this.toArray().forEach(function(e,t){var i=r.children[t];Et(i,this.options.draggable,r,!1)&&(n[e]=i)},this),t&&this.captureAnimationState(),e.forEach(function(e){n[e]&&(r.removeChild(n[e]),r.appendChild(n[e]))}),t&&this.animateAll()},save:function(){var e=this.options.store;e&&e.set&&e.set(this)},closest:function(e,t){return Et(e,t||this.options.draggable,this.el,!1)},option:function(e,t){var n=this.options;if(t===void 0)return n[e];var r=$t.modifyOption(this,e,t);r===void 0?n[e]=t:n[e]=r,e===`group`&&Vn(n)},destroy:function(){nn(`destroy`,this);var e=this.el;e[qt]=null,E(e,`mousedown`,this._onTapStart),E(e,`touchstart`,this._onTapStart),E(e,`pointerdown`,this._onTapStart),this.nativeDraggable&&(E(e,`dragover`,this),E(e,`dragenter`,this)),Array.prototype.forEach.call(e.querySelectorAll(`[draggable]`),function(e){e.removeAttribute(`draggable`)}),this._onDrop(),this._disableDelayedDragEvents(),gn.splice(gn.indexOf(this.el),1),this.el=e=null},_hideClone:function(){if(!sn){if(nn(`hideClone`,this),P.eventCanceled)return;D(N,`display`,`none`),this.options.removeCloneOnHide&&N.parentNode&&N.parentNode.removeChild(N),sn=!0}},_showClone:function(e){if(e.lastPutMode!==`clone`){this._hideClone();return}if(sn){if(nn(`showClone`,this),P.eventCanceled)return;k.parentNode==M&&!this.options.group.revertClone?M.insertBefore(N,k):an?M.insertBefore(N,an):M.appendChild(N),this.options.group.revertClone&&this.animate(k,N),D(N,`display`,``),sn=!1}}};function Kn(e){e.dataTransfer&&(e.dataTransfer.dropEffect=`move`),e.cancelable&&e.preventDefault()}function qn(e,t,n,r,i,a,o,s){var c,l=e[qt],u=l.options.onMove,d;return window.CustomEvent&&!_t&&!vt?c=new CustomEvent(`move`,{bubbles:!0,cancelable:!0}):(c=document.createEvent(`Event`),c.initEvent(`move`,!0,!0)),c.to=t,c.from=e,c.dragged=n,c.draggedRect=r,c.related=i||t,c.relatedRect=a||O(t),c.willInsertAfter=s,c.originalEvent=o,e.dispatchEvent(c),u&&(d=u.call(l,c,o)),d}function Jn(e){e.draggable=!1}function Yn(){jn=!1}function Xn(e,t,n){var r=O(Nt(n.el,0,n.options,!0)),i=Kt(n.el,n.options,j),a=10;return t?e.clientX<i.left-a||e.clientY<r.top&&e.clientX<r.right:e.clientY<i.top-a||e.clientY<r.bottom&&e.clientX<r.left}function Zn(e,t,n){var r=O(Pt(n.el,n.options.draggable)),i=Kt(n.el,n.options,j),a=10;return t?e.clientX>i.right+a||e.clientY>r.bottom&&e.clientX>r.left:e.clientY>i.bottom+a||e.clientX>r.right&&e.clientY>r.top}function Qn(e,t,n,r,i,a,o,s){var c=r?e.clientY:e.clientX,l=r?n.height:n.width,u=r?n.top:n.left,d=r?n.bottom:n.right,f=!1;if(!o){if(s&&On<l*i){if(!En&&(Tn===1?c>u+l*a/2:c<d-l*a/2)&&(En=!0),En)f=!0;else if(Tn===1?c<u+On:c>d-On)return-Tn}else if(c>u+l*(1-i)/2&&c<d-l*(1-i)/2)return $n(t)}return f||=o,f&&(c<u+l*a/2||c>d-l*a/2)?c>u+l/2?1:-1:0}function $n(e){return Ft(k)<Ft(e)?1:-1}function er(e){for(var t=e.tagName+e.className+e.src+e.href+e.textContent,n=t.length,r=0;n--;)r+=t.charCodeAt(n);return r.toString(36)}function tr(e){Mn.length=0;for(var t=e.getElementsByTagName(`input`),n=t.length;n--;){var r=t[n];r.checked&&Mn.push(r)}}function nr(e){return setTimeout(e,0)}function rr(e){return clearTimeout(e)}Nn&&T(document,`touchmove`,function(e){(P.active||mn)&&e.cancelable&&e.preventDefault()}),P.utils={on:T,off:E,css:D,find:At,is:function(e,t){return!!Et(e,t,e,!1)},extend:zt,throttle:Ht,closest:Et,toggleClass:Ot,clone:Gt,index:Ft,nextTick:nr,cancelNextTick:rr,detectDirection:Rn,getChild:Nt,expando:qt},P.get=function(e){return e[qt]},P.mount=function(){var e=[...arguments];e[0].constructor===Array&&(e=e[0]),e.forEach(function(e){if(!e.prototype||!e.prototype.constructor)throw`Sortable: Mounted plugin must be a constructor function, not ${{}.toString.call(e)}`;e.utils&&(P.utils=lt(lt({},P.utils),e.utils)),$t.mount(e)})},P.create=function(e,t){return new P(e,t)},P.version=ht;var F=[],ir,ar,or=!1,sr,cr,lr,ur;function dr(){function e(){for(var e in this.defaults={scroll:!0,forceAutoScrollFallback:!1,scrollSensitivity:30,scrollSpeed:10,bubbleScroll:!0},this)e.charAt(0)===`_`&&typeof this[e]==`function`&&(this[e]=this[e].bind(this))}return e.prototype={dragStarted:function(e){var t=e.originalEvent;this.sortable.nativeDraggable?T(document,`dragover`,this._handleAutoScroll):this.options.supportPointer?T(document,`pointermove`,this._handleFallbackAutoScroll):t.touches?T(document,`touchmove`,this._handleFallbackAutoScroll):T(document,`mousemove`,this._handleFallbackAutoScroll)},dragOverCompleted:function(e){var t=e.originalEvent;!this.options.dragOverBubble&&!t.rootEl&&this._handleAutoScroll(t)},drop:function(){this.sortable.nativeDraggable?E(document,`dragover`,this._handleAutoScroll):(E(document,`pointermove`,this._handleFallbackAutoScroll),E(document,`touchmove`,this._handleFallbackAutoScroll),E(document,`mousemove`,this._handleFallbackAutoScroll)),pr(),fr(),Ut()},nulling:function(){lr=ar=ir=or=ur=sr=cr=null,F.length=0},_handleFallbackAutoScroll:function(e){this._handleAutoScroll(e,!0)},_handleAutoScroll:function(e,t){var n=this,r=(e.touches?e.touches[0]:e).clientX,i=(e.touches?e.touches[0]:e).clientY,a=document.elementFromPoint(r,i);if(lr=e,t||this.options.forceAutoScrollFallback||vt||_t||bt){mr(e,this.options,a,t);var o=Rt(a,!0);or&&(!ur||r!==sr||i!==cr)&&(ur&&pr(),ur=setInterval(function(){var a=Rt(document.elementFromPoint(r,i),!0);a!==o&&(o=a,fr()),mr(e,n.options,a,t)},10),sr=r,cr=i)}else{if(!this.options.bubbleScroll||Rt(a,!0)===jt()){fr();return}mr(e,this.options,Rt(a,!1),!1)}}},st(e,{pluginName:`scroll`,initializeByDefault:!0})}function fr(){F.forEach(function(e){clearInterval(e.pid)}),F=[]}function pr(){clearInterval(ur)}var mr=Ht(function(e,t,n,r){if(t.scroll){var i=(e.touches?e.touches[0]:e).clientX,a=(e.touches?e.touches[0]:e).clientY,o=t.scrollSensitivity,s=t.scrollSpeed,c=jt(),l=!1,u;ar!==n&&(ar=n,fr(),ir=t.scroll,u=t.scrollFn,ir===!0&&(ir=Rt(n,!0)));var d=0,f=ir;do{var p=f,m=O(p),h=m.top,g=m.bottom,_=m.left,v=m.right,y=m.width,b=m.height,x=void 0,S=void 0,C=p.scrollWidth,ee=p.scrollHeight,te=D(p),ne=p.scrollLeft,re=p.scrollTop;p===c?(x=y<C&&(te.overflowX===`auto`||te.overflowX===`scroll`||te.overflowX===`visible`),S=b<ee&&(te.overflowY===`auto`||te.overflowY===`scroll`||te.overflowY===`visible`)):(x=y<C&&(te.overflowX===`auto`||te.overflowX===`scroll`),S=b<ee&&(te.overflowY===`auto`||te.overflowY===`scroll`));var ie=x&&(Math.abs(v-i)<=o&&ne+y<C)-(Math.abs(_-i)<=o&&!!ne),ae=S&&(Math.abs(g-a)<=o&&re+b<ee)-(Math.abs(h-a)<=o&&!!re);if(!F[d])for(var oe=0;oe<=d;oe++)F[oe]||(F[oe]={});(F[d].vx!=ie||F[d].vy!=ae||F[d].el!==p)&&(F[d].el=p,F[d].vx=ie,F[d].vy=ae,clearInterval(F[d].pid),(ie!=0||ae!=0)&&(l=!0,F[d].pid=setInterval(function(){r&&this.layer===0&&P.active._onTouchMove(lr);var t=F[this.layer].vy?F[this.layer].vy*s:0,n=F[this.layer].vx?F[this.layer].vx*s:0;typeof u==`function`&&u.call(P.dragged.parentNode[qt],n,t,e,lr,F[this.layer].el)!==`continue`||Wt(F[this.layer].el,n,t)}.bind({layer:d}),24))),d++}while(t.bubbleScroll&&f!==c&&(f=Rt(f,!1)));or=l}},30),hr=function(e){var t=e.originalEvent,n=e.putSortable,r=e.dragEl,i=e.activeSortable,a=e.dispatchSortableEvent,o=e.hideGhostForTarget,s=e.unhideGhostForTarget;if(t){var c=n||i;o();var l=t.changedTouches&&t.changedTouches.length?t.changedTouches[0]:t,u=document.elementFromPoint(l.clientX,l.clientY);s(),c&&!c.el.contains(u)&&(a(`spill`),this.onSpill({dragEl:r,putSortable:n}))}};function gr(){}gr.prototype={startIndex:null,dragStart:function(e){this.startIndex=e.oldDraggableIndex},onSpill:function(e){var t=e.dragEl,n=e.putSortable;this.sortable.captureAnimationState(),n&&n.captureAnimationState();var r=Nt(this.sortable.el,this.startIndex,this.options);r?this.sortable.el.insertBefore(t,r):this.sortable.el.appendChild(t),this.sortable.animateAll(),n&&n.animateAll()},drop:hr},st(gr,{pluginName:`revertOnSpill`});function _r(){}_r.prototype={onSpill:function(e){var t=e.dragEl,n=e.putSortable||this.sortable;n.captureAnimationState(),t.parentNode&&t.parentNode.removeChild(t),n.animateAll()},drop:hr},st(_r,{pluginName:`removeOnSpill`}),P.mount(new dr),P.mount(_r,gr);var vr={animation:180,bubbleScroll:!1,fallbackTolerance:4,forceAutoScrollFallback:!0,scrollSensitivity:56,scrollSpeed:18};function yr(e,t,n){return[...e.querySelectorAll(t)].map(e=>e.dataset[n]).filter(e=>e!==void 0)}function br(e){return e.item.nextSibling}function xr(e,t,n=null){let{item:r,oldIndex:i,newIndex:a}=t;if(i==null||a==null||i===a)return;if(r.parentNode?.removeChild(r),n){e.insertBefore(r,n);return}let o=e.children;i>=o.length?e.appendChild(r):e.insertBefore(r,o[i]??null)}function Sr(e,t){if(t){e.dataset.dragging=`true`;return}delete e.dataset.dragging}function Cr(e,t){let n=t==null?void 0:e[t];if(!n)return{movedId:void 0,movedIndex:-1,afterId:null,beforeId:null};let r=e.indexOf(n);return{movedId:n,movedIndex:r,afterId:r>0?e[r-1]:null,beforeId:r>=0&&r<e.length-1?e[r+1]:null}}var wr=`modulepreload`,Tr=function(e){return`/`+e},Er={},Dr=function(e,t,n){let r=Promise.resolve();if(t&&t.length>0){let e=document.getElementsByTagName(`link`),i=document.querySelector(`meta[property=csp-nonce]`),a=i?.nonce||i?.getAttribute(`nonce`);function o(e){return Promise.all(e.map(e=>Promise.resolve(e).then(e=>({status:`fulfilled`,value:e}),e=>({status:`rejected`,reason:e}))))}r=o(t.map(t=>{if(t=Tr(t,n),t in Er)return;Er[t]=!0;let r=t.endsWith(`.css`),i=r?`[rel="stylesheet"]`:``;if(n)for(let n=e.length-1;n>=0;n--){let i=e[n];if(i.href===t&&(!r||i.rel===`stylesheet`))return}else if(document.querySelector(`link[href="${t}"]${i}`))return;let o=document.createElement(`link`);if(o.rel=r?`stylesheet`:wr,r||(o.as=`script`),o.crossOrigin=``,o.href=t,a&&o.setAttribute(`nonce`,a),document.head.appendChild(o),r)return new Promise((e,n)=>{o.addEventListener(`load`,e),o.addEventListener(`error`,()=>n(Error(`Unable to preload CSS for ${t}`)))})}))}function i(e){let t=new Event(`vite:preloadError`,{cancelable:!0});if(t.payload=e,window.dispatchEvent(t),!t.defaultPrevented)throw e}return r.then(t=>{for(let e of t||[])e.status===`rejected`&&i(e.reason);return e().catch(i)})},Or={media:`
777
+ <rect x="2.75" y="3" width="12.5" height="11.25" rx="3" />
778
+ <circle cx="6.15" cy="6.85" r="0.85" fill="currentColor" stroke="none" />
779
+ <path d="M3.6 11.95 6.75 8.8c.42-.42 1.11-.42 1.53 0l1.4 1.4" />
780
+ <path d="m8.95 10.2 1.38-1.38c.46-.46 1.21-.46 1.67 0l2.4 2.4" />
781
+ `,attachedText:`
782
+ <rect x="3" y="2.75" width="12" height="12.5" rx="3.1" />
783
+ <path d="M5.85 6.35h6.3" />
784
+ <path d="M5.85 9h6.3" />
785
+ <path d="M5.85 11.65h4.35" />
786
+ `,emoji:`
787
+ <circle cx="9" cy="9" r="6.8" />
788
+ <path d="M6.2 10.55c.52 1.08 1.46 1.8 2.8 1.8s2.28-.72 2.8-1.8" />
789
+ <circle cx="6.5" cy="7.15" r="0.7" fill="currentColor" stroke="none" />
790
+ <circle cx="11.5" cy="7.15" r="0.7" fill="currentColor" stroke="none" />
791
+ `,rate:`
792
+ <path
793
+ d="m9 1.95 2.08 4.21 4.65.67-3.36 3.29.8 4.63L9 12.55l-4.17 2.2.8-4.63-3.36-3.29 4.65-.67z"
794
+ fill="currentColor"
795
+ fill-opacity="0.12"
796
+ stroke="none"
797
+ />
798
+ <path
799
+ d="m9 1.95 2.08 4.21 4.65.67-3.36 3.29.8 4.63L9 12.55l-4.17 2.2.8-4.63-3.36-3.29 4.65-.67z"
800
+ stroke-width="1.6"
801
+ />
802
+ `,title:`
803
+ <rect
804
+ x="3.35"
805
+ y="3.2"
806
+ width="11.3"
807
+ height="2.05"
808
+ rx="0.68"
809
+ fill="currentColor"
810
+ stroke="none"
811
+ />
812
+ <rect
813
+ x="7.8"
814
+ y="4.6"
815
+ width="2.4"
816
+ height="9.45"
817
+ rx="0.78"
818
+ fill="currentColor"
819
+ stroke="none"
820
+ />
821
+ <rect
822
+ x="6.75"
823
+ y="13.15"
824
+ width="4.5"
825
+ height="1.12"
826
+ rx="0.56"
827
+ fill="currentColor"
828
+ stroke="none"
829
+ />
830
+ `,fullscreen:`
831
+ <path d="M5.85 3H3v2.85" stroke-width="1.48" />
832
+ <path d="M12.15 3H15v2.85" stroke-width="1.48" />
833
+ <path d="M3 12.15V15h2.85" stroke-width="1.48" />
834
+ <path d="M15 12.15V15h-2.85" stroke-width="1.48" />
835
+ `};function kr(e){return s`<svg
836
+ class="compose-tool-icon"
837
+ width="18"
838
+ height="18"
839
+ viewBox="0 0 18 18"
840
+ fill="none"
841
+ stroke="currentColor"
842
+ stroke-width="1.55"
843
+ stroke-linecap="round"
844
+ stroke-linejoin="round"
845
+ aria-hidden="true"
846
+ >
847
+ ${be(e)}
848
+ </svg>`}var Ar=class e extends o{static properties={format:{type:String},labels:{type:Object},uploadMaxFileSize:{type:Number},_title:{state:!0},_bodyJson:{state:!0},_url:{state:!0},_quoteText:{state:!0},_quoteAuthor:{state:!0},_rating:{state:!0},_showTitle:{state:!0},_showRating:{state:!0},_attachedTexts:{state:!0},_attachments:{state:!0},_attachmentOrder:{state:!0},_showAltPanel:{state:!0},_altPanelIndex:{state:!0},_showEmojiPicker:{state:!0},_showUrlValidation:{state:!0},_showLinkTitleValidation:{state:!0}};_editor=null;_fileInput=null;_lastFocusedField=null;_emojiPickerEl=null;_emojiContainer=null;_urlStatusId=`compose-url-status-${crypto.randomUUID()}`;_onDocClickBound=this._onDocumentClick.bind(this);_scrollBufferApplied=!1;_filePickerCleanup=null;_suppressAttachedTextOpenUntil=0;#e=null;#t=null;createRenderRoot(){return this}constructor(){super(),this.format=`note`,this.labels={},this.uploadMaxFileSize=500,this._title=``,this._bodyJson=null,this._url=``,this._quoteText=``,this._quoteAuthor=``,this._rating=0,this._showTitle=!1,this._showRating=!1,this._attachedTexts=[],this._attachments=[],this._attachmentOrder=[],this._showAltPanel=!1,this._altPanelIndex=0,this._showEmojiPicker=!1,this._showUrlValidation=!1,this._showLinkTitleValidation=!1}connectedCallback(){super.connectedCallback(),document.addEventListener(`jant:slash-image`,this._onSlashImage)}disconnectedCallback(){super.disconnectedCallback(),this._editor?.destroy(),this._editor=null,this.#e?.destroy(),this.#e=null,document.removeEventListener(`jant:slash-image`,this._onSlashImage),document.removeEventListener(`click`,this._onDocClickBound,!0),this._emojiContainer?.remove(),this._filePickerCleanup?.(),this._filePickerCleanup=null}_onSlashImage=()=>{document.querySelector(`.compose-fullscreen-dialog[open]`)||this._editor&&this._triggerSlashImagePicker()};_slashImageInput=null;_triggerSlashImagePicker(){this._slashImageInput||(this._slashImageInput=document.createElement(`input`),this._slashImageInput.type=`file`,this._slashImageInput.accept=`image/*`,this._slashImageInput.style.display=`none`,this._slashImageInput.addEventListener(`change`,()=>{let e=this._slashImageInput?.files?.[0];e&&this._editor&&this._uploadAndInsertImage(e),this._slashImageInput&&(this._slashImageInput.value=``)}),document.body.appendChild(this._slashImageInput)),this._trackFilePickerSession(this._slashImageInput),this._slashImageInput.click()}_uploadAndInsertImage(e){let t=this._editor;t&&S(t,e)}_dispatchFilePickerEvent(e,t){this.dispatchEvent(new CustomEvent(e,{bubbles:!0,composed:!0,detail:t}))}_trackFilePickerSession(e){this._filePickerCleanup?.();let t=!1,n=e=>{t||(t=!0,o(),this._dispatchFilePickerEvent(`jant:file-picker-close`,{cancelled:e}))},r=()=>n(!1),i=()=>n(!0),a=()=>{globalThis.setTimeout(()=>{n(!(e.files&&e.files.length>0))},0)},o=()=>{e.removeEventListener(`change`,r),e.removeEventListener(`cancel`,i),window.removeEventListener(`focus`,a),this._filePickerCleanup===o&&(this._filePickerCleanup=null)};this._filePickerCleanup=o,e.addEventListener(`change`,r,{once:!0}),e.addEventListener(`cancel`,i,{once:!0}),window.addEventListener(`focus`,a,{once:!0}),this._dispatchFilePickerEvent(`jant:file-picker-open`)}_isEmptyDoc(e){return!e.content||e.content.length===0?!0:e.content.every(e=>e.type===`paragraph`&&(!e.content||e.content.length===0))}_normalizeDocJson(e){return e?this._isEmptyDoc(e)?null:e:null}getNormalizedBodyJson(){return this._normalizeDocJson(this._bodyJson)}getEffectiveAttachedTexts(){return this._attachedTexts.flatMap(e=>{let t=this._normalizeDocJson(e.bodyJson);return t?[{...e,bodyJson:t,originalBodyJson:this._normalizeDocJson(e.originalBodyJson??null)}]:[]})}getEffectiveAttachmentOrder(){let e=new Set(this.getEffectiveAttachedTexts().map(e=>e.clientId)),t=new Set(this._attachments.map(e=>e.clientId));return this._attachmentOrder.filter(n=>t.has(n)||e.has(n))}_getEffectiveRating(){return this._showRating?this._rating:0}getData(){let e=this.getNormalizedBodyJson(),t=this.getEffectiveAttachedTexts(),n=this.getEffectiveAttachmentOrder(),r=e?JSON.stringify(e):``,i={rating:this._getEffectiveRating(),attachedTexts:t,attachments:this._attachments,attachmentOrder:n};switch(this.format){case`link`:return{...i,title:this._title,body:r,url:this._url,quoteText:``,quoteAuthor:``};case`quote`:return{...i,title:``,body:r,url:this._url,quoteText:this._quoteText,quoteAuthor:this._quoteAuthor};default:return{...i,title:this._showTitle?this._title:``,body:r,url:``,quoteText:``,quoteAuthor:``}}}reset(){this._title=``,this._bodyJson=null,this._editor?.commands.clearContent(),this._url=``,this._quoteText=``,this._quoteAuthor=``,this._rating=0,this._showTitle=!1,this._showRating=!1,this._attachedTexts=[];for(let e of this._attachments)URL.revokeObjectURL(e.previewUrl);this._attachments=[],this._attachmentOrder=[],this._showAltPanel=!1,this._altPanelIndex=0,this._showUrlValidation=!1,this._showLinkTitleValidation=!1,this.closeEmojiPicker()}updateAttachmentStatus(e,t,n,r){this._attachments=this._attachments.map(i=>i.clientId===e?{...i,status:t,mediaId:n,error:r}:i)}updateAttachmentPreview(e,t){this._attachments=this._attachments.map(n=>n.clientId===e?(URL.revokeObjectURL(n.previewUrl),{...n,file:t,previewUrl:URL.createObjectURL(t)}):n)}updateAttachmentProgress(e,t){this._attachments=this._attachments.map(n=>n.clientId===e?{...n,progress:t}:n)}focusInput(e){if(this.format===`link`){this.focusUrlInput(e);return}if(this.format===`quote`){this._focusTextControl(this.querySelector(`.compose-quote-text`),e);return}if(e){this._editor?.commands.focus(e);return}this._editor?.commands.focus()}focusUrlInput(e){this._focusTextControl(this.querySelector(`.compose-url-input`),e)}focusLinkTitleInput(e){this._focusTextControl(this.querySelector(`.compose-link-title`),e)}getUrlValidationMessage(){return this.format===`note`?null:this._url.trim()?r(this._url)?null:this.labels.urlInvalid:this.format===`link`?this.labels.linkUrlRequired:null}getLinkTitleValidationMessage(){return this.format===`link`?this._title.trim()?null:this.labels.linkTitleRequired:null}_getInlineUrlValidationMessage(){return this.format===`link`&&!this._url.trim()?null:this.getUrlValidationMessage()}_getInlineLinkTitleValidationMessage(){return this.format!==`link`||!this._title.trim()?null:this.getLinkTitleValidationMessage()}revealUrlValidation(){return this._showUrlValidation=!0,this.getUrlValidationMessage()}revealLinkTitleValidation(){return this._showLinkTitleValidation=!0,this.getLinkTitleValidationMessage()}isEmojiPickerOpen(){return this._showEmojiPicker}_focusTextControl(e,t){if(!e||(e.focus(),!t))return;let n=t===`end`?e.value.length:0;e.setSelectionRange(n,n)}_initEditor(){let e=this.querySelector(`.compose-tiptap-body`);if(!e||this._editor)return;this._editor=y({element:e,placeholder:this.format===`note`?this.labels.bodyPlaceholder:this.labels.thoughtsPlaceholder,content:this._bodyJson,toolbarMode:`compose`,onUpdate:e=>{this._bodyJson=e,this._ensureScrollBuffer()},onFocus:()=>{this._lastFocusedField=null},pasteMedia:{shouldInsertInline:e=>this._shouldPasteInlineImage(e),onPasteFiles:e=>{this.addFiles(e)}}}),this._scrollBufferApplied=!1;let t=this._editor.view.dom,n=t.lastElementChild,r=n?n.offsetTop+n.offsetHeight:0,i=this.format===`note`?120:60;t.style.minHeight=`${r+i}px`}_ensureScrollBuffer(){if(this._scrollBufferApplied)return;let e=this._editor?.view?.dom;if(!e)return;let t=this.querySelector(`.compose-body`);t&&t.scrollHeight>t.clientHeight+20&&(e.style.paddingBottom=`80px`,this._scrollBufferApplied=!0)}_destroyEditor(){this._editor?.destroy(),this._editor=null}static _CONTENT_PROPS=new Set([`_title`,`_bodyJson`,`_url`,`_quoteText`,`_quoteAuthor`,`_rating`,`_showTitle`,`_showRating`,`_attachedTexts`,`_attachmentOrder`]);updated(t){super.updated(t),this._editor||this._initEditor(),t.has(`format`)&&t.get(`format`)!==void 0&&(this._showUrlValidation&&=!1,this._showLinkTitleValidation&&=!1,this._destroyEditor(),this.updateComplete.then(()=>this._initEditor())),(t.has(`_attachmentOrder`)||t.has(`_attachments`)||t.has(`_attachedTexts`))&&(this._attachmentOrder.length>1?this.#n():(this.#e?.destroy(),this.#e=null));for(let n of t.keys())if(e._CONTENT_PROPS.has(n)){this.dispatchEvent(new Event(`jant:compose-content-changed`,{bubbles:!0}));break}}getEditorState(){return{json:this._editor?.getJSON()??this._bodyJson,title:this._title,showTitle:this._showTitle}}populate(e){if(e.title&&(this._title=e.title),e.url&&(this._url=e.url),e.quoteText&&(this._quoteText=e.quoteText),e.quoteAuthor&&(this._quoteAuthor=e.quoteAuthor),e.rating&&e.rating>0&&(this._rating=e.rating,this._showRating=!0),e.showTitle===void 0?e.title&&e.format===`note`&&(this._showTitle=!0):this._showTitle=e.showTitle,e.showRating!==void 0&&(this._showRating=e.showRating),e.bodyJson)try{let t=JSON.parse(e.bodyJson);this._bodyJson=t,this._editor&&this._editor.commands.setContent(t)}catch{}if(e.media?.length){let t=e.media.map(e=>({clientId:crypto.randomUUID(),file:new File([],e.originalName??`existing`,{type:e.mimeType}),previewUrl:e.previewUrl,status:`done`,progress:null,mediaId:e.id,alt:e.alt??``,error:null,summary:e.summary??null,chars:e.chars??null}));this._attachments=t,this._attachmentOrder=t.map(e=>e.clientId)}if(e.textAttachments?.length){let t=e.textAttachments.map(e=>{let t=null;try{t=JSON.parse(e.bodyJson)}catch{}return{clientId:e.clientId??crypto.randomUUID(),bodyJson:t,bodyHtml:e.bodyHtml??``,summary:e.summary,mediaId:e.mediaId,originalBodyJson:t}});this._attachedTexts=t,this._attachmentOrder=[...this._attachmentOrder,...t.map(e=>e.clientId)]}if(e.attachmentOrder?.length){let t=e.attachmentOrder.map(e=>this._attachments.find(t=>t.mediaId===e||t.clientId===e)?.clientId||this._attachedTexts.find(t=>t.mediaId===e||t.clientId===e)?.clientId).filter(e=>e!==void 0),n=this._attachmentOrder.filter(e=>!t.includes(e));this._attachmentOrder=[...t,...n]}this._showUrlValidation=!1,this._showLinkTitleValidation=!1}setEditorState(e,t,n){this._bodyJson=e,this._title=t,this.format===`note`&&(this._showTitle=n||t.length>0),this._editor&&this._editor.commands.setContent(e??{type:`doc`,content:[{type:`paragraph`}]})}static SUMMARY_LENGTH=100;_computeSummary(t){let n=t.replace(/\s+/g,` `).trim();return n.length<=e.SUMMARY_LENGTH?n:n.slice(0,e.SUMMARY_LENGTH)+`…`}_openAttachedText(){let e={clientId:crypto.randomUUID(),bodyJson:null,bodyHtml:``,summary:``};this._attachedTexts=[...this._attachedTexts,e],this._attachmentOrder=[...this._attachmentOrder,e.clientId];let t=this._attachedTexts.length-1;this.dispatchEvent(new CustomEvent(`jant:attached-panel-open`,{bubbles:!0,detail:{index:t}}))}_moveAttachment(e,t){let n=this._attachmentOrder.indexOf(e),r=n+t;if(n===-1||r<0||r>=this._attachmentOrder.length)return;let i=[...this._attachmentOrder],[a]=i.splice(n,1);a&&(i.splice(r,0,a),this._attachmentOrder=i,this.#r(e))}_handleAttachmentKeydown(e,t,n){if(t.key===`ArrowLeft`||t.key===`ArrowUp`){t.preventDefault(),this._moveAttachment(e,-1);return}if(t.key===`ArrowRight`||t.key===`ArrowDown`){t.preventDefault(),this._moveAttachment(e,1);return}n&&(t.key===`Enter`||t.key===` `)&&(t.preventDefault(),n())}#n(){let e=this.querySelector(`[data-attachment-list]`);!e||this.#e||this._attachmentOrder.length<=1||(this.#e=P.create(e,{...vr,chosenClass:`compose-attachment-chosen`,direction:`horizontal`,dragClass:`compose-attachment-drag`,filter:`button, a, input, textarea, select, option, [contenteditable='true']`,ghostClass:`compose-attachment-ghost`,handle:`[data-attachment-sortable]`,preventOnFilter:!1,scroll:e,onChoose:()=>{Sr(e,!0)},onStart:e=>{this.#t=br(e)},onUnchoose:()=>{Sr(e,!1)},onEnd:t=>{let n=yr(e,`[data-attachment-id]`,`attachmentId`);if(xr(e,t,this.#t),this.#t=null,Sr(e,!1),this.#e?.destroy(),this.#e=null,n.length===this._attachmentOrder.length){this._attachmentOrder=n;let{movedId:e}=Cr(n,t.newIndex);e&&(this._suppressAttachedTextOpenUntil=Date.now()+250,this.#r(e))}}}))}#r(e){this.updateComplete.then(()=>{this.querySelector(`[data-attachment-id="${e}"]`)?.scrollIntoView({behavior:`smooth`,block:`nearest`,inline:`nearest`})})}_maybeEditAttachedText(e){Date.now()<this._suppressAttachedTextOpenUntil||this._editAttachedText(e)}_editAttachedText(e){this.dispatchEvent(new CustomEvent(`jant:attached-panel-open`,{bubbles:!0,detail:{index:e}}))}_removeAttachedText(e){let t=this._attachedTexts[e];this._attachedTexts=this._attachedTexts.filter((t,n)=>n!==e),t&&(this._attachmentOrder=this._attachmentOrder.filter(e=>e!==t.clientId))}updateAttachedText(e,t,n){let r=this._normalizeDocJson(t),i=this._extractPlainText(r);this._attachedTexts=this._attachedTexts.map((t,a)=>a===e?{...t,bodyJson:r,bodyHtml:r?n??``:``,summary:this._computeSummary(i)}:t)}closeAttachedPanel(e){let t=this._attachedTexts[e];t&&!this._hasAttachedTextContent(t.bodyJson)&&(this._attachedTexts=this._attachedTexts.filter((t,n)=>n!==e),this._attachmentOrder=this._attachmentOrder.filter(e=>e!==t.clientId))}_hasAttachedTextContent(e){let t=this._normalizeDocJson(e);return t?this._extractPlainText(t).trim().length>0:!1}_extractPlainText(e){if(!e)return``;let t=``,n=e=>{e.text&&(t+=e.text),e.content&&e.content.forEach(n)};return n(e),t}_onInput(e,t){let n=t.target;this[e]=n.value,n.tagName===`TEXTAREA`&&this._autoResize(n)}_autoResize(e){e.style.height=`auto`,e.style.height=`${e.scrollHeight}px`}_setRating(e){this._rating=this._rating===e?0:e}_shouldPasteInlineImage(e){return!e.type.startsWith(`image/`)||this.format===`quote`?!1:this.format===`note`?this._showTitle&&this._title.trim().length>0:this._title.trim().length>0}_openFilePicker(){this._fileInput||(this._fileInput=document.createElement(`input`),this._fileInput.type=`file`,this._fileInput.accept=`*/*`,this._fileInput.multiple=!0,this._fileInput.style.display=`none`,this._fileInput.addEventListener(`change`,()=>this._handleFilesSelected()),this.appendChild(this._fileInput)),this._fileInput.value=``,this._trackFilePickerSession(this._fileInput),this._fileInput.click()}_handleFilesSelected(){let e=this._fileInput?.files;!e||e.length===0||this.addFiles(e)}addFiles(e){let t=Array.from(e);if(t.length===0)return;let n=[],r=[];for(let e of t){let t=Fe(e,{maxFileSizeMB:this.uploadMaxFileSize});if(t){m(t,`error`);continue}let i=crypto.randomUUID(),a=URL.createObjectURL(e);n.push({clientId:i,file:e,previewUrl:a,status:`pending`,progress:null,mediaId:null,alt:``,error:null,summary:null,chars:null}),r.push({file:e,clientId:i})}if(n.length!==0){this._attachments=[...this._attachments,...n],this._attachmentOrder=[...this._attachmentOrder,...n.map(e=>e.clientId)];for(let e of n)Ne(e.file.type)===`text`&&e.file.text().then(t=>{let n=this._computeSummary(t),r=t.length;this._attachments=this._attachments.map(t=>t.clientId===e.clientId?{...t,summary:n,chars:r}:t)});this.dispatchEvent(new CustomEvent(`jant:files-selected`,{bubbles:!0,detail:{files:r}}))}}removeAttachment(e){let t=this._attachments.findIndex(t=>t.clientId===e);t!==-1&&this._removeAttachment(t)}_removeAttachment(e){let t=this._attachments[e];t&&(URL.revokeObjectURL(t.previewUrl),this.dispatchEvent(new CustomEvent(`jant:attachment-removed`,{bubbles:!0,detail:{clientId:t.clientId,mediaId:t.mediaId}}))),t&&(this._attachmentOrder=this._attachmentOrder.filter(e=>e!==t.clientId)),this._attachments=this._attachments.filter((t,n)=>n!==e),this._showAltPanel&&this._altPanelIndex===e?(this._showAltPanel=!1,this.dispatchEvent(new CustomEvent(`jant:alt-panel-close`,{bubbles:!0}))):this._showAltPanel&&this._altPanelIndex>e&&--this._altPanelIndex}_retryAllFailed(){let e=this._attachments.filter(e=>e.status===`error`);e.length!==0&&(this._attachments=this._attachments.map(e=>e.status===`error`?{...e,status:`pending`,progress:null,error:null}:e),this.dispatchEvent(new CustomEvent(`jant:files-selected`,{bubbles:!0,detail:{files:e.map(e=>({file:e.file,clientId:e.clientId}))}})))}_openAltPanel(e){this._altPanelIndex=e,this._showAltPanel=!0,this.dispatchEvent(new CustomEvent(`jant:alt-panel-open`,{bubbles:!0,detail:{index:e}}))}updateAlt(e,t){this._attachments=this._attachments.map((n,r)=>r===e?{...n,alt:t}:n)}_onFieldFocus(e){this._lastFocusedField=e.target}_toggleEmojiPicker(){this._showEmojiPicker?this.closeEmojiPicker():(this._showEmojiPicker=!0,this._mountEmojiPicker(),globalThis.setTimeout(()=>{document.addEventListener(`click`,this._onDocClickBound)},0))}closeEmojiPicker(e){if(!this._showEmojiPicker){e?.restoreFocus&&this._restoreEmojiFocus();return}this._showEmojiPicker=!1,this._emojiContainer?.remove(),document.removeEventListener(`click`,this._onDocClickBound),e?.restoreFocus&&this._restoreEmojiFocus()}_restoreEmojiFocus(){let e=this._lastFocusedField;if(e&&this.contains(e)&&!e.disabled){this._focusTextControl(e,`end`);return}this.focusInput(`end`)}_onDocumentClick(e){let t=e.target;this.querySelector(`.compose-emoji-btn`)?.contains(t)||this._emojiContainer?.contains(t)||this.closeEmojiPicker()}async _mountEmojiPicker(){let e=this.closest(`dialog`);if(this._emojiContainer||(this._emojiContainer=document.createElement(`div`),this._emojiContainer.className=`compose-emoji-picker`),(e??document.body).appendChild(this._emojiContainer),!this._emojiPickerEl){let[{default:e},{Picker:t}]=await Promise.all([Dr(()=>import(`./chunks/native-CR5HLOyf.js`),[]),Dr(()=>import(`./chunks/module-ChVQstFd.js`),[])]);if(!this._showEmojiPicker)return;this._emojiPickerEl=new t({data:e,onEmojiSelect:e=>{this._insertEmoji(e.native),this.closeEmojiPicker()},theme:`auto`,previewPosition:`none`,skinTonePosition:`none`})}this._emojiContainer.innerHTML=``,this._emojiContainer.appendChild(this._emojiPickerEl);let t=this.querySelector(`.compose-emoji-btn`);if(t&&e){let n=t.getBoundingClientRect(),r=e.getBoundingClientRect(),i=n.left-r.left,a=n.top-r.top,o=i+n.width/2-352/2;o=Math.max(-r.left+8,Math.min(o,r.width-8));let s=a-435-8;r.top+s<8&&(s=a+n.height+8),this._emojiContainer.style.left=`${o}px`,this._emojiContainer.style.top=`${s}px`}}_insertEmoji(e){let t=this._lastFocusedField;if(!t){this._editor&&this._editor.chain().focus().insertContent(e).run();return}let n=t.selectionStart??t.value.length,r=t.selectionEnd??n,i=t.value.slice(0,n),a=t.value.slice(r);t.value=i+e+a,t.dispatchEvent(new Event(`input`,{bubbles:!0}));let o=n+e.length;globalThis.requestAnimationFrame(()=>{t.focus(),t.setSelectionRange(o,o)})}_getCategory(e){return Ne(e.file.type)}_formatSize(e){return e<1024?`${e} B`:e<1024*1024?`${(e/1024).toFixed(1)} KB`:`${(e/(1024*1024)).toFixed(1)} MB`}_formatChars(e){return e<1e3?`${e} chars`:e<1e6?`${parseFloat((e/1e3).toFixed(1))}k chars`:`${parseFloat((e/1e6).toFixed(1))}M chars`}_renderFileIcon(e,t){let n;return n=e===`application/pdf`?`<text x="12" y="16.5" text-anchor="middle" fill="currentColor" stroke="none" font-size="6" font-weight="700" font-family="system-ui, sans-serif">PDF</text>`:e===`text/markdown`?`<text x="12" y="16.5" text-anchor="middle" fill="currentColor" stroke="none" font-size="10" font-weight="700" font-family="system-ui, sans-serif">#</text>`:e===`text/csv`?`<line x1="8" y1="12" x2="16" y2="12"/><line x1="8" y1="15" x2="16" y2="15"/><line x1="8" y1="18" x2="16" y2="18"/><line x1="10.7" y1="12" x2="10.7" y2="18"/><line x1="13.3" y1="12" x2="13.3" y2="18"/>`:Ne(e)===`archive`?`<line x1="12" y1="10" x2="12" y2="11.5"/><line x1="12" y1="13" x2="12" y2="14.5"/><line x1="12" y1="16" x2="12" y2="17.5"/>`:e===`text/x-tiptap+json`?`<line x1="16" y1="11" x2="8" y2="11"/><line x1="16" y1="14" x2="8" y2="14"/><line x1="12" y1="17" x2="8" y2="17"/>`:`<line x1="16" y1="13" x2="8" y2="13"/><line x1="16" y1="17" x2="8" y2="17"/><line x1="10" y1="9" x2="8" y2="9"/>`,s`<svg
849
+ width="${t}"
850
+ height="${t}"
851
+ viewBox="0 0 24 24"
852
+ fill="none"
853
+ stroke="currentColor"
854
+ stroke-width="1.5"
855
+ stroke-linecap="round"
856
+ stroke-linejoin="round"
857
+ >
858
+ ${be(`<path d="M14 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V8z"/><polyline points="14 2 14 8 20 8"/>`+n)}
859
+ </svg>`}_renderNoteFields(){return s`
860
+ <div class="compose-field-enter">
861
+ ${this._showTitle?s`
862
+ <div class="compose-note-title-row">
863
+ <input
864
+ type="text"
865
+ .value=${this._title}
866
+ @input=${e=>this._onInput(`_title`,e)}
867
+ @focus=${e=>this._onFieldFocus(e)}
868
+ @keydown=${e=>{e.key===`Enter`&&(e.preventDefault(),this._editor?.commands.focus(`start`))}}
869
+ class="compose-input compose-note-title"
870
+ placeholder=${this.labels.titlePlaceholder}
871
+ />
872
+ <button
873
+ type="button"
874
+ class="compose-note-title-dismiss"
875
+ @click=${()=>{this._showTitle=!1}}
876
+ >
877
+
878
+ </button>
879
+ </div>
880
+ `:i}
881
+ <div class="compose-tiptap-body"></div>
882
+ </div>
883
+ `}_renderLinkFields(){let e=this._showUrlValidation?this._getInlineUrlValidationMessage():null,t=this._showLinkTitleValidation?this._getInlineLinkTitleValidationMessage():null;return s`
884
+ <div class="compose-field-enter">
885
+ <div
886
+ class=${w({"compose-link-url-wrap":!0,"compose-link-url-wrap-invalid":!!e})}
887
+ >
888
+ <span class="text-base opacity-50 shrink-0">🔗</span>
889
+ <input
890
+ type="url"
891
+ .value=${this._url}
892
+ @input=${e=>this._onInput(`_url`,e)}
893
+ @focus=${e=>this._onFieldFocus(e)}
894
+ @blur=${()=>{this._showUrlValidation=!0}}
895
+ class="compose-input compose-url-input text-[0.9rem]"
896
+ placeholder=${this.labels.urlPlaceholder}
897
+ aria-invalid=${e?`true`:`false`}
898
+ aria-describedby=${at(e?this._urlStatusId:void 0)}
899
+ />
900
+ </div>
901
+ ${e?s`<p
902
+ id=${this._urlStatusId}
903
+ class="compose-url-status compose-url-status-error"
904
+ data-compose-url-status="error"
905
+ >
906
+ ${e}
907
+ </p>`:i}
908
+ <input
909
+ type="text"
910
+ .value=${this._title}
911
+ @input=${e=>this._onInput(`_title`,e)}
912
+ @focus=${e=>this._onFieldFocus(e)}
913
+ @blur=${()=>{this._showLinkTitleValidation=!0}}
914
+ class="compose-input compose-link-title"
915
+ placeholder=${this.labels.linkTitlePlaceholder}
916
+ aria-invalid=${t?`true`:`false`}
917
+ />
918
+ ${t?s`<p
919
+ class="compose-url-status compose-url-status-error"
920
+ data-compose-link-title-error="error"
921
+ >
922
+ ${t}
923
+ </p>`:i}
924
+ <div class="compose-divider"></div>
925
+ <div class="compose-tiptap-body compose-tiptap-thoughts"></div>
926
+ </div>
927
+ `}_renderQuoteFields(){let e=this._showUrlValidation?this.getUrlValidationMessage():null;return s`
928
+ <div class="compose-field-enter">
929
+ <div class="compose-quote-wrap">
930
+ <span class="compose-quote-mark">"</span>
931
+ <textarea
932
+ .value=${this._quoteText}
933
+ @input=${e=>this._onInput(`_quoteText`,e)}
934
+ @focus=${e=>this._onFieldFocus(e)}
935
+ class="compose-input compose-quote-text"
936
+ placeholder=${this.labels.quotePlaceholder}
937
+ rows="5"
938
+ ></textarea>
939
+ </div>
940
+ <div class="compose-quote-author-row">
941
+ <span class="compose-quote-dash">—</span>
942
+ <input
943
+ type="text"
944
+ .value=${this._quoteAuthor}
945
+ @input=${e=>this._onInput(`_quoteAuthor`,e)}
946
+ @focus=${e=>this._onFieldFocus(e)}
947
+ class="compose-input compose-quote-author"
948
+ placeholder=${this.labels.authorPlaceholder}
949
+ />
950
+ </div>
951
+ <div class="compose-quote-source">
952
+ <input
953
+ type="url"
954
+ .value=${this._url}
955
+ @input=${e=>this._onInput(`_url`,e)}
956
+ @focus=${e=>this._onFieldFocus(e)}
957
+ @blur=${()=>{this._showUrlValidation=!0}}
958
+ class="compose-input compose-url-input text-[0.78rem]"
959
+ placeholder=${this.labels.sourcePlaceholder}
960
+ aria-invalid=${e?`true`:`false`}
961
+ aria-describedby=${at(e?this._urlStatusId:void 0)}
962
+ />
963
+ ${e?s`<p
964
+ id=${this._urlStatusId}
965
+ class="compose-url-status compose-url-status-error"
966
+ data-compose-url-status="error"
967
+ >
968
+ ${e}
969
+ </p>`:i}
970
+ </div>
971
+ <div class="compose-divider"></div>
972
+ <div
973
+ class="compose-tiptap-body compose-tiptap-thoughts compose-tiptap-thoughts-quote"
974
+ ></div>
975
+ </div>
976
+ `}_renderStarRating(){return this._showRating?s`
977
+ <div class="compose-star-rating">
978
+ ${[1,2,3,4,5].map(e=>s`
979
+ <button
980
+ type="button"
981
+ class=${w({"compose-star":!0,"compose-star-filled":this._rating>=e})}
982
+ @click=${()=>this._setRating(e)}
983
+ >
984
+
985
+ </button>
986
+ `)}
987
+ ${this._rating>0?s`<span class="compose-star-label">${this._rating}/5</span>`:i}
988
+ </div>
989
+ `:i}_renderAttachmentPreview(e){let t=this._getCategory(e);return t===`video`?s`
990
+ <div class="compose-attachment-thumb">
991
+ <video
992
+ src=${e.previewUrl}
993
+ class="compose-attachment-img"
994
+ preload="metadata"
995
+ muted
996
+ ></video>
997
+ <div class="compose-attachment-play-icon">
998
+ <svg width="24" height="24" viewBox="0 0 24 24" fill="white">
999
+ <path d="M8 5v14l11-7z" />
1000
+ </svg>
1001
+ </div>
1002
+ </div>
1003
+ `:t===`audio`?s`
1004
+ <div class="compose-attachment-file-card">
1005
+ <div class="compose-attachment-file-icon">
1006
+ <svg
1007
+ width="20"
1008
+ height="20"
1009
+ viewBox="0 0 24 24"
1010
+ fill="none"
1011
+ stroke="currentColor"
1012
+ stroke-width="1.5"
1013
+ stroke-linecap="round"
1014
+ stroke-linejoin="round"
1015
+ >
1016
+ <path d="M9 18V5l12-2v13" />
1017
+ <circle cx="6" cy="18" r="3" />
1018
+ <circle cx="18" cy="16" r="3" />
1019
+ </svg>
1020
+ </div>
1021
+ <span class="compose-attachment-file-name">${e.file.name}</span>
1022
+ <span class="compose-attachment-file-size"
1023
+ >${this._formatSize(e.file.size)}</span
1024
+ >
1025
+ </div>
1026
+ `:t===`document`?s`
1027
+ <div class="compose-attachment-file-card">
1028
+ <div class="compose-attachment-file-icon">
1029
+ ${this._renderFileIcon(e.file.type,20)}
1030
+ </div>
1031
+ <span class="compose-attachment-file-name">${e.file.name}</span>
1032
+ <span class="compose-attachment-file-size"
1033
+ >${this._formatSize(e.file.size)}</span
1034
+ >
1035
+ </div>
1036
+ `:t===`text`?s`
1037
+ <div class="compose-attachment-file-card">
1038
+ <div class="compose-attachment-file-icon">
1039
+ ${this._renderFileIcon(e.file.type,20)}
1040
+ </div>
1041
+ <span class="compose-attachment-file-name">${e.file.name}</span>
1042
+ ${e.summary?s`<span class="compose-attachment-text-summary"
1043
+ >${e.summary}</span
1044
+ >`:i}
1045
+ ${typeof e.chars==`number`&&e.chars>0?s`<span class="compose-attachment-file-size"
1046
+ >${this._formatChars(e.chars)}</span
1047
+ >`:i}
1048
+ </div>
1049
+ `:t===`image`?s`
1050
+ <div class="compose-attachment-thumb">
1051
+ <img src=${e.previewUrl} alt="" class="compose-attachment-img" />
1052
+ </div>
1053
+ `:s`
1054
+ <div class="compose-attachment-file-card">
1055
+ <div class="compose-attachment-file-icon">
1056
+ ${this._renderFileIcon(e.file.type,20)}
1057
+ </div>
1058
+ <span class="compose-attachment-file-name">${e.file.name}</span>
1059
+ <span class="compose-attachment-file-size"
1060
+ >${this._formatSize(e.file.size)}</span
1061
+ >
1062
+ </div>
1063
+ `}_renderAttachmentOverlay(e,t){return s`
1064
+ ${e.status===`error`?s`
1065
+ <button
1066
+ type="button"
1067
+ class="compose-attachment-overlay compose-attachment-retry"
1068
+ @click=${e=>{e.stopPropagation(),this._retryAllFailed()}}
1069
+ >
1070
+ <span class="compose-retry-content">
1071
+ <svg
1072
+ width="20"
1073
+ height="20"
1074
+ viewBox="0 0 24 24"
1075
+ fill="none"
1076
+ stroke="currentColor"
1077
+ stroke-width="2"
1078
+ stroke-linecap="round"
1079
+ stroke-linejoin="round"
1080
+ >
1081
+ <path
1082
+ d="M21 12a9 9 0 0 0-9-9 9.75 9.75 0 0 0-6.74 2.74L3 8"
1083
+ />
1084
+ <path d="M3 3v5h5" />
1085
+ <path
1086
+ d="M3 12a9 9 0 0 0 9 9 9.75 9.75 0 0 0 6.74-2.74L21 16"
1087
+ />
1088
+ <path d="M16 16h5v5" />
1089
+ </svg>
1090
+ <span class="compose-retry-label">${this.labels.retryAll}</span>
1091
+ </span>
1092
+ </button>
1093
+ `:i}
1094
+ ${this._renderAttachmentRemoveButton(e=>{e.stopPropagation(),this._removeAttachment(t)})}
1095
+ `}_renderAttachmentRemoveButton(e){return s`
1096
+ <button
1097
+ type="button"
1098
+ class="compose-attachment-remove"
1099
+ title=${this.labels.removeAttachment}
1100
+ aria-label=${this.labels.removeAttachment}
1101
+ @click=${e}
1102
+ >
1103
+ <svg
1104
+ width="14"
1105
+ height="14"
1106
+ viewBox="0 0 14 14"
1107
+ fill="none"
1108
+ stroke="currentColor"
1109
+ stroke-width="1.9"
1110
+ stroke-linecap="round"
1111
+ >
1112
+ <path d="M3.5 3.5 10.5 10.5" />
1113
+ <path d="M10.5 3.5 3.5 10.5" />
1114
+ </svg>
1115
+ </button>
1116
+ `}_renderAttachedTextCard(e,t){return s`
1117
+ <div class="compose-attachment" data-attachment-id=${e.clientId}>
1118
+ <div
1119
+ class="compose-attachment-thumb compose-attachment-sortable"
1120
+ data-attachment-sortable
1121
+ tabindex="0"
1122
+ @click=${()=>this._maybeEditAttachedText(t)}
1123
+ @keydown=${n=>this._handleAttachmentKeydown(e.clientId,n,()=>this._maybeEditAttachedText(t))}
1124
+ >
1125
+ <div class="compose-attachment-text-card">
1126
+ <div class="compose-attachment-file-icon">
1127
+ ${this._renderFileIcon(`text/x-tiptap+json`,20)}
1128
+ </div>
1129
+ <span class="compose-attachment-text-summary">${e.summary}</span>
1130
+ ${e.bodyJson?s`<span class="compose-attachment-file-size"
1131
+ >${this._formatChars(this._extractPlainText(e.bodyJson).length)}</span
1132
+ >`:i}
1133
+ </div>
1134
+ ${this._renderAttachmentRemoveButton(e=>{e.stopPropagation(),this._removeAttachedText(t)})}
1135
+ </div>
1136
+ </div>
1137
+ `}_renderMediaAttachment(e,t){let n=this._getCategory(e),r=n!==`image`&&n!==`video`;return s`
1138
+ <div class="compose-attachment" data-attachment-id=${e.clientId}>
1139
+ ${r?s`
1140
+ <div class="compose-attachment-thumb">
1141
+ <div
1142
+ class="compose-attachment-sortable"
1143
+ data-attachment-sortable
1144
+ tabindex="0"
1145
+ @keydown=${t=>this._handleAttachmentKeydown(e.clientId,t)}
1146
+ >
1147
+ ${this._renderAttachmentPreview(e)}
1148
+ </div>
1149
+ ${this._renderAttachmentOverlay(e,t)}
1150
+ </div>
1151
+ `:s`
1152
+ <div class="compose-attachment-thumb">
1153
+ <div
1154
+ class="compose-attachment-sortable"
1155
+ data-attachment-sortable
1156
+ tabindex="0"
1157
+ @keydown=${t=>this._handleAttachmentKeydown(e.clientId,t)}
1158
+ >
1159
+ ${n===`video`?s`
1160
+ <video
1161
+ src=${e.previewUrl}
1162
+ class="compose-attachment-img"
1163
+ preload="metadata"
1164
+ muted
1165
+ ></video>
1166
+ <div class="compose-attachment-play-icon">
1167
+ <svg
1168
+ width="24"
1169
+ height="24"
1170
+ viewBox="0 0 24 24"
1171
+ fill="white"
1172
+ >
1173
+ <path d="M8 5v14l11-7z" />
1174
+ </svg>
1175
+ </div>
1176
+ `:e.status===`processing`?s`
1177
+ <div class="compose-attachment-processing">
1178
+ <svg
1179
+ class="animate-spin size-5"
1180
+ viewBox="0 0 24 24"
1181
+ fill="none"
1182
+ stroke="currentColor"
1183
+ stroke-width="2"
1184
+ >
1185
+ <path
1186
+ d="M12 2a10 10 0 1 0 10 10"
1187
+ stroke-linecap="round"
1188
+ />
1189
+ </svg>
1190
+ </div>
1191
+ `:s`
1192
+ <img
1193
+ src=${e.previewUrl}
1194
+ alt=""
1195
+ class="compose-attachment-img"
1196
+ />
1197
+ `}
1198
+ </div>
1199
+ ${this._renderAttachmentOverlay(e,t)}
1200
+ </div>
1201
+ `}
1202
+ ${n===`image`?s`
1203
+ <button
1204
+ type="button"
1205
+ class=${w({"compose-attachment-alt":!0,"compose-attachment-alt-set":e.alt.length>0})}
1206
+ @click=${()=>this._openAltPanel(t)}
1207
+ >
1208
+ ${e.alt.length>0?`ALT`:`+ ALT`}
1209
+ </button>
1210
+ `:i}
1211
+ </div>
1212
+ `}_renderAttachments(){return this._attachments.length===0&&this._attachedTexts.length===0?i:s`
1213
+ <div class="compose-attachments" data-attachment-list>
1214
+ ${this._attachmentOrder.map(e=>{let t=this._attachments.findIndex(t=>t.clientId===e);if(t!==-1)return this._renderMediaAttachment(this._attachments[t],t);let n=this._attachedTexts.findIndex(t=>t.clientId===e);return n===-1?i:this._renderAttachedTextCard(this._attachedTexts[n],n)})}
1215
+ </div>
1216
+ `}_renderToolsRow(){let e=this._attachedTexts.length>0;return s`
1217
+ <div class="compose-tools-row">
1218
+ <button
1219
+ type="button"
1220
+ class=${w({"compose-tool-btn":!0,"compose-tool-btn-add":this._attachments.length>0})}
1221
+ title=${this._attachments.length>0?``:this.labels.media}
1222
+ @click=${()=>this._openFilePicker()}
1223
+ >
1224
+ ${kr(Or.media)}
1225
+ ${this._attachments.length>0?s`<span class="compose-tool-label"
1226
+ >${this.labels.addMore}</span
1227
+ >`:i}
1228
+ </button>
1229
+
1230
+ <button
1231
+ type="button"
1232
+ class=${w({"compose-tool-btn":!0,"compose-tool-btn-add":e})}
1233
+ title=${e?``:this.labels.attachedText}
1234
+ @click=${()=>this._openAttachedText()}
1235
+ >
1236
+ ${kr(Or.attachedText)}
1237
+ ${e?s`<span class="compose-tool-label"
1238
+ >${this.labels.addMore}</span
1239
+ >`:i}
1240
+ </button>
1241
+
1242
+ <button
1243
+ type="button"
1244
+ class=${w({"compose-tool-btn":!0,"compose-emoji-btn":!0,"compose-tool-btn-active":this._showEmojiPicker})}
1245
+ title=${this.labels.emoji}
1246
+ @click=${()=>this._toggleEmojiPicker()}
1247
+ >
1248
+ ${kr(Or.emoji)}
1249
+ </button>
1250
+
1251
+ <div class="compose-tool-sep"></div>
1252
+
1253
+ <button
1254
+ type="button"
1255
+ class=${w({"compose-tool-btn":!0,"compose-tool-btn-active":this._showRating})}
1256
+ title=${this.labels.rate}
1257
+ @click=${()=>{this._showRating=!this._showRating}}
1258
+ >
1259
+ ${kr(Or.rate)}
1260
+ </button>
1261
+
1262
+ ${this.format===`note`?s`
1263
+ <button
1264
+ type="button"
1265
+ class=${w({"compose-tool-btn":!0,"compose-tool-btn-active":this._showTitle})}
1266
+ title=${this.labels.title}
1267
+ @click=${()=>{let e=!this._showTitle;this._showTitle=e,e&&this.updateComplete.then(()=>{this.querySelector(`.compose-note-title`)?.focus()})}}
1268
+ >
1269
+ ${kr(Or.title)}
1270
+ </button>
1271
+ `:i}
1272
+ ${this.format===`note`?s`
1273
+ <div class="compose-tool-view-group">
1274
+ <button
1275
+ type="button"
1276
+ class="compose-tool-btn compose-tool-btn-view"
1277
+ title=${this.labels.fullscreen}
1278
+ aria-label=${this.labels.fullscreen}
1279
+ @click=${()=>this.openFullscreen()}
1280
+ >
1281
+ ${kr(Or.fullscreen)}
1282
+ </button>
1283
+ </div>
1284
+ `:i}
1285
+ </div>
1286
+ `}openFullscreen(){if(this.format!==`note`)return;let e=this.getEditorState();this.dispatchEvent(new CustomEvent(`jant:fullscreen-open`,{bubbles:!0,detail:{...e,labels:this.labels}}))}render(){return s`
1287
+ <section class="compose-body">
1288
+ ${this.format===`note`?this._renderNoteFields():this.format===`link`?this._renderLinkFields():this._renderQuoteFields()}
1289
+ ${this._renderAttachments()} ${this._renderStarRating()}
1290
+ </section>
1291
+ ${this._renderToolsRow()}
1292
+ `}};customElements.define(`jant-compose-editor`,Ar);var jr=`.tiptap-slash-menu, .tiptap-link-input`,Mr=class extends o{static properties={labels:{type:Object},_open:{state:!0},_title:{state:!0},_showTitle:{state:!0},_replyContext:{state:!0},_replyExpanded:{state:!0}};_editor=null;_content=null;_fileInput=null;createRenderRoot(){return this}constructor(){super(),this.labels={},this._open=!1,this._title=``,this._showTitle=!1,this._replyContext=null,this._replyExpanded=!1}connectedCallback(){super.connectedCallback(),document.addEventListener(`jant:fullscreen-open`,this._onOpen),document.addEventListener(`jant:slash-image`,this._onSlashImage),document.addEventListener(`keydown`,this._onDocumentKeydown,!0)}disconnectedCallback(){super.disconnectedCallback(),document.removeEventListener(`jant:fullscreen-open`,this._onOpen),document.removeEventListener(`jant:slash-image`,this._onSlashImage),document.removeEventListener(`keydown`,this._onDocumentKeydown,!0),this._fileInput?.remove(),this._destroyEditor()}_onSlashImage=()=>{!this._open||!this._editor||this._triggerImagePicker()};_triggerImagePicker(){this._fileInput||(this._fileInput=document.createElement(`input`),this._fileInput.type=`file`,this._fileInput.accept=`image/*`,this._fileInput.style.display=`none`,this._fileInput.addEventListener(`change`,()=>{let e=this._fileInput?.files?.[0];e&&this._editor&&this._uploadAndInsertImage(e),this._fileInput&&(this._fileInput.value=``)}),document.body.appendChild(this._fileInput)),this._fileInput.click()}_uploadAndInsertImage(e){let t=this._editor;t&&S(t,e)}_onOpen=e=>{this._content=e.detail.json,this._title=e.detail.title,e.detail.labels&&(this.labels=e.detail.labels),this._showTitle=e.detail.showTitle||e.detail.title.trim().length>0,this._replyContext=e.detail.replyContext??null,this._replyExpanded=e.detail.replyContext?.expanded??!1,this._open=!0,this.updateComplete.then(()=>{let e=this.querySelector(`.compose-fullscreen-dialog`);e&&!e.open&&e.showModal(),this._initEditor()})};_initEditor(){let e=this.querySelector(`.compose-fullscreen .compose-tiptap-body`);!e||this._editor||(this._editor=y({element:e,placeholder:this.labels.bodyPlaceholder??`Write something…`,content:this._content,toolbarMode:`compose`,onUpdate:e=>{this._content=e},pasteMedia:{shouldInsertInline:e=>e.type.startsWith(`image/`)}}),this._editor.commands.focus(`end`))}_destroyEditor(){this._editor?.destroy(),this._editor=null}_onDialogCancel=e=>{e.preventDefault(),this._close()};_onDocumentKeydown=e=>{!this._open||e.key!==`Escape`||this._hasActiveEscapeOverlay()||(e.preventDefault(),e.stopPropagation(),this._close())};_hasActiveEscapeOverlay(){let e=this.querySelector(`.compose-fullscreen-dialog[open]`);return e?Array.from(e.querySelectorAll(jr)).some(e=>getComputedStyle(e).display!==`none`):!1}_close(){let e=this._editor?.getJSON()??this._content;this._destroyEditor(),this.querySelector(`.compose-fullscreen-dialog`)?.close(),this._open=!1,this._replyContext=null,document.dispatchEvent(new CustomEvent(`jant:fullscreen-close`,{bubbles:!0,detail:{json:e,title:this._title,showTitle:this._showTitle||this._title.trim().length>0,replyExpanded:this._replyExpanded}}))}_revealTitle(){this._showTitle=!0,this.updateComplete.then(()=>{this.querySelector(`.compose-fullscreen-title`)?.focus()})}_renderTitleField(e){let t=w({"compose-fullscreen-title":!0,"compose-fullscreen-title-reply":e===`reply`}),n=w({"compose-fullscreen-title-placeholder":!0,"compose-fullscreen-title-placeholder-reply":e===`reply`});return this._showTitle?s`
1293
+ <div class="compose-fullscreen-title-shell">
1294
+ <input
1295
+ type="text"
1296
+ .value=${this._title}
1297
+ @input=${e=>{this._title=e.target.value}}
1298
+ @keydown=${e=>{e.key===`Enter`&&(e.preventDefault(),this._editor?.commands.focus(`start`))}}
1299
+ class=${t}
1300
+ placeholder=${this.labels.titlePlaceholder??`Title`}
1301
+ />
1302
+ </div>
1303
+ `:s`
1304
+ <button
1305
+ type="button"
1306
+ class=${n}
1307
+ @click=${()=>this._revealTitle()}
1308
+ >
1309
+ ${e===`reply`?this.labels.titlePlaceholder||this.labels.title||`Title`:this.labels.title||`Title`}
1310
+ </button>
1311
+ `}render(){if(!this._open)return i;let e=this._replyContext,t=e=>s`
1312
+ <div
1313
+ class=${w({"compose-fullscreen-editor-surface":!0,"compose-fullscreen-editor-surface-reply":e===`reply`})}
1314
+ >
1315
+ ${this._renderTitleField(e)}
1316
+ <div class="compose-tiptap-body"></div>
1317
+ </div>
1318
+ `;return s`
1319
+ <dialog
1320
+ class="compose-fullscreen-dialog"
1321
+ aria-label=${this.labels.fullscreen||this.labels.note||`Fullscreen`}
1322
+ @cancel=${this._onDialogCancel}
1323
+ >
1324
+ <div class="compose-fullscreen">
1325
+ <header class="compose-fullscreen-toolbar">
1326
+ <div class="compose-fullscreen-toolbar-inner">
1327
+ <button
1328
+ type="button"
1329
+ class="compose-fullscreen-done"
1330
+ @click=${()=>this._close()}
1331
+ >
1332
+ ${this.labels.done||`Done`}
1333
+ </button>
1334
+ </div>
1335
+ </header>
1336
+ <div class="compose-fullscreen-content">
1337
+ <div class="compose-fullscreen-inner">
1338
+ ${e?s`
1339
+ <div
1340
+ class="compose-thread-layout compose-fullscreen-thread-layout"
1341
+ >
1342
+ <div class="compose-reply-row">
1343
+ <div class="compose-thread-dot"></div>
1344
+ <div
1345
+ class=${w({"compose-reply-context":!0,expanded:this._replyExpanded})}
1346
+ >
1347
+ <div class="compose-reply-context-body">
1348
+ ${ne(e.contentHtml)}
1349
+ </div>
1350
+ ${this._replyExpanded?i:s`<div class="compose-reply-fade"></div>`}
1351
+ </div>
1352
+ </div>
1353
+ <div class="compose-reply-meta">
1354
+ ${e.dateText?s`<span>${e.dateText}</span
1355
+ ><span>·</span>`:i}
1356
+ <button
1357
+ type="button"
1358
+ class="compose-reply-toggle"
1359
+ @click=${()=>{this._replyExpanded=!this._replyExpanded}}
1360
+ >
1361
+ ${this._replyExpanded?this.labels.showLess:this.labels.showMore}
1362
+ </button>
1363
+ </div>
1364
+ <div
1365
+ class="compose-editor-row compose-fullscreen-editor-row"
1366
+ >
1367
+ <div class="compose-thread-dot"></div>
1368
+ ${t(`reply`)}
1369
+ </div>
1370
+ </div>
1371
+ `:t(`note`)}
1372
+ </div>
1373
+ </div>
1374
+ </div>
1375
+ </dialog>
1376
+ `}};customElements.define(`jant-compose-fullscreen`,Mr);function I(e){if(!e)throw Error(`Assertion failed.`)}var Nr=e=>{let t=(e%360+360)%360;if(t===0||t===90||t===180||t===270)return t;throw Error(`Invalid rotation ${e}.`)},L=e=>e&&e[e.length-1],Pr=e=>e>=0&&e<2**32,R=e=>{let t=0;for(;e.readBits(1)===0&&t<32;)t++;if(t>=32)throw Error(`Invalid exponential-Golomb code.`);return(1<<t)-1+e.readBits(t)},Fr=e=>{let t=R(e);return t&1?t+1>>1:-(t>>1)},Ir=e=>e.constructor===Uint8Array?e:ArrayBuffer.isView(e)?new Uint8Array(e.buffer,e.byteOffset,e.byteLength):new Uint8Array(e),z=e=>e.constructor===DataView?e:ArrayBuffer.isView(e)?new DataView(e.buffer,e.byteOffset,e.byteLength):new DataView(e),Lr=new TextDecoder,Rr=new TextEncoder,zr=e=>Object.fromEntries(Object.entries(e).map(([e,t])=>[t,e])),Br={bt709:1,bt470bg:5,smpte170m:6,bt2020:9,smpte432:12},Vr=zr(Br),Hr={bt709:1,smpte170m:6,linear:8,"iec61966-2-1":13,pq:16,hlg:18},Ur=zr(Hr),Wr={rgb:0,bt709:1,bt470bg:5,smpte170m:6,"bt2020-ncl":9},Gr=zr(Wr),Kr=e=>!!e&&!!e.primaries&&!!e.transfer&&!!e.matrix&&e.fullRange!==void 0,qr=e=>e instanceof ArrayBuffer||typeof SharedArrayBuffer<`u`&&e instanceof SharedArrayBuffer||ArrayBuffer.isView(e),Jr=class{constructor(){this.currentPromise=Promise.resolve(),this.pending=0}async acquire(){let e,t=new Promise(t=>{let n=!1;e=()=>{n||=(t(),this.pending--,!0)}}),n=this.currentPromise;return this.currentPromise=t,this.pending++,await n,e}},Yr=e=>[...e].map(e=>e.toString(16).padStart(2,`0`)).join(``),Xr=e=>(e=e>>1&1431655765|(e&1431655765)<<1,e=e>>2&858993459|(e&858993459)<<2,e=e>>4&252645135|(e&252645135)<<4,e=e>>8&16711935|(e&16711935)<<8,e=e>>16&65535|(e&65535)<<16,e>>>0),Zr=(e,t,n)=>{let r=0,i=e.length-1,a=-1;for(;r<=i;){let o=r+i>>1,s=n(e[o]);s===t?(a=o,i=o-1):s<t?r=o+1:i=o-1}return a},B=(e,t,n)=>{let r=0,i=e.length-1,a=-1;for(;r<=i;){let o=r+(i-r+1)/2|0;n(e[o])<=t?(a=o,r=o+1):i=o-1}return a},Qr=(e,t,n)=>{let r=B(e,n(t),n);e.splice(r+1,0,t)},$r=()=>{let e,t;return{promise:new Promise((n,r)=>{e=n,t=r}),resolve:e,reject:t}},ei=(e,t)=>{for(let n=e.length-1;n>=0;n--)if(t(e[n]))return e[n]},ti=(e,t)=>{for(let n=e.length-1;n>=0;n--)if(t(e[n]))return n;return-1},ni=async function*(e){Symbol.iterator in e?yield*e[Symbol.iterator]():yield*e[Symbol.asyncIterator]()},ri=e=>{if(!(Symbol.iterator in e)&&!(Symbol.asyncIterator in e))throw TypeError(`Argument must be an iterable or async iterable.`)},ii=e=>{throw Error(`Unexpected value: ${e}`)},ai=(e,t,n)=>{let r=e.getUint8(t),i=e.getUint8(t+1),a=e.getUint8(t+2);return n?r|i<<8|a<<16:r<<16|i<<8|a},oi=(e,t,n)=>ai(e,t,n)<<8>>8,si=(e,t,n,r)=>{n>>>=0,n&=16777215,r?(e.setUint8(t,n&255),e.setUint8(t+1,n>>>8&255),e.setUint8(t+2,n>>>16&255)):(e.setUint8(t,n>>>16&255),e.setUint8(t+1,n>>>8&255),e.setUint8(t+2,n&255))},ci=(e,t,n,r)=>{n=ui(n,-8388608,8388607),n<0&&(n=n+16777216&16777215),si(e,t,n,r)},li=(e,t)=>({async next(){let n=await e.next();return n.done?{value:void 0,done:!0}:{value:t(n.value),done:!1}},return(){return e.return()},throw(t){return e.throw(t)},[Symbol.asyncIterator](){return this}}),ui=(e,t,n)=>Math.max(t,Math.min(n,e)),di=e=>{let t=Math.round(e);return Math.abs(e/t-1)<10*2**-52?t:e},fi=(e,t)=>Math.round(e/t)*t,pi=(e,t)=>Math.floor(e/t)*t,mi=e=>{let t=0;for(;e;)t++,e>>=1;return t},hi=/^[a-z]{3}$/,gi=e=>hi.test(e),_i=1e6*(1+2**-52),vi=(e,t)=>{let n=e<0?-1:1;e=Math.abs(e);let r=0,i=1,a=1,o=0,s=e;for(;;){let e=Math.floor(s),c=e*a+r,l=e*o+i;if(l>t)return{numerator:n*a,denominator:o};if(r=a,i=o,a=c,o=l,s=1/(s-e),!isFinite(s))break}return{numerator:n*a,denominator:o}},yi=class{constructor(){this.currentPromise=Promise.resolve()}call(e){return this.currentPromise=this.currentPromise.then(e)}},bi=null,xi=()=>bi===null?bi=!!(typeof navigator<`u`&&(navigator.vendor?.match(/apple/i)||/AppleWebKit/.test(navigator.userAgent)&&!/Chrome/.test(navigator.userAgent)||/\b(iPad|iPhone|iPod)\b/.test(navigator.userAgent))):bi,Si=null,Ci=()=>Si===null?Si=typeof navigator<`u`&&navigator.userAgent?.includes(`Firefox`):Si,wi=null,Ti=()=>wi===null?wi=!!(typeof navigator<`u`&&(navigator.vendor?.includes(`Google Inc`)||/Chrome/.test(navigator.userAgent))):wi,Ei=null,Di=()=>{if(Ei!==null)return Ei;if(typeof navigator>`u`)return null;let e=/\bChrome\/(\d+)/.exec(navigator.userAgent);return e?Ei=Number(e[1]):null},Oi=(e,t)=>e===-1?t:e,ki=(e,t,n,r)=>e<=r&&n<=t,Ai=function*(e){for(let t in e){let n=e[t];n!==void 0&&(yield{key:t,value:n})}},ji=e=>{let t=atob(e),n=new Uint8Array(t.length);for(let e=0;e<t.length;e++)n[e]=t.charCodeAt(e);return n},Mi=()=>{Symbol.dispose??=Symbol(`Symbol.dispose`)},Ni=e=>typeof e==`number`&&!Number.isNaN(e),Pi=e=>{I(e.den!==0);let t=Math.abs(e.num),n=Math.abs(e.den);for(;n!==0;){let e=t%n;t=n,n=e}let r=t||1;return{num:e.num/r,den:e.den/r}},Fi=(e,t)=>{if(typeof e!=`object`||!e)throw TypeError(`${t} must be an object.`);if(!Number.isInteger(e.left)||e.left<0)throw TypeError(`${t}.left must be a non-negative integer.`);if(!Number.isInteger(e.top)||e.top<0)throw TypeError(`${t}.top must be a non-negative integer.`);if(!Number.isInteger(e.width)||e.width<0)throw TypeError(`${t}.width must be a non-negative integer.`);if(!Number.isInteger(e.height)||e.height<0)throw TypeError(`${t}.height must be a non-negative integer.`)},Ii=class{constructor(e,t){if(this.data=e,this.mimeType=t,!(e instanceof Uint8Array))throw TypeError(`data must be a Uint8Array.`);if(typeof t!=`string`)throw TypeError(`mimeType must be a string.`)}},Li=class{constructor(e,t,n,r){if(this.data=e,this.mimeType=t,this.name=n,this.description=r,!(e instanceof Uint8Array))throw TypeError(`data must be a Uint8Array.`);if(t!==void 0&&typeof t!=`string`)throw TypeError(`mimeType, when provided, must be a string.`);if(n!==void 0&&typeof n!=`string`)throw TypeError(`name, when provided, must be a string.`);if(r!==void 0&&typeof r!=`string`)throw TypeError(`description, when provided, must be a string.`)}},Ri=e=>{if(!e||typeof e!=`object`)throw TypeError(`tags must be an object.`);if(e.title!==void 0&&typeof e.title!=`string`)throw TypeError(`tags.title, when provided, must be a string.`);if(e.description!==void 0&&typeof e.description!=`string`)throw TypeError(`tags.description, when provided, must be a string.`);if(e.artist!==void 0&&typeof e.artist!=`string`)throw TypeError(`tags.artist, when provided, must be a string.`);if(e.album!==void 0&&typeof e.album!=`string`)throw TypeError(`tags.album, when provided, must be a string.`);if(e.albumArtist!==void 0&&typeof e.albumArtist!=`string`)throw TypeError(`tags.albumArtist, when provided, must be a string.`);if(e.trackNumber!==void 0&&(!Number.isInteger(e.trackNumber)||e.trackNumber<=0))throw TypeError(`tags.trackNumber, when provided, must be a positive integer.`);if(e.tracksTotal!==void 0&&(!Number.isInteger(e.tracksTotal)||e.tracksTotal<=0))throw TypeError(`tags.tracksTotal, when provided, must be a positive integer.`);if(e.discNumber!==void 0&&(!Number.isInteger(e.discNumber)||e.discNumber<=0))throw TypeError(`tags.discNumber, when provided, must be a positive integer.`);if(e.discsTotal!==void 0&&(!Number.isInteger(e.discsTotal)||e.discsTotal<=0))throw TypeError(`tags.discsTotal, when provided, must be a positive integer.`);if(e.genre!==void 0&&typeof e.genre!=`string`)throw TypeError(`tags.genre, when provided, must be a string.`);if(e.date!==void 0&&(!(e.date instanceof Date)||Number.isNaN(e.date.getTime())))throw TypeError(`tags.date, when provided, must be a valid Date.`);if(e.lyrics!==void 0&&typeof e.lyrics!=`string`)throw TypeError(`tags.lyrics, when provided, must be a string.`);if(e.images!==void 0){if(!Array.isArray(e.images))throw TypeError(`tags.images, when provided, must be an array.`);for(let t of e.images){if(!t||typeof t!=`object`)throw TypeError(`Each image in tags.images must be an object.`);if(!(t.data instanceof Uint8Array))throw TypeError(`Each image.data must be a Uint8Array.`);if(typeof t.mimeType!=`string`)throw TypeError(`Each image.mimeType must be a string.`);if(![`coverFront`,`coverBack`,`unknown`].includes(t.kind))throw TypeError(`Each image.kind must be 'coverFront', 'coverBack', or 'unknown'.`)}}if(e.comment!==void 0&&typeof e.comment!=`string`)throw TypeError(`tags.comment, when provided, must be a string.`);if(e.raw!==void 0){if(!e.raw||typeof e.raw!=`object`)throw TypeError(`tags.raw, when provided, must be an object.`);for(let t of Object.values(e.raw))if(t!==null&&typeof t!=`string`&&!(t instanceof Uint8Array)&&!(t instanceof Ii)&&!(t instanceof Li))throw TypeError(`Each value in tags.raw must be a string, Uint8Array, RichImageData, AttachedFile, or null.`)}},zi={default:!0,forced:!1,original:!1,commentary:!1,hearingImpaired:!1,visuallyImpaired:!1},Bi=e=>{if(!e||typeof e!=`object`)throw TypeError(`disposition must be an object.`);if(e.default!==void 0&&typeof e.default!=`boolean`)throw TypeError(`disposition.default must be a boolean.`);if(e.forced!==void 0&&typeof e.forced!=`boolean`)throw TypeError(`disposition.forced must be a boolean.`);if(e.original!==void 0&&typeof e.original!=`boolean`)throw TypeError(`disposition.original must be a boolean.`);if(e.commentary!==void 0&&typeof e.commentary!=`boolean`)throw TypeError(`disposition.commentary must be a boolean.`);if(e.hearingImpaired!==void 0&&typeof e.hearingImpaired!=`boolean`)throw TypeError(`disposition.hearingImpaired must be a boolean.`);if(e.visuallyImpaired!==void 0&&typeof e.visuallyImpaired!=`boolean`)throw TypeError(`disposition.visuallyImpaired must be a boolean.`)},V=class e{constructor(e){this.bytes=e,this.pos=0}seekToByte(e){this.pos=8*e}readBit(){let e=Math.floor(this.pos/8),t=this.bytes[e]??0,n=7-(this.pos&7),r=(t&1<<n)>>n;return this.pos++,r}readBits(e){if(e===1)return this.readBit();let t=0;for(let n=0;n<e;n++)t<<=1,t|=this.readBit();return t}writeBits(e,t){let n=this.pos+e;for(let e=this.pos;e<n;e++){let r=Math.floor(e/8),i=this.bytes[r],a=7-(e&7);i&=~(1<<a),i|=(t&1<<n-e-1)>>n-e-1<<a,this.bytes[r]=i}this.pos=n}readAlignedByte(){if(this.pos%8!=0)throw Error(`Bitstream is not byte-aligned.`);let e=this.pos/8,t=this.bytes[e]??0;return this.pos+=8,t}skipBits(e){this.pos+=e}getBitsLeft(){return this.bytes.length*8-this.pos}clone(){let t=new e(this.bytes);return t.pos=this.pos,t}},Vi=[96e3,88200,64e3,48e3,44100,32e3,24e3,22050,16e3,12e3,11025,8e3,7350],Hi=[-1,1,2,3,4,5,6,8],Ui=e=>{if(!e||e.byteLength<2)throw TypeError(`AAC description must be at least 2 bytes long.`);let t=new V(e),n=t.readBits(5);n===31&&(n=32+t.readBits(6));let r=t.readBits(4),i=null;r===15?i=t.readBits(24):r<Vi.length&&(i=Vi[r]);let a=t.readBits(4),o=null;return a>=1&&a<=7&&(o=Hi[a]),{objectType:n,frequencyIndex:r,sampleRate:i,channelConfiguration:a,numberOfChannels:o}},Wi=e=>{let t=Vi.indexOf(e.sampleRate),n=null;t===-1&&(t=15,n=e.sampleRate);let r=Hi.indexOf(e.numberOfChannels);if(r===-1)throw TypeError(`Unsupported number of channels: ${e.numberOfChannels}`);let i=13;e.objectType>=32&&(i+=6),t===15&&(i+=24);let a=Math.ceil(i/8),o=new Uint8Array(a),s=new V(o);return e.objectType<32?s.writeBits(5,e.objectType):(s.writeBits(5,31),s.writeBits(6,e.objectType-32)),s.writeBits(4,t),t===15&&s.writeBits(24,n),s.writeBits(4,r),o},Gi=[`avc`,`hevc`,`vp9`,`av1`,`vp8`],Ki=[`pcm-s16`,`pcm-s16be`,`pcm-s24`,`pcm-s24be`,`pcm-s32`,`pcm-s32be`,`pcm-f32`,`pcm-f32be`,`pcm-f64`,`pcm-f64be`,`pcm-u8`,`pcm-s8`,`ulaw`,`alaw`],qi=[`aac`,`opus`,`mp3`,`vorbis`,`flac`,`ac3`,`eac3`],Ji=[...qi,...Ki],Yi=[`webvtt`],Xi=[{maxMacroblocks:99,maxBitrate:64e3,maxDpbMbs:396,level:10},{maxMacroblocks:396,maxBitrate:192e3,maxDpbMbs:900,level:11},{maxMacroblocks:396,maxBitrate:384e3,maxDpbMbs:2376,level:12},{maxMacroblocks:396,maxBitrate:768e3,maxDpbMbs:2376,level:13},{maxMacroblocks:396,maxBitrate:2e6,maxDpbMbs:2376,level:20},{maxMacroblocks:792,maxBitrate:4e6,maxDpbMbs:4752,level:21},{maxMacroblocks:1620,maxBitrate:4e6,maxDpbMbs:8100,level:22},{maxMacroblocks:1620,maxBitrate:1e7,maxDpbMbs:8100,level:30},{maxMacroblocks:3600,maxBitrate:14e6,maxDpbMbs:18e3,level:31},{maxMacroblocks:5120,maxBitrate:2e7,maxDpbMbs:20480,level:32},{maxMacroblocks:8192,maxBitrate:2e7,maxDpbMbs:32768,level:40},{maxMacroblocks:8192,maxBitrate:5e7,maxDpbMbs:32768,level:41},{maxMacroblocks:8704,maxBitrate:5e7,maxDpbMbs:34816,level:42},{maxMacroblocks:22080,maxBitrate:135e6,maxDpbMbs:110400,level:50},{maxMacroblocks:36864,maxBitrate:24e7,maxDpbMbs:184320,level:51},{maxMacroblocks:36864,maxBitrate:24e7,maxDpbMbs:184320,level:52},{maxMacroblocks:139264,maxBitrate:24e7,maxDpbMbs:696320,level:60},{maxMacroblocks:139264,maxBitrate:48e7,maxDpbMbs:696320,level:61},{maxMacroblocks:139264,maxBitrate:8e8,maxDpbMbs:696320,level:62}],Zi=[{maxPictureSize:36864,maxBitrate:128e3,tier:`L`,level:30},{maxPictureSize:122880,maxBitrate:15e5,tier:`L`,level:60},{maxPictureSize:245760,maxBitrate:3e6,tier:`L`,level:63},{maxPictureSize:552960,maxBitrate:6e6,tier:`L`,level:90},{maxPictureSize:983040,maxBitrate:1e7,tier:`L`,level:93},{maxPictureSize:2228224,maxBitrate:12e6,tier:`L`,level:120},{maxPictureSize:2228224,maxBitrate:3e7,tier:`H`,level:120},{maxPictureSize:2228224,maxBitrate:2e7,tier:`L`,level:123},{maxPictureSize:2228224,maxBitrate:5e7,tier:`H`,level:123},{maxPictureSize:8912896,maxBitrate:25e6,tier:`L`,level:150},{maxPictureSize:8912896,maxBitrate:1e8,tier:`H`,level:150},{maxPictureSize:8912896,maxBitrate:4e7,tier:`L`,level:153},{maxPictureSize:8912896,maxBitrate:16e7,tier:`H`,level:153},{maxPictureSize:8912896,maxBitrate:6e7,tier:`L`,level:156},{maxPictureSize:8912896,maxBitrate:24e7,tier:`H`,level:156},{maxPictureSize:35651584,maxBitrate:6e7,tier:`L`,level:180},{maxPictureSize:35651584,maxBitrate:24e7,tier:`H`,level:180},{maxPictureSize:35651584,maxBitrate:12e7,tier:`L`,level:183},{maxPictureSize:35651584,maxBitrate:48e7,tier:`H`,level:183},{maxPictureSize:35651584,maxBitrate:24e7,tier:`L`,level:186},{maxPictureSize:35651584,maxBitrate:8e8,tier:`H`,level:186}],Qi=[{maxPictureSize:36864,maxBitrate:2e5,level:10},{maxPictureSize:73728,maxBitrate:8e5,level:11},{maxPictureSize:122880,maxBitrate:18e5,level:20},{maxPictureSize:245760,maxBitrate:36e5,level:21},{maxPictureSize:552960,maxBitrate:72e5,level:30},{maxPictureSize:983040,maxBitrate:12e6,level:31},{maxPictureSize:2228224,maxBitrate:18e6,level:40},{maxPictureSize:2228224,maxBitrate:3e7,level:41},{maxPictureSize:8912896,maxBitrate:6e7,level:50},{maxPictureSize:8912896,maxBitrate:12e7,level:51},{maxPictureSize:8912896,maxBitrate:18e7,level:52},{maxPictureSize:35651584,maxBitrate:18e7,level:60},{maxPictureSize:35651584,maxBitrate:24e7,level:61},{maxPictureSize:35651584,maxBitrate:48e7,level:62}],$i=[{maxPictureSize:147456,maxBitrate:15e5,tier:`M`,level:0},{maxPictureSize:278784,maxBitrate:3e6,tier:`M`,level:1},{maxPictureSize:665856,maxBitrate:6e6,tier:`M`,level:4},{maxPictureSize:1065024,maxBitrate:1e7,tier:`M`,level:5},{maxPictureSize:2359296,maxBitrate:12e6,tier:`M`,level:8},{maxPictureSize:2359296,maxBitrate:3e7,tier:`H`,level:8},{maxPictureSize:2359296,maxBitrate:2e7,tier:`M`,level:9},{maxPictureSize:2359296,maxBitrate:5e7,tier:`H`,level:9},{maxPictureSize:8912896,maxBitrate:3e7,tier:`M`,level:12},{maxPictureSize:8912896,maxBitrate:1e8,tier:`H`,level:12},{maxPictureSize:8912896,maxBitrate:4e7,tier:`M`,level:13},{maxPictureSize:8912896,maxBitrate:16e7,tier:`H`,level:13},{maxPictureSize:8912896,maxBitrate:6e7,tier:`M`,level:14},{maxPictureSize:8912896,maxBitrate:24e7,tier:`H`,level:14},{maxPictureSize:35651584,maxBitrate:6e7,tier:`M`,level:15},{maxPictureSize:35651584,maxBitrate:24e7,tier:`H`,level:15},{maxPictureSize:35651584,maxBitrate:6e7,tier:`M`,level:16},{maxPictureSize:35651584,maxBitrate:24e7,tier:`H`,level:16},{maxPictureSize:35651584,maxBitrate:1e8,tier:`M`,level:17},{maxPictureSize:35651584,maxBitrate:48e7,tier:`H`,level:17},{maxPictureSize:35651584,maxBitrate:16e7,tier:`M`,level:18},{maxPictureSize:35651584,maxBitrate:8e8,tier:`H`,level:18},{maxPictureSize:35651584,maxBitrate:16e7,tier:`M`,level:19},{maxPictureSize:35651584,maxBitrate:8e8,tier:`H`,level:19}],ea=`.01.01.01.01.00`,ta=`.0.110.01.01.01.0`,na=(e,t,n,r)=>{if(e===`avc`){let e=Math.ceil(t/16)*Math.ceil(n/16),i=Xi.find(t=>e<=t.maxMacroblocks&&r<=t.maxBitrate)??L(Xi),a=i?i.level:0;return`avc1.${`64`.padStart(2,`0`)}00${a.toString(16).padStart(2,`0`)}`}else if(e===`hevc`){let e=t*n,i=Zi.find(t=>e<=t.maxPictureSize&&r<=t.maxBitrate)??L(Zi);return`hev1.1.6.${i.tier}${i.level}.B0`}else if(e===`vp8`)return`vp8`;else if(e===`vp9`){let e=t*n;return`vp09.00.${(Qi.find(t=>e<=t.maxPictureSize&&r<=t.maxBitrate)??L(Qi)).level.toString().padStart(2,`0`)}.08`}else if(e===`av1`){let e=t*n,i=$i.find(t=>e<=t.maxPictureSize&&r<=t.maxBitrate)??L($i);return`av01.0.${i.level.toString().padStart(2,`0`)}${i.tier}.08`}throw TypeError(`Unhandled codec '${e}'.`)},ra=e=>{let t=e.split(`.`),n=Number(t[1]),r=t[2],i=Number(r.slice(0,-1)),a=(n<<5)+i,o=r.slice(-1)===`H`?1:0,s=Number(t[3])===8?0:1,c=t[4]?Number(t[4]):0,l=t[5]?Number(t[5][0]):1,u=t[5]?Number(t[5][1]):1,d=t[5]?Number(t[5][2]):0;return[129,a,(o<<7)+(s<<6)+0+(c<<4)+(l<<3)+(u<<2)+d,0]},ia=e=>{let{codec:t,codecDescription:n,colorSpace:r,avcCodecInfo:i,hevcCodecInfo:a,vp9CodecInfo:o,av1CodecInfo:s}=e;if(t===`avc`){if(I(e.avcType!==null),i){let t=new Uint8Array([i.avcProfileIndication,i.profileCompatibility,i.avcLevelIndication]);return`avc${e.avcType}.${Yr(t)}`}if(!n||n.byteLength<4)throw TypeError(`AVC decoder description is not provided or is not at least 4 bytes long.`);return`avc${e.avcType}.${Yr(n.subarray(1,4))}`}else if(t===`hevc`){let e,t,r,i,o,s;if(a)e=a.generalProfileSpace,t=a.generalProfileIdc,r=Xr(a.generalProfileCompatibilityFlags),i=a.generalTierFlag,o=a.generalLevelIdc,s=[...a.generalConstraintIndicatorFlags];else{if(!n||n.byteLength<23)throw TypeError(`HEVC decoder description is not provided or is not at least 23 bytes long.`);let a=z(n),c=a.getUint8(1);e=c>>6&3,t=c&31,r=Xr(a.getUint32(2)),i=c>>5&1,o=a.getUint8(12),s=[];for(let e=0;e<6;e++)s.push(a.getUint8(6+e))}let c=`hev1.`;for(c+=[``,`A`,`B`,`C`][e]+t,c+=`.`,c+=r.toString(16).toUpperCase(),c+=`.`,c+=i===0?`L`:`H`,c+=o;s.length>0&&s[s.length-1]===0;)s.pop();return s.length>0&&(c+=`.`,c+=s.map(e=>e.toString(16).toUpperCase()).join(`.`)),c}else if(t===`vp8`)return`vp8`;else if(t===`vp9`){if(!o){let t=e.width*e.height,n=L(Qi).level;for(let e of Qi)if(t<=e.maxPictureSize){n=e.level;break}return`vp09.00.${n.toString().padStart(2,`0`)}.08`}let t=o.profile.toString().padStart(2,`0`),n=o.level.toString().padStart(2,`0`),r=o.bitDepth.toString().padStart(2,`0`),i=o.chromaSubsampling.toString().padStart(2,`0`),a=o.colourPrimaries.toString().padStart(2,`0`),s=o.transferCharacteristics.toString().padStart(2,`0`),c=o.matrixCoefficients.toString().padStart(2,`0`),l=o.videoFullRangeFlag.toString().padStart(2,`0`),u=`vp09.${t}.${n}.${r}.${i}`;return u+=`.${a}.${s}.${c}.${l}`,u.endsWith(ea)&&(u=u.slice(0,-15)),u}else if(t===`av1`){if(!s){let t=e.width*e.height,n=L(Qi).level;for(let e of Qi)if(t<=e.maxPictureSize){n=e.level;break}return`av01.0.${n.toString().padStart(2,`0`)}M.08`}let t=s.profile,n=s.level.toString().padStart(2,`0`),i=s.tier?`H`:`M`,a=s.bitDepth.toString().padStart(2,`0`),o=s.monochrome?`1`:`0`,c=100*s.chromaSubsamplingX+10*s.chromaSubsamplingY+1*(s.chromaSubsamplingX&&s.chromaSubsamplingY?s.chromaSamplePosition:0),l=r?.primaries?Br[r.primaries]:1,u=r?.transfer?Hr[r.transfer]:1,d=r?.matrix?Wr[r.matrix]:1,f=r?.fullRange?1:0,p=`av01.${t}.${n}${i}.${a}`;return p+=`.${o}.${c.toString().padStart(3,`0`)}`,p+=`.${l.toString().padStart(2,`0`)}`,p+=`.${u.toString().padStart(2,`0`)}`,p+=`.${d.toString().padStart(2,`0`)}`,p+=`.${f}`,p.endsWith(ta)&&(p=p.slice(0,-17)),p}throw TypeError(`Unhandled codec '${t}'.`)},aa=(e,t,n)=>{if(e===`aac`)return t>=2&&n<=24e3?`mp4a.40.29`:n<=24e3?`mp4a.40.5`:`mp4a.40.2`;if(e===`mp3`)return`mp3`;if(e===`opus`)return`opus`;if(e===`vorbis`)return`vorbis`;if(e===`flac`)return`flac`;if(e===`ac3`)return`ac-3`;if(e===`eac3`)return`ec-3`;if(Ki.includes(e))return e;throw TypeError(`Unhandled codec '${e}'.`)},oa=e=>{let{codec:t,codecDescription:n,aacCodecInfo:r}=e;if(t===`aac`){if(!r)throw TypeError(`AAC codec info must be provided.`);if(r.isMpeg2)return`mp4a.67`;{let e;return e=r.objectType===null?Ui(n).objectType:r.objectType,`mp4a.40.${e}`}}else if(t===`mp3`)return`mp3`;else if(t===`opus`)return`opus`;else if(t===`vorbis`)return`vorbis`;else if(t===`flac`)return`flac`;else if(t===`ac3`)return`ac-3`;else if(t===`eac3`)return`ec-3`;else if(t&&Ki.includes(t))return t;throw TypeError(`Unhandled codec '${t}'.`)},sa=48e3,ca=/^pcm-([usf])(\d+)+(be)?$/,la=e=>{if(I(Ki.includes(e)),e===`ulaw`)return{dataType:`ulaw`,sampleSize:1,littleEndian:!0,silentValue:255};if(e===`alaw`)return{dataType:`alaw`,sampleSize:1,littleEndian:!0,silentValue:213};let t=ca.exec(e);I(t);let n;n=t[1]===`u`?`unsigned`:t[1]===`s`?`signed`:`float`;let r=Number(t[2])/8,i=t[3]!==`be`;return{dataType:n,sampleSize:r,littleEndian:i,silentValue:e===`pcm-u8`?2**7:0}},ua=e=>e.startsWith(`avc1`)||e.startsWith(`avc3`)?`avc`:e.startsWith(`hev1`)||e.startsWith(`hvc1`)?`hevc`:e===`vp8`?`vp8`:e.startsWith(`vp09`)?`vp9`:e.startsWith(`av01`)?`av1`:e.startsWith(`mp4a.40`)||e===`mp4a.67`?`aac`:e===`mp3`||e===`mp4a.69`||e===`mp4a.6B`||e===`mp4a.6b`?`mp3`:e===`opus`?`opus`:e===`vorbis`?`vorbis`:e===`flac`?`flac`:e===`ac-3`||e===`ac3`?`ac3`:e===`ec-3`||e===`eac3`?`eac3`:e===`ulaw`?`ulaw`:e===`alaw`?`alaw`:ca.test(e)?e:e===`webvtt`?`webvtt`:null,da=e=>e===`avc`?{avc:{format:`avc`}}:e===`hevc`?{hevc:{format:`hevc`}}:{},fa=e=>e===`aac`?{aac:{format:`aac`}}:e===`opus`?{opus:{format:`opus`}}:{},pa=[`avc1`,`avc3`,`hev1`,`hvc1`,`vp8`,`vp09`,`av01`],ma=/^(avc1|avc3)\.[0-9a-fA-F]{6}$/,ha=/^(hev1|hvc1)\.(?:[ABC]?\d+)\.[0-9a-fA-F]{1,8}\.[LH]\d+(?:\.[0-9a-fA-F]{1,2}){0,6}$/,ga=/^vp09(?:\.\d{2}){3}(?:(?:\.\d{2}){5})?$/,_a=/^av01\.\d\.\d{2}[MH]\.\d{2}(?:\.\d\.\d{3}\.\d{2}\.\d{2}\.\d{2}\.\d)?$/,va=e=>{if(!e)throw TypeError(`Video chunk metadata must be provided.`);if(typeof e!=`object`)throw TypeError(`Video chunk metadata must be an object.`);if(!e.decoderConfig)throw TypeError(`Video chunk metadata must include a decoder configuration.`);if(typeof e.decoderConfig!=`object`)throw TypeError(`Video chunk metadata decoder configuration must be an object.`);if(typeof e.decoderConfig.codec!=`string`)throw TypeError(`Video chunk metadata decoder configuration must specify a codec string.`);if(!pa.some(t=>e.decoderConfig.codec.startsWith(t)))throw TypeError(`Video chunk metadata decoder configuration codec string must be a valid video codec string as specified in the Mediabunny Codec Registry.`);if(!Number.isInteger(e.decoderConfig.codedWidth)||e.decoderConfig.codedWidth<=0)throw TypeError(`Video chunk metadata decoder configuration must specify a valid codedWidth (positive integer).`);if(!Number.isInteger(e.decoderConfig.codedHeight)||e.decoderConfig.codedHeight<=0)throw TypeError(`Video chunk metadata decoder configuration must specify a valid codedHeight (positive integer).`);if(e.decoderConfig.description!==void 0&&!qr(e.decoderConfig.description))throw TypeError(`Video chunk metadata decoder configuration description, when defined, must be an ArrayBuffer or an ArrayBuffer view.`);if(e.decoderConfig.colorSpace!==void 0){let{colorSpace:t}=e.decoderConfig;if(typeof t!=`object`)throw TypeError(`Video chunk metadata decoder configuration colorSpace, when provided, must be an object.`);let n=Object.keys(Br);if(t.primaries!=null&&!n.includes(t.primaries))throw TypeError(`Video chunk metadata decoder configuration colorSpace primaries, when defined, must be one of ${n.join(`, `)}.`);let r=Object.keys(Hr);if(t.transfer!=null&&!r.includes(t.transfer))throw TypeError(`Video chunk metadata decoder configuration colorSpace transfer, when defined, must be one of ${r.join(`, `)}.`);let i=Object.keys(Wr);if(t.matrix!=null&&!i.includes(t.matrix))throw TypeError(`Video chunk metadata decoder configuration colorSpace matrix, when defined, must be one of ${i.join(`, `)}.`);if(t.fullRange!=null&&typeof t.fullRange!=`boolean`)throw TypeError(`Video chunk metadata decoder configuration colorSpace fullRange, when defined, must be a boolean.`)}if(e.decoderConfig.codec.startsWith(`avc1`)||e.decoderConfig.codec.startsWith(`avc3`)){if(!ma.test(e.decoderConfig.codec))throw TypeError(`Video chunk metadata decoder configuration codec string for AVC must be a valid AVC codec string as specified in Section 3.4 of RFC 6381.`)}else if(e.decoderConfig.codec.startsWith(`hev1`)||e.decoderConfig.codec.startsWith(`hvc1`)){if(!ha.test(e.decoderConfig.codec))throw TypeError(`Video chunk metadata decoder configuration codec string for HEVC must be a valid HEVC codec string as specified in Section E.3 of ISO 14496-15.`)}else if(e.decoderConfig.codec.startsWith(`vp8`)){if(e.decoderConfig.codec!==`vp8`)throw TypeError(`Video chunk metadata decoder configuration codec string for VP8 must be "vp8".`)}else if(e.decoderConfig.codec.startsWith(`vp09`)){if(!ga.test(e.decoderConfig.codec))throw TypeError(`Video chunk metadata decoder configuration codec string for VP9 must be a valid VP9 codec string as specified in Section "Codecs Parameter String" of https://www.webmproject.org/vp9/mp4/.`)}else if(e.decoderConfig.codec.startsWith(`av01`)&&!_a.test(e.decoderConfig.codec))throw TypeError(`Video chunk metadata decoder configuration codec string for AV1 must be a valid AV1 codec string as specified in Section "Codecs Parameter String" of https://aomediacodec.github.io/av1-isobmff/.`)},ya=[`mp4a`,`mp3`,`opus`,`vorbis`,`flac`,`ulaw`,`alaw`,`pcm`,`ac-3`,`ec-3`],ba=e=>{if(!e)throw TypeError(`Audio chunk metadata must be provided.`);if(typeof e!=`object`)throw TypeError(`Audio chunk metadata must be an object.`);if(!e.decoderConfig)throw TypeError(`Audio chunk metadata must include a decoder configuration.`);if(typeof e.decoderConfig!=`object`)throw TypeError(`Audio chunk metadata decoder configuration must be an object.`);if(typeof e.decoderConfig.codec!=`string`)throw TypeError(`Audio chunk metadata decoder configuration must specify a codec string.`);if(!ya.some(t=>e.decoderConfig.codec.startsWith(t)))throw TypeError(`Audio chunk metadata decoder configuration codec string must be a valid audio codec string as specified in the Mediabunny Codec Registry.`);if(!Number.isInteger(e.decoderConfig.sampleRate)||e.decoderConfig.sampleRate<=0)throw TypeError(`Audio chunk metadata decoder configuration must specify a valid sampleRate (positive integer).`);if(!Number.isInteger(e.decoderConfig.numberOfChannels)||e.decoderConfig.numberOfChannels<=0)throw TypeError(`Audio chunk metadata decoder configuration must specify a valid numberOfChannels (positive integer).`);if(e.decoderConfig.description!==void 0&&!qr(e.decoderConfig.description))throw TypeError(`Audio chunk metadata decoder configuration description, when defined, must be an ArrayBuffer or an ArrayBuffer view.`);if(e.decoderConfig.codec.startsWith(`mp4a`)&&e.decoderConfig.codec!==`mp4a.69`&&e.decoderConfig.codec!==`mp4a.6B`&&e.decoderConfig.codec!==`mp4a.6b`){if(![`mp4a.40.2`,`mp4a.40.02`,`mp4a.40.5`,`mp4a.40.05`,`mp4a.40.29`,`mp4a.67`].includes(e.decoderConfig.codec))throw TypeError(`Audio chunk metadata decoder configuration codec string for AAC must be a valid AAC codec string as specified in https://www.w3.org/TR/webcodecs-aac-codec-registration/.`)}else if(e.decoderConfig.codec.startsWith(`mp3`)||e.decoderConfig.codec.startsWith(`mp4a`)){if(e.decoderConfig.codec!==`mp3`&&e.decoderConfig.codec!==`mp4a.69`&&e.decoderConfig.codec!==`mp4a.6B`&&e.decoderConfig.codec!==`mp4a.6b`)throw TypeError(`Audio chunk metadata decoder configuration codec string for MP3 must be "mp3", "mp4a.69" or "mp4a.6B".`)}else if(e.decoderConfig.codec.startsWith(`opus`)){if(e.decoderConfig.codec!==`opus`)throw TypeError(`Audio chunk metadata decoder configuration codec string for Opus must be "opus".`);if(e.decoderConfig.description&&e.decoderConfig.description.byteLength<18)throw TypeError(`Audio chunk metadata decoder configuration description, when specified, is expected to be an Identification Header as specified in Section 5.1 of RFC 7845.`)}else if(e.decoderConfig.codec.startsWith(`vorbis`)){if(e.decoderConfig.codec!==`vorbis`)throw TypeError(`Audio chunk metadata decoder configuration codec string for Vorbis must be "vorbis".`);if(!e.decoderConfig.description)throw TypeError(`Audio chunk metadata decoder configuration for Vorbis must include a description, which is expected to adhere to the format described in https://www.w3.org/TR/webcodecs-vorbis-codec-registration/.`)}else if(e.decoderConfig.codec.startsWith(`flac`)){if(e.decoderConfig.codec!==`flac`)throw TypeError(`Audio chunk metadata decoder configuration codec string for FLAC must be "flac".`);if(!e.decoderConfig.description||e.decoderConfig.description.byteLength<42)throw TypeError(`Audio chunk metadata decoder configuration for FLAC must include a description, which is expected to adhere to the format described in https://www.w3.org/TR/webcodecs-flac-codec-registration/.`)}else if(e.decoderConfig.codec.startsWith(`ac-3`)||e.decoderConfig.codec.startsWith(`ac3`)){if(e.decoderConfig.codec!==`ac-3`)throw TypeError(`Audio chunk metadata decoder configuration codec string for AC-3 must be "ac-3".`)}else if(e.decoderConfig.codec.startsWith(`ec-3`)||e.decoderConfig.codec.startsWith(`eac3`)){if(e.decoderConfig.codec!==`ec-3`)throw TypeError(`Audio chunk metadata decoder configuration codec string for EC-3 must be "ec-3".`)}else if((e.decoderConfig.codec.startsWith(`pcm`)||e.decoderConfig.codec.startsWith(`ulaw`)||e.decoderConfig.codec.startsWith(`alaw`))&&!Ki.includes(e.decoderConfig.codec))throw TypeError(`Audio chunk metadata decoder configuration codec string for PCM must be one of the supported PCM codecs (${Ki.join(`, `)}).`)},xa=e=>{if(!e)throw TypeError(`Subtitle metadata must be provided.`);if(typeof e!=`object`)throw TypeError(`Subtitle metadata must be an object.`);if(!e.config)throw TypeError(`Subtitle metadata must include a config object.`);if(typeof e.config!=`object`)throw TypeError(`Subtitle metadata config must be an object.`);if(typeof e.config.description!=`string`)throw TypeError(`Subtitle metadata config description must be a string.`)},Sa=[44100,48e3,32e3],Ca=[-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,32,40,48,56,64,80,96,112,128,160,192,224,256,320,-1,-1,32,48,56,64,80,96,112,128,160,192,224,256,320,384,-1,-1,32,64,96,128,160,192,224,256,288,320,352,384,416,448,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,8,16,24,32,40,48,56,64,80,96,112,128,144,160,-1,-1,8,16,24,32,40,48,56,64,80,96,112,128,144,160,-1,-1,32,48,56,64,80,96,112,128,144,160,176,192,224,256,-1],wa=(e,t,n,r,i)=>t===0?0:t===1?Math.floor(144*n/(r<<e))+i:t===2?Math.floor(144*n/r)+i:(Math.floor(12*n/r)+i)*4,Ta=(e,t)=>e===3?t===3?21:36:t===3?13:21,Ea=(e,t)=>{let n=e>>>24,r=e>>>16&255,i=e>>>8&255,a=e&255;if(n!==255&&r!==255&&i!==255&&a!==255)return{header:null,bytesAdvanced:4};if(n!==255||(r&224)!=224)return{header:null,bytesAdvanced:1};let o=0,s=0;r&16?o=r&8?0:1:(o=1,s=1);let c=r>>3&3,l=r>>1&3,u=i>>4&15,d=(i>>2&3)%3,f=i>>1&1,p=a>>6&3,m=a>>4&3,h=a>>3&1,g=a>>2&1,_=a&3,v=Ca[o*16*4+l*16+u];if(v===-1)return{header:null,bytesAdvanced:1};let y=v*1e3,b=Sa[d]>>o+s,x=wa(o,l,y,b,f);if(t!==null&&t<x)return{header:null,bytesAdvanced:1};let S;return S=c===3?l===3?384:1152:l===3?384:l===2?1152:576,{header:{totalSize:x,mpegVersionId:c,layer:l,bitrate:y,frequencyIndex:d,sampleRate:b,channel:p,modeExtension:m,copyright:h,original:g,emphasis:_,audioSamplesInFrame:S},bytesAdvanced:1}},Da=e=>{let t=2130706432,n=0;for(;t!==0;)n>>=1,n|=e&t,t>>=8;return n},Oa=[48e3,44100,32e3],ka=[24e3,22050,16e3],Aa;(function(e){e[e.NON_IDR_SLICE=1]=`NON_IDR_SLICE`,e[e.SLICE_DPA=2]=`SLICE_DPA`,e[e.SLICE_DPB=3]=`SLICE_DPB`,e[e.SLICE_DPC=4]=`SLICE_DPC`,e[e.IDR=5]=`IDR`,e[e.SEI=6]=`SEI`,e[e.SPS=7]=`SPS`,e[e.PPS=8]=`PPS`,e[e.AUD=9]=`AUD`,e[e.SPS_EXT=13]=`SPS_EXT`})(Aa||={});var ja;(function(e){e[e.RASL_N=8]=`RASL_N`,e[e.RASL_R=9]=`RASL_R`,e[e.BLA_W_LP=16]=`BLA_W_LP`,e[e.RSV_IRAP_VCL23=23]=`RSV_IRAP_VCL23`,e[e.VPS_NUT=32]=`VPS_NUT`,e[e.SPS_NUT=33]=`SPS_NUT`,e[e.PPS_NUT=34]=`PPS_NUT`,e[e.AUD_NUT=35]=`AUD_NUT`,e[e.PREFIX_SEI_NUT=39]=`PREFIX_SEI_NUT`,e[e.SUFFIX_SEI_NUT=40]=`SUFFIX_SEI_NUT`})(ja||={});var Ma=function*(e){let t=0,n=-1;for(;t<e.length-2;){let r=e.indexOf(0,t);if(r===-1||r>=e.length-2)break;t=r;let i=0;if(t+3<e.length&&e[t+1]===0&&e[t+2]===0&&e[t+3]===1?i=4:e[t+1]===0&&e[t+2]===1&&(i=3),i===0){t++;continue}n!==-1&&t>n&&(yield{offset:n,length:t-n}),n=t+i,t=n}n!==-1&&n<e.length&&(yield{offset:n,length:e.length-n})},Na=function*(e,t){let n=0,r=new DataView(e.buffer,e.byteOffset,e.byteLength);for(;n+t<=e.length;){let e;t===1?e=r.getUint8(n):t===2?e=r.getUint16(n,!1):t===3?e=ai(r,n,!1):(I(t===4),e=r.getUint32(n,!1)),n+=t,yield{offset:n,length:e},n+=e}},Pa=(e,t)=>t.description?Na(e,(Ir(t.description)[4]&3)+1):Ma(e),Fa=e=>e&31,Ia=e=>{let t=[],n=e.length;for(let r=0;r<n;r++)r+2<n&&e[r]===0&&e[r+1]===0&&e[r+2]===3?(t.push(0,0),r+=2):t.push(e[r]);return new Uint8Array(t)},La=new Uint8Array([0,0,0,1]),Ra=e=>{let t=e.reduce((e,t)=>e+La.byteLength+t.byteLength,0),n=new Uint8Array(t),r=0;for(let t of e)n.set(La,r),r+=La.byteLength,n.set(t,r),r+=t.byteLength;return n},za=(e,t)=>{let n=e.reduce((e,n)=>e+t+n.byteLength,0),r=new Uint8Array(n),i=0;for(let n of e){let e=new DataView(r.buffer,r.byteOffset,r.byteLength);switch(t){case 1:e.setUint8(i,n.byteLength);break;case 2:e.setUint16(i,n.byteLength,!1);break;case 3:si(e,i,n.byteLength,!1);break;case 4:e.setUint32(i,n.byteLength,!1);break}i+=t,r.set(n,i),i+=n.byteLength}return r},Ba=(e,t)=>t.description?za(e,(Ir(t.description)[4]&3)+1):Ra(e),Va=e=>{try{let t=[],n=[],r=[];for(let i of Ma(e)){let a=e.subarray(i.offset,i.offset+i.length),o=Fa(a[0]);o===Aa.SPS?t.push(a):o===Aa.PPS?n.push(a):o===Aa.SPS_EXT&&r.push(a)}if(t.length===0||n.length===0)return null;let i=t[0],a=Ga(i);I(a!==null);let o=a.profileIdc===100||a.profileIdc===110||a.profileIdc===122||a.profileIdc===144;return{configurationVersion:1,avcProfileIndication:a.profileIdc,profileCompatibility:a.constraintFlags,avcLevelIndication:a.levelIdc,lengthSizeMinusOne:3,sequenceParameterSets:t,pictureParameterSets:n,chromaFormat:o?a.chromaFormatIdc:null,bitDepthLumaMinus8:o?a.bitDepthLumaMinus8:null,bitDepthChromaMinus8:o?a.bitDepthChromaMinus8:null,sequenceParameterSetExt:o?r:null}}catch(e){return console.error(`Error building AVC Decoder Configuration Record:`,e),null}},Ha=e=>{let t=[];t.push(e.configurationVersion),t.push(e.avcProfileIndication),t.push(e.profileCompatibility),t.push(e.avcLevelIndication),t.push(252|e.lengthSizeMinusOne&3),t.push(224|e.sequenceParameterSets.length&31);for(let n of e.sequenceParameterSets){let e=n.byteLength;t.push(e>>8),t.push(e&255);for(let r=0;r<e;r++)t.push(n[r])}t.push(e.pictureParameterSets.length);for(let n of e.pictureParameterSets){let e=n.byteLength;t.push(e>>8),t.push(e&255);for(let r=0;r<e;r++)t.push(n[r])}if(e.avcProfileIndication===100||e.avcProfileIndication===110||e.avcProfileIndication===122||e.avcProfileIndication===144){I(e.chromaFormat!==null),I(e.bitDepthLumaMinus8!==null),I(e.bitDepthChromaMinus8!==null),I(e.sequenceParameterSetExt!==null),t.push(252|e.chromaFormat&3),t.push(248|e.bitDepthLumaMinus8&7),t.push(248|e.bitDepthChromaMinus8&7),t.push(e.sequenceParameterSetExt.length);for(let n of e.sequenceParameterSetExt){let e=n.byteLength;t.push(e>>8),t.push(e&255);for(let r=0;r<e;r++)t.push(n[r])}}return new Uint8Array(t)},Ua=e=>{try{let t=z(e),n=0,r=t.getUint8(n++),i=t.getUint8(n++),a=t.getUint8(n++),o=t.getUint8(n++),s=t.getUint8(n++)&3,c=t.getUint8(n++)&31,l=[];for(let r=0;r<c;r++){let r=t.getUint16(n,!1);n+=2,l.push(e.subarray(n,n+r)),n+=r}let u=t.getUint8(n++),d=[];for(let r=0;r<u;r++){let r=t.getUint16(n,!1);n+=2,d.push(e.subarray(n,n+r)),n+=r}let f={configurationVersion:r,avcProfileIndication:i,profileCompatibility:a,avcLevelIndication:o,lengthSizeMinusOne:s,sequenceParameterSets:l,pictureParameterSets:d,chromaFormat:null,bitDepthLumaMinus8:null,bitDepthChromaMinus8:null,sequenceParameterSetExt:null};if((i===100||i===110||i===122||i===144)&&n+4<=e.length){let r=t.getUint8(n++)&3,i=t.getUint8(n++)&7,a=t.getUint8(n++)&7,o=t.getUint8(n++);f.chromaFormat=r,f.bitDepthLumaMinus8=i,f.bitDepthChromaMinus8=a;let s=[];for(let r=0;r<o;r++){let r=t.getUint16(n,!1);n+=2,s.push(e.subarray(n,n+r)),n+=r}f.sequenceParameterSetExt=s}return f}catch(e){return console.error(`Error deserializing AVC Decoder Configuration Record:`,e),null}},Wa={1:{num:1,den:1},2:{num:12,den:11},3:{num:10,den:11},4:{num:16,den:11},5:{num:40,den:33},6:{num:24,den:11},7:{num:20,den:11},8:{num:32,den:11},9:{num:80,den:33},10:{num:18,den:11},11:{num:15,den:11},12:{num:64,den:33},13:{num:160,den:99},14:{num:4,den:3},15:{num:3,den:2},16:{num:2,den:1}},Ga=e=>{try{let t=new V(Ia(e));if(t.skipBits(1),t.skipBits(2),t.readBits(5)!==7)return null;let n=t.readAlignedByte(),r=t.readAlignedByte(),i=t.readAlignedByte();R(t);let a=1,o=0,s=0,c=0;if((n===100||n===110||n===122||n===244||n===44||n===83||n===86||n===118||n===128)&&(a=R(t),a===3&&(c=t.readBits(1)),o=R(t),s=R(t),t.skipBits(1),t.readBits(1))){for(let e=0;e<(a===3?12:8);e++)if(t.readBits(1)){let n=e<6?16:64,r=8,i=8;for(let e=0;e<n;e++){if(i!==0){let e=Fr(t);i=(r+e+256)%256}r=i===0?r:i}}}R(t);let l=R(t);if(l===0)R(t);else if(l===1){t.skipBits(1),Fr(t),Fr(t);let e=R(t);for(let n=0;n<e;n++)Fr(t)}R(t),t.skipBits(1);let u=R(t),d=R(t),f=16*(u+1),p=16*(d+1),m=f,h=p,g=t.readBits(1);if(g||t.skipBits(1),t.skipBits(1),t.readBits(1)){let e=R(t),n=R(t),r=R(t),i=R(t),o,s;if((c===0?a:0)===0)o=1,s=2-g;else{let e=a===3?1:2,t=a===1?2:1;o=e,s=t*(2-g)}m-=o*(e+n),h-=s*(r+i)}let _=2,v=2,y=2,b=0,x={num:1,den:1},S=null,C=null;if(t.readBits(1)){if(t.readBits(1)){let e=t.readBits(8);if(e===255)x={num:t.readBits(16),den:t.readBits(16)};else{let t=Wa[e];t&&(x=t)}}t.readBits(1)&&t.skipBits(1),t.readBits(1)&&(t.skipBits(3),b=t.readBits(1),t.readBits(1)&&(_=t.readBits(8),v=t.readBits(8),y=t.readBits(8))),t.readBits(1)&&(R(t),R(t)),t.readBits(1)&&(t.skipBits(32),t.skipBits(32),t.skipBits(1));let e=t.readBits(1);e&&Ka(t);let n=t.readBits(1);n&&Ka(t),(e||n)&&t.skipBits(1),t.skipBits(1),t.readBits(1)&&(t.skipBits(1),R(t),R(t),R(t),R(t),S=R(t),C=R(t))}if(S===null){I(C===null);let e=r&16;if((n===44||n===86||n===100||n===110||n===122||n===244)&&e)S=0,C=0;else{let e=u+1,t=d+1,n=(2-g)*t,r=Xi.find(e=>e.level>=i)??L(Xi),a=Math.min(Math.floor(r.maxDpbMbs/(e*n)),16);S=a,C=a}}return I(C!==null),{profileIdc:n,constraintFlags:r,levelIdc:i,frameMbsOnlyFlag:g,chromaFormatIdc:a,bitDepthLumaMinus8:o,bitDepthChromaMinus8:s,codedWidth:f,codedHeight:p,displayWidth:m,displayHeight:h,pixelAspectRatio:x,colourPrimaries:_,matrixCoefficients:y,transferCharacteristics:v,fullRangeFlag:b,numReorderFrames:S,maxDecFrameBuffering:C}}catch(e){return console.error(`Error parsing AVC SPS:`,e),null}},Ka=e=>{let t=R(e);e.skipBits(4),e.skipBits(4);for(let n=0;n<=t;n++)R(e),R(e),e.skipBits(1);e.skipBits(5),e.skipBits(5),e.skipBits(5),e.skipBits(5)},qa=(e,t)=>t.description?Na(e,(Ir(t.description)[21]&3)+1):Ma(e),Ja=e=>e>>1&63,Ya=e=>{try{let t=new V(Ia(e));t.skipBits(16),t.readBits(4);let n=t.readBits(3),r=t.readBits(1),{general_profile_space:i,general_tier_flag:a,general_profile_idc:o,general_profile_compatibility_flags:s,general_constraint_indicator_flags:c,general_level_idc:l}=Za(t,n);R(t);let u=R(t),d=0;u===3&&(d=t.readBits(1));let f=R(t),p=R(t),m=f,h=p;if(t.readBits(1)){let e=R(t),n=R(t),r=R(t),i=R(t),a=1,o=1,s=d===0?u:0;s===1?(a=2,o=2):s===2&&(a=2,o=1),m-=(e+n)*a,h-=(r+i)*o}let g=R(t),_=R(t);R(t);let v=t.readBits(1)?0:n,y=0;for(let e=v;e<=n;e++)R(t),y=R(t),R(t);if(R(t),R(t),R(t),R(t),R(t),R(t),t.readBits(1)&&t.readBits(1)&&Qa(t),t.skipBits(1),t.skipBits(1),t.readBits(1)&&(t.skipBits(4),t.skipBits(4),R(t),R(t),t.skipBits(1)),$a(t,R(t)),t.readBits(1)){let e=R(t);for(let n=0;n<e;n++)R(t),t.skipBits(1)}t.skipBits(1),t.skipBits(1);let b=2,x=2,S=2,C=0,ee=0,te={num:1,den:1};if(t.readBits(1)){let e=to(t,n);te=e.pixelAspectRatio,b=e.colourPrimaries,x=e.transferCharacteristics,S=e.matrixCoefficients,C=e.fullRangeFlag,ee=e.minSpatialSegmentationIdc}return{displayWidth:m,displayHeight:h,pixelAspectRatio:te,colourPrimaries:b,transferCharacteristics:x,matrixCoefficients:S,fullRangeFlag:C,maxDecFrameBuffering:y+1,spsMaxSubLayersMinus1:n,spsTemporalIdNestingFlag:r,generalProfileSpace:i,generalTierFlag:a,generalProfileIdc:o,generalProfileCompatibilityFlags:s,generalConstraintIndicatorFlags:c,generalLevelIdc:l,chromaFormatIdc:u,bitDepthLumaMinus8:g,bitDepthChromaMinus8:_,minSpatialSegmentationIdc:ee}}catch(e){return console.error(`Error parsing HEVC SPS:`,e),null}},Xa=e=>{try{let t=[],n=[],r=[],i=[];for(let a of Ma(e)){let o=e.subarray(a.offset,a.offset+a.length),s=Ja(o[0]);s===ja.VPS_NUT?t.push(o):s===ja.SPS_NUT?n.push(o):s===ja.PPS_NUT?r.push(o):(s===ja.PREFIX_SEI_NUT||s===ja.SUFFIX_SEI_NUT)&&i.push(o)}if(n.length===0||r.length===0)return null;let a=Ya(n[0]);if(!a)return null;let o=0;if(r.length>0){let e=r[0],t=new V(Ia(e));t.skipBits(16),R(t),R(t),t.skipBits(1),t.skipBits(1),t.skipBits(3),t.skipBits(1),t.skipBits(1),R(t),R(t),Fr(t),t.skipBits(1),t.skipBits(1),t.readBits(1)&&R(t),Fr(t),Fr(t),t.skipBits(1),t.skipBits(1),t.skipBits(1),t.skipBits(1);let n=t.readBits(1),i=t.readBits(1);o=!n&&!i?0:n&&!i?2:!n&&i?3:0}let s=[...t.length?[{arrayCompleteness:1,nalUnitType:ja.VPS_NUT,nalUnits:t}]:[],...n.length?[{arrayCompleteness:1,nalUnitType:ja.SPS_NUT,nalUnits:n}]:[],...r.length?[{arrayCompleteness:1,nalUnitType:ja.PPS_NUT,nalUnits:r}]:[],...i.length?[{arrayCompleteness:1,nalUnitType:Ja(i[0][0]),nalUnits:i}]:[]];return{configurationVersion:1,generalProfileSpace:a.generalProfileSpace,generalTierFlag:a.generalTierFlag,generalProfileIdc:a.generalProfileIdc,generalProfileCompatibilityFlags:a.generalProfileCompatibilityFlags,generalConstraintIndicatorFlags:a.generalConstraintIndicatorFlags,generalLevelIdc:a.generalLevelIdc,minSpatialSegmentationIdc:a.minSpatialSegmentationIdc,parallelismType:o,chromaFormatIdc:a.chromaFormatIdc,bitDepthLumaMinus8:a.bitDepthLumaMinus8,bitDepthChromaMinus8:a.bitDepthChromaMinus8,avgFrameRate:0,constantFrameRate:0,numTemporalLayers:a.spsMaxSubLayersMinus1+1,temporalIdNested:a.spsTemporalIdNestingFlag,lengthSizeMinusOne:3,arrays:s}}catch(e){return console.error(`Error building HEVC Decoder Configuration Record:`,e),null}},Za=(e,t)=>{let n=e.readBits(2),r=e.readBits(1),i=e.readBits(5),a=0;for(let t=0;t<32;t++)a=a<<1|e.readBits(1);let o=new Uint8Array(6);for(let t=0;t<6;t++)o[t]=e.readBits(8);let s=e.readBits(8),c=[],l=[];for(let n=0;n<t;n++)c.push(e.readBits(1)),l.push(e.readBits(1));if(t>0)for(let n=t;n<8;n++)e.skipBits(2);for(let n=0;n<t;n++)c[n]&&e.skipBits(88),l[n]&&e.skipBits(8);return{general_profile_space:n,general_tier_flag:r,general_profile_idc:i,general_profile_compatibility_flags:a,general_constraint_indicator_flags:o,general_level_idc:s}},Qa=e=>{for(let t=0;t<4;t++)for(let n=0;n<(t===3?2:6);n++)if(!e.readBits(1))R(e);else{let n=Math.min(64,1<<4+(t<<1));t>1&&Fr(e);for(let t=0;t<n;t++)Fr(e)}},$a=(e,t)=>{let n=[];for(let r=0;r<t;r++)n[r]=eo(e,r,t,n)},eo=(e,t,n,r)=>{let i=0,a=0,o=0;if(t!==0&&(a=e.readBits(1)),a){o=t===n?t-(R(e)+1):t-1,e.readBits(1),R(e);let a=r[o]??0;for(let t=0;t<=a;t++)e.readBits(1)||e.readBits(1);i=r[o]}else{let t=R(e),n=R(e);for(let n=0;n<t;n++)R(e),e.readBits(1);for(let t=0;t<n;t++)R(e),e.readBits(1);i=t+n}return i},to=(e,t)=>{let n=2,r=2,i=2,a=0,o=0,s={num:1,den:1};if(e.readBits(1)){let t=e.readBits(8);if(t===255)s={num:e.readBits(16),den:e.readBits(16)};else{let e=Wa[t];e&&(s=e)}}return e.readBits(1)&&e.readBits(1),e.readBits(1)&&(e.readBits(3),a=e.readBits(1),e.readBits(1)&&(n=e.readBits(8),r=e.readBits(8),i=e.readBits(8))),e.readBits(1)&&(R(e),R(e)),e.readBits(1),e.readBits(1),e.readBits(1),e.readBits(1)&&(R(e),R(e),R(e),R(e)),e.readBits(1)&&(e.readBits(32),e.readBits(32),e.readBits(1)&&R(e),e.readBits(1)&&no(e,!0,t)),e.readBits(1)&&(e.readBits(1),e.readBits(1),e.readBits(1),o=R(e),R(e),R(e),R(e),R(e)),{pixelAspectRatio:s,colourPrimaries:n,transferCharacteristics:r,matrixCoefficients:i,fullRangeFlag:a,minSpatialSegmentationIdc:o}},no=(e,t,n)=>{let r=!1,i=!1,a=!1;t&&(r=e.readBits(1)===1,i=e.readBits(1)===1,(r||i)&&(a=e.readBits(1)===1,a&&(e.readBits(8),e.readBits(5),e.readBits(1),e.readBits(5)),e.readBits(4),e.readBits(4),a&&e.readBits(4),e.readBits(5),e.readBits(5),e.readBits(5)));for(let t=0;t<=n;t++){let t=e.readBits(1)===1,n=!0;t||(n=e.readBits(1)===1);let o=!1;n?R(e):o=e.readBits(1)===1;let s=1;o||(s=R(e)+1),r&&ro(e,s,a),i&&ro(e,s,a)}},ro=(e,t,n)=>{for(let r=0;r<t;r++)R(e),R(e),n&&(R(e),R(e)),e.readBits(1)},io=e=>{let t=[];t.push(e.configurationVersion),t.push((e.generalProfileSpace&3)<<6|(e.generalTierFlag&1)<<5|e.generalProfileIdc&31),t.push(e.generalProfileCompatibilityFlags>>>24&255),t.push(e.generalProfileCompatibilityFlags>>>16&255),t.push(e.generalProfileCompatibilityFlags>>>8&255),t.push(e.generalProfileCompatibilityFlags&255),t.push(...e.generalConstraintIndicatorFlags),t.push(e.generalLevelIdc&255),t.push(240|e.minSpatialSegmentationIdc>>8&15),t.push(e.minSpatialSegmentationIdc&255),t.push(252|e.parallelismType&3),t.push(252|e.chromaFormatIdc&3),t.push(248|e.bitDepthLumaMinus8&7),t.push(248|e.bitDepthChromaMinus8&7),t.push(e.avgFrameRate>>8&255),t.push(e.avgFrameRate&255),t.push((e.constantFrameRate&3)<<6|(e.numTemporalLayers&7)<<3|(e.temporalIdNested&1)<<2|e.lengthSizeMinusOne&3),t.push(e.arrays.length&255);for(let n of e.arrays){t.push((n.arrayCompleteness&1)<<7|0|n.nalUnitType&63),t.push(n.nalUnits.length>>8&255),t.push(n.nalUnits.length&255);for(let e of n.nalUnits){t.push(e.length>>8&255),t.push(e.length&255);for(let n=0;n<e.length;n++)t.push(e[n])}}return new Uint8Array(t)},ao=e=>{let t=new V(e);if(t.readBits(2)!==2)return null;let n=t.readBits(1),r=(t.readBits(1)<<1)+n;if(r===3&&t.skipBits(1),t.readBits(1)===1||t.readBits(1)!==0||(t.skipBits(2),t.readBits(24)!==4817730))return null;let i=8;r>=2&&(i=t.readBits(1)?12:10);let a=t.readBits(3),o=0,s=0;if(a!==7)if(s=t.readBits(1),r===1||r===3){let e=t.readBits(1),n=t.readBits(1);o=!e&&!n?3:e&&!n?2:1,t.skipBits(1)}else o=1;else o=3,s=1;let c=t.readBits(16),l=t.readBits(16),u=(c+1)*(l+1),d=L(Qi).level;for(let e of Qi)if(u<=e.maxPictureSize){d=e.level;break}return{profile:r,level:d,bitDepth:i,chromaSubsampling:o,videoFullRangeFlag:s,colourPrimaries:a===2?1:a===1?6:2,transferCharacteristics:a===2?1:a===1?6:2,matrixCoefficients:a===7?0:a===2?1:a===1?6:2}},oo=function*(e){let t=new V(e),n=()=>{let e=0;for(let n=0;n<8;n++){let r=t.readAlignedByte();if(e|=(r&127)<<n*7,!(r&128))break;if(n===7&&r&128)return null}return e>=2**32-1?null:e};for(;t.getBitsLeft()>=8;){t.skipBits(1);let r=t.readBits(4),i=t.readBits(1),a=t.readBits(1);t.skipBits(1),i&&t.skipBits(8);let o;if(a){let e=n();if(e===null)return;o=e}else o=Math.floor(t.getBitsLeft()/8);I(t.pos%8==0),yield{type:r,data:e.subarray(t.pos/8,t.pos/8+o)},t.skipBits(o*8)}},so=e=>{for(let{type:t,data:n}of oo(e)){if(t!==1)continue;let e=new V(n),r=e.readBits(3);e.readBits(1);let i=e.readBits(1),a=0,o=0,s=0;if(i)a=e.readBits(5);else{if(e.readBits(1)&&(e.skipBits(32),e.skipBits(32),e.readBits(1)))return null;let t=e.readBits(1);t&&(s=e.readBits(5),e.skipBits(32),e.skipBits(5),e.skipBits(5));let n=e.readBits(5);for(let r=0;r<=n;r++){e.skipBits(12);let n=e.readBits(5);if(r===0&&(a=n),n>7){let t=e.readBits(1);r===0&&(o=t)}if(t&&e.readBits(1)){let t=s+1;e.skipBits(t),e.skipBits(t),e.skipBits(1)}e.readBits(1)&&e.skipBits(4)}}let c=e.readBits(4),l=e.readBits(4),u=c+1;e.skipBits(u);let d=l+1;e.skipBits(d);let f=0;if(f=i?0:e.readBits(1),f&&(e.skipBits(4),e.skipBits(3)),e.skipBits(1),e.skipBits(1),e.skipBits(1),!i){e.skipBits(1),e.skipBits(1),e.skipBits(1),e.skipBits(1);let t=e.readBits(1);t&&(e.skipBits(1),e.skipBits(1));let n=e.readBits(1),r=0;r=n?2:e.readBits(1),r>0&&(e.readBits(1)||e.skipBits(1)),t&&e.skipBits(3)}e.skipBits(1),e.skipBits(1),e.skipBits(1);let p=e.readBits(1),m=8;r===2&&p?m=e.readBits(1)?12:10:r<=2&&(m=p?10:8);let h=0;r!==1&&(h=e.readBits(1));let g=1,_=1,v=0;return h||(r===0?(g=1,_=1):r===1?(g=0,_=0):m===12&&(g=e.readBits(1),g&&(_=e.readBits(1))),g&&_&&(v=e.readBits(2))),{profile:r,level:a,tier:o,bitDepth:m,monochrome:h,chromaSubsamplingX:g,chromaSubsamplingY:_,chromaSamplePosition:v}}return null},co=e=>{let t=z(e),n=t.getUint8(9),r=t.getUint16(10,!0),i=t.getUint32(12,!0),a=t.getInt16(16,!0),o=t.getUint8(18),s=null;return o&&(s=e.subarray(19,21+n)),{outputChannelCount:n,preSkip:r,inputSampleRate:i,outputGain:a,channelMappingFamily:o,channelMappingTable:s}},lo=[480,960,1920,2880,480,960,1920,2880,480,960,1920,2880,480,960,480,960,120,240,480,960,120,240,480,960,120,240,480,960,120,240,480,960],uo=e=>({durationInSamples:lo[e[0]>>3]}),fo=e=>{if(e.length<7)throw Error(`Setup header is too short.`);if(e[0]!==5)throw Error(`Wrong packet type in Setup header.`);if(String.fromCharCode(...e.slice(1,7))!==`vorbis`)throw Error(`Invalid packet signature in Setup header.`);let t=e.length,n=new Uint8Array(t);for(let r=0;r<t;r++)n[r]=e[t-1-r];let r=new V(n),i=0;for(;r.getBitsLeft()>97;)if(r.readBits(1)===1){i=r.pos;break}if(i===0)throw Error(`Invalid Setup header: framing bit not found.`);let a=0,o=!1,s=0;for(;r.getBitsLeft()>=97;){let e=r.pos,t=r.readBits(8),n=r.readBits(16),i=r.readBits(16);if(t>63||n!==0||i!==0){r.pos=e;break}if(r.skipBits(1),a++,a>64)break;r.clone().readBits(6)+1===a&&(o=!0,s=a)}if(!o)throw Error(`Invalid Setup header: mode header not found.`);if(s>63)throw Error(`Unsupported mode count: ${s}.`);let c=s;r.pos=0,r.skipBits(i);let l=Array(c).fill(0);for(let e=c-1;e>=0;e--)r.skipBits(40),l[e]=r.readBits(1);return{modeBlockflags:l}},po=(e,t,n)=>{switch(e){case`avc`:for(let e of Pa(n,t)){let t=n[e.offset],r=Fa(t);if(r>=Aa.NON_IDR_SLICE&&r<=Aa.SLICE_DPC)return`delta`;if(r===Aa.IDR)return`key`;if(r===Aa.SEI&&(!Ti()||Di()>=144)){let t=Ia(n.subarray(e.offset,e.offset+e.length)),r=1;do{let e=0;for(;;){let n=t[r++];if(n===void 0||(e+=n,n<255))break}let n=0;for(;;){let e=t[r++];if(e===void 0||(n+=e,e<255))break}if(e===6){let e=new V(t);e.pos=8*r;let n=R(e),i=e.readBits(1);if(n===0&&i===1)return`key`}r+=n}while(r<t.length-1)}}return`delta`;case`hevc`:for(let e of qa(n,t)){let t=Ja(n[e.offset]);if(t<ja.BLA_W_LP)return`delta`;if(t<=ja.RSV_IRAP_VCL23)return`key`}return`delta`;case`vp8`:return n[0]&1?`delta`:`key`;case`vp9`:{let e=new V(n);if(e.readBits(2)!==2)return null;let t=e.readBits(1);return(e.readBits(1)<<1)+t===3&&e.skipBits(1),e.readBits(1)?null:e.readBits(1)===0?`key`:`delta`}case`av1`:{let e=!1;for(let{type:t,data:r}of oo(n))if(t===1){let t=new V(r);t.skipBits(4),e=!!t.readBits(1)}else if(t===3||t===6||t===7){if(e)return`key`;let t=new V(r);return t.readBits(1)?null:t.readBits(2)===0?`key`:`delta`}return null}default:ii(e),I(!1)}},mo;(function(e){e[e.STREAMINFO=0]=`STREAMINFO`,e[e.VORBIS_COMMENT=4]=`VORBIS_COMMENT`,e[e.PICTURE=6]=`PICTURE`})(mo||={});var ho=(e,t)=>{let n=z(e),r=0,i=n.getUint32(r,!0);r+=4;let a=Lr.decode(e.subarray(r,r+i));r+=i,i>0&&(t.raw??={},t.raw.vendor??=a);let o=n.getUint32(r,!0);r+=4;for(let i=0;i<o;i++){let i=n.getUint32(r,!0);r+=4;let a=Lr.decode(e.subarray(r,r+i));r+=i;let o=a.indexOf(`=`);if(o===-1)continue;let s=a.slice(0,o).toUpperCase(),c=a.slice(o+1);switch(t.raw??={},t.raw[s]??=c,s){case`TITLE`:t.title??=c;break;case`DESCRIPTION`:t.description??=c;break;case`ARTIST`:t.artist??=c;break;case`ALBUM`:t.album??=c;break;case`ALBUMARTIST`:t.albumArtist??=c;break;case`COMMENT`:t.comment??=c;break;case`LYRICS`:t.lyrics??=c;break;case`TRACKNUMBER`:{let e=c.split(`/`),n=Number.parseInt(e[0],10),r=e[1]&&Number.parseInt(e[1],10);Number.isInteger(n)&&n>0&&(t.trackNumber??=n),r&&Number.isInteger(r)&&r>0&&(t.tracksTotal??=r)}break;case`TRACKTOTAL`:{let e=Number.parseInt(c,10);Number.isInteger(e)&&e>0&&(t.tracksTotal??=e)}break;case`DISCNUMBER`:{let e=c.split(`/`),n=Number.parseInt(e[0],10),r=e[1]&&Number.parseInt(e[1],10);Number.isInteger(n)&&n>0&&(t.discNumber??=n),r&&Number.isInteger(r)&&r>0&&(t.discsTotal??=r)}break;case`DISCTOTAL`:{let e=Number.parseInt(c,10);Number.isInteger(e)&&e>0&&(t.discsTotal??=e)}break;case`DATE`:{let e=new Date(c);Number.isNaN(e.getTime())||(t.date??=e)}break;case`GENRE`:t.genre??=c;break;case`METADATA_BLOCK_PICTURE`:{let e=ji(c),n=z(e),r=n.getUint32(0,!1),i=n.getUint32(4,!1),a=String.fromCharCode(...e.subarray(8,8+i)),o=n.getUint32(8+i,!1),s=Lr.decode(e.subarray(12+i,12+i+o)),l=n.getUint32(i+o+28),u=e.subarray(i+o+32,i+o+32+l);t.images??=[],t.images.push({data:u,mimeType:a,kind:r===3?`coverFront`:r===4?`coverBack`:`unknown`,name:void 0,description:s||void 0})}break}}},go=[2,1,2,3,3,4,4,5],_o=e=>{if(e.length<7||e[0]!==11||e[1]!==119)return null;let t=new V(e);t.skipBits(16),t.skipBits(16);let n=t.readBits(2);if(n===3)return null;let r=t.readBits(6),i=t.readBits(5);if(i>8)return null;let a=t.readBits(3),o=t.readBits(3);return o&1&&o!==1&&t.skipBits(2),o&4&&t.skipBits(2),o===2&&t.skipBits(2),{fscod:n,bsid:i,bsmod:a,acmod:o,lfeon:t.readBits(1),bitRateCode:Math.floor(r/2)}},vo=[128,138,192,128,140,192,160,174,240,160,176,240,192,208,288,192,210,288,224,242,336,224,244,336,256,278,384,256,280,384,320,348,480,320,350,480,384,416,288*2,384,418,288*2,448,486,336*2,448,488,336*2,256*2,278*2,384*2,256*2,279*2,384*2,320*2,348*2,480*2,320*2,349*2,480*2,384*2,417*2,576*2,384*2,418*2,576*2,448*2,487*2,672*2,448*2,488*2,672*2,512*2,557*2,768*2,512*2,558*2,768*2,640*2,696*2,960*2,640*2,697*2,960*2,768*2,835*2,1152*2,768*2,836*2,1152*2,896*2,975*2,1344*2,896*2,976*2,1344*2,1024*2,1114*2,1536*2,1024*2,1115*2,1536*2,1152*2,1253*2,1728*2,1152*2,1254*2,1728*2,1280*2,1393*2,1920*2,1280*2,1394*2,1920*2],yo=1536;new Uint8Array([5,4,65,67,45,51]),new Uint8Array([5,4,69,65,67,51]);var bo=[1,2,3,6],xo=e=>{if(e.length<6||e[0]!==11||e[1]!==119)return null;let t=new V(e);t.skipBits(16);let n=t.readBits(2);if(t.skipBits(3),n!==0&&n!==2)return null;let r=t.readBits(11),i=t.readBits(2),a=0,o;i===3?(a=t.readBits(2),o=3):o=t.readBits(2);let s=t.readBits(3),c=t.readBits(1),l=t.readBits(5);if(l<11||l>16)return null;let u=bo[o],d;return d=i<3?Oa[i]/1e3:ka[a]/1e3,{dataRate:Math.round((r+1)*d/(u*16)),substreams:[{fscod:i,fscod2:a,bsid:l,bsmod:0,acmod:s,lfeon:c,numDepSub:0,chanLoc:0}]}},So=e=>{if(e.length<2)return null;let t=new V(e),n=t.readBits(13),r=t.readBits(3),i=[];for(let n=0;n<=r&&!(Math.ceil(t.pos/8)+3>e.length);n++){let e=t.readBits(2),n=t.readBits(5);t.skipBits(1),t.skipBits(1);let r=t.readBits(3),a=t.readBits(3),o=t.readBits(1);t.skipBits(3);let s=t.readBits(4),c=0;s>0?c=t.readBits(9):t.skipBits(1),i.push({fscod:e,fscod2:null,bsid:n,bsmod:r,acmod:a,lfeon:o,numDepSub:s,chanLoc:c})}return i.length===0?null:{dataRate:n,substreams:i}},Co=e=>{let t=e.substreams[0];return I(t),t.fscod<3?Oa[t.fscod]:t.fscod2!==null&&t.fscod2<3?ka[t.fscod2]:null},wo=e=>{let t=e.substreams[0];I(t);let n=go[t.acmod]+t.lfeon;if(t.numDepSub>0){let e=[2,2,1,1,2,2,2,1,1];for(let r=0;r<9;r++)t.chanLoc&1<<8-r&&(n+=e[r])}return n},To=class{constructor(e){this.input=e}},Eo=[],Do=[],Oo=[],ko=[],Ao=new Uint8Array,H=class e{constructor(e,t,n,r,i=-1,a,o){if(this.data=e,this.type=t,this.timestamp=n,this.duration=r,this.sequenceNumber=i,e===Ao&&a===void 0)throw Error(`Internal error: byteLength must be explicitly provided when constructing metadata-only packets.`);if(a===void 0&&(a=e.byteLength),!(e instanceof Uint8Array))throw TypeError(`data must be a Uint8Array.`);if(t!==`key`&&t!==`delta`)throw TypeError(`type must be either "key" or "delta".`);if(!Number.isFinite(n))throw TypeError(`timestamp must be a number.`);if(!Number.isFinite(r)||r<0)throw TypeError(`duration must be a non-negative number.`);if(!Number.isFinite(i))throw TypeError(`sequenceNumber must be a number.`);if(!Number.isInteger(a)||a<0)throw TypeError(`byteLength must be a non-negative integer.`);if(o!==void 0&&(typeof o!=`object`||!o))throw TypeError(`sideData, when provided, must be an object.`);if(o?.alpha!==void 0&&!(o.alpha instanceof Uint8Array))throw TypeError(`sideData.alpha, when provided, must be a Uint8Array.`);if(o?.alphaByteLength!==void 0&&(!Number.isInteger(o.alphaByteLength)||o.alphaByteLength<0))throw TypeError(`sideData.alphaByteLength, when provided, must be a non-negative integer.`);this.byteLength=a,this.sideData=o??{},this.sideData.alpha&&this.sideData.alphaByteLength===void 0&&(this.sideData.alphaByteLength=this.sideData.alpha.byteLength)}get isMetadataOnly(){return this.data===Ao}get microsecondTimestamp(){return Math.trunc(_i*this.timestamp)}get microsecondDuration(){return Math.trunc(_i*this.duration)}toEncodedVideoChunk(){if(this.isMetadataOnly)throw TypeError(`Metadata-only packets cannot be converted to a video chunk.`);if(typeof EncodedVideoChunk>`u`)throw Error(`Your browser does not support EncodedVideoChunk.`);return new EncodedVideoChunk({data:this.data,type:this.type,timestamp:this.microsecondTimestamp,duration:this.microsecondDuration})}alphaToEncodedVideoChunk(e=this.type){if(!this.sideData.alpha)throw TypeError(`This packet does not contain alpha side data.`);if(this.isMetadataOnly)throw TypeError(`Metadata-only packets cannot be converted to a video chunk.`);if(typeof EncodedVideoChunk>`u`)throw Error(`Your browser does not support EncodedVideoChunk.`);return new EncodedVideoChunk({data:this.sideData.alpha,type:e,timestamp:this.microsecondTimestamp,duration:this.microsecondDuration})}toEncodedAudioChunk(){if(this.isMetadataOnly)throw TypeError(`Metadata-only packets cannot be converted to an audio chunk.`);if(typeof EncodedAudioChunk>`u`)throw Error(`Your browser does not support EncodedAudioChunk.`);return new EncodedAudioChunk({data:this.data,type:this.type,timestamp:this.microsecondTimestamp,duration:this.microsecondDuration})}static fromEncodedChunk(t,n){if(!(t instanceof EncodedVideoChunk||t instanceof EncodedAudioChunk))throw TypeError(`chunk must be an EncodedVideoChunk or EncodedAudioChunk.`);let r=new Uint8Array(t.byteLength);return t.copyTo(r),new e(r,t.type,t.timestamp/1e6,(t.duration??0)/1e6,void 0,void 0,n)}clone(t){if(t!==void 0&&(typeof t!=`object`||!t))throw TypeError(`options, when provided, must be an object.`);if(t?.data!==void 0&&!(t.data instanceof Uint8Array))throw TypeError(`options.data, when provided, must be a Uint8Array.`);if(t?.type!==void 0&&t.type!==`key`&&t.type!==`delta`)throw TypeError(`options.type, when provided, must be either "key" or "delta".`);if(t?.timestamp!==void 0&&!Number.isFinite(t.timestamp))throw TypeError(`options.timestamp, when provided, must be a number.`);if(t?.duration!==void 0&&!Number.isFinite(t.duration))throw TypeError(`options.duration, when provided, must be a number.`);if(t?.sequenceNumber!==void 0&&!Number.isFinite(t.sequenceNumber))throw TypeError(`options.sequenceNumber, when provided, must be a number.`);if(t?.sideData!==void 0&&(typeof t.sideData!=`object`||t.sideData===null))throw TypeError(`options.sideData, when provided, must be an object.`);return new e(t?.data??this.data,t?.type??this.type,t?.timestamp??this.timestamp,t?.duration??this.duration,t?.sequenceNumber??this.sequenceNumber,this.byteLength,t?.sideData??this.sideData)}},jo=e=>{let t=8191,n=e,r=4096,i=0,a=12,o=0;for(n<0&&(n=-n,i=128),n+=33,n>t&&(n=t);(n&r)!==r&&a>=5;)r>>=1,a--;return o=n>>a-4&15,~(i|a-5<<4|o)&255},Mo=e=>{let t=0,n=0,r=~e;r&128&&(r&=-129,t=-1),n=((r&240)>>4)+5;let i=(1<<n|(r&15)<<n-4|1<<n-5)-33;return t===0?i:-i},No=e=>{let t=4095,n=2048,r=0,i=11,a=0,o=e;for(o<0&&(o=-o,r=128),o>t&&(o=t);(o&n)!==n&&i>=5;)n>>=1,i--;return a=o>>(i===4?1:i-4)&15,(r|i-4<<4|a)^85},Po=e=>{let t=0,n=0,r=e^85;r&128&&(r&=-129,t=-1),n=((r&240)>>4)+4;let i=0;return i=n===4?r<<1|1:1<<n|(r&15)<<n-4|1<<n-5,t===0?i:-i};Mi();var Fo=-1/0,Io=-1/0,Lo=null;typeof FinalizationRegistry<`u`&&(Lo=new FinalizationRegistry(e=>{let t=Date.now();e.type===`video`?(t-Fo>=1e3&&(console.error(`A VideoSample was garbage collected without first being closed. For proper resource management, make sure to call close() on all your VideoSamples as soon as you're done using them.`),Fo=t),typeof VideoFrame<`u`&&e.data instanceof VideoFrame&&e.data.close()):(t-Io>=1e3&&(console.error(`An AudioSample was garbage collected without first being closed. For proper resource management, make sure to call close() on all your AudioSamples as soon as you're done using them.`),Io=t),typeof AudioData<`u`&&e.data instanceof AudioData&&e.data.close())}));var Ro=[`I420`,`I420P10`,`I420P12`,`I420A`,`I420AP10`,`I420AP12`,`I422`,`I422P10`,`I422P12`,`I422A`,`I422AP10`,`I422AP12`,`I444`,`I444P10`,`I444P12`,`I444A`,`I444AP10`,`I444AP12`,`NV12`,`RGBA`,`RGBX`,`BGRA`,`BGRX`],zo=new Set(Ro),Bo=class e{get codedWidth(){return this.visibleRect.width}get codedHeight(){return this.visibleRect.height}get displayWidth(){return this.rotation%180==0?this.squarePixelWidth:this.squarePixelHeight}get displayHeight(){return this.rotation%180==0?this.squarePixelHeight:this.squarePixelWidth}get microsecondTimestamp(){return Math.trunc(_i*this.timestamp)}get microsecondDuration(){return Math.trunc(_i*this.duration)}get hasAlpha(){return this.format&&this.format.includes(`A`)}constructor(t,n){if(this._closed=!1,t instanceof ArrayBuffer||typeof SharedArrayBuffer<`u`&&t instanceof SharedArrayBuffer||ArrayBuffer.isView(t)){if(!n||typeof n!=`object`)throw TypeError(`init must be an object.`);if(n.format===void 0||!zo.has(n.format))throw TypeError(`init.format must be one of: `+Ro.join(`, `));if(!Number.isInteger(n.codedWidth)||n.codedWidth<=0)throw TypeError(`init.codedWidth must be a positive integer.`);if(!Number.isInteger(n.codedHeight)||n.codedHeight<=0)throw TypeError(`init.codedHeight must be a positive integer.`);if(n.rotation!==void 0&&![0,90,180,270].includes(n.rotation))throw TypeError(`init.rotation, when provided, must be 0, 90, 180, or 270.`);if(!Number.isFinite(n.timestamp))throw TypeError(`init.timestamp must be a number.`);if(n.duration!==void 0&&(!Number.isFinite(n.duration)||n.duration<0))throw TypeError(`init.duration, when provided, must be a non-negative number.`);if(n.layout!==void 0){if(!Array.isArray(n.layout))throw TypeError(`init.layout, when provided, must be an array.`);for(let e of n.layout){if(!e||typeof e!=`object`||Array.isArray(e))throw TypeError(`Each entry in init.layout must be an object.`);if(!Number.isInteger(e.offset)||e.offset<0)throw TypeError(`plane.offset must be a non-negative integer.`);if(!Number.isInteger(e.stride)||e.stride<0)throw TypeError(`plane.stride must be a non-negative integer.`)}}if(n.visibleRect!==void 0&&Fi(n.visibleRect,`init.visibleRect`),n.displayWidth!==void 0&&(!Number.isInteger(n.displayWidth)||n.displayWidth<=0))throw TypeError(`init.displayWidth, when provided, must be a positive integer.`);if(n.displayHeight!==void 0&&(!Number.isInteger(n.displayHeight)||n.displayHeight<=0))throw TypeError(`init.displayHeight, when provided, must be a positive integer.`);if(n.displayWidth!==void 0!=(n.displayHeight!==void 0))throw TypeError(`init.displayWidth and init.displayHeight must be either both provided or both omitted.`);this._data=Ir(t).slice(),this._layout=n.layout??Ko(n.format,n.codedWidth,n.codedHeight),this.format=n.format,this.rotation=n.rotation??0,this.timestamp=n.timestamp,this.duration=n.duration??0,this.colorSpace=new Vo(n.colorSpace),this.visibleRect={left:n.visibleRect?.left??0,top:n.visibleRect?.top??0,width:n.visibleRect?.width??n.codedWidth,height:n.visibleRect?.height??n.codedHeight},n.displayWidth===void 0?(this.squarePixelWidth=this.codedWidth,this.squarePixelHeight=this.codedHeight):(this.squarePixelWidth=this.rotation%180==0?n.displayWidth:n.displayHeight,this.squarePixelHeight=this.rotation%180==0?n.displayHeight:n.displayWidth)}else if(typeof VideoFrame<`u`&&t instanceof VideoFrame){if(n?.rotation!==void 0&&![0,90,180,270].includes(n.rotation))throw TypeError(`init.rotation, when provided, must be 0, 90, 180, or 270.`);if(n?.timestamp!==void 0&&!Number.isFinite(n?.timestamp))throw TypeError(`init.timestamp, when provided, must be a number.`);if(n?.duration!==void 0&&(!Number.isFinite(n.duration)||n.duration<0))throw TypeError(`init.duration, when provided, must be a non-negative number.`);n?.visibleRect!==void 0&&Fi(n.visibleRect,`init.visibleRect`),this._data=t,this._layout=null,this.format=t.format,this.visibleRect={left:t.visibleRect?.x??0,top:t.visibleRect?.y??0,width:t.visibleRect?.width??t.codedWidth,height:t.visibleRect?.height??t.codedHeight},this.rotation=n?.rotation??0,this.squarePixelWidth=t.displayWidth,this.squarePixelHeight=t.displayHeight,this.timestamp=n?.timestamp??t.timestamp/1e6,this.duration=n?.duration??(t.duration??0)/1e6,this.colorSpace=new Vo(t.colorSpace)}else if(typeof HTMLImageElement<`u`&&t instanceof HTMLImageElement||typeof SVGImageElement<`u`&&t instanceof SVGImageElement||typeof ImageBitmap<`u`&&t instanceof ImageBitmap||typeof HTMLVideoElement<`u`&&t instanceof HTMLVideoElement||typeof HTMLCanvasElement<`u`&&t instanceof HTMLCanvasElement||typeof OffscreenCanvas<`u`&&t instanceof OffscreenCanvas){if(!n||typeof n!=`object`)throw TypeError(`init must be an object.`);if(n.rotation!==void 0&&![0,90,180,270].includes(n.rotation))throw TypeError(`init.rotation, when provided, must be 0, 90, 180, or 270.`);if(!Number.isFinite(n.timestamp))throw TypeError(`init.timestamp must be a number.`);if(n.duration!==void 0&&(!Number.isFinite(n.duration)||n.duration<0))throw TypeError(`init.duration, when provided, must be a non-negative number.`);if(typeof VideoFrame<`u`)return new e(new VideoFrame(t,{timestamp:Math.trunc(n.timestamp*_i),duration:Math.trunc((n.duration??0)*_i)||void 0}),n);let r=0,i=0;if(`naturalWidth`in t?(r=t.naturalWidth,i=t.naturalHeight):`videoWidth`in t?(r=t.videoWidth,i=t.videoHeight):`width`in t&&(r=Number(t.width),i=Number(t.height)),!r||!i)throw TypeError(`Could not determine dimensions.`);let a=new OffscreenCanvas(r,i),o=a.getContext(`2d`,{alpha:Ci(),willReadFrequently:!0});I(o),o.drawImage(t,0,0),this._data=a,this._layout=null,this.format=`RGBX`,this.visibleRect={left:0,top:0,width:r,height:i},this.squarePixelWidth=r,this.squarePixelHeight=i,this.rotation=n.rotation??0,this.timestamp=n.timestamp,this.duration=n.duration??0,this.colorSpace=new Vo({matrix:`rgb`,primaries:`bt709`,transfer:`iec61966-2-1`,fullRange:!0})}else throw TypeError(`Invalid data type: Must be a BufferSource or CanvasImageSource.`);this.pixelAspectRatio=Pi({num:this.squarePixelWidth*this.codedHeight,den:this.squarePixelHeight*this.codedWidth}),Lo?.register(this,{type:`video`,data:this._data},this)}clone(){if(this._closed)throw Error(`VideoSample is closed.`);return I(this._data!==null),Ho(this._data)?new e(this._data.clone(),{timestamp:this.timestamp,duration:this.duration,rotation:this.rotation}):this._data instanceof Uint8Array?(I(this._layout),new e(this._data,{format:this.format,layout:this._layout,codedWidth:this.codedWidth,codedHeight:this.codedHeight,timestamp:this.timestamp,duration:this.duration,colorSpace:this.colorSpace,rotation:this.rotation,visibleRect:this.visibleRect,displayWidth:this.displayWidth,displayHeight:this.displayHeight})):new e(this._data,{format:this.format,codedWidth:this.codedWidth,codedHeight:this.codedHeight,timestamp:this.timestamp,duration:this.duration,colorSpace:this.colorSpace,rotation:this.rotation,visibleRect:this.visibleRect,displayWidth:this.displayWidth,displayHeight:this.displayHeight})}close(){this._closed||=(Lo?.unregister(this),Ho(this._data)?this._data.close():this._data=null,!0)}allocationSize(e={}){if(Go(e),this._closed)throw Error(`VideoSample is closed.`);if(this.format===null)throw Error(`Cannot get allocation size when format is null. Sorry!`);if(I(this._data!==null),!Ho(this._data)&&(e.colorSpace||e.format&&e.format!==this.format||e.layout||e.rect)){let t=this.toVideoFrame(),n=t.allocationSize(e);return t.close(),n}return Ho(this._data)?this._data.allocationSize(e):this._data instanceof Uint8Array?this._data.byteLength:this.codedWidth*this.codedHeight*4}async copyTo(e,t={}){if(!qr(e))throw TypeError(`destination must be an ArrayBuffer or an ArrayBuffer view.`);if(Go(t),this._closed)throw Error(`VideoSample is closed.`);if(this.format===null)throw Error(`Cannot copy video sample data when format is null. Sorry!`);if(I(this._data!==null),!Ho(this._data)&&(t.colorSpace||t.format&&t.format!==this.format||t.layout||t.rect)){let n=this.toVideoFrame(),r=await n.copyTo(e,t);return n.close(),r}if(Ho(this._data))return this._data.copyTo(e,t);if(this._data instanceof Uint8Array)return I(this._layout),Ir(e).set(this._data),this._layout;{let t=this._data.getContext(`2d`);I(t);let n=t.getImageData(0,0,this.codedWidth,this.codedHeight);return Ir(e).set(n.data),[{offset:0,stride:4*this.codedWidth}]}}toVideoFrame(){if(this._closed)throw Error(`VideoSample is closed.`);return I(this._data!==null),Ho(this._data)?new VideoFrame(this._data,{timestamp:this.microsecondTimestamp,duration:this.microsecondDuration||void 0}):this._data instanceof Uint8Array?new VideoFrame(this._data,{format:this.format,codedWidth:this.codedWidth,codedHeight:this.codedHeight,timestamp:this.microsecondTimestamp,duration:this.microsecondDuration||void 0,colorSpace:this.colorSpace}):new VideoFrame(this._data,{timestamp:this.microsecondTimestamp,duration:this.microsecondDuration||void 0})}draw(e,t,n,r,i,a,o,s,c){let l=0,u=0,d=this.displayWidth,f=this.displayHeight,p=0,m=0,h=this.displayWidth,g=this.displayHeight;if(a===void 0?(p=t,m=n,r!==void 0&&(h=r,g=i)):(l=t,u=n,d=r,f=i,p=a,m=o,s===void 0?(h=d,g=f):(h=s,g=c)),!(typeof CanvasRenderingContext2D<`u`&&e instanceof CanvasRenderingContext2D||typeof OffscreenCanvasRenderingContext2D<`u`&&e instanceof OffscreenCanvasRenderingContext2D))throw TypeError(`context must be a CanvasRenderingContext2D or OffscreenCanvasRenderingContext2D.`);if(!Number.isFinite(l))throw TypeError(`sx must be a number.`);if(!Number.isFinite(u))throw TypeError(`sy must be a number.`);if(!Number.isFinite(d)||d<0)throw TypeError(`sWidth must be a non-negative number.`);if(!Number.isFinite(f)||f<0)throw TypeError(`sHeight must be a non-negative number.`);if(!Number.isFinite(p))throw TypeError(`dx must be a number.`);if(!Number.isFinite(m))throw TypeError(`dy must be a number.`);if(!Number.isFinite(h)||h<0)throw TypeError(`dWidth must be a non-negative number.`);if(!Number.isFinite(g)||g<0)throw TypeError(`dHeight must be a non-negative number.`);if(this._closed)throw Error(`VideoSample is closed.`);({sx:l,sy:u,sWidth:d,sHeight:f}=this._rotateSourceRegion(l,u,d,f,this.rotation));let _=this.toCanvasImageSource();e.save();let v=p+h/2,y=m+g/2;e.translate(v,y),e.rotate(this.rotation*Math.PI/180);let b=this.rotation%180==0?1:h/g;e.scale(1/b,b),e.drawImage(_,l,u,d,f,-h/2,-g/2,h,g),e.restore()}drawWithFit(e,t){if(!(typeof CanvasRenderingContext2D<`u`&&e instanceof CanvasRenderingContext2D||typeof OffscreenCanvasRenderingContext2D<`u`&&e instanceof OffscreenCanvasRenderingContext2D))throw TypeError(`context must be a CanvasRenderingContext2D or OffscreenCanvasRenderingContext2D.`);if(!t||typeof t!=`object`)throw TypeError(`options must be an object.`);if(![`fill`,`contain`,`cover`].includes(t.fit))throw TypeError(`options.fit must be 'fill', 'contain', or 'cover'.`);if(t.rotation!==void 0&&![0,90,180,270].includes(t.rotation))throw TypeError(`options.rotation, when provided, must be 0, 90, 180, or 270.`);t.crop!==void 0&&Wo(t.crop,`options.`);let n=e.canvas.width,r=e.canvas.height,i=t.rotation??this.rotation,[a,o]=i%180==0?[this.squarePixelWidth,this.squarePixelHeight]:[this.squarePixelHeight,this.squarePixelWidth];t.crop&&Uo(t.crop,a,o);let s,c,l,u,{sx:d,sy:f,sWidth:p,sHeight:m}=this._rotateSourceRegion(t.crop?.left??0,t.crop?.top??0,t.crop?.width??a,t.crop?.height??o,i);if(t.fit===`fill`)s=0,c=0,l=n,u=r;else{let[e,i]=t.crop?[t.crop.width,t.crop.height]:[a,o],d=t.fit===`contain`?Math.min(n/e,r/i):Math.max(n/e,r/i);l=e*d,u=i*d,s=(n-l)/2,c=(r-u)/2}e.save();let h=i%180==0?1:l/u;e.translate(n/2,r/2),e.rotate(i*Math.PI/180),e.scale(1/h,h),e.translate(-n/2,-r/2),e.drawImage(this.toCanvasImageSource(),d,f,p,m,s,c,l,u),e.restore()}_rotateSourceRegion(e,t,n,r,i){return i===90?[e,t,n,r]=[t,this.squarePixelHeight-e-n,r,n]:i===180?[e,t]=[this.squarePixelWidth-e-n,this.squarePixelHeight-t-r]:i===270&&([e,t,n,r]=[this.squarePixelWidth-t-r,e,r,n]),{sx:e,sy:t,sWidth:n,sHeight:r}}toCanvasImageSource(){if(this._closed)throw Error(`VideoSample is closed.`);if(I(this._data!==null),this._data instanceof Uint8Array){let e=this.toVideoFrame();return queueMicrotask(()=>e.close()),e}else return this._data}setRotation(e){if(![0,90,180,270].includes(e))throw TypeError(`newRotation must be 0, 90, 180, or 270.`);this.rotation=e}setTimestamp(e){if(!Number.isFinite(e))throw TypeError(`newTimestamp must be a number.`);this.timestamp=e}setDuration(e){if(!Number.isFinite(e)||e<0)throw TypeError(`newDuration must be a non-negative number.`);this.duration=e}[Symbol.dispose](){this.close()}},Vo=class{constructor(e){if(e!==void 0){if(!e||typeof e!=`object`)throw TypeError(`init.colorSpace, when provided, must be an object.`);let t=Object.keys(Br);if(e.primaries!=null&&!t.includes(e.primaries))throw TypeError(`init.colorSpace.primaries, when provided, must be one of ${t.join(`, `)}.`);let n=Object.keys(Hr);if(e.transfer!=null&&!n.includes(e.transfer))throw TypeError(`init.colorSpace.transfer, when provided, must be one of ${n.join(`, `)}.`);let r=Object.keys(Wr);if(e.matrix!=null&&!r.includes(e.matrix))throw TypeError(`init.colorSpace.matrix, when provided, must be one of ${r.join(`, `)}.`);if(e.fullRange!=null&&typeof e.fullRange!=`boolean`)throw TypeError(`init.colorSpace.fullRange, when provided, must be a boolean.`)}this.primaries=e?.primaries??null,this.transfer=e?.transfer??null,this.matrix=e?.matrix??null,this.fullRange=e?.fullRange??null}toJSON(){return{primaries:this.primaries,transfer:this.transfer,matrix:this.matrix,fullRange:this.fullRange}}},Ho=e=>typeof VideoFrame<`u`&&e instanceof VideoFrame,Uo=(e,t,n)=>{e.left=Math.min(e.left,t),e.top=Math.min(e.top,n),e.width=Math.min(e.width,t-e.left),e.height=Math.min(e.height,n-e.top),I(e.width>=0),I(e.height>=0)},Wo=(e,t)=>{if(!e||typeof e!=`object`)throw TypeError(t+`crop, when provided, must be an object.`);if(!Number.isInteger(e.left)||e.left<0)throw TypeError(t+`crop.left must be a non-negative integer.`);if(!Number.isInteger(e.top)||e.top<0)throw TypeError(t+`crop.top must be a non-negative integer.`);if(!Number.isInteger(e.width)||e.width<0)throw TypeError(t+`crop.width must be a non-negative integer.`);if(!Number.isInteger(e.height)||e.height<0)throw TypeError(t+`crop.height must be a non-negative integer.`)},Go=e=>{if(!e||typeof e!=`object`)throw TypeError(`options must be an object.`);if(e.colorSpace!==void 0&&![`display-p3`,`srgb`].includes(e.colorSpace))throw TypeError(`options.colorSpace, when provided, must be 'display-p3' or 'srgb'.`);if(e.format!==void 0&&typeof e.format!=`string`)throw TypeError(`options.format, when provided, must be a string.`);if(e.layout!==void 0){if(!Array.isArray(e.layout))throw TypeError(`options.layout, when provided, must be an array.`);for(let t of e.layout){if(!t||typeof t!=`object`)throw TypeError(`Each entry in options.layout must be an object.`);if(!Number.isInteger(t.offset)||t.offset<0)throw TypeError(`plane.offset must be a non-negative integer.`);if(!Number.isInteger(t.stride)||t.stride<0)throw TypeError(`plane.stride must be a non-negative integer.`)}}if(e.rect!==void 0){if(!e.rect||typeof e.rect!=`object`)throw TypeError(`options.rect, when provided, must be an object.`);if(e.rect.x!==void 0&&(!Number.isInteger(e.rect.x)||e.rect.x<0))throw TypeError(`options.rect.x, when provided, must be a non-negative integer.`);if(e.rect.y!==void 0&&(!Number.isInteger(e.rect.y)||e.rect.y<0))throw TypeError(`options.rect.y, when provided, must be a non-negative integer.`);if(e.rect.width!==void 0&&(!Number.isInteger(e.rect.width)||e.rect.width<0))throw TypeError(`options.rect.width, when provided, must be a non-negative integer.`);if(e.rect.height!==void 0&&(!Number.isInteger(e.rect.height)||e.rect.height<0))throw TypeError(`options.rect.height, when provided, must be a non-negative integer.`)}},Ko=(e,t,n)=>{let r=qo(e),i=[],a=0;for(let e of r){let r=Math.ceil(t/e.widthDivisor),o=Math.ceil(n/e.heightDivisor),s=r*e.sampleBytes,c=s*o;i.push({offset:a,stride:s}),a+=c}return i},qo=e=>{let t=(e,t,n,r,i)=>{let a=[{sampleBytes:e,widthDivisor:1,heightDivisor:1},{sampleBytes:t,widthDivisor:n,heightDivisor:r},{sampleBytes:t,widthDivisor:n,heightDivisor:r}];return i&&a.push({sampleBytes:e,widthDivisor:1,heightDivisor:1}),a};switch(e){case`I420`:return t(1,1,2,2,!1);case`I420P10`:case`I420P12`:return t(2,2,2,2,!1);case`I420A`:return t(1,1,2,2,!0);case`I420AP10`:case`I420AP12`:return t(2,2,2,2,!0);case`I422`:return t(1,1,2,1,!1);case`I422P10`:case`I422P12`:return t(2,2,2,1,!1);case`I422A`:return t(1,1,2,1,!0);case`I422AP10`:case`I422AP12`:return t(2,2,2,1,!0);case`I444`:return t(1,1,1,1,!1);case`I444P10`:case`I444P12`:return t(2,2,1,1,!1);case`I444A`:return t(1,1,1,1,!0);case`I444AP10`:case`I444AP12`:return t(2,2,1,1,!0);case`NV12`:return[{sampleBytes:1,widthDivisor:1,heightDivisor:1},{sampleBytes:2,widthDivisor:2,heightDivisor:2}];case`RGBA`:case`RGBX`:case`BGRA`:case`BGRX`:return[{sampleBytes:4,widthDivisor:1,heightDivisor:1}];default:ii(e),I(!1)}},Jo=new Set([`f32`,`f32-planar`,`s16`,`s16-planar`,`s32`,`s32-planar`,`u8`,`u8-planar`]),Yo=class e{get microsecondTimestamp(){return Math.trunc(_i*this.timestamp)}get microsecondDuration(){return Math.trunc(_i*this.duration)}constructor(e){if(this._closed=!1,es(e)){if(e.format===null)throw TypeError(`AudioData with null format is not supported.`);this._data=e,this.format=e.format,this.sampleRate=e.sampleRate,this.numberOfFrames=e.numberOfFrames,this.numberOfChannels=e.numberOfChannels,this.timestamp=e.timestamp/1e6,this.duration=e.numberOfFrames/e.sampleRate}else{if(!e||typeof e!=`object`)throw TypeError(`Invalid AudioDataInit: must be an object.`);if(!Jo.has(e.format))throw TypeError(`Invalid AudioDataInit: invalid format.`);if(!Number.isFinite(e.sampleRate)||e.sampleRate<=0)throw TypeError(`Invalid AudioDataInit: sampleRate must be > 0.`);if(!Number.isInteger(e.numberOfChannels)||e.numberOfChannels===0)throw TypeError(`Invalid AudioDataInit: numberOfChannels must be an integer > 0.`);if(!Number.isFinite(e?.timestamp))throw TypeError(`init.timestamp must be a number.`);let t=e.data.byteLength/(Xo(e.format)*e.numberOfChannels);if(!Number.isInteger(t))throw TypeError(`Invalid AudioDataInit: data size is not a multiple of frame size.`);this.format=e.format,this.sampleRate=e.sampleRate,this.numberOfFrames=t,this.numberOfChannels=e.numberOfChannels,this.timestamp=e.timestamp,this.duration=t/e.sampleRate;let n;if(e.data instanceof ArrayBuffer)n=new Uint8Array(e.data);else if(ArrayBuffer.isView(e.data))n=new Uint8Array(e.data.buffer,e.data.byteOffset,e.data.byteLength);else throw TypeError(`Invalid AudioDataInit: data is not a BufferSource.`);let r=this.numberOfFrames*this.numberOfChannels*Xo(this.format);if(n.byteLength<r)throw TypeError(`Invalid AudioDataInit: insufficient data size.`);this._data=n}Lo?.register(this,{type:`audio`,data:this._data},this)}allocationSize(e){if(!e||typeof e!=`object`)throw TypeError(`options must be an object.`);if(!Number.isInteger(e.planeIndex)||e.planeIndex<0)throw TypeError(`planeIndex must be a non-negative integer.`);if(e.format!==void 0&&!Jo.has(e.format))throw TypeError(`Invalid format.`);if(e.frameOffset!==void 0&&(!Number.isInteger(e.frameOffset)||e.frameOffset<0))throw TypeError(`frameOffset must be a non-negative integer.`);if(e.frameCount!==void 0&&(!Number.isInteger(e.frameCount)||e.frameCount<0))throw TypeError(`frameCount must be a non-negative integer.`);if(this._closed)throw Error(`AudioSample is closed.`);let t=e.format??this.format,n=e.frameOffset??0;if(n>=this.numberOfFrames)throw RangeError(`frameOffset out of range`);let r=e.frameCount===void 0?this.numberOfFrames-n:e.frameCount;if(r>this.numberOfFrames-n)throw RangeError(`frameCount out of range`);let i=Xo(t),a=Zo(t);if(a&&e.planeIndex>=this.numberOfChannels||!a&&e.planeIndex!==0)throw RangeError(`planeIndex out of range`);return(a?r:r*this.numberOfChannels)*i}copyTo(e,t){if(!qr(e))throw TypeError(`destination must be an ArrayBuffer or an ArrayBuffer view.`);if(!t||typeof t!=`object`)throw TypeError(`options must be an object.`);if(!Number.isInteger(t.planeIndex)||t.planeIndex<0)throw TypeError(`planeIndex must be a non-negative integer.`);if(t.format!==void 0&&!Jo.has(t.format))throw TypeError(`Invalid format.`);if(t.frameOffset!==void 0&&(!Number.isInteger(t.frameOffset)||t.frameOffset<0))throw TypeError(`frameOffset must be a non-negative integer.`);if(t.frameCount!==void 0&&(!Number.isInteger(t.frameCount)||t.frameCount<0))throw TypeError(`frameCount must be a non-negative integer.`);if(this._closed)throw Error(`AudioSample is closed.`);let{planeIndex:n,format:r,frameCount:i,frameOffset:a}=t,o=this.format,s=r??this.format;if(!s)throw Error(`Destination format not determined`);let c=this.numberOfFrames,l=this.numberOfChannels,u=a??0;if(u>=c)throw RangeError(`frameOffset out of range`);let d=i===void 0?c-u:i;if(d>c-u)throw RangeError(`frameCount out of range`);let f=Xo(s),p=Zo(s);if(p&&n>=l||!p&&n!==0)throw RangeError(`planeIndex out of range`);let m=(p?d:d*l)*f;if(e.byteLength<m)throw RangeError(`Destination buffer is too small`);let h=z(e),g=$o(s);if(es(this._data))xi()&&l>2&&s!==o?ts(this._data,h,o,s,l,n,u,d):this._data.copyTo(e,{planeIndex:n,frameOffset:u,frameCount:d,format:s});else{let e=this._data,t=z(e),r=Qo(o),i=Xo(o),a=Zo(o);for(let e=0;e<d;e++)if(p){let o=e*f,s;s=a?(n*c+(e+u))*i:((e+u)*l+n)*i,g(h,o,r(t,s))}else for(let n=0;n<l;n++){let o=(e*l+n)*f,s;s=a?(n*c+(e+u))*i:((e+u)*l+n)*i,g(h,o,r(t,s))}}}clone(){if(this._closed)throw Error(`AudioSample is closed.`);if(es(this._data)){let t=new e(this._data.clone());return t.setTimestamp(this.timestamp),t}else return new e({format:this.format,sampleRate:this.sampleRate,numberOfFrames:this.numberOfFrames,numberOfChannels:this.numberOfChannels,timestamp:this.timestamp,data:this._data})}close(){this._closed||=(Lo?.unregister(this),es(this._data)?this._data.close():this._data=new Uint8Array,!0)}toAudioData(){if(this._closed)throw Error(`AudioSample is closed.`);if(es(this._data)){if(this._data.timestamp===this.microsecondTimestamp)return this._data.clone();if(Zo(this.format)){let e=this.allocationSize({planeIndex:0,format:this.format}),t=new ArrayBuffer(e*this.numberOfChannels);for(let n=0;n<this.numberOfChannels;n++)this.copyTo(new Uint8Array(t,n*e,e),{planeIndex:n,format:this.format});return new AudioData({format:this.format,sampleRate:this.sampleRate,numberOfFrames:this.numberOfFrames,numberOfChannels:this.numberOfChannels,timestamp:this.microsecondTimestamp,data:t})}else{let e=new ArrayBuffer(this.allocationSize({planeIndex:0,format:this.format}));return this.copyTo(e,{planeIndex:0,format:this.format}),new AudioData({format:this.format,sampleRate:this.sampleRate,numberOfFrames:this.numberOfFrames,numberOfChannels:this.numberOfChannels,timestamp:this.microsecondTimestamp,data:e})}}else return new AudioData({format:this.format,sampleRate:this.sampleRate,numberOfFrames:this.numberOfFrames,numberOfChannels:this.numberOfChannels,timestamp:this.microsecondTimestamp,data:this._data.buffer instanceof ArrayBuffer?this._data.buffer:this._data.slice()})}toAudioBuffer(){if(this._closed)throw Error(`AudioSample is closed.`);let e=new AudioBuffer({numberOfChannels:this.numberOfChannels,length:this.numberOfFrames,sampleRate:this.sampleRate}),t=new Float32Array(this.allocationSize({planeIndex:0,format:`f32-planar`})/4);for(let n=0;n<this.numberOfChannels;n++)this.copyTo(t,{planeIndex:n,format:`f32-planar`}),e.copyToChannel(t,n);return e}setTimestamp(e){if(!Number.isFinite(e))throw TypeError(`newTimestamp must be a number.`);this.timestamp=e}[Symbol.dispose](){this.close()}static*_fromAudioBuffer(t,n){if(!(t instanceof AudioBuffer))throw TypeError(`audioBuffer must be an AudioBuffer.`);let r=t.numberOfChannels,i=t.sampleRate,a=t.length,o=Math.floor(24e4/r),s=0,c=a;for(;c>0;){let a=Math.min(o,c),l=new Float32Array(r*a);for(let e=0;e<r;e++)t.copyFromChannel(l.subarray(e*a,(e+1)*a),e,s);yield new e({format:`f32-planar`,sampleRate:i,numberOfFrames:a,numberOfChannels:r,timestamp:n+s/i,data:l}),s+=a,c-=a}}static fromAudioBuffer(t,n){if(!(t instanceof AudioBuffer))throw TypeError(`audioBuffer must be an AudioBuffer.`);let r=t.numberOfChannels,i=t.sampleRate,a=t.length,o=Math.floor(24e4/r),s=0,c=a,l=[];for(;c>0;){let a=Math.min(o,c),u=new Float32Array(r*a);for(let e=0;e<r;e++)t.copyFromChannel(u.subarray(e*a,(e+1)*a),e,s);let d=new e({format:`f32-planar`,sampleRate:i,numberOfFrames:a,numberOfChannels:r,timestamp:n+s/i,data:u});l.push(d),s+=a,c-=a}return l}},Xo=e=>{switch(e){case`u8`:case`u8-planar`:return 1;case`s16`:case`s16-planar`:return 2;case`s32`:case`s32-planar`:return 4;case`f32`:case`f32-planar`:return 4;default:throw Error(`Unknown AudioSampleFormat`)}},Zo=e=>{switch(e){case`u8-planar`:case`s16-planar`:case`s32-planar`:case`f32-planar`:return!0;default:return!1}},Qo=e=>{switch(e){case`u8`:case`u8-planar`:return(e,t)=>(e.getUint8(t)-128)/128;case`s16`:case`s16-planar`:return(e,t)=>e.getInt16(t,!0)/32768;case`s32`:case`s32-planar`:return(e,t)=>e.getInt32(t,!0)/2147483648;case`f32`:case`f32-planar`:return(e,t)=>e.getFloat32(t,!0)}},$o=e=>{switch(e){case`u8`:case`u8-planar`:return(e,t,n)=>e.setUint8(t,ui((n+1)*127.5,0,255));case`s16`:case`s16-planar`:return(e,t,n)=>e.setInt16(t,ui(Math.round(n*32767),-32768,32767),!0);case`s32`:case`s32-planar`:return(e,t,n)=>e.setInt32(t,ui(Math.round(n*2147483647),-2147483648,2147483647),!0);case`f32`:case`f32-planar`:return(e,t,n)=>e.setFloat32(t,n,!0)}},es=e=>typeof AudioData<`u`&&e instanceof AudioData,ts=(e,t,n,r,i,a,o,s)=>{let c=Qo(n),l=$o(r),u=Xo(n),d=Xo(r),f=Zo(n);if(Zo(r))if(f){let r=new ArrayBuffer(s*u),i=z(r);e.copyTo(r,{planeIndex:a,frameOffset:o,frameCount:s,format:n});for(let e=0;e<s;e++){let n=e*u;l(t,e*d,c(i,n))}}else{let r=new ArrayBuffer(s*i*u),f=z(r);e.copyTo(r,{planeIndex:0,frameOffset:o,frameCount:s,format:n});for(let e=0;e<s;e++){let n=(e*i+a)*u;l(t,e*d,c(f,n))}}else if(f){let r=s*u,a=new ArrayBuffer(r),f=z(a);for(let r=0;r<i;r++){e.copyTo(a,{planeIndex:r,frameOffset:o,frameCount:s,format:n});for(let e=0;e<s;e++){let n=e*u;l(t,(e*i+r)*d,c(f,n))}}}else{let r=new ArrayBuffer(s*i*u),a=z(r);e.copyTo(r,{planeIndex:0,frameOffset:o,frameCount:s,format:n});for(let e=0;e<s;e++)for(let n=0;n<i;n++){let r=e*i+n,o=r*u;l(t,r*d,c(a,o))}}},ns=e=>{if(!e||typeof e!=`object`)throw TypeError(`options must be an object.`);if(e.metadataOnly!==void 0&&typeof e.metadataOnly!=`boolean`)throw TypeError(`options.metadataOnly, when defined, must be a boolean.`);if(e.verifyKeyPackets!==void 0&&typeof e.verifyKeyPackets!=`boolean`)throw TypeError(`options.verifyKeyPackets, when defined, must be a boolean.`);if(e.verifyKeyPackets&&e.metadataOnly)throw TypeError(`options.verifyKeyPackets and options.metadataOnly cannot be enabled together.`)},rs=e=>{if(!Ni(e))throw TypeError(`timestamp must be a number.`)},is=(e,t,n)=>n.verifyKeyPackets?t.then(async t=>{if(!t||t.type===`delta`)return t;let n=await e.determinePacketType(t);return n&&(t.type=n),t}):t,as=class{constructor(e){if(!(e instanceof gs))throw TypeError(`track must be an InputTrack.`);this._track=e}getFirstPacket(e={}){if(ns(e),this._track.input._disposed)throw new Tl;return is(this._track,this._track._backing.getFirstPacket(e),e)}async getFirstKeyPacket(e={}){ns(e);let t=await this.getFirstPacket(e);return t?t.type===`key`?t:this.getNextKeyPacket(t,e):null}getPacket(e,t={}){if(rs(e),ns(t),this._track.input._disposed)throw new Tl;return is(this._track,this._track._backing.getPacket(e,t),t)}getNextPacket(e,t={}){if(!(e instanceof H))throw TypeError(`packet must be an EncodedPacket.`);if(ns(t),this._track.input._disposed)throw new Tl;return is(this._track,this._track._backing.getNextPacket(e,t),t)}async getKeyPacket(e,t={}){if(rs(e),ns(t),this._track.input._disposed)throw new Tl;if(!t.verifyKeyPackets)return this._track._backing.getKeyPacket(e,t);let n=await this._track._backing.getKeyPacket(e,t);return n&&(I(n.type===`key`),await this._track.determinePacketType(n)===`delta`?this.getKeyPacket(n.timestamp-1/this._track.timeResolution,t):n)}async getNextKeyPacket(e,t={}){if(!(e instanceof H))throw TypeError(`packet must be an EncodedPacket.`);if(ns(t),this._track.input._disposed)throw new Tl;if(!t.verifyKeyPackets)return this._track._backing.getNextKeyPacket(e,t);let n=await this._track._backing.getNextKeyPacket(e,t);return n&&(I(n.type===`key`),await this._track.determinePacketType(n)===`delta`?this.getNextKeyPacket(n,t):n)}packets(e,t,n={}){if(e!==void 0&&!(e instanceof H))throw TypeError(`startPacket must be an EncodedPacket.`);if(e!==void 0&&e.isMetadataOnly&&!n?.metadataOnly)throw TypeError(`startPacket can only be metadata-only if options.metadataOnly is enabled.`);if(t!==void 0&&!(t instanceof H))throw TypeError(`endPacket must be an EncodedPacket.`);if(ns(n),this._track.input._disposed)throw new Tl;let r=[],{promise:i,resolve:a}=$r(),{promise:o,resolve:s}=$r(),c=!1,l=!1,u=null,d=[],f=()=>Math.max(2,d.length);(async()=>{let u=e??await this.getFirstPacket(n);for(;u&&!l&&!this._track.input._disposed&&!(t&&u.sequenceNumber>=t?.sequenceNumber);){if(r.length>f()){({promise:o,resolve:s}=$r()),await o;continue}r.push(u),a(),{promise:i,resolve:a}=$r(),u=await this.getNextPacket(u,n)}c=!0,a()})().catch(e=>{u||(u=e,a())});let p=this._track;return{async next(){for(;;)if(p.input._disposed)throw new Tl;else if(l)return{value:void 0,done:!0};else if(u)throw u;else if(r.length>0){let e=r.shift(),t=performance.now();for(d.push(t);d.length>0&&t-d[0]>=1e3;)d.shift();return s(),{value:e,done:!1}}else if(c)return{value:void 0,done:!0};else await i},async return(){return l=!0,s(),a(),{value:void 0,done:!0}},async throw(e){throw e},[Symbol.asyncIterator](){return this}}}},os=class{constructor(e,t){this.onSample=e,this.onError=t}},ss=class{mediaSamplesInRange(e=0,t=1/0){rs(e),rs(t);let n=[],r=!1,i=null,{promise:a,resolve:o}=$r(),{promise:s,resolve:c}=$r(),l=!1,u=!1,d=!1,f=null;(async()=>{let p=await this._createDecoder(s=>{if(c(),s.timestamp>=t&&(u=!0),u){s.close();return}i&&(s.timestamp>e?(n.push(i),r=!0):i.close()),s.timestamp>=e&&(n.push(s),r=!0),i=r?null:s,n.length>0&&(o(),{promise:a,resolve:o}=$r())},e=>{f||(f=e,o())}),m=this._createPacketSink(),h=await m.getKeyPacket(e,{verifyKeyPackets:!0})??await m.getFirstKeyPacket({verifyKeyPackets:!0}),g=h,_=m.packets(h??void 0,void 0);for(await _.next();g&&!u&&!this._track.input._disposed;){let e=cs(n.length);if(n.length+p.getDecodeQueueSize()>e){({promise:s,resolve:c}=$r()),await s;continue}p.decode(g);let t=await _.next();if(t.done)break;g=t.value}await _.return(),!d&&!this._track.input._disposed&&await p.flush(),p.close(),!r&&i&&n.push(i),l=!0,o()})().catch(e=>{f||(f=e,o())});let p=this._track,m=()=>{i?.close();for(let e of n)e.close()};return{async next(){for(;;)if(p.input._disposed)throw m(),new Tl;else if(d)return{value:void 0,done:!0};else if(f)throw m(),f;else if(n.length>0){let e=n.shift();return c(),{value:e,done:!1}}else if(!l)await a;else return{value:void 0,done:!0}},async return(){return d=!0,u=!0,c(),o(),m(),{value:void 0,done:!0}},async throw(e){throw e},[Symbol.asyncIterator](){return this}}}mediaSamplesAtTimestamps(e){ri(e);let t=ni(e),n=[],r=[],{promise:i,resolve:a}=$r(),{promise:o,resolve:s}=$r(),c=!1,l=!1,u=null,d=e=>{r.push(e),a(),{promise:i,resolve:a}=$r()};(async()=>{let e=await this._createDecoder(e=>{if(s(),l){e.close();return}let t=0;for(;n.length>0&&e.timestamp-n[0]>-1e-10;)t++,n.shift();if(t>0)for(let n=0;n<t;n++)d(n<t-1?e.clone():e);else e.close()},e=>{u||(u=e,a())}),i=this._createPacketSink(),f=null,p=null,m=-1,h=async()=>{I(p);let t=p;for(e.decode(t);t.sequenceNumber<m;){let n=cs(r.length);for(;r.length+e.getDecodeQueueSize()>n&&!l;)({promise:o,resolve:s}=$r()),await o;if(l)break;let a=await i.getNextPacket(t);I(a),e.decode(a),t=a}m=-1},g=async()=>{await e.flush();for(let e=0;e<n.length;e++)d(null);n.length=0};for await(let e of t){if(rs(e),l||this._track.input._disposed)break;let t=await i.getPacket(e),r=t&&await i.getKeyPacket(e,{verifyKeyPackets:!0});if(!r){m!==-1&&(await h(),await g()),d(null),f=null;continue}f&&(r.sequenceNumber!==p.sequenceNumber||t.timestamp<f.timestamp)&&(await h(),await g()),n.push(t.timestamp),m=Math.max(t.sequenceNumber,m),f=t,p=r}!l&&!this._track.input._disposed&&(m!==-1&&await h(),await g()),e.close(),c=!0,a()})().catch(e=>{u||(u=e,a())});let f=this._track,p=()=>{for(let e of r)e?.close()};return{async next(){for(;;)if(f.input._disposed)throw p(),new Tl;else if(l)return{value:void 0,done:!0};else if(u)throw p(),u;else if(r.length>0){let e=r.shift();return I(e!==void 0),s(),{value:e,done:!1}}else if(!c)await i;else return{value:void 0,done:!0}},async return(){return l=!0,s(),a(),p(),{value:void 0,done:!0}},async throw(e){throw e},[Symbol.asyncIterator](){return this}}}},cs=e=>e===0?40:8,ls=class extends os{constructor(e,t,n,r,i,a){super(e,t),this.codec=n,this.decoderConfig=r,this.rotation=i,this.timeResolution=a,this.decoder=null,this.customDecoder=null,this.customDecoderCallSerializer=new yi,this.customDecoderQueueSize=0,this.inputTimestamps=[],this.sampleQueue=[],this.currentPacketIndex=0,this.raslSkipped=!1,this.alphaDecoder=null,this.alphaHadKeyframe=!1,this.colorQueue=[],this.alphaQueue=[],this.merger=null,this.mergerCreationFailed=!1,this.decodedAlphaChunkCount=0,this.alphaDecoderQueueSize=0,this.nullAlphaFrameQueue=[],this.currentAlphaPacketIndex=0,this.alphaRaslSkipped=!1;let o=Eo.find(e=>e.supports(n,r));if(o)this.customDecoder=new o,this.customDecoder.codec=n,this.customDecoder.config=r,this.customDecoder.onSample=e=>{if(!(e instanceof Bo))throw TypeError(`The argument passed to onSample must be a VideoSample.`);this.finalizeAndEmitSample(e)},this.customDecoderCallSerializer.call(()=>this.customDecoder.init());else{let e=e=>{if(this.alphaQueue.length>0){let t=this.alphaQueue.shift();I(t!==void 0),this.mergeAlpha(e,t)}else this.colorQueue.push(e)};if(n===`avc`&&this.decoderConfig.description&&Ti()){let e=Ua(Ir(this.decoderConfig.description));if(e&&e.sequenceParameterSets.length>0){let t=Ga(e.sequenceParameterSets[0]);t&&t.frameMbsOnlyFlag===0&&(this.decoderConfig={...this.decoderConfig,hardwareAcceleration:`prefer-software`})}}let t=Error(`Decoding error`).stack;this.decoder=new VideoDecoder({output:t=>{try{e(t)}catch(e){this.onError(e)}},error:e=>{e.stack=t,this.onError(e)}}),this.decoder.configure(this.decoderConfig)}}getDecodeQueueSize(){return this.customDecoder?this.customDecoderQueueSize:(I(this.decoder),Math.max(this.decoder.decodeQueueSize,this.alphaDecoder?.decodeQueueSize??0))}decode(e){if(this.codec===`hevc`&&this.currentPacketIndex>0&&!this.raslSkipped){if(this.hasHevcRaslPicture(e.data))return;this.raslSkipped=!0}if(this.customDecoder)this.customDecoderQueueSize++,this.customDecoderCallSerializer.call(()=>this.customDecoder.decode(e)).then(()=>this.customDecoderQueueSize--);else{if(I(this.decoder),xi()||Qr(this.inputTimestamps,e.timestamp,e=>e),Ti()&&this.currentPacketIndex===0&&this.codec===`avc`){let t=[];for(let n of Pa(e.data,this.decoderConfig)){let r=Fa(e.data[n.offset]);r>=20&&r<=31||t.push(e.data.subarray(n.offset,n.offset+n.length))}e=new H(Ba(t,this.decoderConfig),e.type,e.timestamp,e.duration)}this.decoder.decode(e.toEncodedVideoChunk()),this.decodeAlphaData(e)}this.currentPacketIndex++}decodeAlphaData(e){if(!e.sideData.alpha||this.mergerCreationFailed){this.pushNullAlphaFrame();return}if(!this.merger)try{this.merger=new us}catch(t){console.error(`Due to an error, only color data will be decoded.`,t),this.mergerCreationFailed=!0,this.decodeAlphaData(e);return}if(!this.alphaDecoder){let e=e=>{if(this.alphaDecoderQueueSize--,this.colorQueue.length>0){let t=this.colorQueue.shift();I(t!==void 0),this.mergeAlpha(t,e)}else this.alphaQueue.push(e);for(this.decodedAlphaChunkCount++;this.nullAlphaFrameQueue.length>0&&this.nullAlphaFrameQueue[0]===this.decodedAlphaChunkCount;)if(this.nullAlphaFrameQueue.shift(),this.colorQueue.length>0){let e=this.colorQueue.shift();I(e!==void 0),this.mergeAlpha(e,null)}else this.alphaQueue.push(null)},t=Error(`Decoding error`).stack;this.alphaDecoder=new VideoDecoder({output:t=>{try{e(t)}catch(e){this.onError(e)}},error:e=>{e.stack=t,this.onError(e)}}),this.alphaDecoder.configure(this.decoderConfig)}let t=po(this.codec,this.decoderConfig,e.sideData.alpha);if(this.alphaHadKeyframe||=t===`key`,this.alphaHadKeyframe){if(this.codec===`hevc`&&this.currentAlphaPacketIndex>0&&!this.alphaRaslSkipped){if(this.hasHevcRaslPicture(e.sideData.alpha)){this.pushNullAlphaFrame();return}this.alphaRaslSkipped=!0}this.currentAlphaPacketIndex++,this.alphaDecoder.decode(e.alphaToEncodedVideoChunk(t??e.type)),this.alphaDecoderQueueSize++}else this.pushNullAlphaFrame()}pushNullAlphaFrame(){this.alphaDecoderQueueSize===0?this.alphaQueue.push(null):this.nullAlphaFrameQueue.push(this.decodedAlphaChunkCount+this.alphaDecoderQueueSize)}hasHevcRaslPicture(e){for(let t of qa(e,this.decoderConfig)){let n=Ja(e[t.offset]);if(n===ja.RASL_N||n===ja.RASL_R)return!0}return!1}sampleHandler(e){if(xi()){if(this.sampleQueue.length>0&&e.timestamp>=L(this.sampleQueue).timestamp){for(let e of this.sampleQueue)this.finalizeAndEmitSample(e);this.sampleQueue.length=0}Qr(this.sampleQueue,e,e=>e.timestamp)}else{let t=this.inputTimestamps.shift();I(t!==void 0),e.setTimestamp(t),this.finalizeAndEmitSample(e)}}finalizeAndEmitSample(e){e.setTimestamp(Math.round(e.timestamp*this.timeResolution)/this.timeResolution),e.setDuration(Math.round(e.duration*this.timeResolution)/this.timeResolution),e.setRotation(this.rotation),this.onSample(e)}mergeAlpha(e,t){if(!t){let t=new Bo(e);this.sampleHandler(t);return}I(this.merger),this.merger.update(e,t),e.close(),t.close();let n=new Bo(new VideoFrame(this.merger.canvas,{timestamp:e.timestamp,duration:e.duration??void 0}));this.sampleHandler(n)}async flush(){if(this.customDecoder?await this.customDecoderCallSerializer.call(()=>this.customDecoder.flush()):(I(this.decoder),await Promise.all([this.decoder.flush(),this.alphaDecoder?.flush()]),this.colorQueue.forEach(e=>e.close()),this.colorQueue.length=0,this.alphaQueue.forEach(e=>e?.close()),this.alphaQueue.length=0,this.alphaHadKeyframe=!1,this.decodedAlphaChunkCount=0,this.alphaDecoderQueueSize=0,this.nullAlphaFrameQueue.length=0,this.currentAlphaPacketIndex=0,this.alphaRaslSkipped=!1),xi()){for(let e of this.sampleQueue)this.finalizeAndEmitSample(e);this.sampleQueue.length=0}this.currentPacketIndex=0,this.raslSkipped=!1}close(){this.customDecoder?this.customDecoderCallSerializer.call(()=>this.customDecoder.close()):(I(this.decoder),this.decoder.close(),this.alphaDecoder?.close(),this.colorQueue.forEach(e=>e.close()),this.colorQueue.length=0,this.alphaQueue.forEach(e=>e?.close()),this.alphaQueue.length=0,this.merger?.close());for(let e of this.sampleQueue)e.close();this.sampleQueue.length=0}},us=class{constructor(){typeof OffscreenCanvas<`u`?this.canvas=new OffscreenCanvas(300,150):this.canvas=document.createElement(`canvas`);let e=this.canvas.getContext(`webgl2`,{premultipliedAlpha:!1});if(!e)throw Error(`Couldn't acquire WebGL 2 context.`);this.gl=e,this.program=this.createProgram(),this.vao=this.createVAO(),this.colorTexture=this.createTexture(),this.alphaTexture=this.createTexture(),this.gl.useProgram(this.program),this.gl.uniform1i(this.gl.getUniformLocation(this.program,`u_colorTexture`),0),this.gl.uniform1i(this.gl.getUniformLocation(this.program,`u_alphaTexture`),1)}createProgram(){let e=this.createShader(this.gl.VERTEX_SHADER,`#version 300 es
1377
+ in vec2 a_position;
1378
+ in vec2 a_texCoord;
1379
+ out vec2 v_texCoord;
1380
+
1381
+ void main() {
1382
+ gl_Position = vec4(a_position, 0.0, 1.0);
1383
+ v_texCoord = a_texCoord;
1384
+ }
1385
+ `),t=this.createShader(this.gl.FRAGMENT_SHADER,`#version 300 es
1386
+ precision highp float;
1387
+
1388
+ uniform sampler2D u_colorTexture;
1389
+ uniform sampler2D u_alphaTexture;
1390
+ in vec2 v_texCoord;
1391
+ out vec4 fragColor;
1392
+
1393
+ void main() {
1394
+ vec3 color = texture(u_colorTexture, v_texCoord).rgb;
1395
+ float alpha = texture(u_alphaTexture, v_texCoord).r;
1396
+ fragColor = vec4(color, alpha);
1397
+ }
1398
+ `),n=this.gl.createProgram();return this.gl.attachShader(n,e),this.gl.attachShader(n,t),this.gl.linkProgram(n),n}createShader(e,t){let n=this.gl.createShader(e);return this.gl.shaderSource(n,t),this.gl.compileShader(n),n}createVAO(){let e=this.gl.createVertexArray();this.gl.bindVertexArray(e);let t=new Float32Array([-1,-1,0,1,1,-1,1,1,-1,1,0,0,1,1,1,0]),n=this.gl.createBuffer();this.gl.bindBuffer(this.gl.ARRAY_BUFFER,n),this.gl.bufferData(this.gl.ARRAY_BUFFER,t,this.gl.STATIC_DRAW);let r=this.gl.getAttribLocation(this.program,`a_position`),i=this.gl.getAttribLocation(this.program,`a_texCoord`);return this.gl.enableVertexAttribArray(r),this.gl.vertexAttribPointer(r,2,this.gl.FLOAT,!1,16,0),this.gl.enableVertexAttribArray(i),this.gl.vertexAttribPointer(i,2,this.gl.FLOAT,!1,16,8),e}createTexture(){let e=this.gl.createTexture();return this.gl.bindTexture(this.gl.TEXTURE_2D,e),this.gl.texParameteri(this.gl.TEXTURE_2D,this.gl.TEXTURE_WRAP_S,this.gl.CLAMP_TO_EDGE),this.gl.texParameteri(this.gl.TEXTURE_2D,this.gl.TEXTURE_WRAP_T,this.gl.CLAMP_TO_EDGE),this.gl.texParameteri(this.gl.TEXTURE_2D,this.gl.TEXTURE_MIN_FILTER,this.gl.LINEAR),this.gl.texParameteri(this.gl.TEXTURE_2D,this.gl.TEXTURE_MAG_FILTER,this.gl.LINEAR),e}update(e,t){(e.displayWidth!==this.canvas.width||e.displayHeight!==this.canvas.height)&&(this.canvas.width=e.displayWidth,this.canvas.height=e.displayHeight),this.gl.activeTexture(this.gl.TEXTURE0),this.gl.bindTexture(this.gl.TEXTURE_2D,this.colorTexture),this.gl.texImage2D(this.gl.TEXTURE_2D,0,this.gl.RGBA,this.gl.RGBA,this.gl.UNSIGNED_BYTE,e),this.gl.activeTexture(this.gl.TEXTURE1),this.gl.bindTexture(this.gl.TEXTURE_2D,this.alphaTexture),this.gl.texImage2D(this.gl.TEXTURE_2D,0,this.gl.RGBA,this.gl.RGBA,this.gl.UNSIGNED_BYTE,t),this.gl.viewport(0,0,this.canvas.width,this.canvas.height),this.gl.clear(this.gl.COLOR_BUFFER_BIT),this.gl.bindVertexArray(this.vao),this.gl.drawArrays(this.gl.TRIANGLE_STRIP,0,4)}close(){this.gl.getExtension(`WEBGL_lose_context`)?.loseContext(),this.gl=null}},ds=class extends ss{constructor(e){if(!(e instanceof _s))throw TypeError(`videoTrack must be an InputVideoTrack.`);super(),this._track=e}async _createDecoder(e,t){if(!await this._track.canDecode())throw Error(`This video track cannot be decoded by this browser. Make sure to check decodability before using a track.`);let n=this._track.codec,r=this._track.rotation,i=await this._track.getDecoderConfig(),a=this._track.timeResolution;return I(n&&i),new ls(e,t,n,i,r,a)}_createPacketSink(){return new as(this._track)}async getSample(e){rs(e);for await(let t of this.mediaSamplesAtTimestamps([e]))return t;throw Error(`Internal error: Iterator returned nothing.`)}samples(e=0,t=1/0){return this.mediaSamplesInRange(e,t)}samplesAtTimestamps(e){return this.mediaSamplesAtTimestamps(e)}},fs=class{constructor(e,t={}){if(this._nextCanvasIndex=0,!(e instanceof _s))throw TypeError(`videoTrack must be an InputVideoTrack.`);if(t&&typeof t!=`object`)throw TypeError(`options must be an object.`);if(t.alpha!==void 0&&typeof t.alpha!=`boolean`)throw TypeError(`options.alpha, when provided, must be a boolean.`);if(t.width!==void 0&&(!Number.isInteger(t.width)||t.width<=0))throw TypeError(`options.width, when defined, must be a positive integer.`);if(t.height!==void 0&&(!Number.isInteger(t.height)||t.height<=0))throw TypeError(`options.height, when defined, must be a positive integer.`);if(t.fit!==void 0&&![`fill`,`contain`,`cover`].includes(t.fit))throw TypeError(`options.fit, when provided, must be one of "fill", "contain", or "cover".`);if(t.width!==void 0&&t.height!==void 0&&t.fit===void 0)throw TypeError(`When both options.width and options.height are provided, options.fit must also be provided.`);if(t.rotation!==void 0&&![0,90,180,270].includes(t.rotation))throw TypeError(`options.rotation, when provided, must be 0, 90, 180 or 270.`);if(t.crop!==void 0&&Wo(t.crop,`options.`),t.poolSize!==void 0&&(typeof t.poolSize!=`number`||!Number.isInteger(t.poolSize)||t.poolSize<0))throw TypeError(`poolSize must be a non-negative integer.`);let n=t.rotation??e.rotation,[r,i]=n%180==0?[e.squarePixelWidth,e.squarePixelHeight]:[e.squarePixelHeight,e.squarePixelWidth],a=t.crop;a&&Uo(a,r,i);let[o,s]=a?[a.width,a.height]:[r,i],c=o/s;t.width!==void 0&&t.height===void 0?(o=t.width,s=Math.round(o/c)):t.width===void 0&&t.height!==void 0?(s=t.height,o=Math.round(s*c)):t.width!==void 0&&t.height!==void 0&&(o=t.width,s=t.height),this._videoTrack=e,this._alpha=t.alpha??!1,this._width=o,this._height=s,this._rotation=n,this._crop=a,this._fit=t.fit??`fill`,this._videoSampleSink=new ds(e),this._canvasPool=Array.from({length:t.poolSize??0},()=>null)}_videoSampleToWrappedCanvas(e){let t=this._canvasPool[this._nextCanvasIndex],n=!1;t||(typeof document<`u`?(t=document.createElement(`canvas`),t.width=this._width,t.height=this._height):t=new OffscreenCanvas(this._width,this._height),this._canvasPool.length>0&&(this._canvasPool[this._nextCanvasIndex]=t),n=!0),this._canvasPool.length>0&&(this._nextCanvasIndex=(this._nextCanvasIndex+1)%this._canvasPool.length);let r=t.getContext(`2d`,{alpha:this._alpha||Ci()});I(r),r.resetTransform(),n||(!this._alpha&&Ci()?(r.fillStyle=`black`,r.fillRect(0,0,this._width,this._height)):r.clearRect(0,0,this._width,this._height)),e.drawWithFit(r,{fit:this._fit,rotation:this._rotation,crop:this._crop});let i={canvas:t,timestamp:e.timestamp,duration:e.duration};return e.close(),i}async getCanvas(e){rs(e);let t=await this._videoSampleSink.getSample(e);return t&&this._videoSampleToWrappedCanvas(t)}canvases(e=0,t=1/0){return li(this._videoSampleSink.samples(e,t),e=>this._videoSampleToWrappedCanvas(e))}canvasesAtTimestamps(e){return li(this._videoSampleSink.samplesAtTimestamps(e),e=>e&&this._videoSampleToWrappedCanvas(e))}},ps=class extends os{constructor(e,t,n,r){super(e,t),this.decoder=null,this.customDecoder=null,this.customDecoderCallSerializer=new yi,this.customDecoderQueueSize=0,this.currentTimestamp=null;let i=t=>{(this.currentTimestamp===null||Math.abs(t.timestamp-this.currentTimestamp)>=t.duration)&&(this.currentTimestamp=t.timestamp);let n=this.currentTimestamp;if(this.currentTimestamp+=t.duration,t.numberOfFrames===0){t.close();return}let i=r.sampleRate;t.setTimestamp(Math.round(n*i)/i),e(t)},a=Do.find(e=>e.supports(n,r));if(a)this.customDecoder=new a,this.customDecoder.codec=n,this.customDecoder.config=r,this.customDecoder.onSample=e=>{if(!(e instanceof Yo))throw TypeError(`The argument passed to onSample must be an AudioSample.`);i(e)},this.customDecoderCallSerializer.call(()=>this.customDecoder.init());else{let e=Error(`Decoding error`).stack;this.decoder=new AudioDecoder({output:e=>{try{i(new Yo(e))}catch(e){this.onError(e)}},error:t=>{t.stack=e,this.onError(t)}}),this.decoder.configure(r)}}getDecodeQueueSize(){return this.customDecoder?this.customDecoderQueueSize:(I(this.decoder),this.decoder.decodeQueueSize)}decode(e){this.customDecoder?(this.customDecoderQueueSize++,this.customDecoderCallSerializer.call(()=>this.customDecoder.decode(e)).then(()=>this.customDecoderQueueSize--)):(I(this.decoder),this.decoder.decode(e.toEncodedAudioChunk()))}flush(){return this.customDecoder?this.customDecoderCallSerializer.call(()=>this.customDecoder.flush()):(I(this.decoder),this.decoder.flush())}close(){this.customDecoder?this.customDecoderCallSerializer.call(()=>this.customDecoder.close()):(I(this.decoder),this.decoder.close())}},ms=class extends os{constructor(e,t,n){super(e,t),this.decoderConfig=n,this.currentTimestamp=null,I(Ki.includes(n.codec)),this.codec=n.codec;let{dataType:r,sampleSize:i,littleEndian:a}=la(this.codec);switch(this.inputSampleSize=i,i){case 1:r===`unsigned`?this.readInputValue=(e,t)=>e.getUint8(t)-2**7:r===`signed`?this.readInputValue=(e,t)=>e.getInt8(t):r===`ulaw`?this.readInputValue=(e,t)=>Mo(e.getUint8(t)):r===`alaw`?this.readInputValue=(e,t)=>Po(e.getUint8(t)):I(!1);break;case 2:r===`unsigned`?this.readInputValue=(e,t)=>e.getUint16(t,a)-2**15:r===`signed`?this.readInputValue=(e,t)=>e.getInt16(t,a):I(!1);break;case 3:r===`unsigned`?this.readInputValue=(e,t)=>ai(e,t,a)-2**23:r===`signed`?this.readInputValue=(e,t)=>oi(e,t,a):I(!1);break;case 4:r===`unsigned`?this.readInputValue=(e,t)=>e.getUint32(t,a)-2**31:r===`signed`?this.readInputValue=(e,t)=>e.getInt32(t,a):r===`float`?this.readInputValue=(e,t)=>e.getFloat32(t,a):I(!1);break;case 8:r===`float`?this.readInputValue=(e,t)=>e.getFloat64(t,a):I(!1);break;default:ii(i),I(!1)}switch(i){case 1:r===`ulaw`||r===`alaw`?(this.outputSampleSize=2,this.outputFormat=`s16`,this.writeOutputValue=(e,t,n)=>e.setInt16(t,n,!0)):(this.outputSampleSize=1,this.outputFormat=`u8`,this.writeOutputValue=(e,t,n)=>e.setUint8(t,n+2**7));break;case 2:this.outputSampleSize=2,this.outputFormat=`s16`,this.writeOutputValue=(e,t,n)=>e.setInt16(t,n,!0);break;case 3:this.outputSampleSize=4,this.outputFormat=`s32`,this.writeOutputValue=(e,t,n)=>e.setInt32(t,n<<8,!0);break;case 4:this.outputSampleSize=4,r===`float`?(this.outputFormat=`f32`,this.writeOutputValue=(e,t,n)=>e.setFloat32(t,n,!0)):(this.outputFormat=`s32`,this.writeOutputValue=(e,t,n)=>e.setInt32(t,n,!0));break;case 8:this.outputSampleSize=4,this.outputFormat=`f32`,this.writeOutputValue=(e,t,n)=>e.setFloat32(t,n,!0);break;default:ii(i),I(!1)}}getDecodeQueueSize(){return 0}decode(e){let t=z(e.data),n=e.byteLength/this.decoderConfig.numberOfChannels/this.inputSampleSize,r=n*this.decoderConfig.numberOfChannels*this.outputSampleSize,i=new ArrayBuffer(r),a=new DataView(i);for(let e=0;e<n*this.decoderConfig.numberOfChannels;e++){let n=e*this.inputSampleSize,r=e*this.outputSampleSize,i=this.readInputValue(t,n);this.writeOutputValue(a,r,i)}let o=n/this.decoderConfig.sampleRate;(this.currentTimestamp===null||Math.abs(e.timestamp-this.currentTimestamp)>=o)&&(this.currentTimestamp=e.timestamp);let s=this.currentTimestamp;this.currentTimestamp+=o;let c=new Yo({format:this.outputFormat,data:i,numberOfChannels:this.decoderConfig.numberOfChannels,sampleRate:this.decoderConfig.sampleRate,numberOfFrames:n,timestamp:s});this.onSample(c)}async flush(){}close(){}},hs=class extends ss{constructor(e){if(!(e instanceof vs))throw TypeError(`audioTrack must be an InputAudioTrack.`);super(),this._track=e}async _createDecoder(e,t){if(!await this._track.canDecode())throw Error(`This audio track cannot be decoded by this browser. Make sure to check decodability before using a track.`);let n=this._track.codec,r=await this._track.getDecoderConfig();return I(n&&r),Ki.includes(r.codec)?new ms(e,t,r):new ps(e,t,n,r)}_createPacketSink(){return new as(this._track)}async getSample(e){rs(e);for await(let t of this.mediaSamplesAtTimestamps([e]))return t;throw Error(`Internal error: Iterator returned nothing.`)}samples(e=0,t=1/0){return this.mediaSamplesInRange(e,t)}samplesAtTimestamps(e){return this.mediaSamplesAtTimestamps(e)}},gs=class{constructor(e,t){this.input=e,this._backing=t}isVideoTrack(){return this instanceof _s}isAudioTrack(){return this instanceof vs}get id(){return this._backing.getId()}get number(){return this._backing.getNumber()}get internalCodecId(){return this._backing.getInternalCodecId()}get languageCode(){return this._backing.getLanguageCode()}get name(){return this._backing.getName()}get timeResolution(){return this._backing.getTimeResolution()}get disposition(){return this._backing.getDisposition()}getFirstTimestamp(){return this._backing.getFirstTimestamp()}computeDuration(){return this._backing.computeDuration()}async computePacketStats(e=1/0){let t=new as(this),n=1/0,r=-1/0,i=0,a=0;for await(let o of t.packets(void 0,void 0,{metadataOnly:!0})){if(i>=e&&o.timestamp>=r)break;n=Math.min(n,o.timestamp),r=Math.max(r,o.timestamp+o.duration),i++,a+=o.byteLength}return{packetCount:i,averagePacketRate:i?Number((i/(r-n)).toPrecision(16)):0,averageBitrate:i?Number((8*a/(r-n)).toPrecision(16)):0}}},_s=class extends gs{constructor(e,t){super(e,t),this._backing=t,this.pixelAspectRatio=Pi({num:this._backing.getSquarePixelWidth()*this._backing.getCodedHeight(),den:this._backing.getSquarePixelHeight()*this._backing.getCodedWidth()})}get type(){return`video`}get codec(){return this._backing.getCodec()}get codedWidth(){return this._backing.getCodedWidth()}get codedHeight(){return this._backing.getCodedHeight()}get rotation(){return this._backing.getRotation()}get squarePixelWidth(){return this._backing.getSquarePixelWidth()}get squarePixelHeight(){return this._backing.getSquarePixelHeight()}get displayWidth(){return this._backing.getRotation()%180==0?this.squarePixelWidth:this.squarePixelHeight}get displayHeight(){return this._backing.getRotation()%180==0?this.squarePixelHeight:this.squarePixelWidth}getColorSpace(){return this._backing.getColorSpace()}async hasHighDynamicRange(){let e=await this._backing.getColorSpace();return e.primaries===`bt2020`||e.primaries===`smpte432`||e.transfer===`pg`||e.transfer===`hlg`||e.matrix===`bt2020-ncl`}canBeTransparent(){return this._backing.canBeTransparent()}getDecoderConfig(){return this._backing.getDecoderConfig()}async getCodecParameterString(){return(await this._backing.getDecoderConfig())?.codec??null}async canDecode(){try{let e=await this._backing.getDecoderConfig();if(!e)return!1;let t=this._backing.getCodec();return I(t!==null),Eo.some(n=>n.supports(t,e))?!0:typeof VideoDecoder>`u`?!1:(await VideoDecoder.isConfigSupported(e)).supported===!0}catch(e){return console.error(`Error during decodability check:`,e),!1}}async determinePacketType(e){if(!(e instanceof H))throw TypeError(`packet must be an EncodedPacket.`);if(e.isMetadataOnly)throw TypeError(`packet must not be metadata-only to determine its type.`);if(this.codec===null)return null;let t=await this.getDecoderConfig();return I(t),po(this.codec,t,e.data)}},vs=class extends gs{constructor(e,t){super(e,t),this._backing=t}get type(){return`audio`}get codec(){return this._backing.getCodec()}get numberOfChannels(){return this._backing.getNumberOfChannels()}get sampleRate(){return this._backing.getSampleRate()}getDecoderConfig(){return this._backing.getDecoderConfig()}async getCodecParameterString(){return(await this._backing.getDecoderConfig())?.codec??null}async canDecode(){try{let e=await this._backing.getDecoderConfig();if(!e)return!1;let t=this._backing.getCodec();return I(t!==null),Do.some(n=>n.supports(t,e))||e.codec.startsWith(`pcm-`)?!0:typeof AudioDecoder>`u`?!1:(await AudioDecoder.isConfigSupported(e)).supported===!0}catch(e){return console.error(`Error during decodability check:`,e),!1}}async determinePacketType(e){if(!(e instanceof H))throw TypeError(`packet must be an EncodedPacket.`);return this.codec===null?null:`key`}},ys=e=>{let t=(e.hasVideo?`video/`:e.hasAudio?`audio/`:`application/`)+(e.isQuickTime?`quicktime`:`mp4`);if(e.codecStrings.length>0){let n=[...new Set(e.codecStrings)];t+=`; codecs="${n.join(`, `)}"`}return t},bs=e=>{let t=q(e),n=Ul(e,4),r=8;t===1&&(t=Rl(e),r=16);let i=t-r;return i<0?null:{name:n,totalSize:t,headerSize:r,contentSize:i}},xs=e=>Fl(e)/65536,Ss=e=>Fl(e)/1073741824,Cs=e=>{let t=0;for(let n=0;n<4;n++){t<<=7;let n=K(e);if(t|=n&127,!(n&128))break}return t},ws=e=>{let t=Al(e);return e.skip(2),t=Math.min(t,e.remainingLength),Lr.decode(G(e,t))},Ts=e=>{let t=bs(e);if(!t||t.name!==`data`||e.remainingLength<8)return null;let n=q(e);e.skip(4);let r=G(e,t.contentSize-8);switch(n){case 1:return Lr.decode(r);case 2:return new TextDecoder(`utf-16be`).decode(r);case 13:return new Ii(r,`image/jpeg`);case 14:return new Ii(r,`image/png`);case 27:return new Ii(r,`image/bmp`);default:return r}},Es=class extends To{constructor(e){super(e),this.moovSlice=null,this.currentTrack=null,this.tracks=[],this.metadataPromise=null,this.movieTimescale=-1,this.movieDurationInTimescale=-1,this.isQuickTime=!1,this.metadataTags={},this.currentMetadataKeys=null,this.isFragmented=!1,this.fragmentTrackDefaults=[],this.currentFragment=null,this.lastReadFragment=null,this.reader=e._reader}async computeDuration(){let e=await this.getTracks(),t=await Promise.all(e.map(e=>e.computeDuration()));return Math.max(0,...t)}async getTracks(){return await this.readMetadata(),this.tracks.map(e=>e.inputTrack)}async getMimeType(){await this.readMetadata();let e=await Promise.all(this.tracks.map(e=>e.inputTrack.getCodecParameterString()));return ys({isQuickTime:this.isQuickTime,hasVideo:this.tracks.some(e=>e.info?.type===`video`),hasAudio:this.tracks.some(e=>e.info?.type===`audio`),codecStrings:e.filter(Boolean)})}async getMetadataTags(){return await this.readMetadata(),this.metadataTags}readMetadata(){return this.metadataPromise??=(async()=>{let e=0;for(;;){let t=this.reader.requestSliceRange(e,8,16);if(t instanceof Promise&&(t=await t),!t)break;let n=e,r=bs(t);if(!r)break;if(r.name===`ftyp`)this.isQuickTime=Ul(t,4)===`qt `;else if(r.name===`moov`){let e=this.reader.requestSlice(t.filePos,r.contentSize);if(e instanceof Promise&&(e=await e),!e)break;this.moovSlice=e,this.readContiguousBoxes(this.moovSlice),this.tracks.sort((e,t)=>Number(t.disposition.default)-Number(e.disposition.default));for(let e of this.tracks){let t=e.editListPreviousSegmentDurations/this.movieTimescale;e.editListOffset-=Math.round(t*e.timescale)}break}e=n+r.totalSize}if(this.isFragmented&&this.reader.fileSize!==null){let e=this.reader.requestSlice(this.reader.fileSize-4,4);e instanceof Promise&&(e=await e),I(e);let t=q(e),n=this.reader.fileSize-t;if(n>=0&&n<=this.reader.fileSize-16){let e=this.reader.requestSliceRange(n,8,16);if(e instanceof Promise&&(e=await e),e){let t=bs(e);if(t&&t.name===`mfra`){let n=this.reader.requestSlice(e.filePos,t.contentSize);n instanceof Promise&&(n=await n),n&&this.readContiguousBoxes(n)}}}}})()}getSampleTableForTrack(e){if(e.sampleTable)return e.sampleTable;let t={sampleTimingEntries:[],sampleCompositionTimeOffsets:[],sampleSizes:[],keySampleIndices:null,chunkOffsets:[],sampleToChunk:[],presentationTimestamps:null,presentationTimestampIndexMap:null};e.sampleTable=t,I(this.moovSlice);let n=this.moovSlice.slice(e.sampleTableByteOffset);if(this.currentTrack=e,this.traverseBox(n),this.currentTrack=null,e.info?.type===`audio`&&e.info.codec&&Ki.includes(e.info.codec)&&t.sampleCompositionTimeOffsets.length===0){I(e.info?.type===`audio`);let n=la(e.info.codec),r=[],i=[];for(let a=0;a<t.sampleToChunk.length;a++){let o=t.sampleToChunk[a],s=t.sampleToChunk[a+1],c=(s?s.startChunkIndex:t.chunkOffsets.length)-o.startChunkIndex;for(let a=0;a<c;a++){let s=o.startSampleIndex+a*o.samplesPerChunk,c=s+o.samplesPerChunk,l=B(t.sampleTimingEntries,s,e=>e.startIndex),u=t.sampleTimingEntries[l],d=B(t.sampleTimingEntries,c,e=>e.startIndex),f=t.sampleTimingEntries[d],p=u.startDecodeTimestamp+(s-u.startIndex)*u.delta,m=f.startDecodeTimestamp+(c-f.startIndex)*f.delta-p,h=L(r);h&&h.delta===m?h.count++:r.push({startIndex:o.startChunkIndex+a,startDecodeTimestamp:p,count:1,delta:m});let g=o.samplesPerChunk*n.sampleSize*e.info.numberOfChannels;i.push(g)}o.startSampleIndex=o.startChunkIndex,o.samplesPerChunk=1}t.sampleTimingEntries=r,t.sampleSizes=i}if(t.sampleCompositionTimeOffsets.length>0){t.presentationTimestamps=[];for(let e of t.sampleTimingEntries)for(let n=0;n<e.count;n++)t.presentationTimestamps.push({presentationTimestamp:e.startDecodeTimestamp+n*e.delta,sampleIndex:e.startIndex+n});for(let e of t.sampleCompositionTimeOffsets)for(let n=0;n<e.count;n++){let r=e.startIndex+n,i=t.presentationTimestamps[r];i&&(i.presentationTimestamp+=e.offset)}t.presentationTimestamps.sort((e,t)=>e.presentationTimestamp-t.presentationTimestamp),t.presentationTimestampIndexMap=Array(t.presentationTimestamps.length).fill(-1);for(let e=0;e<t.presentationTimestamps.length;e++)t.presentationTimestampIndexMap[t.presentationTimestamps[e].sampleIndex]=e}return t}async readFragment(e){if(this.lastReadFragment?.moofOffset===e)return this.lastReadFragment;let t=this.reader.requestSliceRange(e,8,16);t instanceof Promise&&(t=await t),I(t);let n=bs(t);I(n?.name===`moof`);let r=this.reader.requestSlice(e,n.totalSize);r instanceof Promise&&(r=await r),I(r),this.traverseBox(r);let i=this.lastReadFragment;I(i&&i.moofOffset===e);for(let[,e]of i.trackData){let t=e.track,{fragmentPositionCache:n}=t;if(!e.startTimestampIsFinal){let r=t.fragmentLookupTable.find(e=>e.moofOffset===i.moofOffset);if(r)Ps(e,r.timestamp);else{let t=B(n,i.moofOffset-1,e=>e.moofOffset);if(t!==-1){let r=n[t];Ps(e,r.endTimestamp)}}e.startTimestampIsFinal=!0}let r=B(n,e.startTimestamp,e=>e.startTimestamp);(r===-1||n[r].moofOffset!==i.moofOffset)&&n.splice(r+1,0,{moofOffset:i.moofOffset,startTimestamp:e.startTimestamp,endTimestamp:e.endTimestamp})}return i}readContiguousBoxes(e){let t=e.filePos;for(;e.filePos-t<=e.length-8&&this.traverseBox(e););}*iterateContiguousBoxes(e){let t=e.filePos;for(;e.filePos-t<=e.length-8;){let t=e.filePos,n=bs(e);if(!n)break;yield{boxInfo:n,slice:e},e.filePos=t+n.totalSize}}traverseBox(e){let t=e.filePos,n=bs(e);if(!n)return!1;let r=e.filePos,i=t+n.totalSize;switch(n.name){case`mdia`:case`minf`:case`dinf`:case`mfra`:case`edts`:this.readContiguousBoxes(e.slice(r,n.contentSize));break;case`mvhd`:{let t=K(e);e.skip(3),t===1?(e.skip(16),this.movieTimescale=q(e),this.movieDurationInTimescale=Rl(e)):(e.skip(8),this.movieTimescale=q(e),this.movieDurationInTimescale=q(e))}break;case`trak`:{let t={id:-1,demuxer:this,inputTrack:null,disposition:{...zi},info:null,timescale:-1,durationInMovieTimescale:-1,durationInMediaTimescale:-1,rotation:0,internalCodecId:null,name:null,languageCode:`und`,sampleTableByteOffset:-1,sampleTable:null,fragmentLookupTable:[],currentFragmentState:null,fragmentPositionCache:[],editListPreviousSegmentDurations:0,editListOffset:0};if(this.currentTrack=t,this.readContiguousBoxes(e.slice(r,n.contentSize)),t.id!==-1&&t.timescale!==-1&&t.info!==null){if(t.info.type===`video`&&t.info.width!==-1){let e=t;t.inputTrack=new _s(this.input,new Os(e)),this.tracks.push(t)}else if(t.info.type===`audio`&&t.info.numberOfChannels!==-1){let e=t;t.inputTrack=new vs(this.input,new ks(e)),this.tracks.push(t)}}this.currentTrack=null}break;case`tkhd`:{let t=this.currentTrack;if(!t)break;let n=K(e),r=!!(jl(e)&1);if(t.disposition.default=r,n===0)e.skip(8),t.id=q(e),e.skip(4),t.durationInMovieTimescale=q(e);else if(n===1)e.skip(16),t.id=q(e),e.skip(4),t.durationInMovieTimescale=Rl(e);else throw Error(`Incorrect track header version ${n}.`);e.skip(16);let i=Nr(fi(Fs([xs(e),xs(e),Ss(e),xs(e),xs(e),Ss(e),xs(e),xs(e),Ss(e)]),90));I(i===0||i===90||i===180||i===270),t.rotation=i}break;case`elst`:{let t=this.currentTrack;if(!t)break;let n=K(e);e.skip(3);let r=!1,i=0,a=q(e);for(let o=0;o<a;o++){let a=n===1?Rl(e):q(e),o=n===1?zl(e):Fl(e),s=xs(e);if(a!==0){if(r){console.warn(`Unsupported edit list: multiple edits are not currently supported. Only using first edit.`);break}if(o===-1){i+=a;continue}if(s!==1){console.warn(`Unsupported edit list entry: media rate must be 1.`);break}t.editListPreviousSegmentDurations=i,t.editListOffset=o,r=!0}}}break;case`mdhd`:{let t=this.currentTrack;if(!t)break;let n=K(e);e.skip(3),n===0?(e.skip(8),t.timescale=q(e),t.durationInMediaTimescale=q(e)):n===1&&(e.skip(16),t.timescale=q(e),t.durationInMediaTimescale=Rl(e));let r=Al(e);if(r>0){t.languageCode=``;for(let e=0;e<3;e++)t.languageCode=String.fromCharCode(96+(r&31))+t.languageCode,r>>=5;gi(t.languageCode)||(t.languageCode=`und`)}}break;case`hdlr`:{let t=this.currentTrack;if(!t)break;e.skip(8);let n=Ul(e,4);n===`vide`?t.info={type:`video`,width:-1,height:-1,squarePixelWidth:-1,squarePixelHeight:-1,codec:null,codecDescription:null,colorSpace:null,avcType:null,avcCodecInfo:null,hevcCodecInfo:null,vp9CodecInfo:null,av1CodecInfo:null}:n===`soun`&&(t.info={type:`audio`,numberOfChannels:-1,sampleRate:-1,codec:null,codecDescription:null,aacCodecInfo:null})}break;case`stbl`:{let i=this.currentTrack;if(!i)break;i.sampleTableByteOffset=t,this.readContiguousBoxes(e.slice(r,n.contentSize))}break;case`stsd`:{let t=this.currentTrack;if(!t||t.info===null||t.sampleTable)break;let n=K(e);e.skip(3);let r=q(e);for(let i=0;i<r;i++){let r=e.filePos,i=bs(e);if(!i)break;t.internalCodecId=i.name;let a=i.name.toLowerCase();if(t.info.type===`video`)a===`avc1`||a===`avc3`?(t.info.codec=`avc`,t.info.avcType=a===`avc1`?1:3):a===`hvc1`||a===`hev1`?t.info.codec=`hevc`:a===`vp08`?t.info.codec=`vp8`:a===`vp09`?t.info.codec=`vp9`:a===`av01`?t.info.codec=`av1`:console.warn(`Unsupported video codec (sample entry type '${i.name}').`),e.skip(24),t.info.width=Al(e),t.info.height=Al(e),t.info.squarePixelWidth=t.info.width,t.info.squarePixelHeight=t.info.height,e.skip(50),this.readContiguousBoxes(e.slice(e.filePos,r+i.totalSize-e.filePos));else{a===`mp4a`||(a===`opus`?t.info.codec=`opus`:a===`flac`?t.info.codec=`flac`:a===`twos`||a===`sowt`||a===`raw `||a===`in24`||a===`in32`||a===`fl32`||a===`fl64`||a===`lpcm`||a===`ipcm`||a===`fpcm`||(a===`ulaw`?t.info.codec=`ulaw`:a===`alaw`?t.info.codec=`alaw`:a===`ac-3`?t.info.codec=`ac3`:a===`ec-3`?t.info.codec=`eac3`:console.warn(`Unsupported audio codec (sample entry type '${i.name}').`))),e.skip(8);let o=Al(e);e.skip(6);let s=Al(e),c=Al(e);e.skip(4);let l=q(e)/65536;if(n===0&&o>0){if(o===1)e.skip(4),c=8*q(e),e.skip(8);else if(o===2){e.skip(4),l=Hl(e),s=q(e),e.skip(4),c=q(e);let n=q(e);if(e.skip(8),a===`lpcm`){let e=c+7>>3,r=!!(n&1),i=!!(n&2),a=n&4?-1:0;c>0&&c<=64&&(r?c===32&&(t.info.codec=i?`pcm-f32be`:`pcm-f32`):a&1<<e-1?e===1?t.info.codec=`pcm-s8`:e===2?t.info.codec=i?`pcm-s16be`:`pcm-s16`:e===3?t.info.codec=i?`pcm-s24be`:`pcm-s24`:e===4&&(t.info.codec=i?`pcm-s32be`:`pcm-s32`):e===1&&(t.info.codec=`pcm-u8`)),t.info.codec===null&&console.warn(`Unsupported PCM format.`)}}}t.info.codec===`opus`&&(l=sa),t.info.numberOfChannels=s,t.info.sampleRate=l,a===`twos`?c===8?t.info.codec=`pcm-s8`:c===16?t.info.codec=`pcm-s16be`:(console.warn(`Unsupported sample size ${c} for codec 'twos'.`),t.info.codec=null):a===`sowt`?c===8?t.info.codec=`pcm-s8`:c===16?t.info.codec=`pcm-s16`:(console.warn(`Unsupported sample size ${c} for codec 'sowt'.`),t.info.codec=null):a===`raw `?t.info.codec=`pcm-u8`:a===`in24`?t.info.codec=`pcm-s24be`:a===`in32`?t.info.codec=`pcm-s32be`:a===`fl32`?t.info.codec=`pcm-f32be`:a===`fl64`?t.info.codec=`pcm-f64be`:a===`ipcm`?t.info.codec=`pcm-s16be`:a===`fpcm`&&(t.info.codec=`pcm-f32be`),this.readContiguousBoxes(e.slice(e.filePos,r+i.totalSize-e.filePos))}}}break;case`avcC`:{let t=this.currentTrack;if(!t)break;I(t.info),t.info.codecDescription=G(e,n.contentSize)}break;case`hvcC`:{let t=this.currentTrack;if(!t)break;I(t.info),t.info.codecDescription=G(e,n.contentSize)}break;case`vpcC`:{let t=this.currentTrack;if(!t)break;I(t.info?.type===`video`),e.skip(4);let n=K(e),r=K(e),i=K(e),a=i>>4,o=i>>1&7,s=i&1,c=K(e),l=K(e),u=K(e);t.info.vp9CodecInfo={profile:n,level:r,bitDepth:a,chromaSubsampling:o,videoFullRangeFlag:s,colourPrimaries:c,transferCharacteristics:l,matrixCoefficients:u}}break;case`av1C`:{let t=this.currentTrack;if(!t)break;I(t.info?.type===`video`),e.skip(1);let n=K(e),r=n>>5,i=n&31,a=K(e),o=a>>7,s=a>>6&1,c=a>>5&1,l=a>>4&1,u=a>>3&1,d=a>>2&1,f=a&3,p=r===2&&s?c?12:10:s?10:8;t.info.av1CodecInfo={profile:r,level:i,tier:o,bitDepth:p,monochrome:l,chromaSubsamplingX:u,chromaSubsamplingY:d,chromaSamplePosition:f}}break;case`colr`:{let t=this.currentTrack;if(!t||(I(t.info?.type===`video`),Ul(e,4)!==`nclx`))break;let n=Al(e),r=Al(e),i=Al(e),a=!!(K(e)&128);t.info.colorSpace={primaries:Vr[n],transfer:Ur[r],matrix:Gr[i],fullRange:a}}break;case`pasp`:{let t=this.currentTrack;if(!t)break;I(t.info?.type===`video`);let n=q(e),r=q(e);n>r?t.info.squarePixelWidth=Math.round(t.info.width*n/r):t.info.squarePixelHeight=Math.round(t.info.height*r/n)}break;case`wave`:this.readContiguousBoxes(e.slice(r,n.contentSize));break;case`esds`:{let t=this.currentTrack;if(!t)break;I(t.info?.type===`audio`),e.skip(4),I(K(e)===3),Cs(e),e.skip(2);let n=K(e),r=(n&128)!=0,i=(n&64)!=0,a=(n&32)!=0;if(r&&e.skip(2),i){let t=K(e);e.skip(t)}a&&e.skip(2),I(K(e)===4);let o=Cs(e),s=e.filePos,c=K(e);if(c===64||c===103?(t.info.codec=`aac`,t.info.aacCodecInfo={isMpeg2:c===103,objectType:null}):c===105||c===107?t.info.codec=`mp3`:c===221?t.info.codec=`vorbis`:console.warn(`Unsupported audio codec (objectTypeIndication ${c}) - discarding track.`),e.skip(12),o>e.filePos-s){I(K(e)===5);let n=Cs(e);if(t.info.codecDescription=G(e,n),t.info.codec===`aac`){let e=Ui(t.info.codecDescription);e.numberOfChannels!==null&&(t.info.numberOfChannels=e.numberOfChannels),e.sampleRate!==null&&(t.info.sampleRate=e.sampleRate)}}}break;case`enda`:{let t=this.currentTrack;if(!t)break;I(t.info?.type===`audio`),Al(e)&255&&(t.info.codec===`pcm-s16be`?t.info.codec=`pcm-s16`:t.info.codec===`pcm-s24be`?t.info.codec=`pcm-s24`:t.info.codec===`pcm-s32be`?t.info.codec=`pcm-s32`:t.info.codec===`pcm-f32be`?t.info.codec=`pcm-f32`:t.info.codec===`pcm-f64be`&&(t.info.codec=`pcm-f64`))}break;case`pcmC`:{let t=this.currentTrack;if(!t)break;I(t.info?.type===`audio`),e.skip(4);let n=!!(K(e)&1),r=K(e);t.info.codec===`pcm-s16be`?n?r===16?t.info.codec=`pcm-s16`:r===24?t.info.codec=`pcm-s24`:r===32?t.info.codec=`pcm-s32`:(console.warn(`Invalid ipcm sample size ${r}.`),t.info.codec=null):r===16?t.info.codec=`pcm-s16be`:r===24?t.info.codec=`pcm-s24be`:r===32?t.info.codec=`pcm-s32be`:(console.warn(`Invalid ipcm sample size ${r}.`),t.info.codec=null):t.info.codec===`pcm-f32be`&&(n?r===32?t.info.codec=`pcm-f32`:r===64?t.info.codec=`pcm-f64`:(console.warn(`Invalid fpcm sample size ${r}.`),t.info.codec=null):r===32?t.info.codec=`pcm-f32be`:r===64?t.info.codec=`pcm-f64be`:(console.warn(`Invalid fpcm sample size ${r}.`),t.info.codec=null));break}case`dOps`:{let t=this.currentTrack;if(!t)break;I(t.info?.type===`audio`),e.skip(1);let n=K(e),r=Al(e),i=q(e),a=Ml(e),o=K(e),s;s=o===0?new Uint8Array:G(e,2+n);let c=new Uint8Array(19+s.byteLength),l=new DataView(c.buffer);l.setUint32(0,1332770163,!1),l.setUint32(4,1214603620,!1),l.setUint8(8,1),l.setUint8(9,n),l.setUint16(10,r,!0),l.setUint32(12,i,!0),l.setInt16(16,a,!0),l.setUint8(18,o),c.set(s,19),t.info.codecDescription=c,t.info.numberOfChannels=n}break;case`dfLa`:{let t=this.currentTrack;if(!t)break;I(t.info?.type===`audio`),e.skip(4);let n=e.filePos;for(;e.filePos<i;){let n=K(e),r=jl(e);if((n&127)===mo.STREAMINFO){e.skip(10);let n=q(e),r=n>>>12,i=(n>>9&7)+1;t.info.sampleRate=r,t.info.numberOfChannels=i,e.skip(20)}else e.skip(r);if(n&128)break}let r=e.filePos;e.filePos=n;let a=G(e,r-n),o=new Uint8Array(4+a.byteLength);new DataView(o.buffer).setUint32(0,1716281667,!1),o.set(a,4),t.info.codecDescription=o}break;case`dac3`:{let t=this.currentTrack;if(!t)break;I(t.info?.type===`audio`);let n=new V(G(e,3)),r=n.readBits(2);n.skipBits(8);let i=n.readBits(3),a=n.readBits(1);r<3&&(t.info.sampleRate=Oa[r]),t.info.numberOfChannels=go[i]+a}break;case`dec3`:{let t=this.currentTrack;if(!t)break;I(t.info?.type===`audio`);let r=So(G(e,n.contentSize));if(!r){console.warn(`Invalid dec3 box contents, ignoring.`);break}let i=Co(r);i!==null&&(t.info.sampleRate=i),t.info.numberOfChannels=wo(r)}break;case`stts`:{let t=this.currentTrack;if(!t||!t.sampleTable)break;e.skip(4);let n=q(e),r=0,i=0;for(let a=0;a<n;a++){let n=q(e),a=q(e);t.sampleTable.sampleTimingEntries.push({startIndex:r,startDecodeTimestamp:i,count:n,delta:a}),r+=n,i+=n*a}}break;case`ctts`:{let t=this.currentTrack;if(!t||!t.sampleTable)break;e.skip(4);let n=q(e),r=0;for(let i=0;i<n;i++){let n=q(e),i=Fl(e);t.sampleTable.sampleCompositionTimeOffsets.push({startIndex:r,count:n,offset:i}),r+=n}}break;case`stsz`:{let t=this.currentTrack;if(!t||!t.sampleTable)break;e.skip(4);let n=q(e),r=q(e);if(n===0)for(let n=0;n<r;n++){let n=q(e);t.sampleTable.sampleSizes.push(n)}else t.sampleTable.sampleSizes.push(n)}break;case`stz2`:{let t=this.currentTrack;if(!t||!t.sampleTable)break;e.skip(4),e.skip(3);let n=K(e),r=q(e),i=new V(G(e,Math.ceil(r*n/8)));for(let e=0;e<r;e++){let e=i.readBits(n);t.sampleTable.sampleSizes.push(e)}}break;case`stss`:{let t=this.currentTrack;if(!t||!t.sampleTable)break;e.skip(4),t.sampleTable.keySampleIndices=[];let n=q(e);for(let r=0;r<n;r++){let n=q(e)-1;t.sampleTable.keySampleIndices.push(n)}t.sampleTable.keySampleIndices[0]!==0&&t.sampleTable.keySampleIndices.unshift(0)}break;case`stsc`:{let t=this.currentTrack;if(!t||!t.sampleTable)break;e.skip(4);let n=q(e);for(let r=0;r<n;r++){let n=q(e)-1,r=q(e),i=q(e);t.sampleTable.sampleToChunk.push({startSampleIndex:-1,startChunkIndex:n,samplesPerChunk:r,sampleDescriptionIndex:i})}let r=0;for(let e=0;e<t.sampleTable.sampleToChunk.length;e++)if(t.sampleTable.sampleToChunk[e].startSampleIndex=r,e<t.sampleTable.sampleToChunk.length-1){let n=t.sampleTable.sampleToChunk[e+1].startChunkIndex-t.sampleTable.sampleToChunk[e].startChunkIndex;r+=n*t.sampleTable.sampleToChunk[e].samplesPerChunk}}break;case`stco`:{let t=this.currentTrack;if(!t||!t.sampleTable)break;e.skip(4);let n=q(e);for(let r=0;r<n;r++){let n=q(e);t.sampleTable.chunkOffsets.push(n)}}break;case`co64`:{let t=this.currentTrack;if(!t||!t.sampleTable)break;e.skip(4);let n=q(e);for(let r=0;r<n;r++){let n=Rl(e);t.sampleTable.chunkOffsets.push(n)}}break;case`mvex`:this.isFragmented=!0,this.readContiguousBoxes(e.slice(r,n.contentSize));break;case`mehd`:{let t=K(e);e.skip(3),this.movieDurationInTimescale=t===1?Rl(e):q(e)}break;case`trex`:{e.skip(4);let t=q(e),n=q(e),r=q(e),i=q(e),a=q(e);this.fragmentTrackDefaults.push({trackId:t,defaultSampleDescriptionIndex:n,defaultSampleDuration:r,defaultSampleSize:i,defaultSampleFlags:a})}break;case`tfra`:{let t=K(e);e.skip(3);let n=q(e),r=this.tracks.find(e=>e.id===n);if(!r)break;let i=q(e),a=(i&48)>>4,o=(i&12)>>2,s=i&3,c=[K,Al,jl,q],l=c[a],u=c[o],d=c[s],f=q(e);for(let n=0;n<f;n++){let n=t===1?Rl(e):q(e),i=t===1?Rl(e):q(e);l(e),u(e),d(e),r.fragmentLookupTable.push({timestamp:n,moofOffset:i})}r.fragmentLookupTable.sort((e,t)=>e.timestamp-t.timestamp);for(let e=0;e<r.fragmentLookupTable.length-1;e++){let t=r.fragmentLookupTable[e],n=r.fragmentLookupTable[e+1];t.timestamp===n.timestamp&&(r.fragmentLookupTable.splice(e+1,1),e--)}}break;case`moof`:this.currentFragment={moofOffset:t,moofSize:n.totalSize,implicitBaseDataOffset:t,trackData:new Map},this.readContiguousBoxes(e.slice(r,n.contentSize)),this.lastReadFragment=this.currentFragment,this.currentFragment=null;break;case`traf`:if(I(this.currentFragment),this.readContiguousBoxes(e.slice(r,n.contentSize)),this.currentTrack){let e=this.currentFragment.trackData.get(this.currentTrack.id);if(e){let{currentFragmentState:t}=this.currentTrack;I(t),t.startTimestamp!==null&&(Ps(e,t.startTimestamp),e.startTimestampIsFinal=!0)}this.currentTrack.currentFragmentState=null,this.currentTrack=null}break;case`tfhd`:{I(this.currentFragment),e.skip(1);let t=jl(e),n=!!(t&1),r=!!(t&2),i=!!(t&8),a=!!(t&16),o=!!(t&32),s=!!(t&65536),c=!!(t&131072),l=q(e),u=this.tracks.find(e=>e.id===l);if(!u)break;let d=this.fragmentTrackDefaults.find(e=>e.trackId===l);this.currentTrack=u,u.currentFragmentState={baseDataOffset:this.currentFragment.implicitBaseDataOffset,sampleDescriptionIndex:d?.defaultSampleDescriptionIndex??null,defaultSampleDuration:d?.defaultSampleDuration??null,defaultSampleSize:d?.defaultSampleSize??null,defaultSampleFlags:d?.defaultSampleFlags??null,startTimestamp:null},n?u.currentFragmentState.baseDataOffset=Rl(e):c&&(u.currentFragmentState.baseDataOffset=this.currentFragment.moofOffset),r&&(u.currentFragmentState.sampleDescriptionIndex=q(e)),i&&(u.currentFragmentState.defaultSampleDuration=q(e)),a&&(u.currentFragmentState.defaultSampleSize=q(e)),o&&(u.currentFragmentState.defaultSampleFlags=q(e)),s&&(u.currentFragmentState.defaultSampleDuration=0)}break;case`tfdt`:{let t=this.currentTrack;if(!t)break;I(t.currentFragmentState);let n=K(e);e.skip(3);let r=n===0?q(e):Rl(e);t.currentFragmentState.startTimestamp=r}break;case`trun`:{let t=this.currentTrack;if(!t)break;if(I(this.currentFragment),I(t.currentFragmentState),this.currentFragment.trackData.has(t.id)){console.warn(`Can't have two trun boxes for the same track in one fragment. Ignoring...`);break}let n=K(e),r=jl(e),i=!!(r&1),a=!!(r&4),o=!!(r&256),s=!!(r&512),c=!!(r&1024),l=!!(r&2048),u=q(e),d=t.currentFragmentState.baseDataOffset;i&&(d+=Fl(e));let f=null;a&&(f=q(e));let p=d;if(u===0){this.currentFragment.implicitBaseDataOffset=p;break}let m=0,h={track:t,startTimestamp:0,endTimestamp:0,firstKeyFrameTimestamp:null,samples:[],presentationTimestamps:[],startTimestampIsFinal:!1};this.currentFragment.trackData.set(t.id,h);for(let r=0;r<u;r++){let i;o?i=q(e):(I(t.currentFragmentState.defaultSampleDuration!==null),i=t.currentFragmentState.defaultSampleDuration);let a;s?a=q(e):(I(t.currentFragmentState.defaultSampleSize!==null),a=t.currentFragmentState.defaultSampleSize);let u;c?u=q(e):(I(t.currentFragmentState.defaultSampleFlags!==null),u=t.currentFragmentState.defaultSampleFlags),r===0&&f!==null&&(u=f);let d=0;l&&(d=n===0?q(e):Fl(e));let g=!(u&65536);h.samples.push({presentationTimestamp:m+d,duration:i,byteOffset:p,byteSize:a,isKeyFrame:g}),p+=a,m+=i}h.presentationTimestamps=h.samples.map((e,t)=>({presentationTimestamp:e.presentationTimestamp,sampleIndex:t})).sort((e,t)=>e.presentationTimestamp-t.presentationTimestamp);for(let e=0;e<h.presentationTimestamps.length;e++){let t=h.presentationTimestamps[e],n=h.samples[t.sampleIndex];h.firstKeyFrameTimestamp===null&&n.isKeyFrame&&(h.firstKeyFrameTimestamp=n.presentationTimestamp),e<h.presentationTimestamps.length-1&&(n.duration=h.presentationTimestamps[e+1].presentationTimestamp-t.presentationTimestamp)}let g=h.samples[h.presentationTimestamps[0].sampleIndex],_=h.samples[L(h.presentationTimestamps).sampleIndex];h.startTimestamp=g.presentationTimestamp,h.endTimestamp=_.presentationTimestamp+_.duration,this.currentFragment.implicitBaseDataOffset=p}break;case`udta`:{let t=this.iterateContiguousBoxes(e.slice(r,n.contentSize));for(let{boxInfo:e,slice:n}of t){if(e.name!==`meta`&&!this.currentTrack){let t=n.filePos;this.metadataTags.raw??={},e.name[0]===`©`?this.metadataTags.raw[e.name]??=ws(n):this.metadataTags.raw[e.name]??=G(n,e.contentSize),n.filePos=t}switch(e.name){case`meta`:n.skip(-e.headerSize),this.traverseBox(n);break;case`©nam`:case`name`:this.currentTrack?this.currentTrack.name=Lr.decode(G(n,e.contentSize)):this.metadataTags.title??=ws(n);break;case`©des`:this.currentTrack||(this.metadataTags.description??=ws(n));break;case`©ART`:this.currentTrack||(this.metadataTags.artist??=ws(n));break;case`©alb`:this.currentTrack||(this.metadataTags.album??=ws(n));break;case`albr`:this.currentTrack||(this.metadataTags.albumArtist??=ws(n));break;case`©gen`:this.currentTrack||(this.metadataTags.genre??=ws(n));break;case`©day`:if(!this.currentTrack){let e=new Date(ws(n));Number.isNaN(e.getTime())||(this.metadataTags.date??=e)}break;case`©cmt`:this.currentTrack||(this.metadataTags.comment??=ws(n));break;case`©lyr`:this.currentTrack||(this.metadataTags.lyrics??=ws(n));break}}}break;case`meta`:{if(this.currentTrack)break;let t=q(e)!==0;this.currentMetadataKeys=new Map,t?this.readContiguousBoxes(e.slice(r,n.contentSize)):this.readContiguousBoxes(e.slice(r+4,n.contentSize-4)),this.currentMetadataKeys=null}break;case`keys`:{if(!this.currentMetadataKeys)break;e.skip(4);let t=q(e);for(let n=0;n<t;n++){let t=q(e);e.skip(4);let r=Lr.decode(G(e,t-8));this.currentMetadataKeys.set(n+1,r)}}break;case`ilst`:{if(!this.currentMetadataKeys)break;let t=this.iterateContiguousBoxes(e.slice(r,n.contentSize));for(let{boxInfo:e,slice:n}of t){let t=e.name,r=(t.charCodeAt(0)<<24)+(t.charCodeAt(1)<<16)+(t.charCodeAt(2)<<8)+t.charCodeAt(3);this.currentMetadataKeys.has(r)&&(t=this.currentMetadataKeys.get(r));let i=Ts(n);switch(this.metadataTags.raw??={},this.metadataTags.raw[t]??=i,t){case`©nam`:case`titl`:case`com.apple.quicktime.title`:case`title`:typeof i==`string`&&(this.metadataTags.title??=i);break;case`©des`:case`desc`:case`dscp`:case`com.apple.quicktime.description`:case`description`:typeof i==`string`&&(this.metadataTags.description??=i);break;case`©ART`:case`com.apple.quicktime.artist`:case`artist`:typeof i==`string`&&(this.metadataTags.artist??=i);break;case`©alb`:case`albm`:case`com.apple.quicktime.album`:case`album`:typeof i==`string`&&(this.metadataTags.album??=i);break;case`aART`:case`album_artist`:typeof i==`string`&&(this.metadataTags.albumArtist??=i);break;case`©cmt`:case`com.apple.quicktime.comment`:case`comment`:typeof i==`string`&&(this.metadataTags.comment??=i);break;case`©gen`:case`gnre`:case`com.apple.quicktime.genre`:case`genre`:typeof i==`string`&&(this.metadataTags.genre??=i);break;case`©lyr`:case`lyrics`:typeof i==`string`&&(this.metadataTags.lyrics??=i);break;case`©day`:case`rldt`:case`com.apple.quicktime.creationdate`:case`date`:if(typeof i==`string`){let e=new Date(i);Number.isNaN(e.getTime())||(this.metadataTags.date??=e)}break;case`covr`:case`com.apple.quicktime.artwork`:i instanceof Ii?(this.metadataTags.images??=[],this.metadataTags.images.push({data:i.data,kind:`coverFront`,mimeType:i.mimeType})):i instanceof Uint8Array&&(this.metadataTags.images??=[],this.metadataTags.images.push({data:i,kind:`coverFront`,mimeType:`image/*`}));break;case`track`:if(typeof i==`string`){let e=i.split(`/`),t=Number.parseInt(e[0],10),n=e[1]&&Number.parseInt(e[1],10);Number.isInteger(t)&&t>0&&(this.metadataTags.trackNumber??=t),n&&Number.isInteger(n)&&n>0&&(this.metadataTags.tracksTotal??=n)}break;case`trkn`:if(i instanceof Uint8Array&&i.length>=6){let e=z(i),t=e.getUint16(2,!1),n=e.getUint16(4,!1);t>0&&(this.metadataTags.trackNumber??=t),n>0&&(this.metadataTags.tracksTotal??=n)}break;case`disc`:case`disk`:if(i instanceof Uint8Array&&i.length>=6){let e=z(i),t=e.getUint16(2,!1),n=e.getUint16(4,!1);t>0&&(this.metadataTags.discNumber??=t),n>0&&(this.metadataTags.discsTotal??=n)}break}}}break}return e.filePos=i,!0}},Ds=class{constructor(e){this.internalTrack=e,this.packetToSampleIndex=new WeakMap,this.packetToFragmentLocation=new WeakMap}getId(){return this.internalTrack.id}getNumber(){let e=this.internalTrack.demuxer,t=this.internalTrack.inputTrack.type,n=0;for(let r of e.tracks)if(r.inputTrack.type===t&&n++,r===this.internalTrack)break;return n}getCodec(){throw Error(`Not implemented on base class.`)}getInternalCodecId(){return this.internalTrack.internalCodecId}getName(){return this.internalTrack.name}getLanguageCode(){return this.internalTrack.languageCode}getTimeResolution(){return this.internalTrack.timescale}getDisposition(){return this.internalTrack.disposition}async computeDuration(){let e=await this.getPacket(1/0,{metadataOnly:!0});return(e?.timestamp??0)+(e?.duration??0)}async getFirstTimestamp(){return(await this.getFirstPacket({metadataOnly:!0}))?.timestamp??0}async getFirstPacket(e){let t=await this.fetchPacketForSampleIndex(0,e);return t||!this.internalTrack.demuxer.isFragmented?t:this.performFragmentedLookup(null,e=>e.trackData.get(this.internalTrack.id)?{sampleIndex:0,correctSampleFound:!0}:{sampleIndex:-1,correctSampleFound:!1},-1/0,1/0,e)}mapTimestampIntoTimescale(e){return di(e*this.internalTrack.timescale)+this.internalTrack.editListOffset}async getPacket(e,t){let n=this.mapTimestampIntoTimescale(e),r=this.internalTrack.demuxer.getSampleTableForTrack(this.internalTrack),i=As(r,n),a=await this.fetchPacketForSampleIndex(i,t);return!Is(r)||!this.internalTrack.demuxer.isFragmented?a:this.performFragmentedLookup(null,e=>{let t=e.trackData.get(this.internalTrack.id);if(!t)return{sampleIndex:-1,correctSampleFound:!1};let r=B(t.presentationTimestamps,n,e=>e.presentationTimestamp);return{sampleIndex:r===-1?-1:t.presentationTimestamps[r].sampleIndex,correctSampleFound:r!==-1&&n<t.endTimestamp}},n,n,t)}async getNextPacket(e,t){let n=this.packetToSampleIndex.get(e);if(n!==void 0)return this.fetchPacketForSampleIndex(n+1,t);let r=this.packetToFragmentLocation.get(e);if(r===void 0)throw Error(`Packet was not created from this track.`);return this.performFragmentedLookup(r.fragment,e=>{if(e===r.fragment){let t=e.trackData.get(this.internalTrack.id);if(r.sampleIndex+1<t.samples.length)return{sampleIndex:r.sampleIndex+1,correctSampleFound:!0}}else if(e.trackData.get(this.internalTrack.id))return{sampleIndex:0,correctSampleFound:!0};return{sampleIndex:-1,correctSampleFound:!1}},-1/0,1/0,t)}async getKeyPacket(e,t){let n=this.mapTimestampIntoTimescale(e),r=this.internalTrack.demuxer.getSampleTableForTrack(this.internalTrack),i=js(r,n),a=await this.fetchPacketForSampleIndex(i,t);return!Is(r)||!this.internalTrack.demuxer.isFragmented?a:this.performFragmentedLookup(null,e=>{let t=e.trackData.get(this.internalTrack.id);if(!t)return{sampleIndex:-1,correctSampleFound:!1};let r=ti(t.presentationTimestamps,e=>t.samples[e.sampleIndex].isKeyFrame&&e.presentationTimestamp<=n);return{sampleIndex:r===-1?-1:t.presentationTimestamps[r].sampleIndex,correctSampleFound:r!==-1&&n<t.endTimestamp}},n,n,t)}async getNextKeyPacket(e,t){let n=this.packetToSampleIndex.get(e);if(n!==void 0){let e=Ns(this.internalTrack.demuxer.getSampleTableForTrack(this.internalTrack),n);return this.fetchPacketForSampleIndex(e,t)}let r=this.packetToFragmentLocation.get(e);if(r===void 0)throw Error(`Packet was not created from this track.`);return this.performFragmentedLookup(r.fragment,e=>{if(e===r.fragment){let t=e.trackData.get(this.internalTrack.id).samples.findIndex((e,t)=>e.isKeyFrame&&t>r.sampleIndex);if(t!==-1)return{sampleIndex:t,correctSampleFound:!0}}else{let t=e.trackData.get(this.internalTrack.id);if(t&&t.firstKeyFrameTimestamp!==null){let e=t.samples.findIndex(e=>e.isKeyFrame);return I(e!==-1),{sampleIndex:e,correctSampleFound:!0}}}return{sampleIndex:-1,correctSampleFound:!1}},-1/0,1/0,t)}async fetchPacketForSampleIndex(e,t){if(e===-1)return null;let n=Ms(this.internalTrack.demuxer.getSampleTableForTrack(this.internalTrack),e);if(!n)return null;let r;if(t.metadataOnly)r=Ao;else{let e=this.internalTrack.demuxer.reader.requestSlice(n.sampleOffset,n.sampleSize);e instanceof Promise&&(e=await e),I(e),r=G(e,n.sampleSize)}let i=(n.presentationTimestamp-this.internalTrack.editListOffset)/this.internalTrack.timescale,a=n.duration/this.internalTrack.timescale,o=new H(r,n.isKeyFrame?`key`:`delta`,i,a,e,n.sampleSize);return this.packetToSampleIndex.set(o,e),o}async fetchPacketInFragment(e,t,n){if(t===-1)return null;let r=e.trackData.get(this.internalTrack.id).samples[t];I(r);let i;if(n.metadataOnly)i=Ao;else{let e=this.internalTrack.demuxer.reader.requestSlice(r.byteOffset,r.byteSize);e instanceof Promise&&(e=await e),I(e),i=G(e,r.byteSize)}let a=(r.presentationTimestamp-this.internalTrack.editListOffset)/this.internalTrack.timescale,o=r.duration/this.internalTrack.timescale,s=new H(i,r.isKeyFrame?`key`:`delta`,a,o,e.moofOffset+t,r.byteSize);return this.packetToFragmentLocation.set(s,{fragment:e,sampleIndex:t}),s}async performFragmentedLookup(e,t,n,r,i){let a=this.internalTrack.demuxer,o=null,s=null,c=-1;if(e){let{sampleIndex:n,correctSampleFound:r}=t(e);if(r)return this.fetchPacketInFragment(e,n,i);n!==-1&&(s=e,c=n)}let l=B(this.internalTrack.fragmentLookupTable,n,e=>e.timestamp),u=l===-1?null:this.internalTrack.fragmentLookupTable[l],d=B(this.internalTrack.fragmentPositionCache,n,e=>e.startTimestamp),f=d===-1?null:this.internalTrack.fragmentPositionCache[d],p=Math.max(u?.moofOffset??0,f?.moofOffset??0)||null,m;for(e?p===null||e.moofOffset>=p?(m=e.moofOffset+e.moofSize,o=e):m=p:m=p??0;;){if(o){let e=o.trackData.get(this.internalTrack.id);if(e&&e.startTimestamp>r)break}let e=a.reader.requestSliceRange(m,8,16);if(e instanceof Promise&&(e=await e),!e)break;let n=m,l=bs(e);if(!l)break;if(l.name===`moof`){o=await a.readFragment(n);let{sampleIndex:e,correctSampleFound:r}=t(o);if(r)return this.fetchPacketInFragment(o,e,i);e!==-1&&(s=o,c=e)}m=n+l.totalSize}if(u&&(!s||s.moofOffset<u.moofOffset)){let e=this.internalTrack.fragmentLookupTable[l-1];I(!e||e.timestamp<u.timestamp);let n=e?.timestamp??-1/0;return this.performFragmentedLookup(null,t,n,r,i)}return s?this.fetchPacketInFragment(s,c,i):null}},Os=class extends Ds{constructor(e){super(e),this.decoderConfigPromise=null,this.internalTrack=e}getCodec(){return this.internalTrack.info.codec}getCodedWidth(){return this.internalTrack.info.width}getCodedHeight(){return this.internalTrack.info.height}getSquarePixelWidth(){return this.internalTrack.info.squarePixelWidth}getSquarePixelHeight(){return this.internalTrack.info.squarePixelHeight}getRotation(){return this.internalTrack.rotation}async getColorSpace(){return{primaries:this.internalTrack.info.colorSpace?.primaries,transfer:this.internalTrack.info.colorSpace?.transfer,matrix:this.internalTrack.info.colorSpace?.matrix,fullRange:this.internalTrack.info.colorSpace?.fullRange}}async canBeTransparent(){return!1}async getDecoderConfig(){return this.internalTrack.info.codec?this.decoderConfigPromise??=(async()=>{if(this.internalTrack.info.codec===`vp9`&&!this.internalTrack.info.vp9CodecInfo){let e=await this.getFirstPacket({});this.internalTrack.info.vp9CodecInfo=e&&ao(e.data)}else if(this.internalTrack.info.codec===`av1`&&!this.internalTrack.info.av1CodecInfo){let e=await this.getFirstPacket({});this.internalTrack.info.av1CodecInfo=e&&so(e.data)}return{codec:ia(this.internalTrack.info),codedWidth:this.internalTrack.info.width,codedHeight:this.internalTrack.info.height,displayAspectWidth:this.internalTrack.info.squarePixelWidth,displayAspectHeight:this.internalTrack.info.squarePixelHeight,description:this.internalTrack.info.codecDescription??void 0,colorSpace:this.internalTrack.info.colorSpace??void 0}})():null}},ks=class extends Ds{constructor(e){super(e),this.decoderConfig=null,this.internalTrack=e}getCodec(){return this.internalTrack.info.codec}getNumberOfChannels(){return this.internalTrack.info.numberOfChannels}getSampleRate(){return this.internalTrack.info.sampleRate}async getDecoderConfig(){return this.internalTrack.info.codec?this.decoderConfig??={codec:oa(this.internalTrack.info),numberOfChannels:this.internalTrack.info.numberOfChannels,sampleRate:this.internalTrack.info.sampleRate,description:this.internalTrack.info.codecDescription??void 0}:null}},As=(e,t)=>{if(e.presentationTimestamps){let n=B(e.presentationTimestamps,t,e=>e.presentationTimestamp);return n===-1?-1:e.presentationTimestamps[n].sampleIndex}else{let n=B(e.sampleTimingEntries,t,e=>e.startDecodeTimestamp);if(n===-1)return-1;let r=e.sampleTimingEntries[n];return r.startIndex+Math.min(Math.floor((t-r.startDecodeTimestamp)/r.delta),r.count-1)}},js=(e,t)=>{if(!e.keySampleIndices)return As(e,t);if(e.presentationTimestamps){let n=B(e.presentationTimestamps,t,e=>e.presentationTimestamp);if(n===-1)return-1;for(let t=n;t>=0;t--){let n=e.presentationTimestamps[t].sampleIndex;if(Zr(e.keySampleIndices,n,e=>e)!==-1)return n}return-1}else{let n=As(e,t),r=B(e.keySampleIndices,n,e=>e);return e.keySampleIndices[r]??-1}},Ms=(e,t)=>{let n=B(e.sampleTimingEntries,t,e=>e.startIndex),r=e.sampleTimingEntries[n];if(!r||r.startIndex+r.count<=t)return null;let i=r.startDecodeTimestamp+(t-r.startIndex)*r.delta,a=B(e.sampleCompositionTimeOffsets,t,e=>e.startIndex),o=e.sampleCompositionTimeOffsets[a];o&&t-o.startIndex<o.count&&(i+=o.offset);let s=e.sampleSizes[Math.min(t,e.sampleSizes.length-1)],c=B(e.sampleToChunk,t,e=>e.startSampleIndex),l=e.sampleToChunk[c];I(l);let u=l.startChunkIndex+Math.floor((t-l.startSampleIndex)/l.samplesPerChunk),d=e.chunkOffsets[u],f=l.startSampleIndex+(u-l.startChunkIndex)*l.samplesPerChunk,p=0,m=d;if(e.sampleSizes.length===1)m+=s*(t-f),p+=s*l.samplesPerChunk;else for(let n=f;n<f+l.samplesPerChunk;n++){let r=e.sampleSizes[n];n<t&&(m+=r),p+=r}let h=r.delta;if(e.presentationTimestamps){let n=e.presentationTimestampIndexMap[t];I(n!==void 0),n<e.presentationTimestamps.length-1&&(h=e.presentationTimestamps[n+1].presentationTimestamp-i)}return{presentationTimestamp:i,duration:h,sampleOffset:m,sampleSize:s,chunkOffset:d,chunkSize:p,isKeyFrame:e.keySampleIndices?Zr(e.keySampleIndices,t,e=>e)!==-1:!0}},Ns=(e,t)=>{if(!e.keySampleIndices)return t+1;let n=B(e.keySampleIndices,t,e=>e);return e.keySampleIndices[n+1]??-1},Ps=(e,t)=>{e.startTimestamp+=t,e.endTimestamp+=t;for(let n of e.samples)n.presentationTimestamp+=t;for(let n of e.presentationTimestamps)n.presentationTimestamp+=t},Fs=e=>{let[t,,,n]=e,r=Math.hypot(t,n),i=t/r,a=n/r,o=-Math.atan2(a,i)*(180/Math.PI);return Number.isFinite(o)?o:0},Is=e=>e.sampleSizes.length===0,U;(function(e){e[e.EBML=440786851]=`EBML`,e[e.EBMLVersion=17030]=`EBMLVersion`,e[e.EBMLReadVersion=17143]=`EBMLReadVersion`,e[e.EBMLMaxIDLength=17138]=`EBMLMaxIDLength`,e[e.EBMLMaxSizeLength=17139]=`EBMLMaxSizeLength`,e[e.DocType=17026]=`DocType`,e[e.DocTypeVersion=17031]=`DocTypeVersion`,e[e.DocTypeReadVersion=17029]=`DocTypeReadVersion`,e[e.Void=236]=`Void`,e[e.Segment=408125543]=`Segment`,e[e.SeekHead=290298740]=`SeekHead`,e[e.Seek=19899]=`Seek`,e[e.SeekID=21419]=`SeekID`,e[e.SeekPosition=21420]=`SeekPosition`,e[e.Duration=17545]=`Duration`,e[e.Info=357149030]=`Info`,e[e.TimestampScale=2807729]=`TimestampScale`,e[e.MuxingApp=19840]=`MuxingApp`,e[e.WritingApp=22337]=`WritingApp`,e[e.Tracks=374648427]=`Tracks`,e[e.TrackEntry=174]=`TrackEntry`,e[e.TrackNumber=215]=`TrackNumber`,e[e.TrackUID=29637]=`TrackUID`,e[e.TrackType=131]=`TrackType`,e[e.FlagEnabled=185]=`FlagEnabled`,e[e.FlagDefault=136]=`FlagDefault`,e[e.FlagForced=21930]=`FlagForced`,e[e.FlagOriginal=21934]=`FlagOriginal`,e[e.FlagHearingImpaired=21931]=`FlagHearingImpaired`,e[e.FlagVisualImpaired=21932]=`FlagVisualImpaired`,e[e.FlagCommentary=21935]=`FlagCommentary`,e[e.FlagLacing=156]=`FlagLacing`,e[e.Name=21358]=`Name`,e[e.Language=2274716]=`Language`,e[e.LanguageBCP47=2274717]=`LanguageBCP47`,e[e.CodecID=134]=`CodecID`,e[e.CodecPrivate=25506]=`CodecPrivate`,e[e.CodecDelay=22186]=`CodecDelay`,e[e.SeekPreRoll=22203]=`SeekPreRoll`,e[e.DefaultDuration=2352003]=`DefaultDuration`,e[e.Video=224]=`Video`,e[e.PixelWidth=176]=`PixelWidth`,e[e.PixelHeight=186]=`PixelHeight`,e[e.DisplayWidth=21680]=`DisplayWidth`,e[e.DisplayHeight=21690]=`DisplayHeight`,e[e.DisplayUnit=21682]=`DisplayUnit`,e[e.AlphaMode=21440]=`AlphaMode`,e[e.Audio=225]=`Audio`,e[e.SamplingFrequency=181]=`SamplingFrequency`,e[e.Channels=159]=`Channels`,e[e.BitDepth=25188]=`BitDepth`,e[e.SimpleBlock=163]=`SimpleBlock`,e[e.BlockGroup=160]=`BlockGroup`,e[e.Block=161]=`Block`,e[e.BlockAdditions=30113]=`BlockAdditions`,e[e.BlockMore=166]=`BlockMore`,e[e.BlockAdditional=165]=`BlockAdditional`,e[e.BlockAddID=238]=`BlockAddID`,e[e.BlockDuration=155]=`BlockDuration`,e[e.ReferenceBlock=251]=`ReferenceBlock`,e[e.Cluster=524531317]=`Cluster`,e[e.Timestamp=231]=`Timestamp`,e[e.Cues=475249515]=`Cues`,e[e.CuePoint=187]=`CuePoint`,e[e.CueTime=179]=`CueTime`,e[e.CueTrackPositions=183]=`CueTrackPositions`,e[e.CueTrack=247]=`CueTrack`,e[e.CueClusterPosition=241]=`CueClusterPosition`,e[e.Colour=21936]=`Colour`,e[e.MatrixCoefficients=21937]=`MatrixCoefficients`,e[e.TransferCharacteristics=21946]=`TransferCharacteristics`,e[e.Primaries=21947]=`Primaries`,e[e.Range=21945]=`Range`,e[e.Projection=30320]=`Projection`,e[e.ProjectionType=30321]=`ProjectionType`,e[e.ProjectionPoseRoll=30325]=`ProjectionPoseRoll`,e[e.Attachments=423732329]=`Attachments`,e[e.AttachedFile=24999]=`AttachedFile`,e[e.FileDescription=18046]=`FileDescription`,e[e.FileName=18030]=`FileName`,e[e.FileMediaType=18016]=`FileMediaType`,e[e.FileData=18012]=`FileData`,e[e.FileUID=18094]=`FileUID`,e[e.Chapters=272869232]=`Chapters`,e[e.Tags=307544935]=`Tags`,e[e.Tag=29555]=`Tag`,e[e.Targets=25536]=`Targets`,e[e.TargetTypeValue=26826]=`TargetTypeValue`,e[e.TargetType=25546]=`TargetType`,e[e.TagTrackUID=25541]=`TagTrackUID`,e[e.TagEditionUID=25545]=`TagEditionUID`,e[e.TagChapterUID=25540]=`TagChapterUID`,e[e.TagAttachmentUID=25542]=`TagAttachmentUID`,e[e.SimpleTag=26568]=`SimpleTag`,e[e.TagName=17827]=`TagName`,e[e.TagLanguage=17530]=`TagLanguage`,e[e.TagString=17543]=`TagString`,e[e.TagBinary=17541]=`TagBinary`,e[e.ContentEncodings=28032]=`ContentEncodings`,e[e.ContentEncoding=25152]=`ContentEncoding`,e[e.ContentEncodingOrder=20529]=`ContentEncodingOrder`,e[e.ContentEncodingScope=20530]=`ContentEncodingScope`,e[e.ContentCompression=20532]=`ContentCompression`,e[e.ContentCompAlgo=16980]=`ContentCompAlgo`,e[e.ContentCompSettings=16981]=`ContentCompSettings`,e[e.ContentEncryption=20533]=`ContentEncryption`})(U||={});var Ls=[U.EBML,U.Segment],Rs=[U.SeekHead,U.Info,U.Cluster,U.Tracks,U.Cues,U.Attachments,U.Chapters,U.Tags],zs=[...Ls,...Rs],Bs=e=>{if(e.remainingLength<1)return null;let t=K(e);if(e.skip(-1),t===0)return null;let n=1,r=128;for(;(t&r)===0;)n++,r>>=1;return e.remainingLength<n?null:n},Vs=e=>{if(e.remainingLength<1)return null;let t=K(e);if(t===0)return null;let n=1,r=128;for(;(t&r)===0;)n++,r>>=1;if(e.remainingLength<n-1)return null;let i=t&r-1;for(let t=1;t<n;t++)i*=256,i+=K(e);return i},W=(e,t)=>{if(t<1||t>8)throw Error(`Bad unsigned int size `+t);let n=0;for(let r=0;r<t;r++)n*=256,n+=K(e);return n},Hs=(e,t)=>{if(t<1)throw Error(`Bad unsigned int size `+t);let n=0n;for(let r=0;r<t;r++)n<<=8n,n+=BigInt(K(e));return n},Us=e=>{let t=Bs(e);return t===null||e.remainingLength<t?null:W(e,t)},Ws=e=>{if(e.remainingLength<1)return null;if(K(e)===255)return;e.skip(-1);let t=Vs(e);if(t===null)return null;if(t!==72057594037927940)return t},Gs=e=>{I(e.remainingLength>=2);let t=Us(e);if(t===null)return null;let n=Ws(e);return n===null?null:{id:t,size:n}},Ks=(e,t)=>{let n=G(e,t),r=0;for(;r<t&&n[r]!==0;)r+=1;return String.fromCharCode(...n.subarray(0,r))},qs=(e,t)=>{let n=G(e,t),r=0;for(;r<t&&n[r]!==0;)r+=1;return Lr.decode(n.subarray(0,r))},Js=(e,t)=>{if(t===0)return 0;if(t!==4&&t!==8)throw Error(`Bad float size `+t);return t===4?Vl(e):Hl(e)},Ys=async(e,t,n,r)=>{let i=new Set(n),a=t;for(;r===null||a<r;){let t=e.requestSliceRange(a,2,16);if(t instanceof Promise&&(t=await t),!t)break;let n=Gs(t);if(!n)break;if(i.has(n.id))return{pos:a,found:!0};Qs(n.size),a=t.filePos+n.size}return{pos:r!==null&&r>a?r:a,found:!1}},Xs=async(e,t,n,r)=>{let i=2**16,a=new Set(n),o=t;for(;o<r;){let t=e.requestSliceRange(o,0,Math.min(i,r-o));if(t instanceof Promise&&(t=await t),!t||t.length<8)break;for(let e=0;e<t.length-8;e++){t.filePos=o;let e=Us(t);if(e!==null&&a.has(e))return o;o++}}return null},Zs={avc:`V_MPEG4/ISO/AVC`,hevc:`V_MPEGH/ISO/HEVC`,vp8:`V_VP8`,vp9:`V_VP9`,av1:`V_AV1`,aac:`A_AAC`,mp3:`A_MPEG/L3`,opus:`A_OPUS`,vorbis:`A_VORBIS`,flac:`A_FLAC`,ac3:`A_AC3`,eac3:`A_EAC3`,"pcm-u8":`A_PCM/INT/LIT`,"pcm-s16":`A_PCM/INT/LIT`,"pcm-s16be":`A_PCM/INT/BIG`,"pcm-s24":`A_PCM/INT/LIT`,"pcm-s24be":`A_PCM/INT/BIG`,"pcm-s32":`A_PCM/INT/LIT`,"pcm-s32be":`A_PCM/INT/BIG`,"pcm-f32":`A_PCM/FLOAT/IEEE`,"pcm-f64":`A_PCM/FLOAT/IEEE`,webvtt:`S_TEXT/WEBVTT`};function Qs(e){if(e===void 0)throw Error(`Undefined element size is used in a place where it is not supported.`)}var $s=e=>{let t=(e.hasVideo?`video/`:e.hasAudio?`audio/`:`application/`)+(e.isWebM?`webm`:`x-matroska`);if(e.codecStrings.length>0){let n=[...new Set(e.codecStrings.filter(Boolean))];t+=`; codecs="${n.join(`, `)}"`}return t},ec;(function(e){e[e.None=0]=`None`,e[e.Xiph=1]=`Xiph`,e[e.FixedSize=2]=`FixedSize`,e[e.Ebml=3]=`Ebml`})(ec||={});var tc;(function(e){e[e.Block=1]=`Block`,e[e.Private=2]=`Private`,e[e.Next=4]=`Next`})(tc||={});var nc;(function(e){e[e.Zlib=0]=`Zlib`,e[e.Bzlib=1]=`Bzlib`,e[e.lzo1x=2]=`lzo1x`,e[e.HeaderStripping=3]=`HeaderStripping`})(nc||={});var rc=[{id:U.SeekHead,flag:`seekHeadSeen`},{id:U.Info,flag:`infoSeen`},{id:U.Tracks,flag:`tracksSeen`},{id:U.Cues,flag:`cuesSeen`}],ic=10*2**20,ac=class extends To{constructor(e){super(e),this.readMetadataPromise=null,this.segments=[],this.currentSegment=null,this.currentTrack=null,this.currentCluster=null,this.currentBlock=null,this.currentBlockAdditional=null,this.currentCueTime=null,this.currentDecodingInstruction=null,this.currentTagTargetIsMovie=!0,this.currentSimpleTagName=null,this.currentAttachedFile=null,this.isWebM=!1,this.reader=e._reader}async computeDuration(){let e=await this.getTracks(),t=await Promise.all(e.map(e=>e.computeDuration()));return Math.max(0,...t)}async getTracks(){return await this.readMetadata(),this.segments.flatMap(e=>e.tracks.map(e=>e.inputTrack))}async getMimeType(){await this.readMetadata();let e=await this.getTracks(),t=await Promise.all(e.map(e=>e.getCodecParameterString()));return $s({isWebM:this.isWebM,hasVideo:this.segments.some(e=>e.tracks.some(e=>e.info?.type===`video`)),hasAudio:this.segments.some(e=>e.tracks.some(e=>e.info?.type===`audio`)),codecStrings:t.filter(Boolean)})}async getMetadataTags(){await this.readMetadata();for(let e of this.segments)e.metadataTagsCollected||=(this.reader.fileSize!==null&&await this.loadSegmentMetadata(e),!0);let e={};for(let t of this.segments)e={...e,...t.metadataTags};return e}readMetadata(){return this.readMetadataPromise??=(async()=>{let e=0;for(;;){let t=this.reader.requestSliceRange(e,2,16);if(t instanceof Promise&&(t=await t),!t)break;let n=Gs(t);if(!n)break;let r=n.id,i=n.size,a=t.filePos;if(r===U.EBML){Qs(i);let e=this.reader.requestSlice(a,i);if(e instanceof Promise&&(e=await e),!e)break;this.readContiguousElements(e)}else if(r===U.Segment){if(await this.readSegment(a,i),i===void 0||this.reader.fileSize===null)break}else if(r===U.Cluster){if(this.reader.fileSize===null)break;i===void 0&&(i=(await Ys(this.reader,a,zs,this.reader.fileSize)).pos-a);let e=L(this.segments);e&&(e.elementEndPos=a+i)}Qs(i),e=a+i}})()}async readSegment(e,t){this.currentSegment={seekHeadSeen:!1,infoSeen:!1,tracksSeen:!1,cuesSeen:!1,tagsSeen:!1,attachmentsSeen:!1,timestampScale:-1,timestampFactor:-1,duration:-1,seekEntries:[],tracks:[],cuePoints:[],dataStartPos:e,elementEndPos:t===void 0?null:e+t,clusterSeekStartPos:e,lastReadCluster:null,metadataTags:{},metadataTagsCollected:!1},this.segments.push(this.currentSegment);let n=e;for(;this.currentSegment.elementEndPos===null||n<this.currentSegment.elementEndPos;){let e=this.reader.requestSliceRange(n,2,16);if(e instanceof Promise&&(e=await e),!e)break;let t=n,r=Gs(e);if(!r||!Rs.includes(r.id)&&r.id!==U.Void){let e=await Xs(this.reader,t,Rs,Math.min(this.currentSegment.elementEndPos??1/0,t+ic));if(e){n=e;continue}else break}let{id:i,size:a}=r,o=e.filePos,s=rc.findIndex(e=>e.id===i);if(s!==-1){let e=rc[s].flag;this.currentSegment[e]=!0,Qs(a);let t=this.reader.requestSlice(o,a);t instanceof Promise&&(t=await t),t&&this.readContiguousElements(t)}else if(i===U.Tags||i===U.Attachments){i===U.Tags?this.currentSegment.tagsSeen=!0:this.currentSegment.attachmentsSeen=!0,Qs(a);let e=this.reader.requestSlice(o,a);e instanceof Promise&&(e=await e),e&&this.readContiguousElements(e)}else if(i===U.Cluster){this.currentSegment.clusterSeekStartPos=t;break}if(a===void 0)break;n=o+a}if(this.currentSegment.seekEntries.sort((e,t)=>e.segmentPosition-t.segmentPosition),this.reader.fileSize!==null)for(let t of this.currentSegment.seekEntries){let n=rc.find(e=>e.id===t.id);if(!n||this.currentSegment[n.flag])continue;let r=this.reader.requestSliceRange(e+t.segmentPosition,2,16);if(r instanceof Promise&&(r=await r),!r)continue;let i=Gs(r);if(!i)continue;let{id:a,size:o}=i;if(a!==n.id)continue;Qs(o),this.currentSegment[n.flag]=!0;let s=this.reader.requestSlice(r.filePos,o);s instanceof Promise&&(s=await s),s&&this.readContiguousElements(s)}this.currentSegment.timestampScale===-1&&(this.currentSegment.timestampScale=1e6,this.currentSegment.timestampFactor=1e9/1e6);for(let e of this.currentSegment.tracks)e.defaultDurationNs!==null&&(e.defaultDuration=this.currentSegment.timestampFactor*e.defaultDurationNs/1e9);this.currentSegment.tracks.sort((e,t)=>Number(t.disposition.default)-Number(e.disposition.default));let r=new Map(this.currentSegment.tracks.map(e=>[e.id,e]));for(let e of this.currentSegment.cuePoints){let t=r.get(e.trackId);t&&t.cuePoints.push(e)}for(let e of this.currentSegment.tracks){e.cuePoints.sort((e,t)=>e.time-t.time);for(let t=0;t<e.cuePoints.length-1;t++){let n=e.cuePoints[t],r=e.cuePoints[t+1];n.time===r.time&&(e.cuePoints.splice(t+1,1),t--)}}let i=null,a=-1/0;for(let e of this.currentSegment.tracks)e.cuePoints.length>a&&(a=e.cuePoints.length,i=e);for(let e of this.currentSegment.tracks)e.cuePoints.length===0&&(e.cuePoints=i.cuePoints);this.currentSegment=null}async readCluster(e,t){if(t.lastReadCluster?.elementStartPos===e)return t.lastReadCluster;let n=this.reader.requestSliceRange(e,2,16);n instanceof Promise&&(n=await n),I(n);let r=e,i=Gs(n);I(i);let a=i.id;I(a===U.Cluster);let o=i.size,s=n.filePos;o===void 0&&(o=(await Ys(this.reader,s,zs,t.elementEndPos)).pos-s);let c=this.reader.requestSlice(s,o);c instanceof Promise&&(c=await c);let l={segment:t,elementStartPos:r,elementEndPos:s+o,dataStartPos:s,timestamp:-1,trackData:new Map};this.currentCluster=l,c&&(l.elementEndPos=this.readContiguousElements(c,zs));for(let[,e]of l.trackData){let t=e.track;I(e.blocks.length>0);let n=!1;for(let t=0;t<e.blocks.length;t++){let r=e.blocks[t];r.timestamp+=l.timestamp,n||=r.lacing!==ec.None}e.presentationTimestamps=e.blocks.map((e,t)=>({timestamp:e.timestamp,blockIndex:t})).sort((e,t)=>e.timestamp-t.timestamp);for(let n=0;n<e.presentationTimestamps.length;n++){let r=e.presentationTimestamps[n],i=e.blocks[r.blockIndex];e.firstKeyFrameTimestamp===null&&i.isKeyFrame&&(e.firstKeyFrameTimestamp=i.timestamp),n<e.presentationTimestamps.length-1?i.duration=e.presentationTimestamps[n+1].timestamp-i.timestamp:i.duration===0&&t.defaultDuration!=null&&i.lacing===ec.None&&(i.duration=t.defaultDuration)}n&&(this.expandLacedBlocks(e.blocks,t),e.presentationTimestamps=e.blocks.map((e,t)=>({timestamp:e.timestamp,blockIndex:t})).sort((e,t)=>e.timestamp-t.timestamp));let i=e.blocks[e.presentationTimestamps[0].blockIndex],a=e.blocks[L(e.presentationTimestamps).blockIndex];e.startTimestamp=i.timestamp,e.endTimestamp=a.timestamp+a.duration;let o=B(t.clusterPositionCache,e.startTimestamp,e=>e.startTimestamp);(o===-1||t.clusterPositionCache[o].elementStartPos!==r)&&t.clusterPositionCache.splice(o+1,0,{elementStartPos:l.elementStartPos,startTimestamp:e.startTimestamp})}return t.lastReadCluster=l,l}getTrackDataInCluster(e,t){let n=e.trackData.get(t);if(!n){let r=e.segment.tracks.find(e=>e.id===t);if(!r)return null;n={track:r,startTimestamp:0,endTimestamp:0,firstKeyFrameTimestamp:null,blocks:[],presentationTimestamps:[]},e.trackData.set(t,n)}return n}expandLacedBlocks(e,t){for(let n=0;n<e.length;n++){let r=e[n];if(r.lacing===ec.None)continue;r.decoded||=(r.data=this.decodeBlockData(t,r.data),!0);let i=Dl.tempFromBytes(r.data),a=[],o=K(i)+1;switch(r.lacing){case ec.Xiph:{let e=0;for(let t=0;t<o-1;t++){let t=0;for(;i.bufferPos<i.length;){let n=K(i);if(t+=n,n<255){a.push(t),e+=t;break}}}a.push(i.length-(i.bufferPos+e))}break;case ec.FixedSize:{let e=i.length-1,t=Math.floor(e/o);for(let e=0;e<o;e++)a.push(t)}break;case ec.Ebml:{let e=Vs(i);I(e!==null);let t=e;a.push(t);let n=t;for(let e=1;e<o-1;e++){let e=i.bufferPos,r=Vs(i);I(r!==null);let o=r-((1<<(i.bufferPos-e)*7-1)-1);t+=o,a.push(t),n+=t}a.push(i.length-(i.bufferPos+n))}break;default:I(!1)}I(a.length===o),e.splice(n,1);let s=r.duration||o*(t.defaultDuration??0);for(let t=0;t<o;t++){let c=a[t],l=G(i,c),u=r.timestamp+s*t/o,d=s/o;e.splice(n+t,0,{timestamp:u,duration:d,isKeyFrame:r.isKeyFrame,data:l,lacing:ec.None,decoded:!0,mainAdditional:r.mainAdditional})}n+=o,n--}}async loadSegmentMetadata(e){for(let t of e.seekEntries){if(!(t.id===U.Tags&&!e.tagsSeen)&&!(t.id===U.Attachments&&!e.attachmentsSeen))continue;let n=this.reader.requestSliceRange(e.dataStartPos+t.segmentPosition,2,16);if(n instanceof Promise&&(n=await n),!n)continue;let r=Gs(n);if(!r||r.id!==t.id)continue;let{size:i}=r;Qs(i),I(!this.currentSegment),this.currentSegment=e;let a=this.reader.requestSlice(n.filePos,i);a instanceof Promise&&(a=await a),a&&this.readContiguousElements(a),this.currentSegment=null,t.id===U.Tags?e.tagsSeen=!0:t.id===U.Attachments&&(e.attachmentsSeen=!0)}}readContiguousElements(e,t){for(;e.remainingLength>=2;){let n=e.filePos;if(!this.traverseElement(e,t))return n}return e.filePos}traverseElement(e,t){let n=Gs(e);if(!n||t&&t.includes(n.id))return!1;let{id:r,size:i}=n,a=e.filePos;switch(Qs(i),r){case U.DocType:this.isWebM=Ks(e,i)===`webm`;break;case U.Seek:{if(!this.currentSegment)break;let t={id:-1,segmentPosition:-1};this.currentSegment.seekEntries.push(t),this.readContiguousElements(e.slice(a,i)),(t.id===-1||t.segmentPosition===-1)&&this.currentSegment.seekEntries.pop()}break;case U.SeekID:{let t=this.currentSegment?.seekEntries[this.currentSegment.seekEntries.length-1];if(!t)break;t.id=W(e,i)}break;case U.SeekPosition:{let t=this.currentSegment?.seekEntries[this.currentSegment.seekEntries.length-1];if(!t)break;t.segmentPosition=W(e,i)}break;case U.TimestampScale:if(!this.currentSegment)break;this.currentSegment.timestampScale=W(e,i),this.currentSegment.timestampFactor=1e9/this.currentSegment.timestampScale;break;case U.Duration:if(!this.currentSegment)break;this.currentSegment.duration=Js(e,i);break;case U.TrackEntry:if(!this.currentSegment||(this.currentTrack={id:-1,segment:this.currentSegment,demuxer:this,clusterPositionCache:[],cuePoints:[],disposition:{...zi},inputTrack:null,codecId:null,codecPrivate:null,defaultDuration:null,defaultDurationNs:null,name:null,languageCode:`und`,decodingInstructions:[],info:null},this.readContiguousElements(e.slice(a,i)),!this.currentTrack))break;if(this.currentTrack.decodingInstructions.some(e=>e.data?.type!==`decompress`||e.scope!==tc.Block||e.data.algorithm!==nc.HeaderStripping)&&(console.warn(`Track #${this.currentTrack.id} has an unsupported content encoding; dropping.`),this.currentTrack=null),this.currentTrack&&this.currentTrack.id!==-1&&this.currentTrack.codecId&&this.currentTrack.info){let e=this.currentTrack.codecId.indexOf(`/`),t=e===-1?this.currentTrack.codecId:this.currentTrack.codecId.slice(0,e);if(this.currentTrack.info.type===`video`&&this.currentTrack.info.width!==-1&&this.currentTrack.info.height!==-1){if(this.currentTrack.info.squarePixelWidth=this.currentTrack.info.width,this.currentTrack.info.squarePixelHeight=this.currentTrack.info.height,this.currentTrack.info.displayWidth!==null&&this.currentTrack.info.displayHeight!==null){let e=this.currentTrack.info.displayWidth*this.currentTrack.info.height,t=this.currentTrack.info.displayHeight*this.currentTrack.info.width;e>t?this.currentTrack.info.squarePixelWidth=Math.round(this.currentTrack.info.width*e/t):this.currentTrack.info.squarePixelHeight=Math.round(this.currentTrack.info.height*t/e)}this.currentTrack.codecId===Zs.avc?(this.currentTrack.info.codec=`avc`,this.currentTrack.info.codecDescription=this.currentTrack.codecPrivate):this.currentTrack.codecId===Zs.hevc?(this.currentTrack.info.codec=`hevc`,this.currentTrack.info.codecDescription=this.currentTrack.codecPrivate):t===Zs.vp8?this.currentTrack.info.codec=`vp8`:t===Zs.vp9?this.currentTrack.info.codec=`vp9`:t===Zs.av1&&(this.currentTrack.info.codec=`av1`);let e=this.currentTrack,n=new _s(this.input,new sc(e));this.currentTrack.inputTrack=n,this.currentSegment.tracks.push(this.currentTrack)}else if(this.currentTrack.info.type===`audio`&&this.currentTrack.info.numberOfChannels!==-1&&this.currentTrack.info.sampleRate!==-1){t===Zs.aac?(this.currentTrack.info.codec=`aac`,this.currentTrack.info.aacCodecInfo={isMpeg2:this.currentTrack.codecId.includes(`MPEG2`),objectType:null},this.currentTrack.info.codecDescription=this.currentTrack.codecPrivate):this.currentTrack.codecId===Zs.mp3?this.currentTrack.info.codec=`mp3`:t===Zs.opus?(this.currentTrack.info.codec=`opus`,this.currentTrack.info.codecDescription=this.currentTrack.codecPrivate,this.currentTrack.info.sampleRate=sa):t===Zs.vorbis?(this.currentTrack.info.codec=`vorbis`,this.currentTrack.info.codecDescription=this.currentTrack.codecPrivate):t===Zs.flac?(this.currentTrack.info.codec=`flac`,this.currentTrack.info.codecDescription=this.currentTrack.codecPrivate):t===Zs.ac3?(this.currentTrack.info.codec=`ac3`,this.currentTrack.info.codecDescription=this.currentTrack.codecPrivate):t===Zs.eac3?(this.currentTrack.info.codec=`eac3`,this.currentTrack.info.codecDescription=this.currentTrack.codecPrivate):this.currentTrack.codecId===`A_PCM/INT/LIT`?this.currentTrack.info.bitDepth===8?this.currentTrack.info.codec=`pcm-u8`:this.currentTrack.info.bitDepth===16?this.currentTrack.info.codec=`pcm-s16`:this.currentTrack.info.bitDepth===24?this.currentTrack.info.codec=`pcm-s24`:this.currentTrack.info.bitDepth===32&&(this.currentTrack.info.codec=`pcm-s32`):this.currentTrack.codecId===`A_PCM/INT/BIG`?this.currentTrack.info.bitDepth===8?this.currentTrack.info.codec=`pcm-u8`:this.currentTrack.info.bitDepth===16?this.currentTrack.info.codec=`pcm-s16be`:this.currentTrack.info.bitDepth===24?this.currentTrack.info.codec=`pcm-s24be`:this.currentTrack.info.bitDepth===32&&(this.currentTrack.info.codec=`pcm-s32be`):this.currentTrack.codecId===`A_PCM/FLOAT/IEEE`&&(this.currentTrack.info.bitDepth===32?this.currentTrack.info.codec=`pcm-f32`:this.currentTrack.info.bitDepth===64&&(this.currentTrack.info.codec=`pcm-f64`));let e=this.currentTrack,n=new vs(this.input,new cc(e));this.currentTrack.inputTrack=n,this.currentSegment.tracks.push(this.currentTrack)}}this.currentTrack=null;break;case U.TrackNumber:if(!this.currentTrack)break;this.currentTrack.id=W(e,i);break;case U.TrackType:{if(!this.currentTrack)break;let t=W(e,i);t===1?this.currentTrack.info={type:`video`,width:-1,height:-1,displayWidth:null,displayHeight:null,displayUnit:null,squarePixelWidth:-1,squarePixelHeight:-1,rotation:0,codec:null,codecDescription:null,colorSpace:null,alphaMode:!1}:t===2&&(this.currentTrack.info={type:`audio`,numberOfChannels:-1,sampleRate:-1,bitDepth:-1,codec:null,codecDescription:null,aacCodecInfo:null})}break;case U.FlagEnabled:if(!this.currentTrack)break;W(e,i)||(this.currentTrack=null);break;case U.FlagDefault:if(!this.currentTrack)break;this.currentTrack.disposition.default=!!W(e,i);break;case U.FlagForced:if(!this.currentTrack)break;this.currentTrack.disposition.forced=!!W(e,i);break;case U.FlagOriginal:if(!this.currentTrack)break;this.currentTrack.disposition.original=!!W(e,i);break;case U.FlagHearingImpaired:if(!this.currentTrack)break;this.currentTrack.disposition.hearingImpaired=!!W(e,i);break;case U.FlagVisualImpaired:if(!this.currentTrack)break;this.currentTrack.disposition.visuallyImpaired=!!W(e,i);break;case U.FlagCommentary:if(!this.currentTrack)break;this.currentTrack.disposition.commentary=!!W(e,i);break;case U.CodecID:if(!this.currentTrack)break;this.currentTrack.codecId=Ks(e,i);break;case U.CodecPrivate:if(!this.currentTrack)break;this.currentTrack.codecPrivate=G(e,i);break;case U.DefaultDuration:if(!this.currentTrack)break;this.currentTrack.defaultDurationNs=W(e,i);break;case U.Name:if(!this.currentTrack)break;this.currentTrack.name=qs(e,i);break;case U.Language:if(!this.currentTrack||this.currentTrack.languageCode!==`und`)break;this.currentTrack.languageCode=Ks(e,i),gi(this.currentTrack.languageCode)||(this.currentTrack.languageCode=`und`);break;case U.LanguageBCP47:{if(!this.currentTrack)break;let t=Ks(e,i).split(`-`)[0];t?this.currentTrack.languageCode=t:this.currentTrack.languageCode=`und`}break;case U.Video:if(this.currentTrack?.info?.type!==`video`)break;this.readContiguousElements(e.slice(a,i));break;case U.PixelWidth:if(this.currentTrack?.info?.type!==`video`)break;this.currentTrack.info.width=W(e,i);break;case U.PixelHeight:if(this.currentTrack?.info?.type!==`video`)break;this.currentTrack.info.height=W(e,i);break;case U.DisplayWidth:if(this.currentTrack?.info?.type!==`video`)break;this.currentTrack.info.displayWidth=W(e,i);break;case U.DisplayHeight:if(this.currentTrack?.info?.type!==`video`)break;this.currentTrack.info.displayHeight=W(e,i);break;case U.DisplayUnit:if(this.currentTrack?.info?.type!==`video`)break;this.currentTrack.info.displayUnit=W(e,i);break;case U.AlphaMode:if(this.currentTrack?.info?.type!==`video`)break;this.currentTrack.info.alphaMode=W(e,i)===1;break;case U.Colour:if(this.currentTrack?.info?.type!==`video`)break;this.currentTrack.info.colorSpace={},this.readContiguousElements(e.slice(a,i));break;case U.MatrixCoefficients:{if(this.currentTrack?.info?.type!==`video`||!this.currentTrack.info.colorSpace)break;let t=Gr[W(e,i)]??null;this.currentTrack.info.colorSpace.matrix=t}break;case U.Range:if(this.currentTrack?.info?.type!==`video`||!this.currentTrack.info.colorSpace)break;this.currentTrack.info.colorSpace.fullRange=W(e,i)===2;break;case U.TransferCharacteristics:{if(this.currentTrack?.info?.type!==`video`||!this.currentTrack.info.colorSpace)break;let t=Ur[W(e,i)]??null;this.currentTrack.info.colorSpace.transfer=t}break;case U.Primaries:{if(this.currentTrack?.info?.type!==`video`||!this.currentTrack.info.colorSpace)break;let t=Vr[W(e,i)]??null;this.currentTrack.info.colorSpace.primaries=t}break;case U.Projection:if(this.currentTrack?.info?.type!==`video`)break;this.readContiguousElements(e.slice(a,i));break;case U.ProjectionPoseRoll:{if(this.currentTrack?.info?.type!==`video`)break;let t=-Js(e,i);try{this.currentTrack.info.rotation=Nr(t)}catch{}}break;case U.Audio:if(this.currentTrack?.info?.type!==`audio`)break;this.readContiguousElements(e.slice(a,i));break;case U.SamplingFrequency:if(this.currentTrack?.info?.type!==`audio`)break;this.currentTrack.info.sampleRate=Js(e,i);break;case U.Channels:if(this.currentTrack?.info?.type!==`audio`)break;this.currentTrack.info.numberOfChannels=W(e,i);break;case U.BitDepth:if(this.currentTrack?.info?.type!==`audio`)break;this.currentTrack.info.bitDepth=W(e,i);break;case U.CuePoint:if(!this.currentSegment)break;this.readContiguousElements(e.slice(a,i)),this.currentCueTime=null;break;case U.CueTime:this.currentCueTime=W(e,i);break;case U.CueTrackPositions:{if(this.currentCueTime===null)break;I(this.currentSegment);let t={time:this.currentCueTime,trackId:-1,clusterPosition:-1};this.currentSegment.cuePoints.push(t),this.readContiguousElements(e.slice(a,i)),(t.trackId===-1||t.clusterPosition===-1)&&this.currentSegment.cuePoints.pop()}break;case U.CueTrack:{let t=this.currentSegment?.cuePoints[this.currentSegment.cuePoints.length-1];if(!t)break;t.trackId=W(e,i)}break;case U.CueClusterPosition:{let t=this.currentSegment?.cuePoints[this.currentSegment.cuePoints.length-1];if(!t)break;I(this.currentSegment),t.clusterPosition=this.currentSegment.dataStartPos+W(e,i)}break;case U.Timestamp:if(!this.currentCluster)break;this.currentCluster.timestamp=W(e,i);break;case U.SimpleBlock:{if(!this.currentCluster)break;let t=Vs(e);if(t===null)break;let n=this.getTrackDataInCluster(this.currentCluster,t);if(!n)break;let r=Ml(e),o=K(e),s=o>>1&3,c=!!(o&128);n.track.info?.type===`audio`&&n.track.info.codec&&(c=!0);let l=G(e,i-(e.filePos-a)),u=n.track.decodingInstructions.length>0;n.blocks.push({timestamp:r,duration:0,isKeyFrame:c,data:l,lacing:s,decoded:!u,mainAdditional:null})}break;case U.BlockGroup:if(!this.currentCluster)break;this.readContiguousElements(e.slice(a,i)),this.currentBlock=null;break;case U.Block:{if(!this.currentCluster)break;let t=Vs(e);if(t===null)break;let n=this.getTrackDataInCluster(this.currentCluster,t);if(!n)break;let r=Ml(e),o=K(e)>>1&3;this.currentBlock={timestamp:r,duration:0,isKeyFrame:!0,data:G(e,i-(e.filePos-a)),lacing:o,decoded:!(n.track.decodingInstructions.length>0),mainAdditional:null},n.blocks.push(this.currentBlock)}break;case U.BlockAdditions:this.readContiguousElements(e.slice(a,i));break;case U.BlockMore:if(!this.currentBlock)break;this.currentBlockAdditional={addId:1,data:null},this.readContiguousElements(e.slice(a,i)),this.currentBlockAdditional.data&&this.currentBlockAdditional.addId===1&&(this.currentBlock.mainAdditional=this.currentBlockAdditional.data),this.currentBlockAdditional=null;break;case U.BlockAdditional:if(!this.currentBlockAdditional)break;this.currentBlockAdditional.data=G(e,i);break;case U.BlockAddID:if(!this.currentBlockAdditional)break;this.currentBlockAdditional.addId=W(e,i);break;case U.BlockDuration:if(!this.currentBlock)break;this.currentBlock.duration=W(e,i);break;case U.ReferenceBlock:if(!this.currentBlock)break;this.currentBlock.isKeyFrame=!1;break;case U.Tag:this.currentTagTargetIsMovie=!0,this.readContiguousElements(e.slice(a,i));break;case U.Targets:this.readContiguousElements(e.slice(a,i));break;case U.TargetTypeValue:W(e,i)!==50&&(this.currentTagTargetIsMovie=!1);break;case U.TagTrackUID:case U.TagEditionUID:case U.TagChapterUID:case U.TagAttachmentUID:this.currentTagTargetIsMovie=!1;break;case U.SimpleTag:if(!this.currentTagTargetIsMovie)break;this.currentSimpleTagName=null,this.readContiguousElements(e.slice(a,i));break;case U.TagName:this.currentSimpleTagName=qs(e,i);break;case U.TagString:{if(!this.currentSimpleTagName)break;let t=qs(e,i);this.processTagValue(this.currentSimpleTagName,t)}break;case U.TagBinary:{if(!this.currentSimpleTagName)break;let t=G(e,i);this.processTagValue(this.currentSimpleTagName,t)}break;case U.AttachedFile:{if(!this.currentSegment)break;this.currentAttachedFile={fileUid:null,fileName:null,fileMediaType:null,fileData:null,fileDescription:null},this.readContiguousElements(e.slice(a,i));let t=this.currentSegment.metadataTags;if(this.currentAttachedFile.fileUid&&this.currentAttachedFile.fileData&&(t.raw??={},t.raw[this.currentAttachedFile.fileUid.toString()]=new Li(this.currentAttachedFile.fileData,this.currentAttachedFile.fileMediaType??void 0,this.currentAttachedFile.fileName??void 0,this.currentAttachedFile.fileDescription??void 0)),this.currentAttachedFile.fileMediaType?.startsWith(`image/`)&&this.currentAttachedFile.fileData){let e=this.currentAttachedFile.fileName,n=`unknown`;if(e){let t=e.toLowerCase();t.startsWith(`cover.`)?n=`coverFront`:t.startsWith(`back.`)&&(n=`coverBack`)}t.images??=[],t.images.push({data:this.currentAttachedFile.fileData,mimeType:this.currentAttachedFile.fileMediaType,kind:n,name:this.currentAttachedFile.fileName??void 0,description:this.currentAttachedFile.fileDescription??void 0})}this.currentAttachedFile=null}break;case U.FileUID:if(!this.currentAttachedFile)break;this.currentAttachedFile.fileUid=Hs(e,i);break;case U.FileName:if(!this.currentAttachedFile)break;this.currentAttachedFile.fileName=qs(e,i);break;case U.FileMediaType:if(!this.currentAttachedFile)break;this.currentAttachedFile.fileMediaType=Ks(e,i);break;case U.FileData:if(!this.currentAttachedFile)break;this.currentAttachedFile.fileData=G(e,i);break;case U.FileDescription:if(!this.currentAttachedFile)break;this.currentAttachedFile.fileDescription=qs(e,i);break;case U.ContentEncodings:if(!this.currentTrack)break;this.readContiguousElements(e.slice(a,i)),this.currentTrack.decodingInstructions.sort((e,t)=>t.order-e.order);break;case U.ContentEncoding:this.currentDecodingInstruction={order:0,scope:tc.Block,data:null},this.readContiguousElements(e.slice(a,i)),this.currentDecodingInstruction.data&&this.currentTrack.decodingInstructions.push(this.currentDecodingInstruction),this.currentDecodingInstruction=null;break;case U.ContentEncodingOrder:if(!this.currentDecodingInstruction)break;this.currentDecodingInstruction.order=W(e,i);break;case U.ContentEncodingScope:if(!this.currentDecodingInstruction)break;this.currentDecodingInstruction.scope=W(e,i);break;case U.ContentCompression:if(!this.currentDecodingInstruction)break;this.currentDecodingInstruction.data={type:`decompress`,algorithm:nc.Zlib,settings:null},this.readContiguousElements(e.slice(a,i));break;case U.ContentCompAlgo:if(this.currentDecodingInstruction?.data?.type!==`decompress`)break;this.currentDecodingInstruction.data.algorithm=W(e,i);break;case U.ContentCompSettings:if(this.currentDecodingInstruction?.data?.type!==`decompress`)break;this.currentDecodingInstruction.data.settings=G(e,i);break;case U.ContentEncryption:if(!this.currentDecodingInstruction)break;this.currentDecodingInstruction.data={type:`decrypt`};break}return e.filePos=a+i,!0}decodeBlockData(e,t){I(e.decodingInstructions.length>0);let n=t;for(let t of e.decodingInstructions)switch(I(t.data),t.data.type){case`decompress`:switch(t.data.algorithm){case nc.HeaderStripping:if(t.data.settings&&t.data.settings.length>0){let e=t.data.settings,r=new Uint8Array(e.length+n.length);r.set(e,0),r.set(n,e.length),n=r}break;default:}break;default:}return n}processTagValue(e,t){if(!this.currentSegment?.metadataTags)return;let n=this.currentSegment.metadataTags;if(n.raw??={},n.raw[e]??=t,typeof t==`string`)switch(e.toLowerCase()){case`title`:n.title??=t;break;case`description`:n.description??=t;break;case`artist`:n.artist??=t;break;case`album`:n.album??=t;break;case`album_artist`:n.albumArtist??=t;break;case`genre`:n.genre??=t;break;case`comment`:n.comment??=t;break;case`lyrics`:n.lyrics??=t;break;case`date`:{let e=new Date(t);Number.isNaN(e.getTime())||(n.date??=e)}break;case`track_number`:case`part_number`:{let e=t.split(`/`),r=Number.parseInt(e[0],10),i=e[1]&&Number.parseInt(e[1],10);Number.isInteger(r)&&r>0&&(n.trackNumber??=r),i&&Number.isInteger(i)&&i>0&&(n.tracksTotal??=i)}break;case`disc_number`:case`disc`:{let e=t.split(`/`),r=Number.parseInt(e[0],10),i=e[1]&&Number.parseInt(e[1],10);Number.isInteger(r)&&r>0&&(n.discNumber??=r),i&&Number.isInteger(i)&&i>0&&(n.discsTotal??=i)}break}}},oc=class{constructor(e){this.internalTrack=e,this.packetToClusterLocation=new WeakMap}getId(){return this.internalTrack.id}getNumber(){let e=this.internalTrack.demuxer,t=this.internalTrack.inputTrack.type,n=0;for(let r of e.segments)for(let e of r.tracks)if(e.inputTrack.type===t&&n++,e===this.internalTrack)break;return n}getCodec(){throw Error(`Not implemented on base class.`)}getInternalCodecId(){return this.internalTrack.codecId}async computeDuration(){let e=await this.getPacket(1/0,{metadataOnly:!0});return(e?.timestamp??0)+(e?.duration??0)}getName(){return this.internalTrack.name}getLanguageCode(){return this.internalTrack.languageCode}async getFirstTimestamp(){return(await this.getFirstPacket({metadataOnly:!0}))?.timestamp??0}getTimeResolution(){return this.internalTrack.segment.timestampFactor}getDisposition(){return this.internalTrack.disposition}async getFirstPacket(e){return this.performClusterLookup(null,e=>e.trackData.get(this.internalTrack.id)?{blockIndex:0,correctBlockFound:!0}:{blockIndex:-1,correctBlockFound:!1},-1/0,1/0,e)}intoTimescale(e){return di(e*this.internalTrack.segment.timestampFactor)}async getPacket(e,t){let n=this.intoTimescale(e);return this.performClusterLookup(null,e=>{let t=e.trackData.get(this.internalTrack.id);if(!t)return{blockIndex:-1,correctBlockFound:!1};let r=B(t.presentationTimestamps,n,e=>e.timestamp);return{blockIndex:r===-1?-1:t.presentationTimestamps[r].blockIndex,correctBlockFound:r!==-1&&n<t.endTimestamp}},n,n,t)}async getNextPacket(e,t){let n=this.packetToClusterLocation.get(e);if(n===void 0)throw Error(`Packet was not created from this track.`);return this.performClusterLookup(n.cluster,e=>{if(e===n.cluster){let t=e.trackData.get(this.internalTrack.id);if(n.blockIndex+1<t.blocks.length)return{blockIndex:n.blockIndex+1,correctBlockFound:!0}}else if(e.trackData.get(this.internalTrack.id))return{blockIndex:0,correctBlockFound:!0};return{blockIndex:-1,correctBlockFound:!1}},-1/0,1/0,t)}async getKeyPacket(e,t){let n=this.intoTimescale(e);return this.performClusterLookup(null,e=>{let t=e.trackData.get(this.internalTrack.id);if(!t)return{blockIndex:-1,correctBlockFound:!1};let r=ti(t.presentationTimestamps,e=>t.blocks[e.blockIndex].isKeyFrame&&e.timestamp<=n);return{blockIndex:r===-1?-1:t.presentationTimestamps[r].blockIndex,correctBlockFound:r!==-1&&n<t.endTimestamp}},n,n,t)}async getNextKeyPacket(e,t){let n=this.packetToClusterLocation.get(e);if(n===void 0)throw Error(`Packet was not created from this track.`);return this.performClusterLookup(n.cluster,e=>{if(e===n.cluster){let t=e.trackData.get(this.internalTrack.id).blocks.findIndex((e,t)=>e.isKeyFrame&&t>n.blockIndex);if(t!==-1)return{blockIndex:t,correctBlockFound:!0}}else{let t=e.trackData.get(this.internalTrack.id);if(t&&t.firstKeyFrameTimestamp!==null){let e=t.blocks.findIndex(e=>e.isKeyFrame);return I(e!==-1),{blockIndex:e,correctBlockFound:!0}}}return{blockIndex:-1,correctBlockFound:!1}},-1/0,1/0,t)}async fetchPacketInCluster(e,t,n){if(t===-1)return null;let r=e.trackData.get(this.internalTrack.id).blocks[t];I(r),r.decoded||=(r.data=this.internalTrack.demuxer.decodeBlockData(this.internalTrack,r.data),!0);let i=n.metadataOnly?Ao:r.data,a=r.timestamp/this.internalTrack.segment.timestampFactor,o=r.duration/this.internalTrack.segment.timestampFactor,s={};r.mainAdditional&&this.internalTrack.info?.type===`video`&&this.internalTrack.info.alphaMode&&(s.alpha=n.metadataOnly?Ao:r.mainAdditional,s.alphaByteLength=r.mainAdditional.byteLength);let c=new H(i,r.isKeyFrame?`key`:`delta`,a,o,e.dataStartPos+t,r.data.byteLength,s);return this.packetToClusterLocation.set(c,{cluster:e,blockIndex:t}),c}async performClusterLookup(e,t,n,r,i){let{demuxer:a,segment:o}=this.internalTrack,s=null,c=null,l=-1;if(e){let{blockIndex:n,correctBlockFound:r}=t(e);if(r)return this.fetchPacketInCluster(e,n,i);n!==-1&&(c=e,l=n)}let u=B(this.internalTrack.cuePoints,n,e=>e.time),d=u===-1?null:this.internalTrack.cuePoints[u],f=B(this.internalTrack.clusterPositionCache,n,e=>e.startTimestamp),p=f===-1?null:this.internalTrack.clusterPositionCache[f],m=Math.max(d?.clusterPosition??0,p?.elementStartPos??0)||null,h;for(e?m===null||e.elementStartPos>=m?(h=e.elementEndPos,s=e):h=m:h=m??o.clusterSeekStartPos;o.elementEndPos===null||h<=o.elementEndPos-2;){if(s){let e=s.trackData.get(this.internalTrack.id);if(e&&e.startTimestamp>r)break}let e=a.reader.requestSliceRange(h,2,16);if(e instanceof Promise&&(e=await e),!e)break;let n=h,u=Gs(e);if(!u||!Rs.includes(u.id)&&u.id!==U.Void){let e=await Xs(a.reader,n,Rs,Math.min(o.elementEndPos??1/0,n+ic));if(e){h=e;continue}else break}let d=u.id,f=u.size,p=e.filePos;if(d===U.Cluster){s=await a.readCluster(n,o),f=s.elementEndPos-p;let{blockIndex:e,correctBlockFound:r}=t(s);if(r)return this.fetchPacketInCluster(s,e,i);e!==-1&&(c=s,l=e)}f===void 0&&(I(d!==U.Cluster),f=(await Ys(a.reader,p,zs,o.elementEndPos)).pos-p);let m=p+f;if(o.elementEndPos===null){let e=a.reader.requestSliceRange(m,2,16);if(e instanceof Promise&&(e=await e),!e)break;if(Us(e)===U.Segment){o.elementEndPos=m;break}}h=m}if(d&&(!c||c.elementStartPos<d.clusterPosition)){let e=this.internalTrack.cuePoints[u-1];I(!e||e.time<d.time);let n=e?.time??-1/0;return this.performClusterLookup(null,t,n,r,i)}return c?this.fetchPacketInCluster(c,l,i):null}},sc=class extends oc{constructor(e){super(e),this.decoderConfigPromise=null,this.internalTrack=e}getCodec(){return this.internalTrack.info.codec}getCodedWidth(){return this.internalTrack.info.width}getCodedHeight(){return this.internalTrack.info.height}getSquarePixelWidth(){return this.internalTrack.info.squarePixelWidth}getSquarePixelHeight(){return this.internalTrack.info.squarePixelHeight}getRotation(){return this.internalTrack.info.rotation}async getColorSpace(){return{primaries:this.internalTrack.info.colorSpace?.primaries,transfer:this.internalTrack.info.colorSpace?.transfer,matrix:this.internalTrack.info.colorSpace?.matrix,fullRange:this.internalTrack.info.colorSpace?.fullRange}}async canBeTransparent(){return this.internalTrack.info.alphaMode}async getDecoderConfig(){return this.internalTrack.info.codec?this.decoderConfigPromise??=(async()=>{let e=null;return(this.internalTrack.info.codec===`vp9`||this.internalTrack.info.codec===`av1`||this.internalTrack.info.codec===`avc`&&!this.internalTrack.info.codecDescription||this.internalTrack.info.codec===`hevc`&&!this.internalTrack.info.codecDescription)&&(e=await this.getFirstPacket({})),{codec:ia({width:this.internalTrack.info.width,height:this.internalTrack.info.height,codec:this.internalTrack.info.codec,codecDescription:this.internalTrack.info.codecDescription,colorSpace:this.internalTrack.info.colorSpace,avcType:1,avcCodecInfo:this.internalTrack.info.codec===`avc`&&e?Va(e.data):null,hevcCodecInfo:this.internalTrack.info.codec===`hevc`&&e?Xa(e.data):null,vp9CodecInfo:this.internalTrack.info.codec===`vp9`&&e?ao(e.data):null,av1CodecInfo:this.internalTrack.info.codec===`av1`&&e?so(e.data):null}),codedWidth:this.internalTrack.info.width,codedHeight:this.internalTrack.info.height,displayAspectWidth:this.internalTrack.info.squarePixelWidth,displayAspectHeight:this.internalTrack.info.squarePixelHeight,description:this.internalTrack.info.codecDescription??void 0,colorSpace:this.internalTrack.info.colorSpace??void 0}})():null}},cc=class extends oc{constructor(e){super(e),this.decoderConfig=null,this.internalTrack=e}getCodec(){return this.internalTrack.info.codec}getNumberOfChannels(){return this.internalTrack.info.numberOfChannels}getSampleRate(){return this.internalTrack.info.sampleRate}async getDecoderConfig(){return this.internalTrack.info.codec?this.decoderConfig??={codec:oa({codec:this.internalTrack.info.codec,codecDescription:this.internalTrack.info.codecDescription,aacCodecInfo:this.internalTrack.info.aacCodecInfo}),numberOfChannels:this.internalTrack.info.numberOfChannels,sampleRate:this.internalTrack.info.sampleRate,description:this.internalTrack.info.codecDescription??void 0}:null}},lc=async(e,t,n)=>{let r=t;for(;n===null||r<n;){let t=e.requestSlice(r,4);if(t instanceof Promise&&(t=await t),!t)break;let n=Ea(q(t),e.fileSize===null?null:e.fileSize-r);if(n.header)return{header:n.header,startPos:r};r+=n.bytesAdvanced}return null},uc=class extends To{constructor(e){super(e),this.metadataPromise=null,this.firstFrameHeader=null,this.loadedSamples=[],this.metadataTags=null,this.tracks=[],this.readingMutex=new Jr,this.lastSampleLoaded=!1,this.lastLoadedPos=0,this.nextTimestampInSamples=0,this.reader=e._reader}async readMetadata(){return this.metadataPromise??=(async()=>{for(;!this.firstFrameHeader&&!this.lastSampleLoaded;)await this.advanceReader();if(!this.firstFrameHeader)throw Error(`No valid MP3 frame found.`);this.tracks=[new vs(this.input,new dc(this))]})()}async advanceReader(){if(this.lastLoadedPos===0)for(;;){let e=this.reader.requestSlice(this.lastLoadedPos,10);if(e instanceof Promise&&(e=await e),!e){this.lastSampleLoaded=!0;return}let t=Yl(e);if(!t)break;this.lastLoadedPos=e.filePos+t.size}let e=await lc(this.reader,this.lastLoadedPos,this.reader.fileSize);if(!e){this.lastSampleLoaded=!0;return}let t=e.header;this.lastLoadedPos=e.startPos+t.totalSize-1;let n=Ta(t.mpegVersionId,t.channel),r=this.reader.requestSlice(e.startPos+n,4);if(r instanceof Promise&&(r=await r),r){let e=q(r);if(e===1483304551||e===1231971951)return}this.firstFrameHeader||=t,t.sampleRate!==this.firstFrameHeader.sampleRate&&console.warn(`MP3 changed sample rate mid-file: ${this.firstFrameHeader.sampleRate} Hz to ${t.sampleRate} Hz. Might be a bug, so please report this file.`);let i=t.audioSamplesInFrame/this.firstFrameHeader.sampleRate,a={timestamp:this.nextTimestampInSamples/this.firstFrameHeader.sampleRate,duration:i,dataStart:e.startPos,dataSize:t.totalSize};this.loadedSamples.push(a),this.nextTimestampInSamples+=t.audioSamplesInFrame}async getMimeType(){return`audio/mpeg`}async getTracks(){return await this.readMetadata(),this.tracks}async computeDuration(){await this.readMetadata();let e=this.tracks[0];return I(e),e.computeDuration()}async getMetadataTags(){let e=await this.readingMutex.acquire();try{if(await this.readMetadata(),this.metadataTags)return this.metadataTags;this.metadataTags={};let e=0,t=!1;for(;;){let n=this.reader.requestSlice(e,10);if(n instanceof Promise&&(n=await n),!n)break;let r=Yl(n);if(!r)break;t=!0;let i=this.reader.requestSlice(n.filePos,r.size);if(i instanceof Promise&&(i=await i),!i)break;Xl(i,r,this.metadataTags),e=n.filePos+r.size}if(!t&&this.reader.fileSize!==null&&this.reader.fileSize>=128){let e=this.reader.requestSlice(this.reader.fileSize-128,128);e instanceof Promise&&(e=await e),I(e),Ul(e,3)===`TAG`&&ql(e,this.metadataTags)}return this.metadataTags}finally{e()}}},dc=class{constructor(e){this.demuxer=e}getId(){return 1}getNumber(){return 1}async getFirstTimestamp(){return 0}getTimeResolution(){return I(this.demuxer.firstFrameHeader),this.demuxer.firstFrameHeader.sampleRate/this.demuxer.firstFrameHeader.audioSamplesInFrame}async computeDuration(){let e=await this.getPacket(1/0,{metadataOnly:!0});return(e?.timestamp??0)+(e?.duration??0)}getName(){return null}getLanguageCode(){return`und`}getCodec(){return`mp3`}getInternalCodecId(){return null}getNumberOfChannels(){return I(this.demuxer.firstFrameHeader),this.demuxer.firstFrameHeader.channel===3?1:2}getSampleRate(){return I(this.demuxer.firstFrameHeader),this.demuxer.firstFrameHeader.sampleRate}getDisposition(){return{...zi}}async getDecoderConfig(){return I(this.demuxer.firstFrameHeader),{codec:`mp3`,numberOfChannels:this.demuxer.firstFrameHeader.channel===3?1:2,sampleRate:this.demuxer.firstFrameHeader.sampleRate}}async getPacketAtIndex(e,t){if(e===-1)return null;let n=this.demuxer.loadedSamples[e];if(!n)return null;let r;if(t.metadataOnly)r=Ao;else{let e=this.demuxer.reader.requestSlice(n.dataStart,n.dataSize);if(e instanceof Promise&&(e=await e),!e)return null;r=G(e,n.dataSize)}return new H(r,`key`,n.timestamp,n.duration,e,n.dataSize)}getFirstPacket(e){return this.getPacketAtIndex(0,e)}async getNextPacket(e,t){let n=await this.demuxer.readingMutex.acquire();try{let n=Zr(this.demuxer.loadedSamples,e.timestamp,e=>e.timestamp);if(n===-1)throw Error(`Packet was not created from this track.`);let r=n+1;for(;r>=this.demuxer.loadedSamples.length&&!this.demuxer.lastSampleLoaded;)await this.demuxer.advanceReader();return this.getPacketAtIndex(r,t)}finally{n()}}async getPacket(e,t){let n=await this.demuxer.readingMutex.acquire();try{for(;;){let n=B(this.demuxer.loadedSamples,e,e=>e.timestamp);if(n===-1&&this.demuxer.loadedSamples.length>0)return null;if(this.demuxer.lastSampleLoaded||n>=0&&n+1<this.demuxer.loadedSamples.length)return this.getPacketAtIndex(n,t);await this.demuxer.advanceReader()}}finally{n()}}getKeyPacket(e,t){return this.getPacket(e,t)}getNextKeyPacket(e,t){return this.getNextPacket(e,t)}},fc=79764919,pc=new Uint32Array(256);for(let e=0;e<256;e++){let t=e<<24;for(let e=0;e<8;e++)t=t&2147483648?t<<1^fc:t<<1;pc[e]=t>>>0&4294967295}var mc=e=>{let t=z(e),n=t.getUint32(22,!0);t.setUint32(22,0,!0);let r=0;for(let t=0;t<e.length;t++){let n=e[t];r=(r<<8^pc[r>>>24^n])>>>0}return t.setUint32(22,n,!0),r},hc=(e,t,n)=>{let r=0,i=null;if(e.length>0)if(t.codec===`vorbis`){I(t.vorbisInfo);let a=t.vorbisInfo.modeBlockflags.length,o=(1<<mi(a-1))-1<<1,s=(e[0]&o)>>1;if(s>=t.vorbisInfo.modeBlockflags.length)throw Error(`Invalid mode number.`);let c=n,l=t.vorbisInfo.modeBlockflags[s];if(i=t.vorbisInfo.blocksizes[l],l===1){let n=(o|1)+1,r=e[0]&n?1:0;c=t.vorbisInfo.blocksizes[r]}r=c===null?0:c+i>>2}else t.codec===`opus`&&(r=uo(e).durationInSamples);return{durationInSamples:r,vorbisBlockSize:i}},gc=e=>{let t=`audio/ogg`;if(e.codecStrings){let n=[...new Set(e.codecStrings)];t+=`; codecs="${n.join(`, `)}"`}return t},_c=65307,vc=e=>{let t=e.filePos;if(Pl(e)!==1399285583)return null;e.skip(1);let n=K(e),r=Bl(e),i=Pl(e),a=Pl(e),o=Pl(e),s=K(e),c=new Uint8Array(s);for(let t=0;t<s;t++)c[t]=K(e);let l=27+s,u=c.reduce((e,t)=>e+t,0);return{headerStartPos:t,totalSize:l+u,dataStartPos:t+l,dataSize:u,headerType:n,granulePosition:r,serialNumber:i,sequenceNumber:a,checksum:o,lacingValues:c}},yc=(e,t)=>{for(;e.filePos<t-3;){let t=Pl(e),n=t&255,r=t>>>8&255,i=t>>>16&255,a=t>>>24&255;if(!(n!==79&&r!==79&&i!==79&&a!==79)){if(e.skip(-4),t===1399285583)return!0;e.skip(1)}}return!1},bc=class extends To{constructor(e){super(e),this.metadataPromise=null,this.bitstreams=[],this.tracks=[],this.metadataTags={},this.reader=e._reader}async readMetadata(){return this.metadataPromise??=(async()=>{let e=0;for(;;){let t=this.reader.requestSliceRange(e,27,282);if(t instanceof Promise&&(t=await t),!t)break;let n=vc(t);if(!n||!(n.headerType&2))break;this.bitstreams.push({serialNumber:n.serialNumber,bosPage:n,description:null,numberOfChannels:-1,sampleRate:-1,codecInfo:{codec:null,vorbisInfo:null,opusInfo:null},lastMetadataPacket:null}),e=n.headerStartPos+n.totalSize}for(let e of this.bitstreams){let t=await this.readPacket(e.bosPage,0);t&&(t.data.byteLength>=7&&t.data[0]===1&&t.data[1]===118&&t.data[2]===111&&t.data[3]===114&&t.data[4]===98&&t.data[5]===105&&t.data[6]===115?await this.readVorbisMetadata(t,e):t.data.byteLength>=8&&t.data[0]===79&&t.data[1]===112&&t.data[2]===117&&t.data[3]===115&&t.data[4]===72&&t.data[5]===101&&t.data[6]===97&&t.data[7]===100&&await this.readOpusMetadata(t,e),e.codecInfo.codec!==null&&this.tracks.push(new vs(this.input,new xc(e,this))))}})()}async readVorbisMetadata(e,t){let n=await this.findNextPacketStart(e);if(!n)return;let r=await this.readPacket(n.startPage,n.startSegmentIndex);if(!r||(n=await this.findNextPacketStart(r),!n))return;let i=await this.readPacket(n.startPage,n.startSegmentIndex);if(!i||r.data[0]!==3||i.data[0]!==5)return;let a=[],o=e=>{for(;a.push(Math.min(255,e)),!(e<255);)e-=255};o(e.data.length),o(r.data.length);let s=new Uint8Array(1+a.length+e.data.length+r.data.length+i.data.length);s[0]=2,s.set(a,1),s.set(e.data,1+a.length),s.set(r.data,1+a.length+e.data.length),s.set(i.data,1+a.length+e.data.length+r.data.length),t.codecInfo.codec=`vorbis`,t.description=s,t.lastMetadataPacket=i;let c=z(e.data);t.numberOfChannels=c.getUint8(11),t.sampleRate=c.getUint32(12,!0);let l=c.getUint8(28);t.codecInfo.vorbisInfo={blocksizes:[1<<(l&15),1<<(l>>4)],modeBlockflags:fo(i.data).modeBlockflags},ho(r.data.subarray(7),this.metadataTags)}async readOpusMetadata(e,t){let n=await this.findNextPacketStart(e);if(!n)return;let r=await this.readPacket(n.startPage,n.startSegmentIndex);if(!r)return;t.codecInfo.codec=`opus`,t.description=e.data,t.lastMetadataPacket=r;let i=co(e.data);t.numberOfChannels=i.outputChannelCount,t.sampleRate=sa,t.codecInfo.opusInfo={preSkip:i.preSkip},ho(r.data.subarray(8),this.metadataTags)}async readPacket(e,t){I(t<e.lacingValues.length);let n=0;for(let r=0;r<t;r++)n+=e.lacingValues[r];let r=e,i=n,a=t,o=[];outer:for(;;){let t=this.reader.requestSlice(r.dataStartPos,r.dataSize);t instanceof Promise&&(t=await t),I(t);let s=G(t,r.dataSize);for(;;){if(a===r.lacingValues.length){o.push(s.subarray(n,i));break}let e=r.lacingValues[a];if(i+=e,e<255){o.push(s.subarray(n,i));break outer}a++}let c=r.headerStartPos+r.totalSize;for(;;){let t=this.reader.requestSliceRange(c,27,282);if(t instanceof Promise&&(t=await t),!t)return null;let n=vc(t);if(!n)return null;if(r=n,r.serialNumber===e.serialNumber)break;c=r.headerStartPos+r.totalSize}n=0,i=0,a=0}let s=o.reduce((e,t)=>e+t.length,0);if(s===0)return null;let c=new Uint8Array(s),l=0;for(let e=0;e<o.length;e++){let t=o[e];c.set(t,l),l+=t.length}return{data:c,endPage:r,endSegmentIndex:a}}async findNextPacketStart(e){if(e.endSegmentIndex<e.endPage.lacingValues.length-1)return{startPage:e.endPage,startSegmentIndex:e.endSegmentIndex+1};if(e.endPage.headerType&4)return null;let t=e.endPage.headerStartPos+e.endPage.totalSize;for(;;){let n=this.reader.requestSliceRange(t,27,282);if(n instanceof Promise&&(n=await n),!n)return null;let r=vc(n);if(!r)return null;if(r.serialNumber===e.endPage.serialNumber)return{startPage:r,startSegmentIndex:0};t=r.headerStartPos+r.totalSize}}async getMimeType(){return await this.readMetadata(),gc({codecStrings:(await Promise.all(this.tracks.map(e=>e.getCodecParameterString()))).filter(Boolean)})}async getTracks(){return await this.readMetadata(),this.tracks}async computeDuration(){let e=await this.getTracks(),t=await Promise.all(e.map(e=>e.computeDuration()));return Math.max(0,...t)}async getMetadataTags(){return await this.readMetadata(),this.metadataTags}},xc=class{constructor(e,t){this.bitstream=e,this.demuxer=t,this.encodedPacketToMetadata=new WeakMap,this.sequentialScanCache=[],this.sequentialScanMutex=new Jr,this.internalSampleRate=e.codecInfo.codec===`opus`?sa:e.sampleRate}getId(){return this.bitstream.serialNumber}getNumber(){let e=this.demuxer.tracks.findIndex(e=>e._backing.bitstream===this.bitstream);return I(e!==-1),e+1}getNumberOfChannels(){return this.bitstream.numberOfChannels}getSampleRate(){return this.bitstream.sampleRate}getTimeResolution(){return this.bitstream.sampleRate}getCodec(){return this.bitstream.codecInfo.codec}getInternalCodecId(){return null}async getDecoderConfig(){return I(this.bitstream.codecInfo.codec),{codec:this.bitstream.codecInfo.codec,numberOfChannels:this.bitstream.numberOfChannels,sampleRate:this.bitstream.sampleRate,description:this.bitstream.description??void 0}}getName(){return null}getLanguageCode(){return`und`}getDisposition(){return{...zi}}async getFirstTimestamp(){return 0}async computeDuration(){let e=await this.getPacket(1/0,{metadataOnly:!0});return(e?.timestamp??0)+(e?.duration??0)}granulePositionToTimestampInSamples(e){return this.bitstream.codecInfo.codec===`opus`?(I(this.bitstream.codecInfo.opusInfo),e-this.bitstream.codecInfo.opusInfo.preSkip):e}createEncodedPacketFromOggPacket(e,t,n){if(!e)return null;let{durationInSamples:r,vorbisBlockSize:i}=hc(e.data,this.bitstream.codecInfo,t.vorbisLastBlocksize),a=new H(n.metadataOnly?Ao:e.data,`key`,Math.max(0,t.timestampInSamples)/this.internalSampleRate,r/this.internalSampleRate,e.endPage.headerStartPos+e.endSegmentIndex,e.data.byteLength);return this.encodedPacketToMetadata.set(a,{packet:e,timestampInSamples:t.timestampInSamples,durationInSamples:r,vorbisLastBlockSize:t.vorbisLastBlocksize,vorbisBlockSize:i}),a}async getFirstPacket(e){I(this.bitstream.lastMetadataPacket);let t=await this.demuxer.findNextPacketStart(this.bitstream.lastMetadataPacket);if(!t)return null;let n=0;this.bitstream.codecInfo.codec===`opus`&&(I(this.bitstream.codecInfo.opusInfo),n-=this.bitstream.codecInfo.opusInfo.preSkip);let r=await this.demuxer.readPacket(t.startPage,t.startSegmentIndex);return this.createEncodedPacketFromOggPacket(r,{timestampInSamples:n,vorbisLastBlocksize:null},e)}async getNextPacket(e,t){let n=this.encodedPacketToMetadata.get(e);if(!n)throw Error(`Packet was not created from this track.`);let r=await this.demuxer.findNextPacketStart(n.packet);if(!r)return null;let i=n.timestampInSamples+n.durationInSamples,a=await this.demuxer.readPacket(r.startPage,r.startSegmentIndex);return this.createEncodedPacketFromOggPacket(a,{timestampInSamples:i,vorbisLastBlocksize:n.vorbisBlockSize},t)}async getPacket(e,t){if(this.demuxer.reader.fileSize===null)return this.getPacketSequential(e,t);let n=di(e*this.internalSampleRate);if(n===0)return this.getFirstPacket(t);if(n<0)return null;I(this.bitstream.lastMetadataPacket);let r=await this.demuxer.findNextPacketStart(this.bitstream.lastMetadataPacket);if(!r)return null;let i=r.startPage,a=this.demuxer.reader.fileSize,o=[i];outer:for(;i.headerStartPos+i.totalSize<a;){let e=i.headerStartPos,t=Math.floor((e+a)/2),r=t;for(;;){let e=Math.min(r+_c,a-27),s=this.demuxer.reader.requestSlice(r,e-r);if(s instanceof Promise&&(s=await s),I(s),!yc(s,e)){a=t+27;continue outer}let c=this.demuxer.reader.requestSliceRange(s.filePos,27,282);c instanceof Promise&&(c=await c),I(c);let l=vc(c);I(l);let u=!1;if(l.serialNumber===this.bitstream.serialNumber)u=!0;else{let e=this.demuxer.reader.requestSlice(l.headerStartPos,l.totalSize);e instanceof Promise&&(e=await e),I(e),u=mc(G(e,l.totalSize))===l.checksum}if(!u){r=l.headerStartPos+4;continue}if(u&&l.serialNumber!==this.bitstream.serialNumber){r=l.headerStartPos+l.totalSize;continue}if(l.granulePosition===-1){r=l.headerStartPos+l.totalSize;continue}this.granulePositionToTimestampInSamples(l.granulePosition)>n?a=l.headerStartPos:(i=l,o.push(l));continue outer}}let s=r.startPage;for(let e of o){if(e.granulePosition===i.granulePosition)break;(!s||e.headerStartPos>s.headerStartPos)&&(s=e)}let c=s,l=[c];for(;!(c.serialNumber===this.bitstream.serialNumber&&c.granulePosition===i.granulePosition);){let e=c.headerStartPos+c.totalSize,t=this.demuxer.reader.requestSliceRange(e,27,282);t instanceof Promise&&(t=await t),I(t);let n=vc(t);I(n),c=n,c.serialNumber===this.bitstream.serialNumber&&l.push(c)}I(c.granulePosition!==-1);let u=null,d,f,p=c,m=0;if(c.headerStartPos===r.startPage.headerStartPos)d=this.granulePositionToTimestampInSamples(0),f=!0,u=0;else{d=0,f=!1;for(let e=c.lacingValues.length-1;e>=0;e--)if(c.lacingValues[e]<255){u=e+1;break}if(u===null)throw Error(`Invalid page with granule position: no packets end on this page.`);m=u-1;let e={data:Ao,endPage:p,endSegmentIndex:m};if(await this.demuxer.findNextPacketStart(e)){let e=Cc(l,c,u);I(e);let t=Sc(l,e.page,e.segmentIndex);t&&(c=t.page,u=t.segmentIndex)}else for(;;){let e=Cc(l,c,u);if(!e)break;let t=Sc(l,e.page,e.segmentIndex);if(!t)break;if(c=t.page,u=t.segmentIndex,e.page.headerStartPos!==p.headerStartPos){p=e.page,m=e.segmentIndex;break}}}let h=null,g=null;for(;c!==null;){I(u!==null);let e=await this.demuxer.readPacket(c,u);if(!e)break;if(!(c.headerStartPos===r.startPage.headerStartPos&&u<r.startSegmentIndex)){let r=this.createEncodedPacketFromOggPacket(e,{timestampInSamples:d,vorbisLastBlocksize:g?.vorbisBlockSize??null},t);I(r);let i=this.encodedPacketToMetadata.get(r);if(I(i),!f&&e.endPage.headerStartPos===p.headerStartPos&&e.endSegmentIndex===m?(d=this.granulePositionToTimestampInSamples(c.granulePosition),f=!0,r=this.createEncodedPacketFromOggPacket(e,{timestampInSamples:d-i.durationInSamples,vorbisLastBlocksize:g?.vorbisBlockSize??null},t),I(r),i=this.encodedPacketToMetadata.get(r),I(i)):d+=i.durationInSamples,h=r,g=i,f&&(Math.max(d,0)>n||Math.max(i.timestampInSamples,0)===n))break}let i=await this.demuxer.findNextPacketStart(e);if(!i)break;c=i.startPage,u=i.startSegmentIndex}return h}async getPacketSequential(e,t){let n=await this.sequentialScanMutex.acquire();try{let n=di(e*this.internalSampleRate);e=n/this.internalSampleRate;let r=B(this.sequentialScanCache,n,e=>e.timestampInSamples),i;if(r!==-1){let e=this.sequentialScanCache[r];i=this.createEncodedPacketFromOggPacket(e.packet,{timestampInSamples:e.timestampInSamples,vorbisLastBlocksize:e.vorbisLastBlockSize},t)}else i=await this.getFirstPacket(t);let a=0;for(;i&&i.timestamp<e;){let n=await this.getNextPacket(i,t);if(!n||n.timestamp>e)break;if(i=n,a++,a===100){a=0;let e=this.encodedPacketToMetadata.get(i);I(e),this.sequentialScanCache.length>0&&I(L(this.sequentialScanCache).timestampInSamples<=e.timestampInSamples),this.sequentialScanCache.push(e)}}return i}finally{n()}}getKeyPacket(e,t){return this.getPacket(e,t)}getNextKeyPacket(e,t){return this.getNextPacket(e,t)}},Sc=(e,t,n)=>{let r=t,i=n;outer:for(;;){for(i--;i>=0;i--)if(r.lacingValues[i]<255){i++;break outer}if(I(i===-1),!(r.headerType&1)){i=0;break}let t=ei(e,e=>e.headerStartPos<r.headerStartPos);if(!t)return null;r=t,i=r.lacingValues.length}if(I(i!==-1),i===r.lacingValues.length){let t=e[e.indexOf(r)+1];I(t),r=t,i=0}return{page:r,segmentIndex:i}},Cc=(e,t,n)=>{if(n>0)return{page:t,segmentIndex:n-1};let r=ei(e,e=>e.headerStartPos<t.headerStartPos);return r?{page:r,segmentIndex:r.lacingValues.length-1}:null},wc;(function(e){e[e.PCM=1]=`PCM`,e[e.IEEE_FLOAT=3]=`IEEE_FLOAT`,e[e.ALAW=6]=`ALAW`,e[e.MULAW=7]=`MULAW`,e[e.EXTENSIBLE=65534]=`EXTENSIBLE`})(wc||={});var Tc=class extends To{constructor(e){super(e),this.metadataPromise=null,this.dataStart=-1,this.dataSize=-1,this.audioInfo=null,this.tracks=[],this.lastKnownPacketIndex=0,this.metadataTags={},this.reader=e._reader}async readMetadata(){return this.metadataPromise??=(async()=>{let e=this.reader.requestSlice(0,12);e instanceof Promise&&(e=await e),I(e);let t=Ul(e,4),n=t!==`RIFX`,r=t===`RF64`,i=Nl(e,n),a=r?this.reader.fileSize:Math.min(i+8,this.reader.fileSize??1/0);if(Ul(e,4)!==`WAVE`)throw Error(`Invalid WAVE file - wrong format`);let o=0,s=null,c=e.filePos;for(;a===null||c<a;){let e=this.reader.requestSlice(c,8);if(e instanceof Promise&&(e=await e),!e)break;let t=Ul(e,4),i=Nl(e,n),l=e.filePos;if(r&&o===0&&t!==`ds64`)throw Error(`Invalid RF64 file: First chunk must be "ds64".`);if(t===`fmt `)await this.parseFmtChunk(l,i,n);else if(t===`data`){if(s??=i,this.dataStart=e.filePos,this.dataSize=Math.min(s,(a??1/0)-this.dataStart),this.reader.fileSize===null)break}else if(t===`ds64`){let e=this.reader.requestSlice(l,i);if(e instanceof Promise&&(e=await e),!e)break;let t=Ll(e,n);s=Ll(e,n),a=Math.min(t+8,this.reader.fileSize??1/0)}else t===`LIST`?await this.parseListChunk(l,i,n):(t===`ID3 `||t===`id3 `)&&await this.parseId3Chunk(l,i);c=l+i+(i&1),o++}if(!this.audioInfo)throw Error(`Invalid WAVE file - missing "fmt " chunk`);if(this.dataStart===-1)throw Error(`Invalid WAVE file - missing "data" chunk`);let l=this.audioInfo.blockSizeInBytes;this.dataSize=Math.floor(this.dataSize/l)*l,this.tracks.push(new vs(this.input,new Dc(this)))})()}async parseFmtChunk(e,t,n){let r=this.reader.requestSlice(e,t);if(r instanceof Promise&&(r=await r),!r)return;let i=kl(r,n),a=kl(r,n),o=Nl(r,n);r.skip(4);let s=kl(r,n),c;if(c=t===14?8:kl(r,n),t>=18&&i!==357){let e=kl(r,n),a=t-18;if(Math.min(a,e)>=22&&i===wc.EXTENSIBLE){r.skip(6);let e=G(r,16);i=e[0]|e[1]<<8}}(i===wc.MULAW||i===wc.ALAW)&&(c=8),this.audioInfo={format:i,numberOfChannels:a,sampleRate:o,sampleSizeInBytes:Math.ceil(c/8),blockSizeInBytes:s}}async parseListChunk(e,t,n){let r=this.reader.requestSlice(e,t);if(r instanceof Promise&&(r=await r),!r)return;let i=Ul(r,4);if(i!==`INFO`&&i!==`INF0`)return;let a=r.filePos;for(;a<=e+t-8;){r.filePos=a;let e=Ul(r,4),t=Nl(r,n),i=G(r,t),o=0;for(let e=0;e<i.length&&i[e]!==0;e++)o++;let s=String.fromCharCode(...i.subarray(0,o));switch(this.metadataTags.raw??={},this.metadataTags.raw[e]=s,e){case`INAM`:case`TITL`:this.metadataTags.title??=s;break;case`TIT3`:this.metadataTags.description??=s;break;case`IART`:this.metadataTags.artist??=s;break;case`IPRD`:this.metadataTags.album??=s;break;case`IPRT`:case`ITRK`:case`TRCK`:{let e=s.split(`/`),t=Number.parseInt(e[0],10),n=e[1]&&Number.parseInt(e[1],10);Number.isInteger(t)&&t>0&&(this.metadataTags.trackNumber??=t),n&&Number.isInteger(n)&&n>0&&(this.metadataTags.tracksTotal??=n)}break;case`ICRD`:case`IDIT`:{let e=new Date(s);Number.isNaN(e.getTime())||(this.metadataTags.date??=e)}break;case`YEAR`:{let e=Number.parseInt(s,10);Number.isInteger(e)&&e>0&&(this.metadataTags.date??=new Date(e,0,1))}break;case`IGNR`:case`GENR`:this.metadataTags.genre??=s;break;case`ICMT`:case`CMNT`:case`COMM`:this.metadataTags.comment??=s;break}a+=8+t+(t&1)}}async parseId3Chunk(e,t){let n=this.reader.requestSlice(e,t);if(n instanceof Promise&&(n=await n),!n)return;let r=Yl(n);if(r){let i=t-10;r.size=Math.min(r.size,i),r.size>0&&Xl(n.slice(e+10,r.size),r,this.metadataTags)}}getCodec(){if(I(this.audioInfo),this.audioInfo.format===wc.MULAW)return`ulaw`;if(this.audioInfo.format===wc.ALAW)return`alaw`;if(this.audioInfo.format===wc.PCM){if(this.audioInfo.sampleSizeInBytes===1)return`pcm-u8`;if(this.audioInfo.sampleSizeInBytes===2)return`pcm-s16`;if(this.audioInfo.sampleSizeInBytes===3)return`pcm-s24`;if(this.audioInfo.sampleSizeInBytes===4)return`pcm-s32`}return this.audioInfo.format===wc.IEEE_FLOAT&&this.audioInfo.sampleSizeInBytes===4?`pcm-f32`:null}async getMimeType(){return`audio/wav`}async computeDuration(){await this.readMetadata();let e=this.tracks[0];return I(e),e.computeDuration()}async getTracks(){return await this.readMetadata(),this.tracks}async getMetadataTags(){return await this.readMetadata(),this.metadataTags}},Ec=2048,Dc=class{constructor(e){this.demuxer=e}getId(){return 1}getNumber(){return 1}getCodec(){return this.demuxer.getCodec()}getInternalCodecId(){return I(this.demuxer.audioInfo),this.demuxer.audioInfo.format}async getDecoderConfig(){let e=this.demuxer.getCodec();return e?(I(this.demuxer.audioInfo),{codec:e,numberOfChannels:this.demuxer.audioInfo.numberOfChannels,sampleRate:this.demuxer.audioInfo.sampleRate}):null}async computeDuration(){let e=await this.getPacket(1/0,{metadataOnly:!0});return(e?.timestamp??0)+(e?.duration??0)}getNumberOfChannels(){return I(this.demuxer.audioInfo),this.demuxer.audioInfo.numberOfChannels}getSampleRate(){return I(this.demuxer.audioInfo),this.demuxer.audioInfo.sampleRate}getTimeResolution(){return I(this.demuxer.audioInfo),this.demuxer.audioInfo.sampleRate}getName(){return null}getLanguageCode(){return`und`}getDisposition(){return{...zi}}async getFirstTimestamp(){return 0}async getPacketAtIndex(e,t){I(e>=0),I(this.demuxer.audioInfo);let n=e*Ec*this.demuxer.audioInfo.blockSizeInBytes;if(n>=this.demuxer.dataSize)return null;let r=Math.min(Ec*this.demuxer.audioInfo.blockSizeInBytes,this.demuxer.dataSize-n);if(this.demuxer.reader.fileSize===null){let e=this.demuxer.reader.requestSlice(this.demuxer.dataStart+n,r);if(e instanceof Promise&&(e=await e),!e)return null}let i;if(t.metadataOnly)i=Ao;else{let e=this.demuxer.reader.requestSlice(this.demuxer.dataStart+n,r);e instanceof Promise&&(e=await e),I(e),i=G(e,r)}let a=e*Ec/this.demuxer.audioInfo.sampleRate,o=r/this.demuxer.audioInfo.blockSizeInBytes/this.demuxer.audioInfo.sampleRate;return this.demuxer.lastKnownPacketIndex=Math.max(e,this.demuxer.lastKnownPacketIndex),new H(i,`key`,a,o,e,r)}getFirstPacket(e){return this.getPacketAtIndex(0,e)}async getPacket(e,t){I(this.demuxer.audioInfo);let n=Math.floor(Math.min(e*this.demuxer.audioInfo.sampleRate/Ec,(this.demuxer.dataSize-1)/(Ec*this.demuxer.audioInfo.blockSizeInBytes)));if(n<0)return null;let r=await this.getPacketAtIndex(n,t);if(r)return r;if(n===0)return null;I(this.demuxer.reader.fileSize===null);let i=await this.getPacketAtIndex(this.demuxer.lastKnownPacketIndex,t);for(;i;){let e=await this.getNextPacket(i,t);if(!e)break;i=e}return i}getNextPacket(e,t){I(this.demuxer.audioInfo);let n=Math.round(e.timestamp*this.demuxer.audioInfo.sampleRate/Ec);return this.getPacketAtIndex(n+1,t)}getKeyPacket(e,t){return this.getPacket(e,t)}getNextKeyPacket(e,t){return this.getNextPacket(e,t)}},Oc=e=>{let t=e.filePos,n=new V(G(e,9));if(n.readBits(12)!==4095||(n.skipBits(1),n.readBits(2)!==0))return null;let r=n.readBits(1),i=n.readBits(2)+1,a=n.readBits(4);if(a===15)return null;n.skipBits(1);let o=n.readBits(3);if(o===0)throw Error(`ADTS frames with channel configuration 0 are not supported.`);n.skipBits(1),n.skipBits(1),n.skipBits(1),n.skipBits(1);let s=n.readBits(13);n.skipBits(11);let c=n.readBits(2)+1;if(c!==1)throw Error(`ADTS frames with more than one AAC frame are not supported.`);let l=null;return r===1?e.filePos-=2:l=n.readBits(16),{objectType:i,samplingFrequencyIndex:a,channelConfiguration:o,frameLength:s,numberOfAacFrames:c,crcCheck:l,startPos:t}},kc=1024,Ac=class extends To{constructor(e){super(e),this.metadataPromise=null,this.firstFrameHeader=null,this.loadedSamples=[],this.metadataTags=null,this.tracks=[],this.readingMutex=new Jr,this.lastSampleLoaded=!1,this.lastLoadedPos=0,this.nextTimestampInSamples=0,this.reader=e._reader}async readMetadata(){return this.metadataPromise??=(async()=>{for(;!this.firstFrameHeader&&!this.lastSampleLoaded;)await this.advanceReader();I(this.firstFrameHeader),this.tracks=[new vs(this.input,new jc(this))]})()}async advanceReader(){if(this.lastLoadedPos===0)for(;;){let e=this.reader.requestSlice(this.lastLoadedPos,10);if(e instanceof Promise&&(e=await e),!e){this.lastSampleLoaded=!0;return}let t=Yl(e);if(!t)break;this.lastLoadedPos=e.filePos+t.size}let e=this.reader.requestSliceRange(this.lastLoadedPos,7,9);if(e instanceof Promise&&(e=await e),!e){this.lastSampleLoaded=!0;return}let t=Oc(e);if(!t){this.lastSampleLoaded=!0;return}if(this.reader.fileSize!==null&&t.startPos+t.frameLength>this.reader.fileSize){this.lastSampleLoaded=!0;return}this.firstFrameHeader||=t;let n=Vi[t.samplingFrequencyIndex];I(n!==void 0);let r=kc/n,i={timestamp:this.nextTimestampInSamples/n,duration:r,dataStart:t.startPos,dataSize:t.frameLength};this.loadedSamples.push(i),this.nextTimestampInSamples+=kc,this.lastLoadedPos=t.startPos+t.frameLength}async getMimeType(){return`audio/aac`}async getTracks(){return await this.readMetadata(),this.tracks}async computeDuration(){await this.readMetadata();let e=this.tracks[0];return I(e),e.computeDuration()}async getMetadataTags(){let e=await this.readingMutex.acquire();try{if(await this.readMetadata(),this.metadataTags)return this.metadataTags;this.metadataTags={};let e=0;for(;;){let t=this.reader.requestSlice(e,10);if(t instanceof Promise&&(t=await t),!t)break;let n=Yl(t);if(!n)break;let r=this.reader.requestSlice(t.filePos,n.size);if(r instanceof Promise&&(r=await r),!r)break;Xl(r,n,this.metadataTags),e=t.filePos+n.size}return this.metadataTags}finally{e()}}},jc=class{constructor(e){this.demuxer=e}getId(){return 1}getNumber(){return 1}async getFirstTimestamp(){return 0}getTimeResolution(){return this.getSampleRate()/kc}async computeDuration(){let e=await this.getPacket(1/0,{metadataOnly:!0});return(e?.timestamp??0)+(e?.duration??0)}getName(){return null}getLanguageCode(){return`und`}getCodec(){return`aac`}getInternalCodecId(){return I(this.demuxer.firstFrameHeader),this.demuxer.firstFrameHeader.objectType}getNumberOfChannels(){I(this.demuxer.firstFrameHeader);let e=Hi[this.demuxer.firstFrameHeader.channelConfiguration];return I(e!==void 0),e}getSampleRate(){I(this.demuxer.firstFrameHeader);let e=Vi[this.demuxer.firstFrameHeader.samplingFrequencyIndex];return I(e!==void 0),e}getDisposition(){return{...zi}}async getDecoderConfig(){return I(this.demuxer.firstFrameHeader),{codec:`mp4a.40.${this.demuxer.firstFrameHeader.objectType}`,numberOfChannels:this.getNumberOfChannels(),sampleRate:this.getSampleRate()}}async getPacketAtIndex(e,t){if(e===-1)return null;let n=this.demuxer.loadedSamples[e];if(!n)return null;let r;if(t.metadataOnly)r=Ao;else{let e=this.demuxer.reader.requestSlice(n.dataStart,n.dataSize);if(e instanceof Promise&&(e=await e),!e)return null;r=G(e,n.dataSize)}return new H(r,`key`,n.timestamp,n.duration,e,n.dataSize)}getFirstPacket(e){return this.getPacketAtIndex(0,e)}async getNextPacket(e,t){let n=await this.demuxer.readingMutex.acquire();try{let n=Zr(this.demuxer.loadedSamples,e.timestamp,e=>e.timestamp);if(n===-1)throw Error(`Packet was not created from this track.`);let r=n+1;for(;r>=this.demuxer.loadedSamples.length&&!this.demuxer.lastSampleLoaded;)await this.demuxer.advanceReader();return this.getPacketAtIndex(r,t)}finally{n()}}async getPacket(e,t){let n=await this.demuxer.readingMutex.acquire();try{for(;;){let n=B(this.demuxer.loadedSamples,e,e=>e.timestamp);if(n===-1&&this.demuxer.loadedSamples.length>0)return null;if(this.demuxer.lastSampleLoaded||n>=0&&n+1<this.demuxer.loadedSamples.length)return this.getPacketAtIndex(n,t);await this.demuxer.advanceReader()}}finally{n()}}getKeyPacket(e,t){return this.getPacket(e,t)}getNextKeyPacket(e,t){return this.getNextPacket(e,t)}},Mc=e=>e===0?null:e===1?192:e>=2&&e<=5?144*2**e:e===6?`uncommon-u8`:e===7?`uncommon-u16`:e>=8&&e<=15?2**e:null,Nc=(e,t)=>{switch(e){case 0:return t;case 1:return 88200;case 2:return 176400;case 3:return 192e3;case 4:return 8e3;case 5:return 16e3;case 6:return 22050;case 7:return 24e3;case 8:return 32e3;case 9:return 44100;case 10:return 48e3;case 11:return 96e3;case 12:return`uncommon-u8`;case 13:return`uncommon-u16`;case 14:return`uncommon-u16-10`;default:return null}},Pc=e=>{let t=0,n=new V(G(e,1));for(;n.readBits(1)===1;)t++;if(t===0)return n.readBits(7);let r=[],i=t-1,a=new V(G(e,i)),o=8-t-1;for(let e=0;e<o;e++)r.unshift(n.readBits(1));for(let e=0;e<i;e++)for(let e=0;e<8;e++){let t=a.readBits(1);e<2||r.unshift(t)}return r.reduce((e,t,n)=>e|t<<n,0)},Fc=(e,t)=>{if(t===`uncommon-u16`)return Al(e)+1;if(t===`uncommon-u8`)return K(e)+1;if(typeof t==`number`)return t;ii(t),I(!1)},Ic=(e,t)=>t===`uncommon-u16`?Al(e):t===`uncommon-u16-10`?Al(e)*10:t===`uncommon-u8`?K(e):typeof t==`number`?t:null,Lc=e=>{let t=0;for(let n of e){t^=n;for(let e=0;e<8;e++)t&128?t=t<<1^7:t<<=1,t&=255}return t},Rc=class extends To{constructor(e){super(e),this.loadedSamples=[],this.metadataPromise=null,this.track=null,this.metadataTags={},this.audioInfo=null,this.lastLoadedPos=null,this.blockingBit=null,this.readingMutex=new Jr,this.lastSampleLoaded=!1,this.reader=e._reader}async computeDuration(){return await this.readMetadata(),I(this.track),this.track.computeDuration()}async getMetadataTags(){return await this.readMetadata(),this.metadataTags}async getTracks(){return await this.readMetadata(),I(this.track),[this.track]}async getMimeType(){return`audio/flac`}async readMetadata(){let e=4;return this.metadataPromise??=(async()=>{for(;this.reader.fileSize===null||e<this.reader.fileSize;){let t=this.reader.requestSlice(e,4);if(t instanceof Promise&&(t=await t),e+=4,t===null)throw Error(`Metadata block at position ${e} is too small! Corrupted file.`);I(t);let n=K(t),r=jl(t),i=(n&128)!=0;switch(n&127){case mo.STREAMINFO:{let t=this.reader.requestSlice(e,r);if(t instanceof Promise&&(t=await t),I(t),t===null)throw Error(`StreamInfo block at position ${e} is too small! Corrupted file.`);let n=G(t,34),i=new V(n),a=i.readBits(16),o=i.readBits(16),s=i.readBits(24),c=i.readBits(24),l=i.readBits(20),u=i.readBits(3)+1;i.readBits(5);let d=i.readBits(36);i.skipBits(128);let f=new Uint8Array(42);f.set(new Uint8Array([102,76,97,67]),0),f.set(new Uint8Array([128,0,0,34]),4),f.set(n,8),this.audioInfo={numberOfChannels:u,sampleRate:l,totalSamples:d,minimumBlockSize:a,maximumBlockSize:o,minimumFrameSize:s,maximumFrameSize:c,description:f},this.track=new vs(this.input,new zc(this));break}case mo.VORBIS_COMMENT:{let t=this.reader.requestSlice(e,r);t instanceof Promise&&(t=await t),I(t),ho(G(t,r),this.metadataTags);break}case mo.PICTURE:{let t=this.reader.requestSlice(e,r);t instanceof Promise&&(t=await t),I(t);let n=q(t),i=q(t),a=Lr.decode(G(t,i)),o=q(t),s=Lr.decode(G(t,o));t.skip(16);let c=q(t),l=G(t,c);this.metadataTags.images??=[],this.metadataTags.images.push({data:l,mimeType:a,kind:n===3?`coverFront`:n===4?`coverBack`:`unknown`,description:s});break}default:break}if(e+=r,i){this.lastLoadedPos=e;break}}})()}async readNextFlacFrame({startPos:e,isFirstPacket:t}){I(this.audioInfo);let n=this.audioInfo.maximumFrameSize+16,r=await this.reader.requestSliceRange(e,this.audioInfo.minimumFrameSize,n);if(!r)return null;let i=this.readFlacFrameHeader({slice:r,isFirstPacket:t});if(!i)return null;for(r.filePos=e+this.audioInfo.minimumFrameSize;;){if(r.filePos>r.end-6)return{num:i.num,blockSize:i.blockSize,sampleRate:i.sampleRate,size:r.end-e,isLastFrame:!0};if(K(r)===255){let t=r.filePos;if(K(r)!==(this.blockingBit===1?249:248)){r.filePos=t;continue}r.skip(-2);let n=r.filePos-e,a=this.readFlacFrameHeader({slice:r,isFirstPacket:!1});if(!a){r.filePos=t;continue}if(this.blockingBit===0){if(a.num-i.num!==1){r.filePos=t;continue}}else if(a.num-i.num!==i.blockSize){r.filePos=t;continue}return{num:i.num,blockSize:i.blockSize,sampleRate:i.sampleRate,size:n,isLastFrame:!1}}}}readFlacFrameHeader({slice:e,isFirstPacket:t}){let n=e.filePos,r=new V(G(e,4));if(r.readBits(15)!==32764)return null;if(this.blockingBit===null)I(t),this.blockingBit=r.readBits(1);else if(this.blockingBit===1){if(I(!t),r.readBits(1)!==1)return null}else if(this.blockingBit===0){if(I(!t),r.readBits(1)!==0)return null}else throw Error(`Invalid blocking bit`);let i=Mc(r.readBits(4));if(!i)return null;I(this.audioInfo);let a=Nc(r.readBits(4),this.audioInfo.sampleRate);if(!a||(r.readBits(4),r.readBits(3),r.readBits(1)!==0))return null;let o=Pc(e),s=Fc(e,i),c=Ic(e,a);if(c===null||c!==this.audioInfo.sampleRate)return null;let l=e.filePos-n,u=K(e);return e.skip(-l),e.skip(-1),u===Lc(G(e,l))?{num:o,blockSize:s,sampleRate:c}:null}async advanceReader(){await this.readMetadata(),I(this.lastLoadedPos!==null),I(this.audioInfo);let e=this.lastLoadedPos,t=await this.readNextFlacFrame({startPos:e,isFirstPacket:this.loadedSamples.length===0});if(!t){this.lastSampleLoaded=!0;return}let n=this.loadedSamples[this.loadedSamples.length-1],r={blockOffset:n?n.blockOffset+n.blockSize:0,blockSize:t.blockSize,byteOffset:e,byteSize:t.size};if(this.lastLoadedPos+=t.size,this.loadedSamples.push(r),t.isLastFrame){this.lastSampleLoaded=!0;return}}},zc=class{constructor(e){this.demuxer=e}getId(){return 1}getNumber(){return 1}getCodec(){return`flac`}getInternalCodecId(){return null}getNumberOfChannels(){return I(this.demuxer.audioInfo),this.demuxer.audioInfo.numberOfChannels}async computeDuration(){let e=await this.getPacket(1/0,{metadataOnly:!0});return(e?.timestamp??0)+(e?.duration??0)}getSampleRate(){return I(this.demuxer.audioInfo),this.demuxer.audioInfo.sampleRate}getName(){return null}getLanguageCode(){return`und`}getTimeResolution(){return I(this.demuxer.audioInfo),this.demuxer.audioInfo.sampleRate}getDisposition(){return{...zi}}async getFirstTimestamp(){return 0}async getDecoderConfig(){return I(this.demuxer.audioInfo),{codec:`flac`,numberOfChannels:this.demuxer.audioInfo.numberOfChannels,sampleRate:this.demuxer.audioInfo.sampleRate,description:this.demuxer.audioInfo.description}}async getPacket(e,t){if(I(this.demuxer.audioInfo),e<0)throw Error(`Timestamp cannot be negative`);let n=await this.demuxer.readingMutex.acquire();try{for(;;){let n=B(this.demuxer.loadedSamples,e,e=>e.blockOffset/this.demuxer.audioInfo.sampleRate);if(n===-1){await this.demuxer.advanceReader();continue}let r=this.demuxer.loadedSamples[n];if(r.blockOffset/this.demuxer.audioInfo.sampleRate+r.blockSize/this.demuxer.audioInfo.sampleRate<=e){if(this.demuxer.lastSampleLoaded)return this.getPacketAtIndex(this.demuxer.loadedSamples.length-1,t);await this.demuxer.advanceReader();continue}return this.getPacketAtIndex(n,t)}}finally{n()}}async getNextPacket(e,t){let n=await this.demuxer.readingMutex.acquire();try{let n=e.sequenceNumber+1;if(this.demuxer.lastSampleLoaded&&n>=this.demuxer.loadedSamples.length)return null;for(;n>=this.demuxer.loadedSamples.length&&!this.demuxer.lastSampleLoaded;)await this.demuxer.advanceReader();return this.getPacketAtIndex(n,t)}finally{n()}}getKeyPacket(e,t){return this.getPacket(e,t)}getNextKeyPacket(e,t){return this.getNextPacket(e,t)}async getPacketAtIndex(e,t){let n=this.demuxer.loadedSamples[e];if(!n)return null;let r;if(t.metadataOnly)r=Ao;else{let e=this.demuxer.reader.requestSlice(n.byteOffset,n.byteSize);if(e instanceof Promise&&(e=await e),!e)return null;r=G(e,n.byteSize)}I(this.demuxer.audioInfo);let i=n.blockOffset/this.demuxer.audioInfo.sampleRate,a=n.blockSize/this.demuxer.audioInfo.sampleRate;return new H(r,`key`,i,a,e,n.byteSize)}async getFirstPacket(e){for(;this.demuxer.loadedSamples.length===0&&!this.demuxer.lastSampleLoaded;)await this.demuxer.advanceReader();return this.getPacketAtIndex(0,e)}},Bc=9e4,Vc=e=>{let t=`video/MP2T`,n=[...new Set(e.filter(Boolean))];return n.length>0&&(t+=`; codecs="${n.join(`, `)}"`),t},Hc=class extends To{constructor(e){super(e),this.metadataPromise=null,this.elementaryStreams=[],this.tracks=[],this.packetOffset=0,this.packetStride=-1,this.sectionEndPositions=[],this.seekChunkSize=5*1024*1024,this.minReferencePointByteDistance=-1,this.reader=e._reader}async readMetadata(){return this.metadataPromise??=(async()=>{let e=this.reader.requestSlice(0,205);e instanceof Promise&&(e=await e),I(e);let t=G(e,205);if(t[0]===71&&t[188]===71)this.packetOffset=0,this.packetStride=188;else if(t[0]===71&&t[204]===71)this.packetOffset=0,this.packetStride=204;else if(t[4]===71&&t[196]===71)this.packetOffset=4,this.packetStride=192;else throw Error(`Unreachable.`);this.minReferencePointByteDistance=256*this.packetStride;let n=this.packetOffset,r=null,i=!1,a=!1;for(;;){let e=await this.readPacketHeader(n);if(!e)break;if(e.payloadUnitStartIndicator===0){n+=this.packetStride;continue}let t=await this.readSection(n,!0,!a);if(!t)break;let o=!1;if(!a&&t.pid!==0&&!(t.payload[0]===0&&t.payload[1]===0&&t.payload[2]===1)){let e=new V(t.payload),n=e.readAlignedByte();e.skipBits(8*n),o=e.readBits(8)===2}if(t.pid===0&&!i){let e=new V(t.payload),n=e.readAlignedByte();e.skipBits(8*n),e.skipBits(14);let a=e.readBits(10);for(e.skipBits(40);8*(a+3)-e.pos>32;){let t=e.readBits(16);if(e.skipBits(3),t!==0){if(r!==null)throw Error(`Only files with a single program are supported.`);r=e.readBits(13)}}if(r===null)throw Error(`Program Association Table must link to a Program Map Table.`);i=!0}else if((t.pid===r||o)&&!a){let e=new V(t.payload),n=e.readAlignedByte();e.skipBits(8*n),e.skipBits(12);let r=e.readBits(12);e.skipBits(43),e.readBits(13),e.skipBits(6);let i=e.readBits(10);for(e.skipBits(8*i);8*(r+3)-e.pos>32;){let t=e.readBits(8);e.skipBits(3);let n=e.readBits(13);e.skipBits(6);let r=e.readBits(10),i=e.pos+8*r,a=!1,o=!1;for(;e.pos<i;){let t=e.readBits(8),n=e.readBits(8);t===106?a=!0:(t===122||t===204)&&(o=!0),e.skipBits(8*n)}let s=null;switch(t){case 3:case 4:case 15:s={type:`audio`,codec:t===15?`aac`:`mp3`,aacCodecInfo:null,numberOfChannels:-1,sampleRate:-1};break;case 27:case 36:s={type:`video`,codec:t===27?`avc`:`hevc`,avcCodecInfo:null,hevcCodecInfo:null,colorSpace:{primaries:null,transfer:null,matrix:null,fullRange:null},width:-1,height:-1,squarePixelWidth:-1,squarePixelHeight:-1,reorderSize:-1};break;case 129:s={type:`audio`,codec:`ac3`,aacCodecInfo:null,numberOfChannels:-1,sampleRate:-1};break;case 135:s={type:`audio`,codec:`eac3`,aacCodecInfo:null,numberOfChannels:-1,sampleRate:-1};break;case 6:o?s={type:`audio`,codec:`eac3`,aacCodecInfo:null,numberOfChannels:-1,sampleRate:-1}:a&&(s={type:`audio`,codec:`ac3`,aacCodecInfo:null,numberOfChannels:-1,sampleRate:-1});break;default:console.warn(`Unsupported stream_type 0x${t.toString(16)}; ignoring stream.`)}s&&this.elementaryStreams.push({demuxer:this,pid:n,streamType:t,initialized:!1,firstSection:null,info:s,referencePesPackets:[]})}a=!0}else{let e=this.elementaryStreams.find(e=>e.pid===t.pid);if(e&&!e.initialized){let n=Wc(t);if(!n)throw Error(`Couldn't read first PES packet for Elementary Stream with PID ${e.pid}`);if(e.firstSection=t,e.info.type===`video`)if(e.info.codec===`avc`){if(e.info.avcCodecInfo=Va(n.data),!e.info.avcCodecInfo)throw Error(`Invalid AVC video stream; could not extract AVCDecoderConfigurationRecord from first packet.`);let t=e.info.avcCodecInfo.sequenceParameterSets[0];I(t);let r=Ga(t);e.info.width=r.displayWidth,e.info.height=r.displayHeight,r.pixelAspectRatio.num>r.pixelAspectRatio.den?(e.info.squarePixelWidth=Math.round(e.info.width*r.pixelAspectRatio.num/r.pixelAspectRatio.den),e.info.squarePixelHeight=e.info.height):(e.info.squarePixelWidth=e.info.width,e.info.squarePixelHeight=Math.round(e.info.height*r.pixelAspectRatio.den/r.pixelAspectRatio.num)),e.info.colorSpace={primaries:Vr[r.colourPrimaries],transfer:Ur[r.transferCharacteristics],matrix:Gr[r.matrixCoefficients],fullRange:!!r.fullRangeFlag},e.info.reorderSize=r.maxDecFrameBuffering,e.initialized=!0}else if(e.info.codec===`hevc`){if(e.info.hevcCodecInfo=Xa(n.data),!e.info.hevcCodecInfo)throw Error(`Invalid HEVC video stream; could not extract HVCDecoderConfigurationRecord from first packet.`);let t=e.info.hevcCodecInfo.arrays.find(e=>e.nalUnitType===ja.SPS_NUT).nalUnits[0];I(t);let r=Ya(t);e.info.width=r.displayWidth,e.info.height=r.displayHeight,r.pixelAspectRatio.num>r.pixelAspectRatio.den?(e.info.squarePixelWidth=Math.round(e.info.width*r.pixelAspectRatio.num/r.pixelAspectRatio.den),e.info.squarePixelHeight=e.info.height):(e.info.squarePixelWidth=e.info.width,e.info.squarePixelHeight=Math.round(e.info.height*r.pixelAspectRatio.den/r.pixelAspectRatio.num)),e.info.colorSpace={primaries:Vr[r.colourPrimaries],transfer:Ur[r.transferCharacteristics],matrix:Gr[r.matrixCoefficients],fullRange:!!r.fullRangeFlag},e.info.reorderSize=r.maxDecFrameBuffering,e.initialized=!0}else throw Error(`Unhandled.`);else if(e.info.codec===`aac`){let t=Oc(Dl.tempFromBytes(n.data));if(!t)throw Error(`Invalid AAC audio stream; could not read ADTS frame header from first packet.`);e.info.aacCodecInfo={isMpeg2:!1,objectType:t.objectType},e.info.numberOfChannels=Hi[t.channelConfiguration],e.info.sampleRate=Vi[t.samplingFrequencyIndex],e.initialized=!0}else if(e.info.codec===`mp3`){let t=Ea(q(Dl.tempFromBytes(n.data)),n.data.byteLength);if(!t.header)throw Error(`Invalid MP3 audio stream; could not read frame header from first packet.`);e.info.numberOfChannels=t.header.channel===3?1:2,e.info.sampleRate=t.header.sampleRate,e.initialized=!0}else if(e.info.codec===`ac3`){let t=_o(n.data);if(!t)throw Error(`Invalid AC-3 audio stream; could not read sync frame from first packet.`);if(t.fscod===3)throw Error(`Invalid AC-3 audio stream; reserved sample rate code found in first packet.`);e.info.numberOfChannels=go[t.acmod]+t.lfeon,e.info.sampleRate=Oa[t.fscod],e.initialized=!0}else if(e.info.codec===`eac3`){let t=xo(n.data);if(!t)throw Error(`Invalid E-AC-3 audio stream; could not read sync frame from first packet.`);let r=Co(t);if(r===null)throw Error(`Invalid E-AC-3 audio stream; reserved sample rate code found in first packet.`);e.info.numberOfChannels=wo(t),e.info.sampleRate=r,e.initialized=!0}else throw Error(`Unhandled.`)}}if(a&&this.elementaryStreams.every(e=>e.initialized))break;n+=this.packetStride}if(!a)throw i?Error(`No Program Map Table found in the file.`):Error(`No Program Association Table found in the file.`);for(let e of this.elementaryStreams)e.info.type===`video`?this.tracks.push(new _s(this.input,new Kc(e))):this.tracks.push(new vs(this.input,new qc(e)))})()}async getTracks(){return await this.readMetadata(),this.tracks}async getMetadataTags(){return{}}async computeDuration(){let e=await this.getTracks(),t=await Promise.all(e.map(e=>e.computeDuration()));return Math.max(0,...t)}async getMimeType(){await this.readMetadata();let e=await this.getTracks();return Vc(await Promise.all(e.map(e=>e.getCodecParameterString())))}async readSection(e,t,n=!1){let r=e,i=e,a=[],o=0,s=null,c=!0,l=0;for(;;){let e=await this.readPacket(i);if(i+=this.packetStride,!e)break;if(s){if(e.pid!==s.pid){if(n)break;continue}if(e.payloadUnitStartIndicator===1)break}else{if(e.payloadUnitStartIndicator===0)break;s=e}let u=!!(e.adaptationFieldControl&2),d=!!(e.adaptationFieldControl&1),f=0;if(u&&(f=1+e.body[0],e===s&&f>1&&(l=e.body[1]>>6&1)),d&&(f===0?(a.push(e.body),o+=e.body.byteLength):(a.push(e.body.subarray(f)),o+=e.body.byteLength-f)),r=i,!t&&o>=64){c=!1;break}if(Zr(this.sectionEndPositions,r,e=>e)!==-1){c=!1;break}}if(c){let e=B(this.sectionEndPositions,r,e=>e);this.sectionEndPositions.splice(e+1,0,r)}if(!s)return null;let u;if(a.length===1)u=a[0];else{let e=a.reduce((e,t)=>e+t.length,0);u=new Uint8Array(e);let t=0;for(let e of a)u.set(e,t),t+=e.length}return{startPos:e,endPos:t?r:null,pid:s.pid,payload:u,randomAccessIndicator:l}}async readPacketHeader(e){let t=this.reader.requestSlice(e,4);if(t instanceof Promise&&(t=await t),!t)return null;if(K(t)!==71)throw Error(`Invalid TS packet sync byte. Likely an internal bug, please report this file.`);let n=Al(t);n>>15;let r=n>>14&1;n>>13&1;let i=n&8191,a=K(t);a>>6;let o=a>>4&3;return a&15,{payloadUnitStartIndicator:r,pid:i,adaptationFieldControl:o}}async readPacket(e){let t=this.reader.requestSlice(e,188);if(t instanceof Promise&&(t=await t),!t)return null;let n=G(t,188);if(n[0]!==71)throw Error(`Invalid TS packet sync byte. Likely an internal bug, please report this file.`);let r=(n[1]<<8)+n[2];r>>15;let i=r>>14&1;r>>13&1;let a=r&8191,o=n[3];o>>6;let s=o>>4&3;return o&15,{payloadUnitStartIndicator:i,pid:a,adaptationFieldControl:s,body:n.subarray(4)}}},Uc=e=>{if(e.payload.byteLength<3)return null;let t=new V(e.payload);if(t.readBits(24)!==1)return null;let n=t.readBits(8);if(t.skipBits(16),n===188||n===190||n===191||n===240||n===241||n===255||n===242||n===248)return null;t.skipBits(8);let r=t.readBits(2);t.skipBits(14);let i=0;if(r===2||r===3)t.skipBits(4),i+=t.readBits(3)*(1<<30),t.skipBits(1),i+=t.readBits(15)*32768,t.skipBits(1),i+=t.readBits(15);else throw Error(`PES packets without PTS are not currently supported. If you think this file should be supported, please report it.`);return{sectionStartPos:e.startPos,sectionEndPos:e.endPos,pts:i,randomAccessIndicator:e.randomAccessIndicator}},Wc=e=>{I(e.endPos!==null);let t=Uc(e);if(!t)return null;let n=new V(e.payload);n.skipBits(32);let r=n.readBits(16);n.skipBits(16);let i=n.readBits(8),a=n.pos+8*i;n.pos=a;let o=a/8;I(Number.isInteger(o));let s=e.payload.subarray(o,r>0?6+r:e.payload.byteLength);return{...t,data:s}},Gc=class e{constructor(e){this.elementaryStream=e,this.packetBuffers=new WeakMap,this.packetSectionStarts=new WeakMap}getId(){return this.elementaryStream.pid}getNumber(){let t=this.elementaryStream.demuxer,n=this.elementaryStream.info.type,r=0;for(let i of t.tracks)if(i.type===n&&r++,I(i._backing instanceof e),i._backing.elementaryStream===this.elementaryStream)break;return r}getCodec(){throw Error(`Not implemented on base class.`)}getInternalCodecId(){return this.elementaryStream.streamType}getName(){return null}getLanguageCode(){return`und`}getDisposition(){return zi}getTimeResolution(){return Bc}async computeDuration(){let e=await this.getPacket(1/0,{metadataOnly:!0});return(e?.timestamp??0)+(e?.duration??0)}async getFirstTimestamp(){return(await this.getFirstPacket({metadataOnly:!0}))?.timestamp??0}createEncodedPacket(e,t,n){let r;return r=this.allPacketsAreKeyPackets()||e.randomAccessIndicator===1?`key`:`delta`,new H(n.metadataOnly?Ao:e.data,r,e.pts/Bc,Math.max(t/Bc,0),e.sequenceNumber,e.data.byteLength)}async getFirstPacket(e){let t=this.elementaryStream.firstSection;I(t);let n=Wc(t);I(n);let r=new Xc(this.elementaryStream,n),i=new Zc(this,r),a=await i.readNext();if(!a)return null;let o=this.createEncodedPacket(a.packet,a.duration,e);return this.packetBuffers.set(o,i),this.packetSectionStarts.set(o,a.packet.sectionStartPos),o}async getNextPacket(e,t){let n=this.packetBuffers.get(e);if(n){let r=await n.readNext();if(!r)return null;this.packetBuffers.delete(e);let i=this.createEncodedPacket(r.packet,r.duration,t);return this.packetBuffers.set(i,n),this.packetSectionStarts.set(i,r.packet.sectionStartPos),i}let r=this.packetSectionStarts.get(e);if(r===void 0)throw Error(`Packet was not created from this track.`);let i=await this.elementaryStream.demuxer.readSection(r,!0);I(i);let a=Wc(i);I(a);let o=new Xc(this.elementaryStream,a);n=new Zc(this,o);let s=e.sequenceNumber;for(;;){let e=await n.readNext();if(!e)return null;if(e.packet.sequenceNumber>s){let r=this.createEncodedPacket(e.packet,e.duration,t);return this.packetBuffers.set(r,n),this.packetSectionStarts.set(r,e.packet.sectionStartPos),r}}}async getNextKeyPacket(e,t){let n=e;for(;;){if(n=await this.getNextPacket(n,t),!n)return null;if(n.type===`key`)return n}}getPacket(e,t){return this.doPacketLookup(e,!1,t)}getKeyPacket(e,t){return this.doPacketLookup(e,!0,t)}async doPacketLookup(e,t,n){let r=di(e*Bc),i=this.elementaryStream.demuxer,{reader:a,seekChunkSize:o}=i,s=this.elementaryStream.pid,c=async(e,t)=>{let n=e;for(;n<t;){let e=await i.readPacketHeader(n);if(!e)return null;if(e.pid===s&&e.payloadUnitStartIndicator===1){let e=await i.readSection(n,!1);if(!e)return null;let t=Uc(e);if(t)return t}n+=i.packetStride}return null},l=this.elementaryStream.firstSection;I(l);let u=Uc(l);if(I(u),r<u.pts)return null;let d,f=this.elementaryStream.referencePesPackets,p=B(f,r,e=>e.pts),m=p===-1?null:f[p];if(m&&r-m.pts<9e4/2)d=m.sectionStartPos;else{let e=0;if(a.fileSize!==null){let t=Math.ceil(a.fileSize/o);if(t>1){let n=0,a=t-1;for(e=n;n<=a;){let t=Math.floor((n+a)/2),s=pi(t*o,i.packetStride)+u.sectionStartPos,l=await c(s,s+o);if(!l){a=t-1;continue}l.pts<=r?(e=t,n=t+1):a=t-1}}}d=pi(e*o,i.packetStride)+u.sectionStartPos}let h=await c(d,a.fileSize??1/0);h||=u;let g=this.getReorderSize(),_=async(e,t)=>{let a=await i.readSection(e,!0);I(a);let o=Wc(a);I(o);let s=new Xc(this.elementaryStream,o),c=new Zc(this,s);for(;!((L(c.presentationOrderPackets)?.pts??-1/0)>=r||!await c.readNextPacket()););let l=ti(c.presentationOrderPackets,t);if(l===-1)return null;let u=c.presentationOrderPackets[l],d=l===0?0:u.pts-c.presentationOrderPackets[l-1].pts;for(;c.decodeOrderPackets[0]!==u;)c.decodeOrderPackets.shift();c.lastDuration=d;let f=await c.readNext();I(f);let p=this.createEncodedPacket(f.packet,f.duration,n);return this.packetBuffers.set(p,c),this.packetSectionStarts.set(p,f.packet.sectionStartPos),p};if(!t||this.allPacketsAreKeyPackets()){outer:for(;;){let e=h.sectionStartPos+i.packetStride;for(;;){let t=await i.readPacketHeader(e);if(!t)break outer;if(t.pid===s&&t.payloadUnitStartIndicator===1){let t=await i.readSection(e,!1);if(t){let e=Uc(t);if(e){if(e.pts>r)break outer;h=e,Jc(this.elementaryStream,e);break}}}e+=i.packetStride}}outer:for(let e=0;e<g;e++){let e=h.sectionStartPos-i.packetStride;for(;e>=i.packetOffset;){let t=await i.readPacketHeader(e);if(!t)break outer;if(t.pid===s&&t.payloadUnitStartIndicator===1){let t=await i.readSection(e,!1);if(t){let e=Uc(t);if(e){h=e;break}}}e-=i.packetStride}}return _(h.sectionStartPos,e=>e.pts<=r)}else{let e=d,t=null;for(;;){let n=null,l=e<=u.sectionStartPos,d;l?(d=u,n=u):d=await c(e,a.fileSize??1/0);let f=!1,p=0;outer:for(;d&&!(t!==null&&d.sectionStartPos>=t||(d.randomAccessIndicator===1&&d.pts<=r&&(n=d),d.pts>r&&(f=!0),f&&(p++,p>=g)));){let e=d.sectionStartPos+i.packetStride;for(;;){let t=await i.readPacketHeader(e);if(!t)break outer;if(t.pid===s&&t.payloadUnitStartIndicator===1){let t=await i.readSection(e,!1);if(t&&(d=Uc(t),d)){Jc(this.elementaryStream,d);break}}e+=i.packetStride}}if(n){let e=n;if(p===0)outer:for(let t=0;t<g-1;t++){let t=e.sectionStartPos-i.packetStride;for(;t>=i.packetOffset;){let n=await i.readPacketHeader(t);if(!n)break outer;if(n.pid===s&&n.payloadUnitStartIndicator===1){let n=await i.readSection(t,!1);if(n){let t=Uc(n);if(t){e=t;break}}}t-=i.packetStride}}let t=await _(e.sectionStartPos,e=>e.pts<=r&&e.randomAccessIndicator===1);return I(t),t}I(!l),t=e,e=Math.max(pi(e-u.sectionStartPos-o,i.packetStride)+u.sectionStartPos,u.sectionStartPos)}}}},Kc=class extends Gc{constructor(e){super(e),this.elementaryStream=e,this.decoderConfig={codec:ia({width:this.elementaryStream.info.width,height:this.elementaryStream.info.height,codec:this.elementaryStream.info.codec,codecDescription:null,colorSpace:this.elementaryStream.info.colorSpace,avcType:1,avcCodecInfo:this.elementaryStream.info.avcCodecInfo,hevcCodecInfo:this.elementaryStream.info.hevcCodecInfo,vp9CodecInfo:null,av1CodecInfo:null}),codedWidth:this.elementaryStream.info.width,codedHeight:this.elementaryStream.info.height,displayAspectWidth:this.elementaryStream.info.squarePixelWidth,displayAspectHeight:this.elementaryStream.info.squarePixelHeight,colorSpace:this.elementaryStream.info.colorSpace}}getCodec(){return this.elementaryStream.info.codec}getCodedWidth(){return this.elementaryStream.info.width}getCodedHeight(){return this.elementaryStream.info.height}getSquarePixelWidth(){return this.elementaryStream.info.squarePixelWidth}getSquarePixelHeight(){return this.elementaryStream.info.squarePixelHeight}getRotation(){return 0}async getColorSpace(){return this.elementaryStream.info.colorSpace}async canBeTransparent(){return!1}async getDecoderConfig(){return this.decoderConfig}allPacketsAreKeyPackets(){return!1}getReorderSize(){return this.elementaryStream.info.reorderSize}},qc=class extends Gc{constructor(e){super(e),this.elementaryStream=e}getCodec(){return this.elementaryStream.info.codec}getNumberOfChannels(){return this.elementaryStream.info.numberOfChannels}getSampleRate(){return this.elementaryStream.info.sampleRate}async getDecoderConfig(){return{codec:oa({codec:this.elementaryStream.info.codec,codecDescription:null,aacCodecInfo:this.elementaryStream.info.aacCodecInfo}),numberOfChannels:this.elementaryStream.info.numberOfChannels,sampleRate:this.elementaryStream.info.sampleRate}}allPacketsAreKeyPackets(){return!0}getReorderSize(){return 1}},Jc=(e,t)=>{let n=e.referencePesPackets,r=B(n,t.sectionStartPos,e=>e.sectionStartPos);if(r>=0){let i=n[r];if(t.pts<=i.pts)return!1;let a=e.demuxer.minReferencePointByteDistance;if(t.sectionStartPos-i.sectionStartPos<a)return!1;if(r<n.length-1){let e=n[r+1];if(e.pts<t.pts||e.sectionStartPos-t.sectionStartPos<a)return!1}}return n.splice(r+1,0,t),!0},Yc=async e=>{I(!e.suppliedPacket);let t=e.elementaryStream;if(t.info.type===`video`){let n=t.info.codec,r=1024;if(n!==`avc`&&n!==`hevc`)throw Error(`Unhandled.`);let i=null;for(;;){let t=e.ensureBuffered(r);if(t instanceof Promise&&(t=await t),t===0)break;let a=e.currentPos,o=e.readBytes(t),s=o.byteLength,c=0;for(;c<s;){let t=o.indexOf(0,c);if(t===-1||t>=s)break;c=t;let r=a+c;if(c+4>=s){e.seekTo(r);break}let l=o[c+1],u=o[c+2],d=o[c+3],f=0,p=null;if(l===0&&u===0&&d===1?(f=4,p=o[c+4]):l===0&&u===1&&(f=3,p=d),f===0){c++;continue}let m=r;if(i===null){i=m,c+=f;continue}if(p!==null){let t=n===`avc`?Fa(p):Ja(p);if(n===`avc`?t===Aa.AUD:t===ja.AUD_NUT){let t=m-i;return e.seekTo(i),e.supplyPacket(t,0)}}c+=f}if(t<r)break}if(i!==null){let t=e.endPos-i;return e.seekTo(i),e.supplyPacket(t,0)}}else{let n=t.info.codec;for(;;){let r=e.ensureBuffered(128);r instanceof Promise&&(r=await r);let i=e.currentPos;for(;e.currentPos-i<r;){let r=e.readU8();if(n===`aac`){if(r!==255)continue;e.skip(-1);let n=e.currentPos,i=e.ensureBuffered(9);if(i instanceof Promise&&(i=await i),i<9)return;let a=e.readBytes(9),o=Oc(Dl.tempFromBytes(a));if(o){e.seekTo(n);let r=e.ensureBuffered(o.frameLength);return r instanceof Promise&&(r=await r),e.supplyPacket(r,Math.round(kc*Bc/t.info.sampleRate))}else e.seekTo(n+1)}else if(n===`mp3`){if(r!==255)continue;e.skip(-1);let n=e.currentPos,i=e.ensureBuffered(4);if(i instanceof Promise&&(i=await i),i<4)return;let a=Ea(z(e.readBytes(4)).getUint32(0),null);if(a.header){e.seekTo(n);let r=e.ensureBuffered(a.header.totalSize);r instanceof Promise&&(r=await r);let i=a.header.audioSamplesInFrame*Bc/t.info.sampleRate;return e.supplyPacket(r,Math.round(i))}else e.seekTo(n+1)}else if(n===`ac3`){if(r!==11)continue;e.skip(-1);let n=e.currentPos,i=e.ensureBuffered(5);if(i instanceof Promise&&(i=await i),i<5)return;let a=e.readBytes(5);if(a[0]!==11||a[1]!==119){e.seekTo(n+1);continue}let o=a[4]>>6,s=a[4]&63;if(o===3||s>37){e.seekTo(n+1);continue}let c=vo[3*s+o];I(c!==void 0),e.seekTo(n),i=e.ensureBuffered(c),i instanceof Promise&&(i=await i);let l=Math.round(yo*Bc/t.info.sampleRate);return e.supplyPacket(i,l)}else if(n===`eac3`){if(r!==11)continue;e.skip(-1);let n=e.currentPos,i=e.ensureBuffered(5);if(i instanceof Promise&&(i=await i),i<5)return;let a=e.readBytes(5);if(a[0]!==11||a[1]!==119){e.seekTo(n+1);continue}let o=(((a[2]&7)<<8|a[3])+1)*2,s=bo[a[4]>>6==3?3:a[4]>>4&3];e.seekTo(n),i=e.ensureBuffered(o),i instanceof Promise&&(i=await i);let c=s*256,l=Math.round(c*Bc/t.info.sampleRate);return e.supplyPacket(i,l)}else throw Error(`Unhandled.`)}if(r<128)break}}},Xc=class e{constructor(e,t){this.currentPos=0,this.pesPackets=[],this.currentPesPacketIndex=0,this.currentPesPacketPos=0,this.endPos=0,this.nextPts=0,this.suppliedPacket=null,this.elementaryStream=e,this.pid=e.pid,this.demuxer=e.demuxer,this.startingPesPacket=t}clone(){let t=new e(this.elementaryStream,this.startingPesPacket);return t.currentPos=this.currentPos,t.pesPackets=[...this.pesPackets],t.currentPesPacketIndex=this.currentPesPacketIndex,t.currentPesPacketPos=this.currentPesPacketPos,t.endPos=this.endPos,t.nextPts=this.nextPts,t}ensureBuffered(e){let t=this.endPos-this.currentPos;return t>=e?e:this.bufferData(e-t).then(()=>Math.min(this.endPos-this.currentPos,e))}getCurrentPesPacket(){let e=this.pesPackets[this.currentPesPacketIndex];return I(e),e}async bufferData(e){let t=this.endPos+e;for(;this.endPos<t;){let e;if(this.pesPackets.length===0)e=this.startingPesPacket;else{let t=L(this.pesPackets).sectionEndPos;for(I(t!==null);;){let n=await this.demuxer.readPacketHeader(t);if(!n)return;if(n.pid===this.pid){let n=await this.demuxer.readSection(t,!0);if(!n)return;let r=Wc(n);if(r){e=r;break}}t+=this.demuxer.packetStride}}this.pesPackets.push(e),this.endPos+=e.data.byteLength,this.pesPackets.length===1&&(this.nextPts=e.pts)}}readBytes(e){let t=this.getCurrentPesPacket(),n=this.currentPos-this.currentPesPacketPos,r=n+e;if(this.currentPos+=e,r<=t.data.byteLength)return t.data.subarray(n,r);let i=new Uint8Array(e);i.set(t.data.subarray(n));let a=t.data.byteLength-n;for(;;){this.advanceCurrentPacket();let t=this.getCurrentPesPacket(),n=e-a;if(n<=t.data.byteLength){i.set(t.data.subarray(0,n),a);break}i.set(t.data,a),a+=t.data.byteLength}return i}readU8(){let e=this.getCurrentPesPacket(),t=this.currentPos-this.currentPesPacketPos;return this.currentPos++,t<e.data.byteLength?e.data[t]:(this.advanceCurrentPacket(),e=this.getCurrentPesPacket(),e.data[0])}seekTo(e){if(e!==this.currentPos){if(e<this.currentPos)for(;e<this.currentPesPacketPos;){this.currentPesPacketIndex--;let e=this.getCurrentPesPacket();this.currentPesPacketPos-=e.data.byteLength,this.nextPts=e.pts}else for(;;){let t=this.getCurrentPesPacket();if(e<this.currentPesPacketPos+t.data.byteLength)break;this.currentPesPacketPos+=t.data.byteLength,this.currentPesPacketIndex++,this.nextPts=this.getCurrentPesPacket().pts}this.currentPos=e}}skip(e){this.seekTo(this.currentPos+e)}advanceCurrentPacket(){this.currentPesPacketPos+=this.getCurrentPesPacket().data.byteLength,this.currentPesPacketIndex++,this.nextPts=this.getCurrentPesPacket().pts}supplyPacket(e,t){let n=this.getCurrentPesPacket();Jc(this.elementaryStream,n);let r=this.nextPts;this.nextPts+=t;let i=n.sectionStartPos,a=i+(this.currentPos-this.currentPesPacketPos),o=this.readBytes(e),s=n.randomAccessIndicator;I(this.elementaryStream.firstSection),n.sectionStartPos===this.elementaryStream.firstSection.startPos&&(s=1),this.suppliedPacket={pts:r,data:o,sequenceNumber:a,sectionStartPos:i,randomAccessIndicator:s},this.pesPackets.splice(0,this.currentPesPacketIndex),this.currentPesPacketIndex=0}},Zc=class{constructor(e,t){this.decodeOrderPackets=[],this.reorderBuffer=[],this.presentationOrderPackets=[],this.reachedEnd=!1,this.lastDuration=0,this.backing=e,this.context=t,this.reorderSize=e.getReorderSize(),I(this.reorderSize>=0)}async readNext(){if(this.decodeOrderPackets.length===0&&!await this.readNextPacket())return null;await this.ensureCurrentPacketHasNext();let e=this.decodeOrderPackets[0],t=this.presentationOrderPackets.indexOf(e);I(t!==-1);let n;for(t===this.presentationOrderPackets.length-1?n=this.lastDuration:(n=this.presentationOrderPackets[t+1].pts-e.pts,this.lastDuration=n),this.decodeOrderPackets.shift();this.presentationOrderPackets.length>0;){let e=this.presentationOrderPackets[0];if(this.decodeOrderPackets.includes(e))break;this.presentationOrderPackets.shift()}return{packet:e,duration:n}}async readNextPacket(){if(this.reachedEnd)return!1;let e;return this.context.suppliedPacket||await Yc(this.context),e=this.context.suppliedPacket,this.context.suppliedPacket=null,e?(this.decodeOrderPackets.push(e),this.processPacketThroughReorderBuffer(e),!0):(this.reachedEnd=!0,this.flushReorderBuffer(),!1)}async ensureCurrentPacketHasNext(){let e=this.decodeOrderPackets[0];for(I(e);;){let t=this.presentationOrderPackets.indexOf(e);if(t!==-1&&t<=this.presentationOrderPackets.length-2||!await this.readNextPacket())break}}processPacketThroughReorderBuffer(e){if(this.reorderBuffer.push(e),this.reorderBuffer.length>=this.reorderSize){let e=0;for(let t=1;t<this.reorderBuffer.length;t++)this.reorderBuffer[t].pts<this.reorderBuffer[e].pts&&(e=t);let t=this.reorderBuffer.splice(e,1)[0];this.presentationOrderPackets.push(t)}}flushReorderBuffer(){this.reorderBuffer.sort((e,t)=>e.pts-t.pts),this.presentationOrderPackets.push(...this.reorderBuffer),this.reorderBuffer.length=0}},Qc=class{},$c=class extends Qc{async _getMajorBrand(e){let t=e._reader.requestSlice(0,12);return t instanceof Promise&&(t=await t),!t||(t.skip(4),Ul(t,4)!==`ftyp`)?null:Ul(t,4)}_createDemuxer(e){return new Es(e)}},el=class extends $c{async _canReadInput(e){let t=await this._getMajorBrand(e);return!!t&&t!==`qt `}get name(){return`MP4`}get mimeType(){return`video/mp4`}},tl=class extends $c{async _canReadInput(e){return await this._getMajorBrand(e)===`qt `}get name(){return`QuickTime File Format`}get mimeType(){return`video/quicktime`}},nl=class extends Qc{async isSupportedEBMLOfDocType(e,t){let n=e._reader.requestSlice(0,16);if(n instanceof Promise&&(n=await n),!n)return!1;let r=Bs(n);if(r===null||r<1||r>8||W(n,r)!==U.EBML)return!1;let i=Ws(n);if(typeof i!=`number`)return!1;let a=e._reader.requestSlice(n.filePos,i);if(a instanceof Promise&&(a=await a),!a)return!1;let o=n.filePos;for(;a.filePos<=o+i-2;){let e=Gs(a);if(!e)break;let{id:n,size:r}=e,i=a.filePos;if(r===void 0)return!1;switch(n){case U.EBMLVersion:if(W(a,r)!==1)return!1;break;case U.EBMLReadVersion:if(W(a,r)!==1)return!1;break;case U.DocType:if(Ks(a,r)!==t)return!1;break;case U.DocTypeVersion:if(W(a,r)>4)return!1;break}a.filePos=i+r}return!0}_canReadInput(e){return this.isSupportedEBMLOfDocType(e,`matroska`)}_createDemuxer(e){return new ac(e)}get name(){return`Matroska`}get mimeType(){return`video/x-matroska`}},rl=class extends nl{_canReadInput(e){return this.isSupportedEBMLOfDocType(e,`webm`)}get name(){return`WebM`}get mimeType(){return`video/webm`}},il=class extends Qc{async _canReadInput(e){let t=0;for(;;){let n=e._reader.requestSlice(t,10);if(n instanceof Promise&&(n=await n),!n)break;let r=Yl(n);if(!r)break;t=n.filePos+r.size}let n=await lc(e._reader,t,t+4096);if(!n)return!1;let r=n.header,i=Ta(r.mpegVersionId,r.channel),a=e._reader.requestSlice(n.startPos+i,4);if(a instanceof Promise&&(a=await a),!a)return!1;let o=q(a);if(o===1483304551||o===1231971951)return!0;t=n.startPos+n.header.totalSize;let s=await lc(e._reader,t,t+4);if(!s)return!1;let c=s.header;return!(r.channel!==c.channel||r.sampleRate!==c.sampleRate)}_createDemuxer(e){return new uc(e)}get name(){return`MP3`}get mimeType(){return`audio/mpeg`}},al=class extends Qc{async _canReadInput(e){let t=e._reader.requestSlice(0,12);if(t instanceof Promise&&(t=await t),!t)return!1;let n=Ul(t,4);return n!==`RIFF`&&n!==`RIFX`&&n!==`RF64`?!1:(t.skip(4),Ul(t,4)===`WAVE`)}_createDemuxer(e){return new Tc(e)}get name(){return`WAVE`}get mimeType(){return`audio/wav`}},ol=class extends Qc{async _canReadInput(e){let t=e._reader.requestSlice(0,4);return t instanceof Promise&&(t=await t),t?Ul(t,4)===`OggS`:!1}_createDemuxer(e){return new bc(e)}get name(){return`Ogg`}get mimeType(){return`application/ogg`}},sl=class extends Qc{async _canReadInput(e){let t=e._reader.requestSlice(0,4);return t instanceof Promise&&(t=await t),t?Ul(t,4)===`fLaC`:!1}get name(){return`FLAC`}get mimeType(){return`audio/flac`}_createDemuxer(e){return new Rc(e)}},cl=class extends Qc{async _canReadInput(e){let t=0;for(;;){let n=e._reader.requestSlice(t,10);if(n instanceof Promise&&(n=await n),!n)break;let r=Yl(n);if(!r)break;t=n.filePos+r.size}let n=e._reader.requestSliceRange(t,7,9);if(n instanceof Promise&&(n=await n),!n)return!1;let r=Oc(n);if(!r||(t+=r.frameLength,n=e._reader.requestSliceRange(t,7,9),n instanceof Promise&&(n=await n),!n))return!1;let i=Oc(n);return i?r.objectType===i.objectType&&r.samplingFrequencyIndex===i.samplingFrequencyIndex&&r.channelConfiguration===i.channelConfiguration:!1}_createDemuxer(e){return new Ac(e)}get name(){return`ADTS`}get mimeType(){return`audio/aac`}},ll=class extends Qc{async _canReadInput(e){let t=e._reader.requestSlice(0,205);if(t instanceof Promise&&(t=await t),!t)return!1;let n=G(t,205);return n[0]===71&&n[188]===71||n[0]===71&&n[204]===71?!0:n[4]===71&&n[196]===71}_createDemuxer(e){return new Hc(e)}get name(){return`MPEG Transport Stream`}get mimeType(){return`video/MP2T`}},ul=new el,dl=new tl,fl=new nl,pl=new rl,ml=new il,hl=new al,gl=new ol,_l=new cl,vl=[ul,dl,fl,pl,hl,gl,new sl,ml,_l,new ll];n(e(((e,t)=>{t.exports={}}))(),1);var yl=class{constructor(){this._disposed=!1,this._sizePromise=null,this.onread=null}async getSizeOrNull(){if(this._disposed)throw new Tl;return this._sizePromise??=Promise.resolve(this._retrieveSize())}async getSize(){if(this._disposed)throw new Tl;let e=await this.getSizeOrNull();if(e===null)throw Error(`Cannot determine the size of an unsized source.`);return e}},bl=class extends yl{constructor(e,t={}){if(!(e instanceof Blob))throw TypeError(`blob must be a Blob.`);if(!t||typeof t!=`object`)throw TypeError(`options must be an object.`);if(t.maxCacheSize!==void 0&&(!Ni(t.maxCacheSize)||t.maxCacheSize<0))throw TypeError(`options.maxCacheSize, when provided, must be a non-negative number.`);super(),this._readers=new WeakMap,this._blob=e,this._orchestrator=new Cl({maxCacheSize:t.maxCacheSize??8*2**20,maxWorkerCount:4,runWorker:this._runWorker.bind(this),prefetchProfile:Sl.fileSystem})}_retrieveSize(){let e=this._blob.size;return this._orchestrator.fileSize=e,e}_read(e,t){return this._orchestrator.read(e,t)}async _runWorker(e){let t=this._readers.get(e);for(t===void 0&&(t=(`stream`in this._blob)&&!xi()?this._blob.slice(e.currentPos).stream().getReader():null,this._readers.set(e,t));e.currentPos<e.targetPos&&!e.aborted;)if(t){let{done:n,value:r}=await t.read();if(n)throw this._orchestrator.forgetWorker(e),Error(`Blob reader stopped unexpectedly before all requested data was read.`);if(e.aborted)break;this.onread?.(e.currentPos,e.currentPos+r.length),this._orchestrator.supplyWorkerData(e,r)}else{let t=await this._blob.slice(e.currentPos,e.targetPos).arrayBuffer();if(e.aborted)break;this.onread?.(e.currentPos,e.currentPos+t.byteLength),this._orchestrator.supplyWorkerData(e,new Uint8Array(t))}e.running=!1,e.aborted&&await t?.cancel()}_dispose(){this._orchestrator.dispose()}},xl=.5*2**20,Sl={none:(e,t)=>({start:e,end:t}),fileSystem:(e,t)=>{let n=2**16;return e=Math.floor((e-n)/n)*n,t=Math.ceil((t+n)/n)*n,{start:e,end:t}},network:(e,t,n)=>{let r=2**16;e=Math.max(0,Math.floor((e-r)/r)*r);for(let r of n){let n=8*2**20,i=Math.max((r.startPos+r.targetPos)/2,r.targetPos-n);if(ki(e,t,i,r.targetPos)){let e=r.targetPos-r.startPos,i=Math.ceil((e+1)/n)*n,a=2**Math.ceil(Math.log2(e+1)),o=Math.min(a,i);t=Math.max(t,r.startPos+o)}}return t=Math.max(t,e+xl),{start:e,end:t}}},Cl=class{constructor(e){this.options=e,this.fileSize=null,this.nextAge=0,this.workers=[],this.cache=[],this.currentCacheSize=0,this.disposed=!1}read(e,t){I(this.fileSize!==null);let n=this.options.prefetchProfile(e,t,this.workers),r=Math.max(n.start,0),i=Math.min(n.end,this.fileSize);I(r<=e&&t<=i);let a=null,o=B(this.cache,e,e=>e.start),s=o===-1?null:this.cache[o];s&&s.start<=e&&t<=s.end&&(s.age=this.nextAge++,a={bytes:s.bytes,view:s.view,offset:s.start});let c=B(this.cache,r,e=>e.start),l=a?null:new Uint8Array(t-e),u=0,d=r,f=[];if(c!==-1){for(let n=c;n<this.cache.length;n++){let a=this.cache[n];if(a.start>=i)break;if(a.end<=r)continue;let o=Math.max(r,a.start),s=Math.min(i,a.end);if(I(o<=s),d<o&&f.push({start:d,end:o}),d=s,l){let n=Math.max(e,a.start),r=Math.min(t,a.end);if(n<r){let t=n-e;l.set(a.bytes.subarray(n-a.start,r-a.start),t),t===u&&(u=r-e)}}a.age=this.nextAge++}d<i&&f.push({start:d,end:i})}else f.push({start:r,end:i});if(l&&u>=l.length&&(a={bytes:l,view:z(l),offset:e}),f.length===0)return I(a),a;let{promise:p,resolve:m,reject:h}=$r(),g=[];for(let n of f){let r=Math.max(e,n.start),i=Math.min(t,n.end);r===n.start&&i===n.end?g.push(n):r<i&&g.push({start:r,end:i})}for(let t of f){let n=l&&{start:e,bytes:l,holes:g,resolve:m,reject:h},r=!1;for(let e of this.workers)if(ki(t.start-2**17,t.start,e.currentPos,e.targetPos)){e.targetPos=Math.max(e.targetPos,t.end),r=!0,n&&!e.pendingSlices.includes(n)&&e.pendingSlices.push(n),e.running||this.runWorker(e);break}if(!r){let e=this.createWorker(t.start,t.end);n&&(e.pendingSlices=[n]),this.runWorker(e)}}return a||=(I(l),p.then(t=>({bytes:t,view:z(t),offset:e}))),a}createWorker(e,t){let n={startPos:e,currentPos:e,targetPos:t,running:!1,aborted:this.disposed,pendingSlices:[],age:this.nextAge++};for(this.workers.push(n);this.workers.length>this.options.maxWorkerCount;){let e=0,t=this.workers[0];for(let n=1;n<this.workers.length;n++){let r=this.workers[n];r.age<t.age&&(e=n,t=r)}if(t.running&&t.pendingSlices.length>0)break;t.aborted=!0,this.workers.splice(e,1)}return n}runWorker(e){I(!e.running),I(e.currentPos<e.targetPos),e.running=!0,e.age=this.nextAge++,this.options.runWorker(e).catch(t=>{if(e.running=!1,e.pendingSlices.length>0)e.pendingSlices.forEach(e=>e.reject(t)),e.pendingSlices.length=0;else throw t})}supplyWorkerData(e,t){I(!e.aborted);let n=e.currentPos,r=n+t.length;this.insertIntoCache({start:n,end:r,bytes:t,view:z(t),age:this.nextAge++}),e.currentPos+=t.length,e.targetPos=Math.max(e.targetPos,e.currentPos);for(let i=0;i<e.pendingSlices.length;i++){let a=e.pendingSlices[i],o=Math.max(n,a.start),s=Math.min(r,a.start+a.bytes.length);o<s&&a.bytes.set(t.subarray(o-n,s-n),o-a.start);for(let e=0;e<a.holes.length;e++){let t=a.holes[e];n<=t.start&&r>t.start&&(t.start=r),t.end<=t.start&&(a.holes.splice(e,1),e--)}a.holes.length===0&&(a.resolve(a.bytes),e.pendingSlices.splice(i,1),i--)}for(let t=0;t<this.workers.length;t++){let i=this.workers[t];e===i||i.running||ki(n,r,i.currentPos,i.targetPos)&&(this.workers.splice(t,1),t--)}}forgetWorker(e){let t=this.workers.indexOf(e);I(t!==-1),this.workers.splice(t,1)}insertIntoCache(e){if(this.options.maxCacheSize===0)return;let t=B(this.cache,e.start,e=>e.start)+1;if(t>0){let n=this.cache[t-1];if(n.end>=e.end)return;if(n.end>e.start){let r=new Uint8Array(e.end-n.start);r.set(n.bytes,0),r.set(e.bytes,e.start-n.start),this.currentCacheSize+=e.end-n.end,n.bytes=r,n.view=z(r),n.end=e.end,t--,e=n}else this.cache.splice(t,0,e),this.currentCacheSize+=e.bytes.length}else this.cache.splice(t,0,e),this.currentCacheSize+=e.bytes.length;for(let n=t+1;n<this.cache.length;n++){let t=this.cache[n];if(e.end<=t.start)break;if(e.end>=t.end){this.cache.splice(n,1),this.currentCacheSize-=t.bytes.length,n--;continue}let r=new Uint8Array(t.end-e.start);r.set(e.bytes,0),r.set(t.bytes,t.start-e.start),this.currentCacheSize-=e.end-t.start,e.bytes=r,e.view=z(r),e.end=t.end,this.cache.splice(n,1);break}for(;this.currentCacheSize>this.options.maxCacheSize;){let e=0,t=this.cache[0];for(let n=1;n<this.cache.length;n++){let r=this.cache[n];r.age<t.age&&(e=n,t=r)}if(this.currentCacheSize-t.bytes.length<=this.options.maxCacheSize)break;this.cache.splice(e,1),this.currentCacheSize-=t.bytes.length}}dispose(){for(let e of this.workers)e.aborted=!0;this.workers.length=0,this.cache.length=0,this.disposed=!0}};Mi();var wl=class{get disposed(){return this._disposed}constructor(e){if(this._demuxerPromise=null,this._format=null,this._disposed=!1,!e||typeof e!=`object`)throw TypeError(`options must be an object.`);if(!Array.isArray(e.formats)||e.formats.some(e=>!(e instanceof Qc)))throw TypeError(`options.formats must be an array of InputFormat.`);if(!(e.source instanceof yl))throw TypeError(`options.source must be a Source.`);if(e.source._disposed)throw Error(`options.source must not be disposed.`);this._formats=e.formats,this._source=e.source,this._reader=new El(e.source)}_getDemuxer(){return this._demuxerPromise??=(async()=>{this._reader.fileSize=await this._source.getSizeOrNull();for(let e of this._formats)if(await e._canReadInput(this))return this._format=e,e._createDemuxer(this);throw Error(`Input has an unsupported or unrecognizable format.`)})()}get source(){return this._source}async getFormat(){return await this._getDemuxer(),I(this._format),this._format}async computeDuration(){return(await this._getDemuxer()).computeDuration()}async getFirstTimestamp(){let e=await this.getTracks();if(e.length===0)return 0;let t=await Promise.all(e.map(e=>e.getFirstTimestamp()));return Math.min(...t)}async getTracks(){return(await this._getDemuxer()).getTracks()}async getVideoTracks(){return(await this.getTracks()).filter(e=>e.isVideoTrack())}async getAudioTracks(){return(await this.getTracks()).filter(e=>e.isAudioTrack())}async getPrimaryVideoTrack(){return(await this.getTracks()).find(e=>e.isVideoTrack())??null}async getPrimaryAudioTrack(){return(await this.getTracks()).find(e=>e.isAudioTrack())??null}async getMimeType(){return(await this._getDemuxer()).getMimeType()}async getMetadataTags(){return(await this._getDemuxer()).getMetadataTags()}dispose(){this._disposed||(this._disposed=!0,this._source._disposed=!0,this._source._dispose())}[Symbol.dispose](){this.dispose()}},Tl=class extends Error{constructor(e=`Input has been disposed.`){super(e),this.name=`InputDisposedError`}},El=class{constructor(e){this.source=e}requestSlice(e,t){if(this.source._disposed)throw new Tl;if(e<0||this.fileSize!==null&&e+t>this.fileSize)return null;let n=e+t,r=this.source._read(e,n);return r instanceof Promise?r.then(t=>t?new Dl(t.bytes,t.view,t.offset,e,n):null):r?new Dl(r.bytes,r.view,r.offset,e,n):null}requestSliceRange(e,t,n){if(this.source._disposed)throw new Tl;if(e<0)return null;if(this.fileSize!==null)return this.requestSlice(e,ui(this.fileSize-e,t,n));{let r=this.requestSlice(e,n),i=r=>{if(r)return r;let i=r=>(I(r!==null),this.requestSlice(e,ui(r-e,t,n))),a=this.source._retrieveSize();return a instanceof Promise?a.then(i):i(a)};return r instanceof Promise?r.then(i):i(r)}}},Dl=class e{constructor(e,t,n,r,i){this.bytes=e,this.view=t,this.offset=n,this.start=r,this.end=i,this.bufferPos=r-n}static tempFromBytes(t){return new e(t,z(t),0,0,t.length)}get length(){return this.end-this.start}get filePos(){return this.offset+this.bufferPos}set filePos(e){this.bufferPos=e-this.offset}get remainingLength(){return Math.max(this.end-this.filePos,0)}skip(e){this.bufferPos+=e}slice(t,n=this.end-t){if(t<this.start||t+n>this.end)throw RangeError(`Slicing outside of original slice.`);return new e(this.bytes,this.view,this.offset,t,t+n)}},Ol=(e,t)=>{if(e.filePos<e.start||e.filePos+t>e.end)throw RangeError(`Tried reading [${e.filePos}, ${e.filePos+t}), but slice is [${e.start}, ${e.end}). This is likely an internal error, please report it alongside the file that caused it.`)},G=(e,t)=>{Ol(e,t);let n=e.bytes.subarray(e.bufferPos,e.bufferPos+t);return e.bufferPos+=t,n},K=e=>(Ol(e,1),e.view.getUint8(e.bufferPos++)),kl=(e,t)=>{Ol(e,2);let n=e.view.getUint16(e.bufferPos,t);return e.bufferPos+=2,n},Al=e=>{Ol(e,2);let t=e.view.getUint16(e.bufferPos,!1);return e.bufferPos+=2,t},jl=e=>{Ol(e,3);let t=ai(e.view,e.bufferPos,!1);return e.bufferPos+=3,t},Ml=e=>{Ol(e,2);let t=e.view.getInt16(e.bufferPos,!1);return e.bufferPos+=2,t},Nl=(e,t)=>{Ol(e,4);let n=e.view.getUint32(e.bufferPos,t);return e.bufferPos+=4,n},q=e=>{Ol(e,4);let t=e.view.getUint32(e.bufferPos,!1);return e.bufferPos+=4,t},Pl=e=>{Ol(e,4);let t=e.view.getUint32(e.bufferPos,!0);return e.bufferPos+=4,t},Fl=e=>{Ol(e,4);let t=e.view.getInt32(e.bufferPos,!1);return e.bufferPos+=4,t},Il=e=>{Ol(e,4);let t=e.view.getInt32(e.bufferPos,!0);return e.bufferPos+=4,t},Ll=(e,t)=>{let n,r;return t?(n=Nl(e,!0),r=Nl(e,!0)):(r=Nl(e,!1),n=Nl(e,!1)),r*4294967296+n},Rl=e=>{let t=q(e),n=q(e);return t*4294967296+n},zl=e=>{let t=Fl(e),n=q(e);return t*4294967296+n},Bl=e=>{let t=Pl(e);return Il(e)*4294967296+t},Vl=e=>{Ol(e,4);let t=e.view.getFloat32(e.bufferPos,!1);return e.bufferPos+=4,t},Hl=e=>{Ol(e,8);let t=e.view.getFloat64(e.bufferPos,!1);return e.bufferPos+=8,t},Ul=(e,t)=>{Ol(e,t);let n=``;for(let r=0;r<t;r++)n+=String.fromCharCode(e.bytes[e.bufferPos++]);return n},Wl;(function(e){e[e.Unsynchronisation=128]=`Unsynchronisation`,e[e.ExtendedHeader=64]=`ExtendedHeader`,e[e.ExperimentalIndicator=32]=`ExperimentalIndicator`,e[e.Footer=16]=`Footer`})(Wl||={});var Gl;(function(e){e[e.ISO_8859_1=0]=`ISO_8859_1`,e[e.UTF_16_WITH_BOM=1]=`UTF_16_WITH_BOM`,e[e.UTF_16_BE_NO_BOM=2]=`UTF_16_BE_NO_BOM`,e[e.UTF_8=3]=`UTF_8`})(Gl||={});var Kl=`Blues.Classic rock.Country.Dance.Disco.Funk.Grunge.Hip-hop.Jazz.Metal.New age.Oldies.Other.Pop.Rhythm and blues.Rap.Reggae.Rock.Techno.Industrial.Alternative.Ska.Death metal.Pranks.Soundtrack.Euro-techno.Ambient.Trip-hop.Vocal.Jazz & funk.Fusion.Trance.Classical.Instrumental.Acid.House.Game.Sound clip.Gospel.Noise.Alternative rock.Bass.Soul.Punk.Space.Meditative.Instrumental pop.Instrumental rock.Ethnic.Gothic.Darkwave.Techno-industrial.Electronic.Pop-folk.Eurodance.Dream.Southern rock.Comedy.Cult.Gangsta.Top 40.Christian rap.Pop/funk.Jungle music.Native US.Cabaret.New wave.Psychedelic.Rave.Showtunes.Trailer.Lo-fi.Tribal.Acid punk.Acid jazz.Polka.Retro.Musical.Rock 'n' roll.Hard rock.Folk.Folk rock.National folk.Swing.Fast fusion.Bebop.Latin.Revival.Celtic.Bluegrass.Avantgarde.Gothic rock.Progressive rock.Psychedelic rock.Symphonic rock.Slow rock.Big band.Chorus.Easy listening.Acoustic.Humour.Speech.Chanson.Opera.Chamber music.Sonata.Symphony.Booty bass.Primus.Porn groove.Satire.Slow jam.Club.Tango.Samba.Folklore.Ballad.Power ballad.Rhythmic Soul.Freestyle.Duet.Punk rock.Drum solo.A cappella.Euro-house.Dance hall.Goa music.Drum & bass.Club-house.Hardcore techno.Terror.Indie.Britpop.Negerpunk.Polsk punk.Beat.Christian gangsta rap.Heavy metal.Black metal.Crossover.Contemporary Christian.Christian rock.Merengue.Salsa.Thrash metal.Anime.Jpop.Synthpop.Christmas.Art rock.Baroque.Bhangra.Big beat.Breakbeat.Chillout.Downtempo.Dub.EBM.Eclectic.Electro.Electroclash.Emo.Experimental.Garage.Global.IDM.Illbient.Industro-Goth.Jam Band.Krautrock.Leftfield.Lounge.Math rock.New romantic.Nu-breakz.Post-punk.Post-rock.Psytrance.Shoegaze.Space rock.Trop rock.World music.Neoclassical.Audiobook.Audio theatre.Neue Deutsche Welle.Podcast.Indie rock.G-Funk.Dubstep.Garage rock.Psybient`.split(`.`),ql=(e,t)=>{let n=e.filePos;t.raw??={},t.raw.TAG??=G(e,125),e.filePos=n;let r=Jl(e,30);r&&(t.title??=r);let i=Jl(e,30);i&&(t.artist??=i);let a=Jl(e,30);a&&(t.album??=a);let o=Jl(e,4),s=Number.parseInt(o,10);Number.isInteger(s)&&s>0&&(t.date??=new Date(s,0,1));let c=G(e,30),l;if(c[28]===0&&c[29]!==0){let n=c[29];n>0&&(t.trackNumber??=n),e.skip(-30),l=Jl(e,28),e.skip(2)}else e.skip(-30),l=Jl(e,30);l&&(t.comment??=l);let u=K(e);u<Kl.length&&(t.genre??=Kl[u])},Jl=(e,t)=>{let n=G(e,t),r=Oi(n.indexOf(0),n.length),i=n.subarray(0,r),a=``;for(let e=0;e<i.length;e++)a+=String.fromCharCode(i[e]);return a.trimEnd()},Yl=e=>{let t=e.filePos,n=Ul(e,3),r=K(e),i=K(e),a=K(e),o=q(e);return n!==`ID3`||r===255||i===255||o&2155905152?(e.filePos=t,null):{majorVersion:r,revision:i,flags:a,size:Da(o)}},Xl=(e,t,n)=>{if(![2,3,4].includes(t.majorVersion)){console.warn(`Unsupported ID3v2 major version: ${t.majorVersion}`);return}let r=new Zl(t,G(e,t.size));if(t.flags&Wl.Footer&&r.removeFooter(),t.flags&Wl.Unsynchronisation&&t.majorVersion===3&&r.ununsynchronizeAll(),t.flags&Wl.ExtendedHeader){let e=r.readU32();t.majorVersion===3?r.pos+=e:r.pos+=e-4}for(;r.pos<=r.bytes.length-r.frameHeaderSize();){let e=r.readId3V2Frame();if(!e)break;let i=r.pos,a=r.pos+e.size,o=!1,s=!1,c=!1;if(t.majorVersion===3?(o=!!(e.flags&64),s=!!(e.flags&128)):t.majorVersion===4&&(o=!!(e.flags&4),s=!!(e.flags&8),c=!!(e.flags&2)||!!(t.flags&Wl.Unsynchronisation)),o){console.warn(`Skipping encrypted ID3v2 frame ${e.id}`),r.pos=a;continue}if(s){console.warn(`Skipping compressed ID3v2 frame ${e.id}`),r.pos=a;continue}switch(c&&r.ununsynchronizeRegion(r.pos,a),n.raw??={},e.id[0]===`T`?n.raw[e.id]??=r.readId3V2EncodingAndText(a):n.raw[e.id]??=r.readBytes(e.size),r.pos=i,e.id){case`TIT2`:case`TT2`:n.title??=r.readId3V2EncodingAndText(a);break;case`TIT3`:case`TT3`:n.description??=r.readId3V2EncodingAndText(a);break;case`TPE1`:case`TP1`:n.artist??=r.readId3V2EncodingAndText(a);break;case`TALB`:case`TAL`:n.album??=r.readId3V2EncodingAndText(a);break;case`TPE2`:case`TP2`:n.albumArtist??=r.readId3V2EncodingAndText(a);break;case`TRCK`:case`TRK`:{let e=r.readId3V2EncodingAndText(a).split(`/`),t=Number.parseInt(e[0],10),i=e[1]&&Number.parseInt(e[1],10);Number.isInteger(t)&&t>0&&(n.trackNumber??=t),i&&Number.isInteger(i)&&i>0&&(n.tracksTotal??=i)}break;case`TPOS`:case`TPA`:{let e=r.readId3V2EncodingAndText(a).split(`/`),t=Number.parseInt(e[0],10),i=e[1]&&Number.parseInt(e[1],10);Number.isInteger(t)&&t>0&&(n.discNumber??=t),i&&Number.isInteger(i)&&i>0&&(n.discsTotal??=i)}break;case`TCON`:case`TCO`:{let e=r.readId3V2EncodingAndText(a),t=/^\((\d+)\)/.exec(e);if(t){let e=Number.parseInt(t[1]);if(Kl[e]!==void 0){n.genre??=Kl[e];break}}if(t=/^\d+$/.exec(e),t){let e=Number.parseInt(t[0]);if(Kl[e]!==void 0){n.genre??=Kl[e];break}}n.genre??=e}break;case`TDRC`:case`TDAT`:{let e=r.readId3V2EncodingAndText(a),t=new Date(e);Number.isNaN(t.getTime())||(n.date??=t)}break;case`TYER`:case`TYE`:{let e=r.readId3V2EncodingAndText(a),t=Number.parseInt(e,10);Number.isInteger(t)&&(n.date??=new Date(t,0,1))}break;case`USLT`:case`ULT`:{let e=r.readU8();r.pos+=3,r.readId3V2Text(e,a),n.lyrics??=r.readId3V2Text(e,a)}break;case`COMM`:case`COM`:{let e=r.readU8();r.pos+=3,r.readId3V2Text(e,a),n.comment??=r.readId3V2Text(e,a)}break;case`APIC`:case`PIC`:{let e=r.readId3V2TextEncoding(),i;if(t.majorVersion===2){let e=r.readAscii(3);i=e===`PNG`?`image/png`:e===`JPG`?`image/jpeg`:`image/*`}else i=r.readId3V2Text(e,a);let o=r.readU8(),s=r.readId3V2Text(e,a).trimEnd(),c=a-r.pos;if(c>=0){let e=r.readBytes(c);n.images||=[],n.images.push({data:e,mimeType:i,kind:o===3?`coverFront`:o===4?`coverBack`:`unknown`,description:s})}}break;default:r.pos+=e.size;break}r.pos=a}},Zl=class{constructor(e,t){this.header=e,this.bytes=t,this.pos=0,this.view=new DataView(t.buffer,t.byteOffset,t.byteLength)}frameHeaderSize(){return this.header.majorVersion===2?6:10}ununsynchronizeAll(){let e=[];for(let t=0;t<this.bytes.length;t++){let n=this.bytes[t];e.push(n),n===255&&t!==this.bytes.length-1&&this.bytes[t]===0&&t++}this.bytes=new Uint8Array(e),this.view=new DataView(this.bytes.buffer)}ununsynchronizeRegion(e,t){let n=[];for(let r=e;r<t;r++){let e=this.bytes[r];n.push(e),e===255&&r!==t-1&&this.bytes[r+1]===0&&r++}let r=this.bytes.subarray(0,e),i=this.bytes.subarray(t);this.bytes=new Uint8Array(r.length+n.length+i.length),this.bytes.set(r,0),this.bytes.set(n,r.length),this.bytes.set(i,r.length+n.length),this.view=new DataView(this.bytes.buffer)}removeFooter(){this.bytes=this.bytes.subarray(0,this.bytes.length-10),this.view=new DataView(this.bytes.buffer)}readBytes(e){let t=this.bytes.subarray(this.pos,this.pos+e);return this.pos+=e,t}readU8(){let e=this.view.getUint8(this.pos);return this.pos+=1,e}readU16(){let e=this.view.getUint16(this.pos,!1);return this.pos+=2,e}readU24(){let e=this.view.getUint16(this.pos,!1),t=this.view.getUint8(this.pos+1);return this.pos+=3,e*256+t}readU32(){let e=this.view.getUint32(this.pos,!1);return this.pos+=4,e}readAscii(e){let t=``;for(let n=0;n<e;n++)t+=String.fromCharCode(this.view.getUint8(this.pos+n));return this.pos+=e,t}readId3V2Frame(){if(this.header.majorVersion===2){let e=this.readAscii(3);return e===`\0\0\0`?null:{id:e,size:this.readU24(),flags:0}}else{let e=this.readAscii(4);if(e===`\0\0\0\0`)return null;let t=this.readU32(),n=this.header.majorVersion===4?Da(t):t,r=this.readU16(),i=this.pos,a=e=>{let t=this.pos+e;if(t>this.bytes.length)return!1;if(t<=this.bytes.length-this.frameHeaderSize()){this.pos+=e;let t=this.readAscii(4);if(t!==`\0\0\0\0`&&!/[0-9A-Z]{4}/.test(t))return!1}return!0};if(!a(n)){let e=this.header.majorVersion===4?t:Da(t);a(e)&&(n=e)}return this.pos=i,{id:e,size:n,flags:r}}}readId3V2TextEncoding(){let e=this.readU8();if(e>3)throw Error(`Unsupported text encoding: ${e}`);return e}readId3V2Text(e,t){let n=this.pos,r=this.readBytes(t-this.pos);switch(e){case Gl.ISO_8859_1:{let e=``;for(let t=0;t<r.length;t++){let i=r[t];if(i===0){this.pos=n+t+1;break}e+=String.fromCharCode(i)}return e}case Gl.UTF_16_WITH_BOM:if(r[0]===255&&r[1]===254){let e=new TextDecoder(`utf-16le`),t=Oi(r.findIndex((e,t)=>e===0&&r[t+1]===0&&t%2==0),r.length);return this.pos=n+Math.min(t+2,r.length),e.decode(r.subarray(2,t))}else if(r[0]===254&&r[1]===255){let e=new TextDecoder(`utf-16be`),t=Oi(r.findIndex((e,t)=>e===0&&r[t+1]===0&&t%2==0),r.length);return this.pos=n+Math.min(t+2,r.length),e.decode(r.subarray(2,t))}else{let e=Oi(r.findIndex(e=>e===0),r.length);return this.pos=n+Math.min(e+1,r.length),Lr.decode(r.subarray(0,e))}case Gl.UTF_16_BE_NO_BOM:{let e=new TextDecoder(`utf-16be`),t=Oi(r.findIndex((e,t)=>e===0&&r[t+1]===0&&t%2==0),r.length);return this.pos=n+Math.min(t+2,r.length),e.decode(r.subarray(0,t))}case Gl.UTF_8:{let e=Oi(r.findIndex(e=>e===0),r.length);return this.pos=n+Math.min(e+1,r.length),Lr.decode(r.subarray(0,e))}}}readId3V2EncodingAndText(e){if(this.pos>=e)return``;let t=this.readId3V2TextEncoding();return this.readId3V2Text(t,e)}},Ql=class{constructor(e){this.mutex=new Jr,this.firstMediaStreamTimestamp=null,this.trackTimestampInfo=new WeakMap,this.output=e}onTrackClose(e){}validateAndNormalizeTimestamp(e,t,n){if(t+=e.source._timestampOffset,t<0)throw Error(`Timestamps must be non-negative (got ${t}s).`);let r=this.trackTimestampInfo.get(e);if(r){if(n&&(r.maxTimestampBeforeLastKeyPacket=r.maxTimestamp),r.maxTimestampBeforeLastKeyPacket!==null&&t<r.maxTimestampBeforeLastKeyPacket)throw Error(`Timestamps cannot be smaller than the largest timestamp of the previous GOP (a GOP begins with a key packet and ends right before the next key packet). Got ${t}s, but largest timestamp is ${r.maxTimestampBeforeLastKeyPacket}s.`);r.maxTimestamp=Math.max(r.maxTimestamp,t)}else{if(!n)throw Error(`First packet must be a key packet.`);r={maxTimestamp:t,maxTimestampBeforeLastKeyPacket:null},this.trackTimestampInfo.set(e,r)}return t}},$l=/<(?:(\d{2}):)?(\d{2}):(\d{2}).(\d{3})>/g,eu=e=>{let t=Math.floor(e/(3600*1e3)),n=Math.floor(e%(3600*1e3)/(60*1e3)),r=Math.floor(e%(60*1e3)/1e3),i=e%1e3;return t.toString().padStart(2,`0`)+`:`+n.toString().padStart(2,`0`)+`:`+r.toString().padStart(2,`0`)+`.`+i.toString().padStart(3,`0`)},tu=class{constructor(e){this.writer=e,this.helper=new Uint8Array(8),this.helperView=new DataView(this.helper.buffer),this.offsets=new WeakMap}writeU32(e){this.helperView.setUint32(0,e,!1),this.writer.write(this.helper.subarray(0,4))}writeU64(e){this.helperView.setUint32(0,Math.floor(e/2**32),!1),this.helperView.setUint32(4,e,!1),this.writer.write(this.helper.subarray(0,8))}writeAscii(e){for(let t=0;t<e.length;t++)this.helperView.setUint8(t%8,e.charCodeAt(t)),t%8==7&&this.writer.write(this.helper);e.length%8!=0&&this.writer.write(this.helper.subarray(0,e.length%8))}writeBox(e){if(this.offsets.set(e,this.writer.getPos()),e.contents&&!e.children)this.writeBoxHeader(e,e.size??e.contents.byteLength+8),this.writer.write(e.contents);else{let t=this.writer.getPos();if(this.writeBoxHeader(e,0),e.contents&&this.writer.write(e.contents),e.children)for(let t of e.children)t&&this.writeBox(t);let n=this.writer.getPos(),r=e.size??n-t;this.writer.seek(t),this.writeBoxHeader(e,r),this.writer.seek(n)}}writeBoxHeader(e,t){this.writeU32(e.largeSize?1:t),this.writeAscii(e.type),e.largeSize&&this.writeU64(t)}measureBoxHeader(e){return 8+(e.largeSize?8:0)}patchBox(e){let t=this.offsets.get(e);I(t!==void 0);let n=this.writer.getPos();this.writer.seek(t),this.writeBox(e),this.writer.seek(n)}measureBox(e){if(e.contents&&!e.children)return this.measureBoxHeader(e)+e.contents.byteLength;{let t=this.measureBoxHeader(e);if(e.contents&&(t+=e.contents.byteLength),e.children)for(let n of e.children)n&&(t+=this.measureBox(n));return t}}},J=new Uint8Array(8),nu=new DataView(J.buffer),Y=e=>[(e%256+256)%256],X=e=>(nu.setUint16(0,e,!1),[J[0],J[1]]),ru=e=>(nu.setInt16(0,e,!1),[J[0],J[1]]),iu=e=>(nu.setUint32(0,e,!1),[J[1],J[2],J[3]]),Z=e=>(nu.setUint32(0,e,!1),[J[0],J[1],J[2],J[3]]),au=e=>(nu.setInt32(0,e,!1),[J[0],J[1],J[2],J[3]]),ou=e=>(nu.setUint32(0,Math.floor(e/2**32),!1),nu.setUint32(4,e,!1),[J[0],J[1],J[2],J[3],J[4],J[5],J[6],J[7]]),su=e=>(nu.setInt16(0,2**8*e,!1),[J[0],J[1]]),cu=e=>(nu.setInt32(0,2**16*e,!1),[J[0],J[1],J[2],J[3]]),lu=e=>(nu.setInt32(0,2**30*e,!1),[J[0],J[1],J[2],J[3]]),uu=(e,t)=>{let n=[],r=e;do{let e=r&127;r>>=7,n.length>0&&(e|=128),n.push(e),t!==void 0&&t--}while(r>0||t);return n.reverse()},du=(e,t=!1)=>{let n=Array(e.length).fill(null).map((t,n)=>e.charCodeAt(n));return t&&n.push(0),n},fu=e=>{let t=null;for(let n of e)(!t||n.timestamp>t.timestamp)&&(t=n);return t},pu=e=>{let t=e*(Math.PI/180),n=Math.round(Math.cos(t)),r=Math.round(Math.sin(t));return[n,r,0,-r,n,0,0,0,1]},mu=pu(0),hu=e=>[cu(e[0]),cu(e[1]),lu(e[2]),cu(e[3]),cu(e[4]),lu(e[5]),cu(e[6]),cu(e[7]),lu(e[8])],Q=(e,t,n)=>({type:e,contents:t&&new Uint8Array(t.flat(10)),children:n}),$=(e,t,n,r,i)=>Q(e,[Y(t),iu(n),r??[]],i),gu=e=>e.isQuickTime?Q(`ftyp`,[du(`qt `),Z(512),du(`qt `)]):e.fragmented?Q(`ftyp`,[du(`iso5`),Z(512),du(`iso5`),du(`iso6`),du(`mp41`)]):Q(`ftyp`,[du(`isom`),Z(512),du(`isom`),e.holdsAvc?du(`avc1`):[],du(`mp41`)]),_u=e=>({type:`mdat`,largeSize:e}),vu=e=>({type:`free`,size:e}),yu=e=>Q(`moov`,void 0,[bu(e.creationTime,e.trackDatas),...e.trackDatas.map(t=>xu(t,e.creationTime)),e.isFragmented?sd(e.trackDatas):null,Sd(e)]),bu=(e,t)=>{let n=Jd(Math.max(0,...t.filter(e=>e.samples.length>0).map(e=>{let t=fu(e.samples);return t.timestamp+t.duration})),Gd),r=Math.max(0,...t.map(e=>e.track.id))+1,i=!Pr(e)||!Pr(n),a=i?ou:Z;return $(`mvhd`,+i,0,[a(e),a(e),Z(Gd),a(n),cu(1),su(1),Array(10).fill(0),hu(mu),Array(24).fill(0),Z(r)])},xu=(e,t)=>{let n=qd(e);return Q(`trak`,void 0,[Su(e,t),Cu(e,t),n.name===void 0?null:Q(`udta`,void 0,[Q(`name`,[...Rr.encode(n.name)])])])},Su=(e,t)=>{let n=fu(e.samples),r=Jd(n?n.timestamp+n.duration:0,Gd),i=!Pr(t)||!Pr(r),a=i?ou:Z,o;if(e.type===`video`){let t=e.track.metadata.rotation;o=pu(t??0)}else o=mu;let s=2;return e.track.metadata.disposition?.default!==!1&&(s|=1),$(`tkhd`,+i,s,[a(t),a(t),Z(e.track.id),Z(0),a(r),Array(8).fill(0),X(0),X(e.track.id),su(e.type===`audio`?1:0),X(0),hu(o),cu(e.type===`video`?e.info.width:0),cu(e.type===`video`?e.info.height:0)])},Cu=(e,t)=>Q(`mdia`,void 0,[wu(e,t),Du(!0,Tu[e.type],Eu[e.type]),Ou(e)]),wu=(e,t)=>{let n=fu(e.samples),r=Jd(n?n.timestamp+n.duration:0,e.timescale),i=!Pr(t)||!Pr(r),a=i?ou:Z;return $(`mdhd`,+i,0,[a(t),a(t),Z(e.timescale),a(r),X(Id(e.track.metadata.languageCode??`und`)),X(0)])},Tu={video:`vide`,audio:`soun`,subtitle:`text`},Eu={video:`MediabunnyVideoHandler`,audio:`MediabunnySoundHandler`,subtitle:`MediabunnyTextHandler`},Du=(e,t,n,r=`\0\0\0\0`)=>$(`hdlr`,0,0,[e?du(`mhlr`):Z(0),du(t),du(r),Z(0),Z(0),du(n,!0)]),Ou=e=>Q(`minf`,void 0,[ku[e.type](),Au(),Nu(e)]),ku={video:()=>$(`vmhd`,0,1,[X(0),X(0),X(0),X(0)]),audio:()=>$(`smhd`,0,0,[X(0),X(0)]),subtitle:()=>$(`nmhd`,0,0)},Au=()=>Q(`dinf`,void 0,[ju()]),ju=()=>$(`dref`,0,0,[Z(1)],[Mu()]),Mu=()=>$(`url `,0,1),Nu=e=>{let t=e.compositionTimeOffsetTable.length>1||e.compositionTimeOffsetTable.some(e=>e.sampleCompositionTimeOffset!==0);return Q(`stbl`,void 0,[Pu(e),ed(e),t?ad(e):null,t?od(e):null,nd(e),rd(e),id(e),td(e)])},Pu=e=>{let t;if(e.type===`video`)t=Fu(Ad(e.track.source._codec,e.info.decoderConfig.codec),e);else if(e.type===`audio`){let n=Md(e.track.source._codec,e.muxer.isQuickTime);I(n),t=Hu(n,e)}else e.type===`subtitle`&&(t=Qu(Pd[e.track.source._codec],e));return I(t),$(`stsd`,0,0,[Z(1)],[t])},Fu=(e,t)=>Q(e,[[,,,,,,].fill(0),X(1),X(0),X(0),Array(12).fill(0),X(t.info.width),X(t.info.height),Z(4718592),Z(4718592),Z(0),X(1),Array(32).fill(0),X(24),ru(65535)],[jd[t.track.source._codec](t),Iu(t),Kr(t.info.decoderConfig.colorSpace)?Lu(t):null]),Iu=e=>e.info.pixelAspectRatio.num===e.info.pixelAspectRatio.den?null:Q(`pasp`,[Z(e.info.pixelAspectRatio.num),Z(e.info.pixelAspectRatio.den)]),Lu=e=>Q(`colr`,[du(`nclx`),X(Br[e.info.decoderConfig.colorSpace.primaries]),X(Hr[e.info.decoderConfig.colorSpace.transfer]),X(Wr[e.info.decoderConfig.colorSpace.matrix]),Y((e.info.decoderConfig.colorSpace.fullRange?1:0)<<7)]),Ru=e=>e.info.decoderConfig&&Q(`avcC`,[...Ir(e.info.decoderConfig.description)]),zu=e=>e.info.decoderConfig&&Q(`hvcC`,[...Ir(e.info.decoderConfig.description)]),Bu=e=>{if(!e.info.decoderConfig)return null;let t=e.info.decoderConfig,n=t.codec.split(`.`),r=Number(n[1]),i=Number(n[2]),a=Number(n[3]),o=n[4]?Number(n[4]):1,s=n[8]?Number(n[8]):Number(t.colorSpace?.fullRange??0),c=(a<<4)+(o<<1)+s,l=n[5]?Number(n[5]):t.colorSpace?.primaries?Br[t.colorSpace.primaries]:2,u=n[6]?Number(n[6]):t.colorSpace?.transfer?Hr[t.colorSpace.transfer]:2,d=n[7]?Number(n[7]):t.colorSpace?.matrix?Wr[t.colorSpace.matrix]:2;return $(`vpcC`,1,0,[Y(r),Y(i),Y(c),Y(l),Y(u),Y(d),X(0)])},Vu=e=>Q(`av1C`,ra(e.info.decoderConfig.codec)),Hu=(e,t)=>{let n=0,r,i=16,a=Ki.includes(t.track.source._codec);if(a){let e=t.track.source._codec,{sampleSize:r}=la(e);i=8*r,i>16&&(n=1)}if(t.muxer.isQuickTime&&(n=1),n===0)r=[[,,,,,,].fill(0),X(1),X(n),X(0),Z(0),X(t.info.numberOfChannels),X(i),X(0),X(0),X(t.info.sampleRate<2**16?t.info.sampleRate:0),X(0)];else{let e=a?0:-2;r=[[,,,,,,].fill(0),X(1),X(n),X(0),Z(0),X(t.info.numberOfChannels),X(Math.min(i,16)),ru(e),X(0),X(t.info.sampleRate<2**16?t.info.sampleRate:0),X(0),a?[Z(1),Z(i/8),Z(t.info.numberOfChannels*i/8)]:[Z(0),Z(0),Z(0)],Z(2)]}return Q(e,r,[Nd(t.track.source._codec,t.muxer.isQuickTime)?.(t)??null])},Uu=e=>{let t;switch(e.track.source._codec){case`aac`:t=64;break;case`mp3`:t=107;break;case`vorbis`:t=221;break;default:throw Error(`Unhandled audio codec: ${e.track.source._codec}`)}let n=[...Y(t),...Y(21),...iu(0),...Z(0),...Z(0)];if(e.info.decoderConfig.description){let t=Ir(e.info.decoderConfig.description);n=[...n,...Y(5),...uu(t.byteLength),...t]}return n=[...X(1),...Y(0),...Y(4),...uu(n.length),...n,...Y(6),...Y(1),...Y(2)],n=[...Y(3),...uu(n.length),...n],$(`esds`,0,0,n)},Wu=e=>Q(`wave`,void 0,[Gu(e),Ku(e),Q(`\0\0\0\0`)]),Gu=e=>Q(`frma`,[du(Md(e.track.source._codec,e.muxer.isQuickTime))]),Ku=e=>{let{littleEndian:t}=la(e.track.source._codec);return Q(`enda`,[X(+t)])},qu=e=>{let t=e.info.numberOfChannels,n=3840,r=e.info.sampleRate,i=0,a=0,o=new Uint8Array,s=e.info.decoderConfig?.description;if(s){I(s.byteLength>=18);let e=co(Ir(s));t=e.outputChannelCount,n=e.preSkip,r=e.inputSampleRate,i=e.outputGain,a=e.channelMappingFamily,e.channelMappingTable&&(o=e.channelMappingTable)}return Q(`dOps`,[Y(0),Y(t),X(n),Z(r),ru(i),Y(a),...o])},Ju=e=>{let t=e.info.decoderConfig?.description;return I(t),$(`dfLa`,0,0,[...Ir(t).subarray(4)])},Yu=e=>{let{littleEndian:t,sampleSize:n}=la(e.track.source._codec);return $(`pcmC`,0,0,[Y(+t),Y(8*n)])},Xu=e=>{let t=_o(e.info.firstPacket.data);if(!t)throw Error(`Couldn't extract AC-3 frame info from the audio packet. Ensure the packets contain valid AC-3 sync frames (as specified in ETSI TS 102 366).`);let n=new Uint8Array(3),r=new V(n);return r.writeBits(2,t.fscod),r.writeBits(5,t.bsid),r.writeBits(3,t.bsmod),r.writeBits(3,t.acmod),r.writeBits(1,t.lfeon),r.writeBits(5,t.bitRateCode),r.writeBits(5,0),Q(`dac3`,[...n])},Zu=e=>{let t=xo(e.info.firstPacket.data);if(!t)throw Error(`Couldn't extract E-AC-3 frame info from the audio packet. Ensure the packets contain valid E-AC-3 sync frames (as specified in ETSI TS 102 366).`);let n=16;for(let e of t.substreams)n+=23,e.numDepSub>0?n+=9:n+=1;let r=Math.ceil(n/8),i=new Uint8Array(r),a=new V(i);a.writeBits(13,t.dataRate),a.writeBits(3,t.substreams.length-1);for(let e of t.substreams)a.writeBits(2,e.fscod),a.writeBits(5,e.bsid),a.writeBits(1,0),a.writeBits(1,0),a.writeBits(3,e.bsmod),a.writeBits(3,e.acmod),a.writeBits(1,e.lfeon),a.writeBits(3,0),a.writeBits(4,e.numDepSub),e.numDepSub>0?a.writeBits(9,e.chanLoc):a.writeBits(1,0);return Q(`dec3`,[...i])},Qu=(e,t)=>Q(e,[[,,,,,,].fill(0),X(1)],[Fd[t.track.source._codec](t)]),$u=e=>Q(`vttC`,[...Rr.encode(e.info.config.description)]),ed=e=>$(`stts`,0,0,[Z(e.timeToSampleTable.length),e.timeToSampleTable.map(e=>[Z(e.sampleCount),Z(e.sampleDelta)])]),td=e=>{if(e.samples.every(e=>e.type===`key`))return null;let t=[...e.samples.entries()].filter(([,e])=>e.type===`key`);return $(`stss`,0,0,[Z(t.length),t.map(([e])=>Z(e+1))])},nd=e=>$(`stsc`,0,0,[Z(e.compactlyCodedChunkTable.length),e.compactlyCodedChunkTable.map(e=>[Z(e.firstChunk),Z(e.samplesPerChunk),Z(1)])]),rd=e=>{if(e.type===`audio`&&e.info.requiresPcmTransformation){let{sampleSize:t}=la(e.track.source._codec);return $(`stsz`,0,0,[Z(t*e.info.numberOfChannels),Z(e.samples.reduce((t,n)=>t+Jd(n.duration,e.timescale),0))])}return $(`stsz`,0,0,[Z(0),Z(e.samples.length),e.samples.map(e=>Z(e.size))])},id=e=>e.finalizedChunks.length>0&&L(e.finalizedChunks).offset>=2**32?$(`co64`,0,0,[Z(e.finalizedChunks.length),e.finalizedChunks.map(e=>ou(e.offset))]):$(`stco`,0,0,[Z(e.finalizedChunks.length),e.finalizedChunks.map(e=>Z(e.offset))]),ad=e=>$(`ctts`,1,0,[Z(e.compositionTimeOffsetTable.length),e.compositionTimeOffsetTable.map(e=>[Z(e.sampleCount),au(e.sampleCompositionTimeOffset)])]),od=e=>{let t=1/0,n=-1/0,r=1/0,i=-1/0;I(e.compositionTimeOffsetTable.length>0),I(e.samples.length>0);for(let r=0;r<e.compositionTimeOffsetTable.length;r++){let i=e.compositionTimeOffsetTable[r];t=Math.min(t,i.sampleCompositionTimeOffset),n=Math.max(n,i.sampleCompositionTimeOffset)}for(let t=0;t<e.samples.length;t++){let n=e.samples[t];r=Math.min(r,Jd(n.timestamp,e.timescale)),i=Math.max(i,Jd(n.timestamp+n.duration,e.timescale))}let a=Math.max(-t,0);return i>=2**31?null:$(`cslg`,0,0,[au(a),au(t),au(n),au(r),au(i)])},sd=e=>Q(`mvex`,void 0,e.map(cd)),cd=e=>$(`trex`,0,0,[Z(e.track.id),Z(1),Z(0),Z(0),Z(0)]),ld=(e,t)=>Q(`moof`,void 0,[ud(e),...t.map(fd)]),ud=e=>$(`mfhd`,0,0,[Z(e)]),dd=e=>{let t=0,n=0,r=e.type===`delta`;return n|=+r,r?t|=1:t|=2,t<<24|n<<16|0},fd=e=>Q(`traf`,void 0,[pd(e),md(e),hd(e)]),pd=e=>{I(e.currentChunk);let t=0;t|=8,t|=16,t|=32,t|=131072;let n=e.currentChunk.samples[1]??e.currentChunk.samples[0],r={duration:n.timescaleUnitsToNextSample,size:n.size,flags:dd(n)};return $(`tfhd`,0,t,[Z(e.track.id),Z(r.duration),Z(r.size),Z(r.flags)])},md=e=>(I(e.currentChunk),$(`tfdt`,1,0,[ou(Jd(e.currentChunk.startTimestamp,e.timescale))])),hd=e=>{I(e.currentChunk);let t=e.currentChunk.samples.map(e=>e.timescaleUnitsToNextSample),n=e.currentChunk.samples.map(e=>e.size),r=e.currentChunk.samples.map(dd),i=e.currentChunk.samples.map(t=>Jd(t.timestamp-t.decodeTimestamp,e.timescale)),a=new Set(t),o=new Set(n),s=new Set(r),c=new Set(i),l=s.size===2&&r[0]!==r[1],u=a.size>1,d=o.size>1,f=!l&&s.size>1,p=c.size>1||[...c].some(e=>e!==0),m=0;return m|=1,m|=4*l,m|=256*u,m|=512*d,m|=1024*f,m|=2048*p,$(`trun`,1,m,[Z(e.currentChunk.samples.length),Z(e.currentChunk.offset-e.currentChunk.moofOffset||0),l?Z(r[0]):[],e.currentChunk.samples.map((e,a)=>[u?Z(t[a]):[],d?Z(n[a]):[],f?Z(r[a]):[],p?au(i[a]):[]])])},gd=e=>Q(`mfra`,void 0,[...e.map(_d),vd()]),_d=(e,t)=>$(`tfra`,1,0,[Z(e.track.id),Z(63),Z(e.finalizedChunks.length),e.finalizedChunks.map(n=>[ou(Jd(n.samples[0].timestamp,e.timescale)),ou(n.moofOffset),Z(t+1),Z(1),Z(1)])]),vd=()=>$(`mfro`,0,0,[Z(0)]),yd=()=>Q(`vtte`),bd=(e,t,n,r,i)=>Q(`vttc`,void 0,[i===null?null:Q(`vsid`,[au(i)]),n===null?null:Q(`iden`,[...Rr.encode(n)]),t===null?null:Q(`ctim`,[...Rr.encode(eu(t))]),r===null?null:Q(`sttg`,[...Rr.encode(r)]),Q(`payl`,[...Rr.encode(e)])]),xd=e=>Q(`vtta`,[...Rr.encode(e)]),Sd=e=>{let t=[],n=e.format._options.metadataFormat??`auto`,r=e.output._metadataTags;if(n===`mdir`||n===`auto`&&!e.isQuickTime){let e=Dd(r);e&&t.push(e)}else if(n===`mdta`){let e=Od(r);e&&t.push(e)}else (n===`udta`||n===`auto`&&e.isQuickTime)&&Cd(t,e.output._metadataTags);return t.length===0?null:Q(`udta`,void 0,t)},Cd=(e,t)=>{for(let{key:n,value:r}of Ai(t))switch(n){case`title`:e.push(wd(`©nam`,r));break;case`description`:e.push(wd(`©des`,r));break;case`artist`:e.push(wd(`©ART`,r));break;case`album`:e.push(wd(`©alb`,r));break;case`albumArtist`:e.push(wd(`albr`,r));break;case`genre`:e.push(wd(`©gen`,r));break;case`date`:e.push(wd(`©day`,r.toISOString().slice(0,10)));break;case`comment`:e.push(wd(`©cmt`,r));break;case`lyrics`:e.push(wd(`©lyr`,r));break;case`raw`:break;case`discNumber`:case`discsTotal`:case`trackNumber`:case`tracksTotal`:case`images`:break;default:ii(n)}if(t.raw)for(let n in t.raw){let r=t.raw[n];r==null||n.length!==4||e.some(e=>e.type===n)||(typeof r==`string`?e.push(wd(n,r)):r instanceof Uint8Array&&e.push(Q(n,Array.from(r))))}},wd=(e,t)=>{let n=Rr.encode(t);return Q(e,[X(n.length),X(Id(`und`)),Array.from(n)])},Td={"image/jpeg":13,"image/png":14,"image/bmp":27},Ed=(e,t)=>{let n=[];for(let{key:r,value:i}of Ai(e))switch(r){case`title`:n.push({key:t?`title`:`©nam`,value:kd(i)});break;case`description`:n.push({key:t?`description`:`©des`,value:kd(i)});break;case`artist`:n.push({key:t?`artist`:`©ART`,value:kd(i)});break;case`album`:n.push({key:t?`album`:`©alb`,value:kd(i)});break;case`albumArtist`:n.push({key:t?`album_artist`:`aART`,value:kd(i)});break;case`comment`:n.push({key:t?`comment`:`©cmt`,value:kd(i)});break;case`genre`:n.push({key:t?`genre`:`©gen`,value:kd(i)});break;case`lyrics`:n.push({key:t?`lyrics`:`©lyr`,value:kd(i)});break;case`date`:n.push({key:t?`date`:`©day`,value:kd(i.toISOString().slice(0,10))});break;case`images`:for(let e of i)e.kind===`coverFront`&&n.push({key:`covr`,value:Q(`data`,[Z(Td[e.mimeType]??0),Z(0),Array.from(e.data)])});break;case`trackNumber`:if(t){let t=e.tracksTotal===void 0?i.toString():`${i}/${e.tracksTotal}`;n.push({key:`track`,value:kd(t)})}else n.push({key:`trkn`,value:Q(`data`,[Z(0),Z(0),X(0),X(i),X(e.tracksTotal??0),X(0)])});break;case`discNumber`:t||n.push({key:`disc`,value:Q(`data`,[Z(0),Z(0),X(0),X(i),X(e.discsTotal??0),X(0)])});break;case`tracksTotal`:case`discsTotal`:break;case`raw`:break;default:ii(r)}if(e.raw)for(let r in e.raw){let i=e.raw[r];i==null||!t&&r.length!==4||n.some(e=>e.key===r)||(typeof i==`string`?n.push({key:r,value:kd(i)}):i instanceof Uint8Array?n.push({key:r,value:Q(`data`,[Z(0),Z(0),Array.from(i)])}):i instanceof Ii&&n.push({key:r,value:Q(`data`,[Z(Td[i.mimeType]??0),Z(0),Array.from(i.data)])}))}return n},Dd=e=>{let t=Ed(e,!1);return t.length===0?null:$(`meta`,0,0,void 0,[Du(!1,`mdir`,``,`appl`),Q(`ilst`,void 0,t.map(e=>Q(e.key,void 0,[e.value])))])},Od=e=>{let t=Ed(e,!0);return t.length===0?null:Q(`meta`,void 0,[Du(!1,`mdta`,``),$(`keys`,0,0,[Z(t.length)],t.map(e=>Q(`mdta`,[...Rr.encode(e.key)]))),Q(`ilst`,void 0,t.map((e,t)=>Q(String.fromCharCode(...Z(t+1)),void 0,[e.value])))])},kd=e=>Q(`data`,[Z(1),Z(0),...Rr.encode(e)]),Ad=(e,t)=>{switch(e){case`avc`:return t.startsWith(`avc3`)?`avc3`:`avc1`;case`hevc`:return`hvc1`;case`vp8`:return`vp08`;case`vp9`:return`vp09`;case`av1`:return`av01`}},jd={avc:Ru,hevc:zu,vp8:Bu,vp9:Bu,av1:Vu},Md=(e,t)=>{switch(e){case`aac`:return`mp4a`;case`mp3`:return`mp4a`;case`opus`:return`Opus`;case`vorbis`:return`mp4a`;case`flac`:return`fLaC`;case`ulaw`:return`ulaw`;case`alaw`:return`alaw`;case`pcm-u8`:return`raw `;case`pcm-s8`:return`sowt`;case`ac3`:return`ac-3`;case`eac3`:return`ec-3`}if(t)switch(e){case`pcm-s16`:return`sowt`;case`pcm-s16be`:return`twos`;case`pcm-s24`:return`in24`;case`pcm-s24be`:return`in24`;case`pcm-s32`:return`in32`;case`pcm-s32be`:return`in32`;case`pcm-f32`:return`fl32`;case`pcm-f32be`:return`fl32`;case`pcm-f64`:return`fl64`;case`pcm-f64be`:return`fl64`}else switch(e){case`pcm-s16`:return`ipcm`;case`pcm-s16be`:return`ipcm`;case`pcm-s24`:return`ipcm`;case`pcm-s24be`:return`ipcm`;case`pcm-s32`:return`ipcm`;case`pcm-s32be`:return`ipcm`;case`pcm-f32`:return`fpcm`;case`pcm-f32be`:return`fpcm`;case`pcm-f64`:return`fpcm`;case`pcm-f64be`:return`fpcm`}},Nd=(e,t)=>{switch(e){case`aac`:return Uu;case`mp3`:return Uu;case`opus`:return qu;case`vorbis`:return Uu;case`flac`:return Ju;case`ac3`:return Xu;case`eac3`:return Zu}if(t)switch(e){case`pcm-s24`:return Wu;case`pcm-s24be`:return Wu;case`pcm-s32`:return Wu;case`pcm-s32be`:return Wu;case`pcm-f32`:return Wu;case`pcm-f32be`:return Wu;case`pcm-f64`:return Wu;case`pcm-f64be`:return Wu}else switch(e){case`pcm-s16`:return Yu;case`pcm-s16be`:return Yu;case`pcm-s24`:return Yu;case`pcm-s24be`:return Yu;case`pcm-s32`:return Yu;case`pcm-s32be`:return Yu;case`pcm-f32`:return Yu;case`pcm-f32be`:return Yu;case`pcm-f64`:return Yu;case`pcm-f64be`:return Yu}return null},Pd={webvtt:`wvtt`},Fd={webvtt:$u},Id=e=>{I(e.length===3);let t=0;for(let n=0;n<3;n++)t<<=5,t+=e.charCodeAt(n)-96;return t},Ld=class{constructor(){this.ensureMonotonicity=!1,this.trackedWrites=null,this.trackedStart=-1,this.trackedEnd=-1}start(){}maybeTrackWrites(e){if(!this.trackedWrites)return;let t=this.getPos();if(t<this.trackedStart){if(t+e.byteLength<=this.trackedStart)return;e=e.subarray(this.trackedStart-t),t=0}let n=t+e.byteLength-this.trackedStart,r=this.trackedWrites.byteLength;for(;r<n;)r*=2;if(r!==this.trackedWrites.byteLength){let e=new Uint8Array(r);e.set(this.trackedWrites,0),this.trackedWrites=e}this.trackedWrites.set(e,t-this.trackedStart),this.trackedEnd=Math.max(this.trackedEnd,t+e.byteLength)}startTrackingWrites(){this.trackedWrites=new Uint8Array(2**10),this.trackedStart=this.getPos(),this.trackedEnd=this.trackedStart}stopTrackingWrites(){if(!this.trackedWrites)throw Error(`Internal error: Can't get tracked writes since nothing was tracked.`);let e={data:this.trackedWrites.subarray(0,this.trackedEnd-this.trackedStart),start:this.trackedStart,end:this.trackedEnd};return this.trackedWrites=null,e}},Rd=2**16,zd=2**32,Bd=class extends Ld{constructor(e){if(super(),this.pos=0,this.maxPos=0,this.target=e,this.supportsResize=`resize`in new ArrayBuffer(0),this.supportsResize)try{this.buffer=new ArrayBuffer(Rd,{maxByteLength:zd})}catch{this.buffer=new ArrayBuffer(Rd),this.supportsResize=!1}else this.buffer=new ArrayBuffer(Rd);this.bytes=new Uint8Array(this.buffer)}ensureSize(e){let t=this.buffer.byteLength;for(;t<e;)t*=2;if(t!==this.buffer.byteLength){if(t>zd)throw Error(`ArrayBuffer exceeded maximum size of ${zd} bytes. Please consider using another target.`);if(this.supportsResize)this.buffer.resize(t);else{let e=new ArrayBuffer(t),n=new Uint8Array(e);n.set(this.bytes,0),this.buffer=e,this.bytes=n}}}write(e){this.maybeTrackWrites(e),this.ensureSize(this.pos+e.byteLength),this.bytes.set(e,this.pos),this.target.onwrite?.(this.pos,this.pos+e.byteLength),this.pos+=e.byteLength,this.maxPos=Math.max(this.maxPos,this.pos)}seek(e){this.pos=e}getPos(){return this.pos}async flush(){}async finalize(){this.ensureSize(this.pos),this.target.buffer=this.buffer.slice(0,Math.max(this.maxPos,this.pos))}async close(){}getSlice(e,t){return this.bytes.slice(e,t)}},Vd=class extends Ld{constructor(e){super(),this.target=e,this.pos=0}write(e){this.maybeTrackWrites(e),this.target.onwrite?.(this.pos,this.pos+e.byteLength),this.pos+=e.byteLength}getPos(){return this.pos}seek(e){this.pos=e}async flush(){}async finalize(){}async close(){}},Hd=class{constructor(){this._output=null,this.onwrite=null}},Ud=class extends Hd{constructor(){super(...arguments),this.buffer=null}_createWriter(){return new Bd(this)}},Wd=class extends Hd{_createWriter(){return new Vd(this)}},Gd=1e3,Kd=2082844800,qd=e=>{let t={},n=e.track;return n.metadata.name!==void 0&&(t.name=n.metadata.name),t},Jd=(e,t,n=!0)=>{let r=e*t;return n?Math.round(r):r},Yd=class extends Ql{constructor(e,t){super(e),this.auxTarget=new Ud,this.auxWriter=this.auxTarget._createWriter(),this.auxBoxWriter=new tu(this.auxWriter),this.mdat=null,this.ftypSize=null,this.trackDatas=[],this.allTracksKnown=$r(),this.creationTime=Math.floor(Date.now()/1e3)+Kd,this.finalizedChunks=[],this.nextFragmentNumber=1,this.maxWrittenTimestamp=-1/0,this.format=t,this.writer=e._writer,this.boxWriter=new tu(this.writer),this.isQuickTime=t instanceof $d;let n=this.writer instanceof Bd?`in-memory`:!1;this.fastStart=t._options.fastStart??n,this.isFragmented=this.fastStart===`fragmented`,(this.fastStart===`in-memory`||this.isFragmented)&&(this.writer.ensureMonotonicity=!0),this.minimumFragmentDuration=t._options.minimumFragmentDuration??1}async start(){let e=await this.mutex.acquire(),t=this.output._tracks.some(e=>e.type===`video`&&e.source._codec===`avc`);if(this.format._options.onFtyp&&this.writer.startTrackingWrites(),this.boxWriter.writeBox(gu({isQuickTime:this.isQuickTime,holdsAvc:t,fragmented:this.isFragmented})),this.format._options.onFtyp){let{data:e,start:t}=this.writer.stopTrackingWrites();this.format._options.onFtyp(e,t)}if(this.ftypSize=this.writer.getPos(),this.fastStart!==`in-memory`)if(this.fastStart===`reserve`){for(let e of this.output._tracks)if(e.metadata.maximumPacketCount===void 0)throw Error(`All tracks must specify maximumPacketCount in their metadata when using fastStart: 'reserve'.`)}else this.isFragmented||(this.format._options.onMdat&&this.writer.startTrackingWrites(),this.mdat=_u(!0),this.boxWriter.writeBox(this.mdat));await this.writer.flush(),e()}allTracksAreKnown(){for(let e of this.output._tracks)if(!e.source._closed&&!this.trackDatas.some(t=>t.track===e))return!1;return!0}async getMimeType(){await this.allTracksKnown.promise;let e=this.trackDatas.map(e=>e.type===`video`||e.type===`audio`?e.info.decoderConfig.codec:{webvtt:`wvtt`}[e.track.source._codec]);return ys({isQuickTime:this.isQuickTime,hasVideo:this.trackDatas.some(e=>e.type===`video`),hasAudio:this.trackDatas.some(e=>e.type===`audio`),codecStrings:e})}getVideoTrackData(e,t,n){let r=this.trackDatas.find(t=>t.track===e);if(r)return r;va(n),I(n),I(n.decoderConfig);let i={...n.decoderConfig};I(i.codedWidth!==void 0),I(i.codedHeight!==void 0);let a=!1;if(e.source._codec===`avc`&&!i.description){let e=Va(t.data);if(!e)throw Error(`Couldn't extract an AVCDecoderConfigurationRecord from the AVC packet. Make sure the packets are in Annex B format (as specified in ITU-T-REC-H.264) when not providing a description, or provide a description (must be an AVCDecoderConfigurationRecord as specified in ISO 14496-15) and ensure the packets are in AVCC format.`);i.description=Ha(e),a=!0}else if(e.source._codec===`hevc`&&!i.description){let e=Xa(t.data);if(!e)throw Error(`Couldn't extract an HEVCDecoderConfigurationRecord from the HEVC packet. Make sure the packets are in Annex B format (as specified in ITU-T-REC-H.265) when not providing a description, or provide a description (must be an HEVCDecoderConfigurationRecord as specified in ISO 14496-15) and ensure the packets are in HEVC format.`);i.description=io(e),a=!0}let o=vi(1/(e.metadata.frameRate??57600),1e6).denominator,s=i.displayAspectWidth,c=i.displayAspectHeight,l=s===void 0||c===void 0?{num:1,den:1}:Pi({num:s*i.codedHeight,den:c*i.codedWidth}),u={muxer:this,track:e,type:`video`,info:{width:i.codedWidth,height:i.codedHeight,pixelAspectRatio:l,decoderConfig:i,requiresAnnexBTransformation:a},timescale:o,samples:[],sampleQueue:[],timestampProcessingQueue:[],timeToSampleTable:[],compositionTimeOffsetTable:[],lastTimescaleUnits:null,lastSample:null,finalizedChunks:[],currentChunk:null,compactlyCodedChunkTable:[]};return this.trackDatas.push(u),this.trackDatas.sort((e,t)=>e.track.id-t.track.id),this.allTracksAreKnown()&&this.allTracksKnown.resolve(),u}getAudioTrackData(e,t,n){let r=this.trackDatas.find(t=>t.track===e);if(r)return r;ba(n),I(n),I(n.decoderConfig);let i={...n.decoderConfig},a=!1;if(e.source._codec===`aac`&&!i.description){let e=Oc(Dl.tempFromBytes(t.data));if(!e)throw Error(`Couldn't parse ADTS header from the AAC packet. Make sure the packets are in ADTS format (as specified in ISO 13818-7) when not providing a description, or provide a description (must be an AudioSpecificConfig as specified in ISO 14496-3) and ensure the packets are raw AAC data.`);let n=Vi[e.samplingFrequencyIndex],r=Hi[e.channelConfiguration];if(n===void 0||r===void 0)throw Error(`Invalid ADTS frame header.`);i.description=Wi({objectType:e.objectType,sampleRate:n,numberOfChannels:r}),a=!0}let o={muxer:this,track:e,type:`audio`,info:{numberOfChannels:n.decoderConfig.numberOfChannels,sampleRate:n.decoderConfig.sampleRate,decoderConfig:i,requiresPcmTransformation:!this.isFragmented&&Ki.includes(e.source._codec),requiresAdtsStripping:a,firstPacket:t},timescale:i.sampleRate,samples:[],sampleQueue:[],timestampProcessingQueue:[],timeToSampleTable:[],compositionTimeOffsetTable:[],lastTimescaleUnits:null,lastSample:null,finalizedChunks:[],currentChunk:null,compactlyCodedChunkTable:[]};return this.trackDatas.push(o),this.trackDatas.sort((e,t)=>e.track.id-t.track.id),this.allTracksAreKnown()&&this.allTracksKnown.resolve(),o}getSubtitleTrackData(e,t){let n=this.trackDatas.find(t=>t.track===e);if(n)return n;xa(t),I(t),I(t.config);let r={muxer:this,track:e,type:`subtitle`,info:{config:t.config},timescale:1e3,samples:[],sampleQueue:[],timestampProcessingQueue:[],timeToSampleTable:[],compositionTimeOffsetTable:[],lastTimescaleUnits:null,lastSample:null,finalizedChunks:[],currentChunk:null,compactlyCodedChunkTable:[],lastCueEndTimestamp:0,cueQueue:[],nextSourceId:0,cueToSourceId:new WeakMap};return this.trackDatas.push(r),this.trackDatas.sort((e,t)=>e.track.id-t.track.id),this.allTracksAreKnown()&&this.allTracksKnown.resolve(),r}async addEncodedVideoPacket(e,t,n){let r=await this.mutex.acquire();try{let r=this.getVideoTrackData(e,t,n),i=t.data;if(r.info.requiresAnnexBTransformation){let e=[...Ma(i)].map(e=>i.subarray(e.offset,e.offset+e.length));if(e.length===0)throw Error(`Failed to transform packet data. Make sure all packets are provided in Annex B format, as specified in ITU-T-REC-H.264 and ITU-T-REC-H.265.`);i=za(e,4)}let a=this.validateAndNormalizeTimestamp(r.track,t.timestamp,t.type===`key`),o=this.createSampleForTrack(r,i,a,t.duration,t.type);await this.registerSample(r,o)}finally{r()}}async addEncodedAudioPacket(e,t,n){let r=await this.mutex.acquire();try{let r=this.getAudioTrackData(e,t,n),i=t.data;if(r.info.requiresAdtsStripping){let e=Oc(Dl.tempFromBytes(i));if(!e)throw Error(`Expected ADTS frame, didn't get one.`);let t=e.crcCheck===null?7:9;i=i.subarray(t)}let a=this.validateAndNormalizeTimestamp(r.track,t.timestamp,t.type===`key`),o=this.createSampleForTrack(r,i,a,t.duration,t.type);r.info.requiresPcmTransformation&&await this.maybePadWithSilence(r,a),await this.registerSample(r,o)}finally{r()}}async maybePadWithSilence(e,t){let n=L(e.samples),r=n?n.timestamp+n.duration:0,i=t-r,a=Jd(i,e.timescale);if(a>0){let{sampleSize:t,silentValue:n}=la(e.info.decoderConfig.codec),o=a*e.info.numberOfChannels,s=new Uint8Array(t*o).fill(n),c=this.createSampleForTrack(e,new Uint8Array(s.buffer),r,i,`key`);await this.registerSample(e,c)}}async addSubtitleCue(e,t,n){let r=await this.mutex.acquire();try{let r=this.getSubtitleTrackData(e,n);this.validateAndNormalizeTimestamp(r.track,t.timestamp,!0),e.source._codec===`webvtt`&&(r.cueQueue.push(t),await this.processWebVTTCues(r,t.timestamp))}finally{r()}}async processWebVTTCues(e,t){for(;e.cueQueue.length>0;){let n=new Set([]);for(let r of e.cueQueue)I(r.timestamp<=t),I(e.lastCueEndTimestamp<=r.timestamp+r.duration),n.add(Math.max(r.timestamp,e.lastCueEndTimestamp)),n.add(r.timestamp+r.duration);let r=[...n].sort((e,t)=>e-t),i=r[0],a=r[1]??i;if(t<a)break;if(e.lastCueEndTimestamp<i){this.auxWriter.seek(0);let t=yd();this.auxBoxWriter.writeBox(t);let n=this.auxWriter.getSlice(0,this.auxWriter.getPos()),r=this.createSampleForTrack(e,n,e.lastCueEndTimestamp,i-e.lastCueEndTimestamp,`key`);await this.registerSample(e,r),e.lastCueEndTimestamp=i}this.auxWriter.seek(0);for(let t=0;t<e.cueQueue.length;t++){let n=e.cueQueue[t];if(n.timestamp>=a)break;$l.lastIndex=0;let r=$l.test(n.text),o=n.timestamp+n.duration,s=e.cueToSourceId.get(n);if(s===void 0&&a<o&&(s=e.nextSourceId++,e.cueToSourceId.set(n,s)),n.notes){let e=xd(n.notes);this.auxBoxWriter.writeBox(e)}let c=bd(n.text,r?i:null,n.identifier??null,n.settings??null,s??null);this.auxBoxWriter.writeBox(c),o===a&&e.cueQueue.splice(t--,1)}let o=this.auxWriter.getSlice(0,this.auxWriter.getPos()),s=this.createSampleForTrack(e,o,i,a-i,`key`);await this.registerSample(e,s),e.lastCueEndTimestamp=a}}createSampleForTrack(e,t,n,r,i){return{timestamp:n,decodeTimestamp:n,duration:r,data:t,size:t.byteLength,type:i,timescaleUnitsToNextSample:Jd(r,e.timescale)}}processTimestamps(e,t){if(e.timestampProcessingQueue.length===0)return;if(e.type===`audio`&&e.info.requiresPcmTransformation){let t=0;for(let n=0;n<e.timestampProcessingQueue.length;n++){let r=e.timestampProcessingQueue[n],i=Jd(r.duration,e.timescale);t+=i}if(e.timeToSampleTable.length===0)e.timeToSampleTable.push({sampleCount:t,sampleDelta:1});else{let n=L(e.timeToSampleTable);n.sampleCount+=t}e.timestampProcessingQueue.length=0;return}let n=e.timestampProcessingQueue.map(e=>e.timestamp).sort((e,t)=>e-t);for(let t=0;t<e.timestampProcessingQueue.length;t++){let r=e.timestampProcessingQueue[t];r.decodeTimestamp=n[t],!this.isFragmented&&e.lastTimescaleUnits===null&&(r.decodeTimestamp=0);let i=Jd(r.timestamp-r.decodeTimestamp,e.timescale),a=Jd(r.duration,e.timescale);if(e.lastTimescaleUnits!==null){I(e.lastSample);let t=Jd(r.decodeTimestamp,e.timescale,!1),n=Math.round(t-e.lastTimescaleUnits);if(I(n>=0),e.lastTimescaleUnits+=n,e.lastSample.timescaleUnitsToNextSample=n,!this.isFragmented){let t=L(e.timeToSampleTable);if(I(t),t.sampleCount===1){t.sampleDelta=n;let r=e.timeToSampleTable[e.timeToSampleTable.length-2];r&&r.sampleDelta===n&&(r.sampleCount++,e.timeToSampleTable.pop(),t=r)}else t.sampleDelta!==n&&(t.sampleCount--,e.timeToSampleTable.push(t={sampleCount:1,sampleDelta:n}));t.sampleDelta===a?t.sampleCount++:e.timeToSampleTable.push({sampleCount:1,sampleDelta:a});let r=L(e.compositionTimeOffsetTable);I(r),r.sampleCompositionTimeOffset===i?r.sampleCount++:e.compositionTimeOffsetTable.push({sampleCount:1,sampleCompositionTimeOffset:i})}}else e.lastTimescaleUnits=Jd(r.decodeTimestamp,e.timescale,!1),this.isFragmented||(e.timeToSampleTable.push({sampleCount:1,sampleDelta:a}),e.compositionTimeOffsetTable.push({sampleCount:1,sampleCompositionTimeOffset:i}));e.lastSample=r}if(e.timestampProcessingQueue.length=0,I(e.lastSample),I(e.lastTimescaleUnits!==null),t!==void 0&&e.lastSample.timescaleUnitsToNextSample===0){I(t.type===`key`);let n=Jd(t.timestamp,e.timescale,!1),r=Math.round(n-e.lastTimescaleUnits);e.lastSample.timescaleUnitsToNextSample=r}}async registerSample(e,t){t.type===`key`&&this.processTimestamps(e,t),e.timestampProcessingQueue.push(t),this.isFragmented?(e.sampleQueue.push(t),await this.interleaveSamples()):this.fastStart===`reserve`?await this.registerSampleFastStartReserve(e,t):await this.addSampleToTrack(e,t)}async addSampleToTrack(e,t){if(!this.isFragmented&&(e.samples.push(t),this.fastStart===`reserve`)){let t=e.track.metadata.maximumPacketCount;if(I(t!==void 0),e.samples.length>t)throw Error(`Track #${e.track.id} has already reached the maximum packet count (${t}). Either add less packets or increase the maximum packet count.`)}let n=!1;if(!e.currentChunk)n=!0;else{e.currentChunk.startTimestamp=Math.min(e.currentChunk.startTimestamp,t.timestamp);let r=t.timestamp-e.currentChunk.startTimestamp;if(this.isFragmented){let i=this.trackDatas.every(n=>{if(e===n)return t.type===`key`;let r=n.sampleQueue[0];return r?r.type===`key`:n.track.source._closed});r>=this.minimumFragmentDuration&&i&&t.timestamp>this.maxWrittenTimestamp&&(n=!0,await this.finalizeFragment())}else n=r>=.5}n&&(e.currentChunk&&await this.finalizeCurrentChunk(e),e.currentChunk={startTimestamp:t.timestamp,samples:[],offset:null,moofOffset:null}),I(e.currentChunk),e.currentChunk.samples.push(t),this.isFragmented&&(this.maxWrittenTimestamp=Math.max(this.maxWrittenTimestamp,t.timestamp))}async finalizeCurrentChunk(e){if(I(!this.isFragmented),!e.currentChunk)return;e.finalizedChunks.push(e.currentChunk),this.finalizedChunks.push(e.currentChunk);let t=e.currentChunk.samples.length;if(e.type===`audio`&&e.info.requiresPcmTransformation&&(t=e.currentChunk.samples.reduce((t,n)=>t+Jd(n.duration,e.timescale),0)),(e.compactlyCodedChunkTable.length===0||L(e.compactlyCodedChunkTable).samplesPerChunk!==t)&&e.compactlyCodedChunkTable.push({firstChunk:e.finalizedChunks.length,samplesPerChunk:t}),this.fastStart===`in-memory`){e.currentChunk.offset=0;return}e.currentChunk.offset=this.writer.getPos();for(let t of e.currentChunk.samples)I(t.data),this.writer.write(t.data),t.data=null;await this.writer.flush()}async interleaveSamples(e=!1){if(I(this.isFragmented),!(!e&&!this.allTracksAreKnown()))outer:for(;;){let t=null,n=1/0;for(let r of this.trackDatas){if(!e&&r.sampleQueue.length===0&&!r.track.source._closed)break outer;r.sampleQueue.length>0&&r.sampleQueue[0].timestamp<n&&(t=r,n=r.sampleQueue[0].timestamp)}if(!t)break;let r=t.sampleQueue.shift();await this.addSampleToTrack(t,r)}}async finalizeFragment(e=!0){I(this.isFragmented);let t=this.nextFragmentNumber++;if(t===1){this.format._options.onMoov&&this.writer.startTrackingWrites();let e=yu(this);if(this.boxWriter.writeBox(e),this.format._options.onMoov){let{data:e,start:t}=this.writer.stopTrackingWrites();this.format._options.onMoov(e,t)}}let n=this.trackDatas.filter(e=>e.currentChunk),r=ld(t,n),i=this.writer.getPos(),a=i+this.boxWriter.measureBox(r),o=a+8,s=1/0;for(let e of n){e.currentChunk.offset=o,e.currentChunk.moofOffset=i;for(let t of e.currentChunk.samples)o+=t.size;s=Math.min(s,e.currentChunk.startTimestamp)}let c=o-a,l=c>=2**32;if(l)for(let e of n)e.currentChunk.offset+=8;this.format._options.onMoof&&this.writer.startTrackingWrites();let u=ld(t,n);if(this.boxWriter.writeBox(u),this.format._options.onMoof){let{data:e,start:t}=this.writer.stopTrackingWrites();this.format._options.onMoof(e,t,s)}I(this.writer.getPos()===a),this.format._options.onMdat&&this.writer.startTrackingWrites();let d=_u(l);d.size=c,this.boxWriter.writeBox(d),this.writer.seek(a+(l?16:8));for(let e of n)for(let t of e.currentChunk.samples)this.writer.write(t.data),t.data=null;if(this.format._options.onMdat){let{data:e,start:t}=this.writer.stopTrackingWrites();this.format._options.onMdat(e,t)}for(let e of n)e.finalizedChunks.push(e.currentChunk),this.finalizedChunks.push(e.currentChunk),e.currentChunk=null;e&&await this.writer.flush()}async registerSampleFastStartReserve(e,t){if(this.allTracksAreKnown()){if(!this.mdat){let e=yu(this),t=this.boxWriter.measureBox(e)+this.computeSampleTableSizeUpperBound()+4096;I(this.ftypSize!==null),this.writer.seek(this.ftypSize+t),this.format._options.onMdat&&this.writer.startTrackingWrites(),this.mdat=_u(!0),this.boxWriter.writeBox(this.mdat);for(let e of this.trackDatas){for(let t of e.sampleQueue)await this.addSampleToTrack(e,t);e.sampleQueue.length=0}}await this.addSampleToTrack(e,t)}else e.sampleQueue.push(t)}computeSampleTableSizeUpperBound(){I(this.fastStart===`reserve`);let e=0;for(let t of this.trackDatas){let n=t.track.metadata.maximumPacketCount;I(n!==void 0),e+=8*Math.ceil(2/3*n),e+=4*n,e+=8*Math.ceil(2/3*n),e+=12*Math.ceil(2/3*n),e+=4*n,e+=8*n}return e}async onTrackClose(e){let t=await this.mutex.acquire(),n=this.trackDatas.find(t=>t.track===e);n&&(n.type===`subtitle`&&e.source._codec===`webvtt`&&await this.processWebVTTCues(n,1/0),this.processTimestamps(n)),this.allTracksAreKnown()&&this.allTracksKnown.resolve(),this.isFragmented&&await this.interleaveSamples(),t()}async finalize(){let e=await this.mutex.acquire();this.allTracksKnown.resolve();for(let e of this.trackDatas)e.type===`subtitle`&&e.track.source._codec===`webvtt`&&await this.processWebVTTCues(e,1/0),this.processTimestamps(e);if(this.isFragmented)await this.interleaveSamples(!0),await this.finalizeFragment(!1);else for(let e of this.trackDatas)await this.finalizeCurrentChunk(e);if(this.fastStart===`in-memory`){this.mdat=_u(!1);let e;for(let t=0;t<2;t++){let t=yu(this),n=this.boxWriter.measureBox(t);e=this.boxWriter.measureBox(this.mdat);let r=this.writer.getPos()+n+e;for(let t of this.finalizedChunks){t.offset=r;for(let{data:n}of t.samples)I(n),r+=n.byteLength,e+=n.byteLength}if(r<2**32)break;e>=2**32&&(this.mdat.largeSize=!0)}this.format._options.onMoov&&this.writer.startTrackingWrites();let t=yu(this);if(this.boxWriter.writeBox(t),this.format._options.onMoov){let{data:e,start:t}=this.writer.stopTrackingWrites();this.format._options.onMoov(e,t)}this.format._options.onMdat&&this.writer.startTrackingWrites(),this.mdat.size=e,this.boxWriter.writeBox(this.mdat);for(let e of this.finalizedChunks)for(let t of e.samples)I(t.data),this.writer.write(t.data),t.data=null;if(this.format._options.onMdat){let{data:e,start:t}=this.writer.stopTrackingWrites();this.format._options.onMdat(e,t)}}else if(this.isFragmented){let e=this.writer.getPos(),t=gd(this.trackDatas);this.boxWriter.writeBox(t);let n=this.writer.getPos()-e;this.writer.seek(this.writer.getPos()-4),this.boxWriter.writeU32(n)}else{I(this.mdat);let e=this.boxWriter.offsets.get(this.mdat);I(e!==void 0);let t=this.writer.getPos()-e;if(this.mdat.size=t,this.mdat.largeSize=t>=2**32,this.boxWriter.patchBox(this.mdat),this.format._options.onMdat){let{data:e,start:t}=this.writer.stopTrackingWrites();this.format._options.onMdat(e,t)}let n=yu(this);if(this.fastStart===`reserve`){I(this.ftypSize!==null),this.writer.seek(this.ftypSize),this.format._options.onMoov&&this.writer.startTrackingWrites(),this.boxWriter.writeBox(n);let e=this.boxWriter.offsets.get(this.mdat)-this.writer.getPos();this.boxWriter.writeBox(vu(e))}else this.format._options.onMoov&&this.writer.startTrackingWrites(),this.boxWriter.writeBox(n);if(this.format._options.onMoov){let{data:e,start:t}=this.writer.stopTrackingWrites();this.format._options.onMoov(e,t)}}e()}},Xd=class{getSupportedVideoCodecs(){return this.getSupportedCodecs().filter(e=>Gi.includes(e))}getSupportedAudioCodecs(){return this.getSupportedCodecs().filter(e=>Ji.includes(e))}getSupportedSubtitleCodecs(){return this.getSupportedCodecs().filter(e=>Yi.includes(e))}_codecUnsupportedHint(e){return``}},Zd=class extends Xd{constructor(e={}){if(!e||typeof e!=`object`)throw TypeError(`options must be an object.`);if(e.fastStart!==void 0&&![!1,`in-memory`,`reserve`,`fragmented`].includes(e.fastStart))throw TypeError(`options.fastStart, when provided, must be false, 'in-memory', 'reserve', or 'fragmented'.`);if(e.minimumFragmentDuration!==void 0&&(!Number.isFinite(e.minimumFragmentDuration)||e.minimumFragmentDuration<0))throw TypeError(`options.minimumFragmentDuration, when provided, must be a non-negative number.`);if(e.onFtyp!==void 0&&typeof e.onFtyp!=`function`)throw TypeError(`options.onFtyp, when provided, must be a function.`);if(e.onMoov!==void 0&&typeof e.onMoov!=`function`)throw TypeError(`options.onMoov, when provided, must be a function.`);if(e.onMdat!==void 0&&typeof e.onMdat!=`function`)throw TypeError(`options.onMdat, when provided, must be a function.`);if(e.onMoof!==void 0&&typeof e.onMoof!=`function`)throw TypeError(`options.onMoof, when provided, must be a function.`);if(e.metadataFormat!==void 0&&![`mdir`,`mdta`,`udta`,`auto`].includes(e.metadataFormat))throw TypeError(`options.metadataFormat, when provided, must be either 'auto', 'mdir', 'mdta', or 'udta'.`);super(),this._options=e}getSupportedTrackCounts(){let e=2**32-1;return{video:{min:0,max:e},audio:{min:0,max:e},subtitle:{min:0,max:e},total:{min:1,max:e}}}get supportsVideoRotationMetadata(){return!0}get supportsTimestampedMediaData(){return!0}_createMuxer(e){return new Yd(e,this)}},Qd=class extends Zd{constructor(e){super(e)}get _name(){return`MP4`}get fileExtension(){return`.mp4`}get mimeType(){return`video/mp4`}getSupportedCodecs(){return[...Gi,...qi,`pcm-s16`,`pcm-s16be`,`pcm-s24`,`pcm-s24be`,`pcm-s32`,`pcm-s32be`,`pcm-f32`,`pcm-f32be`,`pcm-f64`,`pcm-f64be`,...Yi]}_codecUnsupportedHint(e){return new $d().getSupportedCodecs().includes(e)?` Switching to MOV will grant support for this codec.`:``}},$d=class extends Zd{constructor(e){super(e)}get _name(){return`MOV`}get fileExtension(){return`.mov`}get mimeType(){return`video/quicktime`}getSupportedCodecs(){return[...Gi,...Ji]}_codecUnsupportedHint(e){return new Qd().getSupportedCodecs().includes(e)?` Switching to MP4 will grant support for this codec.`:``}},ef=e=>{if(!e||typeof e!=`object`)throw TypeError(`Encoding config must be an object.`);if(!Gi.includes(e.codec))throw TypeError(`Invalid video codec '${e.codec}'. Must be one of: ${Gi.join(`, `)}.`);if(!(e.bitrate instanceof sf)&&(!Number.isInteger(e.bitrate)||e.bitrate<=0))throw TypeError(`config.bitrate must be a positive integer or a quality.`);if(e.keyFrameInterval!==void 0&&(!Number.isFinite(e.keyFrameInterval)||e.keyFrameInterval<0))throw TypeError(`config.keyFrameInterval, when provided, must be a non-negative number.`);if(e.sizeChangeBehavior!==void 0&&![`deny`,`passThrough`,`fill`,`contain`,`cover`].includes(e.sizeChangeBehavior))throw TypeError(`config.sizeChangeBehavior, when provided, must be 'deny', 'passThrough', 'fill', 'contain' or 'cover'.`);if(e.onEncodedPacket!==void 0&&typeof e.onEncodedPacket!=`function`)throw TypeError(`config.onEncodedChunk, when provided, must be a function.`);if(e.onEncoderConfig!==void 0&&typeof e.onEncoderConfig!=`function`)throw TypeError(`config.onEncoderConfig, when provided, must be a function.`);tf(e.codec,e)},tf=(e,t)=>{if(!t||typeof t!=`object`)throw TypeError(`Encoding options must be an object.`);if(t.alpha!==void 0&&![`discard`,`keep`].includes(t.alpha))throw TypeError(`options.alpha, when provided, must be 'discard' or 'keep'.`);if(t.bitrateMode!==void 0&&![`constant`,`variable`].includes(t.bitrateMode))throw TypeError(`bitrateMode, when provided, must be 'constant' or 'variable'.`);if(t.latencyMode!==void 0&&![`quality`,`realtime`].includes(t.latencyMode))throw TypeError(`latencyMode, when provided, must be 'quality' or 'realtime'.`);if(t.fullCodecString!==void 0&&typeof t.fullCodecString!=`string`)throw TypeError(`fullCodecString, when provided, must be a string.`);if(t.fullCodecString!==void 0&&ua(t.fullCodecString)!==e)throw TypeError(`fullCodecString, when provided, must be a string that matches the specified codec (${e}).`);if(t.hardwareAcceleration!==void 0&&![`no-preference`,`prefer-hardware`,`prefer-software`].includes(t.hardwareAcceleration))throw TypeError(`hardwareAcceleration, when provided, must be 'no-preference', 'prefer-hardware' or 'prefer-software'.`);if(t.scalabilityMode!==void 0&&typeof t.scalabilityMode!=`string`)throw TypeError(`scalabilityMode, when provided, must be a string.`);if(t.contentHint!==void 0&&typeof t.contentHint!=`string`)throw TypeError(`contentHint, when provided, must be a string.`)},nf=e=>{let t=e.bitrate instanceof sf?e.bitrate._toVideoBitrate(e.codec,e.width,e.height):e.bitrate;return{codec:e.fullCodecString??na(e.codec,e.width,e.height,t),width:e.width,height:e.height,displayWidth:e.squarePixelWidth,displayHeight:e.squarePixelHeight,bitrate:t,bitrateMode:e.bitrateMode,alpha:e.alpha??`discard`,framerate:e.framerate,latencyMode:e.latencyMode,hardwareAcceleration:e.hardwareAcceleration,scalabilityMode:e.scalabilityMode,contentHint:e.contentHint,...da(e.codec)}},rf=e=>{if(!e||typeof e!=`object`)throw TypeError(`Encoding config must be an object.`);if(!Ji.includes(e.codec))throw TypeError(`Invalid audio codec '${e.codec}'. Must be one of: ${Ji.join(`, `)}.`);if(e.bitrate===void 0&&(!Ki.includes(e.codec)||e.codec===`flac`))throw TypeError(`config.bitrate must be provided for compressed audio codecs.`);if(e.bitrate!==void 0&&!(e.bitrate instanceof sf)&&(!Number.isInteger(e.bitrate)||e.bitrate<=0))throw TypeError(`config.bitrate, when provided, must be a positive integer or a quality.`);if(e.onEncodedPacket!==void 0&&typeof e.onEncodedPacket!=`function`)throw TypeError(`config.onEncodedChunk, when provided, must be a function.`);if(e.onEncoderConfig!==void 0&&typeof e.onEncoderConfig!=`function`)throw TypeError(`config.onEncoderConfig, when provided, must be a function.`);af(e.codec,e)},af=(e,t)=>{if(!t||typeof t!=`object`)throw TypeError(`Encoding options must be an object.`);if(t.bitrateMode!==void 0&&![`constant`,`variable`].includes(t.bitrateMode))throw TypeError(`bitrateMode, when provided, must be 'constant' or 'variable'.`);if(t.fullCodecString!==void 0&&typeof t.fullCodecString!=`string`)throw TypeError(`fullCodecString, when provided, must be a string.`);if(t.fullCodecString!==void 0&&ua(t.fullCodecString)!==e)throw TypeError(`fullCodecString, when provided, must be a string that matches the specified codec (${e}).`)},of=e=>{let t=e.bitrate instanceof sf?e.bitrate._toAudioBitrate(e.codec):e.bitrate;return{codec:e.fullCodecString??aa(e.codec,e.numberOfChannels,e.sampleRate),numberOfChannels:e.numberOfChannels,sampleRate:e.sampleRate,bitrate:t,bitrateMode:e.bitrateMode,...fa(e.codec)}},sf=class{constructor(e){this._factor=e}_toVideoBitrate(e,t,n){let r=3e6*(t*n/(1920*1080))**.95*{avc:1,hevc:.6,vp9:.6,av1:.4,vp8:1.2}[e]*this._factor;return Math.ceil(r/1e3)*1e3}_toAudioBitrate(e){if(Ki.includes(e)||e===`flac`)return;let t={aac:128e3,opus:64e3,mp3:16e4,vorbis:64e3,ac3:384e3,eac3:192e3}[e];if(!t)throw Error(`Unhandled codec: ${e}`);let n=t*this._factor;return e===`aac`?n=[96e3,128e3,16e4,192e3].reduce((e,t)=>Math.abs(t-n)<Math.abs(e-n)?t:e):e===`opus`||e===`vorbis`?n=Math.max(6e3,n):e===`mp3`&&(n=[8e3,16e3,24e3,32e3,4e4,48e3,64e3,8e4,96e3,112e3,128e3,16e4,192e3,224e3,256e3,32e4].reduce((e,t)=>Math.abs(t-n)<Math.abs(e-n)?t:e)),Math.round(n/1e3)*1e3}},cf=new sf(2),lf=async(e,t={})=>{let{width:n=1280,height:r=720,bitrate:i=1e6,...a}=t;if(!Gi.includes(e))return!1;if(!Number.isInteger(n)||n<=0)throw TypeError(`width must be a positive integer.`);if(!Number.isInteger(r)||r<=0)throw TypeError(`height must be a positive integer.`);if(!(i instanceof sf)&&(!Number.isInteger(i)||i<=0))throw TypeError(`bitrate must be a positive integer or a quality.`);tf(e,a);let o=null;return Oo.length>0&&(o??=nf({codec:e,width:n,height:r,bitrate:i,framerate:void 0,...a}),Oo.some(t=>t.supports(e,o)))?!0:typeof VideoEncoder>`u`||(n%2==1||r%2==1)&&(e===`avc`||e===`hevc`)||(o??=nf({codec:e,width:n,height:r,bitrate:i,framerate:void 0,...a,alpha:`discard`}),!(await VideoEncoder.isConfigSupported(o)).supported)?!1:Ci()?new Promise(async e=>{try{let t=new VideoEncoder({output:()=>{},error:()=>e(!1)});t.configure(o);let i=new Uint8Array(n*r*4),a=new VideoFrame(i,{format:`RGBA`,codedWidth:n,codedHeight:r,timestamp:0});t.encode(a),a.close(),await t.flush(),e(!0)}catch{e(!1)}}):!0},uf=async(e,t={})=>{let{numberOfChannels:n=2,sampleRate:r=48e3,bitrate:i=128e3,...a}=t;if(!Ji.includes(e))return!1;if(!Number.isInteger(n)||n<=0)throw TypeError(`numberOfChannels must be a positive integer.`);if(!Number.isInteger(r)||r<=0)throw TypeError(`sampleRate must be a positive integer.`);if(!(i instanceof sf)&&(!Number.isInteger(i)||i<=0))throw TypeError(`bitrate must be a positive integer.`);af(e,a);let o=null;return ko.length>0&&(o??=of({codec:e,numberOfChannels:n,sampleRate:r,bitrate:i,...a}),ko.some(t=>t.supports(e,o)))||Ki.includes(e)?!0:typeof AudioEncoder>`u`?!1:(o??=of({codec:e,numberOfChannels:n,sampleRate:r,bitrate:i,...a}),(await AudioEncoder.isConfigSupported(o)).supported===!0)},df=async(e=Ji,t)=>{let n=await Promise.all(e.map(e=>uf(e,t)));return e.filter((e,t)=>n[t])},ff=async(e,t)=>{for(let n of e)if(await lf(n,t))return n;return null},pf=class{constructor(){this._connectedTrack=null,this._closingPromise=null,this._closed=!1,this._timestampOffset=0}_ensureValidAdd(){if(!this._connectedTrack)throw Error(`Source is not connected to an output track.`);if(this._connectedTrack.output.state===`canceled`)throw Error(`Output has been canceled.`);if(this._connectedTrack.output.state===`finalizing`||this._connectedTrack.output.state===`finalized`)throw Error(`Output has been finalized.`);if(this._connectedTrack.output.state===`pending`)throw Error(`Output has not started.`);if(this._closed)throw Error(`Source is closed.`)}async _start(){}async _flushAndClose(e){}close(){if(this._closingPromise)return;let e=this._connectedTrack;if(!e)throw Error(`Cannot call close without connecting the source to an output track.`);if(e.output.state===`pending`)throw Error(`Cannot call close before output has been started.`);this._closingPromise=(async()=>{await this._flushAndClose(!1),this._closed=!0,!(e.output.state===`finalizing`||e.output.state===`finalized`)&&e.output._muxer.onTrackClose(e)})()}async _flushOrWaitForOngoingClose(e){return this._closingPromise??=(async()=>{await this._flushAndClose(e),this._closed=!0})()}},mf=class extends pf{constructor(e){if(super(),this._connectedTrack=null,!Gi.includes(e))throw TypeError(`Invalid video codec '${e}'. Must be one of: ${Gi.join(`, `)}.`);this._codec=e}},hf=class extends mf{constructor(e){super(e)}add(e,t){if(!(e instanceof H))throw TypeError(`packet must be an EncodedPacket.`);if(e.isMetadataOnly)throw TypeError(`Metadata-only packets cannot be added.`);if(t!==void 0&&(!t||typeof t!=`object`))throw TypeError(`meta, when provided, must be an object.`);return this._ensureValidAdd(),this._connectedTrack.output._muxer.addEncodedVideoPacket(this._connectedTrack,e,t)}},gf=class{constructor(e,t){this.source=e,this.encodingConfig=t,this.ensureEncoderPromise=null,this.encoderInitialized=!1,this.encoder=null,this.muxer=null,this.lastMultipleOfKeyFrameInterval=-1,this.codedWidth=null,this.codedHeight=null,this.resizeCanvas=null,this.customEncoder=null,this.customEncoderCallSerializer=new yi,this.customEncoderQueueSize=0,this.alphaEncoder=null,this.splitter=null,this.splitterCreationFailed=!1,this.alphaFrameQueue=[],this.error=null}async add(e,t,n){try{if(this.checkForEncoderError(),this.source._ensureValidAdd(),this.codedWidth!==null&&this.codedHeight!==null){if(e.codedWidth!==this.codedWidth||e.codedHeight!==this.codedHeight){let n=this.encodingConfig.sizeChangeBehavior??`deny`;if(n!==`passThrough`){if(n===`deny`)throw Error(`Video sample size must remain constant. Expected ${this.codedWidth}x${this.codedHeight}, got ${e.codedWidth}x${e.codedHeight}. To allow the sample size to change over time, set \`sizeChangeBehavior\` to a value other than 'strict' in the encoding options.`);{let r=!1;this.resizeCanvas||(typeof document<`u`?(this.resizeCanvas=document.createElement(`canvas`),this.resizeCanvas.width=this.codedWidth,this.resizeCanvas.height=this.codedHeight):this.resizeCanvas=new OffscreenCanvas(this.codedWidth,this.codedHeight),r=!0);let i=this.resizeCanvas.getContext(`2d`,{alpha:Ci()});I(i),r||(Ci()?(i.fillStyle=`black`,i.fillRect(0,0,this.codedWidth,this.codedHeight)):i.clearRect(0,0,this.codedWidth,this.codedHeight)),e.drawWithFit(i,{fit:n}),t&&e.close(),e=new Bo(this.resizeCanvas,{timestamp:e.timestamp,duration:e.duration,rotation:e.rotation}),t=!0}}}}else this.codedWidth=e.codedWidth,this.codedHeight=e.codedHeight;this.encoderInitialized||(this.ensureEncoderPromise||this.ensureEncoder(e),this.encoderInitialized||await this.ensureEncoderPromise),I(this.encoderInitialized);let r=this.encodingConfig.keyFrameInterval??5,i=Math.floor(e.timestamp/r),a={...n,keyFrame:n?.keyFrame||r===0||i!==this.lastMultipleOfKeyFrameInterval};if(this.lastMultipleOfKeyFrameInterval=i,this.customEncoder){this.customEncoderQueueSize++;let t=e.clone(),n=this.customEncoderCallSerializer.call(()=>this.customEncoder.encode(t,a)).then(()=>this.customEncoderQueueSize--).catch(e=>this.error??=e).finally(()=>{t.close()});this.customEncoderQueueSize>=4&&await n}else{I(this.encoder);let n=e.toVideoFrame();if(!this.alphaEncoder)this.encoder.encode(n,a),n.close();else if(n.format&&!n.format.includes(`A`)||this.splitterCreationFailed)this.alphaFrameQueue.push(null),this.encoder.encode(n,a),n.close();else{let e=n.displayWidth,t=n.displayHeight;if(!this.splitter)try{this.splitter=new _f(e,t)}catch(e){console.error(`Due to an error, only color data will be encoded.`,e),this.splitterCreationFailed=!0,this.alphaFrameQueue.push(null),this.encoder.encode(n,a),n.close()}if(this.splitter){let e=this.splitter.extractColor(n),t=this.splitter.extractAlpha(n);this.alphaFrameQueue.push(t),this.encoder.encode(e,a),e.close(),n.close()}}t&&e.close(),this.encoder.encodeQueueSize>=4&&await new Promise(e=>this.encoder.addEventListener(`dequeue`,e,{once:!0}))}await this.muxer.mutex.currentPromise}finally{t&&e.close()}}ensureEncoder(e){this.ensureEncoderPromise=(async()=>{let t=nf({width:e.codedWidth,height:e.codedHeight,squarePixelWidth:e.squarePixelWidth,squarePixelHeight:e.squarePixelHeight,...this.encodingConfig,framerate:this.source._connectedTrack?.metadata.frameRate});this.encodingConfig.onEncoderConfig?.(t);let n=Oo.find(e=>e.supports(this.encodingConfig.codec,t));if(n)this.customEncoder=new n,this.customEncoder.codec=this.encodingConfig.codec,this.customEncoder.config=t,this.customEncoder.onPacket=(e,t)=>{if(!(e instanceof H))throw TypeError(`The first argument passed to onPacket must be an EncodedPacket.`);if(t!==void 0&&(!t||typeof t!=`object`))throw TypeError(`The second argument passed to onPacket must be an object or undefined.`);this.encodingConfig.onEncodedPacket?.(e,t),this.muxer.addEncodedVideoPacket(this.source._connectedTrack,e,t).catch(e=>{this.error??=e})},await this.customEncoder.init();else{if(typeof VideoEncoder>`u`)throw Error(`VideoEncoder is not supported by this browser.`);if(t.alpha=`discard`,this.encodingConfig.alpha===`keep`&&(t.latencyMode=`quality`),(t.width%2==1||t.height%2==1)&&(this.encodingConfig.codec===`avc`||this.encodingConfig.codec===`hevc`))throw Error(`The dimensions ${t.width}x${t.height} are not supported for codec '${this.encodingConfig.codec}'; both width and height must be even numbers. Make sure to round your dimensions to the nearest even number.`);if(!(await VideoEncoder.isConfigSupported(t)).supported)throw Error(`This specific encoder configuration (${t.codec}, ${t.bitrate} bps, ${t.width}x${t.height}, hardware acceleration: ${t.hardwareAcceleration??`no-preference`}) is not supported by this browser. Consider using another codec or changing your video parameters.`);let e=[],n=[],r=0,i=0,a=(e,t,n)=>{let r={};if(t){let e=new Uint8Array(t.byteLength);t.copyTo(e),r.alpha=e}let i=H.fromEncodedChunk(e,r);this.encodingConfig.onEncodedPacket?.(i,n),this.muxer.addEncodedVideoPacket(this.source._connectedTrack,i,n).catch(e=>{this.error??=e})},o=Error(`Encoding error`).stack;if(this.encoder=new VideoEncoder({output:(t,o)=>{if(!this.alphaEncoder){a(t,null,o);return}let s=this.alphaFrameQueue.shift();I(s!==void 0),s?(this.alphaEncoder.encode(s,{keyFrame:t.type===`key`}),i++,s.close(),e.push({chunk:t,meta:o})):i===0?a(t,null,o):(n.push(r+i),e.push({chunk:t,meta:o}))},error:e=>{e.stack=o,this.error??=e}}),this.encoder.configure(t),this.encodingConfig.alpha===`keep`){let o=Error(`Encoding error`).stack;this.alphaEncoder=new VideoEncoder({output:(t,o)=>{i--;let s=e.shift();for(I(s!==void 0),a(s.chunk,t,s.meta),r++;n.length>0&&n[0]===r;){n.shift();let t=e.shift();I(t!==void 0),a(t.chunk,null,t.meta)}},error:e=>{e.stack=o,this.error??=e}}),this.alphaEncoder.configure(t)}}I(this.source._connectedTrack),this.muxer=this.source._connectedTrack.output._muxer,this.encoderInitialized=!0})()}async flushAndClose(e){e||this.checkForEncoderError(),this.customEncoder?(e||this.customEncoderCallSerializer.call(()=>this.customEncoder.flush()),await this.customEncoderCallSerializer.call(()=>this.customEncoder.close())):this.encoder&&(e||(await this.encoder.flush(),await this.alphaEncoder?.flush()),this.encoder.state!==`closed`&&this.encoder.close(),this.alphaEncoder&&this.alphaEncoder.state!==`closed`&&this.alphaEncoder.close(),this.alphaFrameQueue.forEach(e=>e?.close()),this.splitter?.close()),e||this.checkForEncoderError()}getQueueSize(){return this.customEncoder?this.customEncoderQueueSize:this.encoder?.encodeQueueSize??0}checkForEncoderError(){if(this.error)throw this.error}},_f=class{constructor(e,t){this.lastFrame=null,typeof OffscreenCanvas<`u`?this.canvas=new OffscreenCanvas(e,t):(this.canvas=document.createElement(`canvas`),this.canvas.width=e,this.canvas.height=t);let n=this.canvas.getContext(`webgl2`,{alpha:!0});if(!n)throw Error(`Couldn't acquire WebGL 2 context.`);this.gl=n,this.colorProgram=this.createColorProgram(),this.alphaProgram=this.createAlphaProgram(),this.vao=this.createVAO(),this.sourceTexture=this.createTexture(),this.alphaResolutionLocation=this.gl.getUniformLocation(this.alphaProgram,`u_resolution`),this.gl.useProgram(this.colorProgram),this.gl.uniform1i(this.gl.getUniformLocation(this.colorProgram,`u_sourceTexture`),0),this.gl.useProgram(this.alphaProgram),this.gl.uniform1i(this.gl.getUniformLocation(this.alphaProgram,`u_sourceTexture`),0)}createVertexShader(){return this.createShader(this.gl.VERTEX_SHADER,`#version 300 es
1399
+ in vec2 a_position;
1400
+ in vec2 a_texCoord;
1401
+ out vec2 v_texCoord;
1402
+
1403
+ void main() {
1404
+ gl_Position = vec4(a_position, 0.0, 1.0);
1405
+ v_texCoord = a_texCoord;
1406
+ }
1407
+ `)}createColorProgram(){let e=this.createVertexShader(),t=this.createShader(this.gl.FRAGMENT_SHADER,`#version 300 es
1408
+ precision highp float;
1409
+
1410
+ uniform sampler2D u_sourceTexture;
1411
+ in vec2 v_texCoord;
1412
+ out vec4 fragColor;
1413
+
1414
+ void main() {
1415
+ vec4 source = texture(u_sourceTexture, v_texCoord);
1416
+ fragColor = vec4(source.rgb, 1.0);
1417
+ }
1418
+ `),n=this.gl.createProgram();return this.gl.attachShader(n,e),this.gl.attachShader(n,t),this.gl.linkProgram(n),n}createAlphaProgram(){let e=this.createVertexShader(),t=this.createShader(this.gl.FRAGMENT_SHADER,`#version 300 es
1419
+ precision highp float;
1420
+
1421
+ uniform sampler2D u_sourceTexture;
1422
+ uniform vec2 u_resolution; // The width and height of the canvas
1423
+ in vec2 v_texCoord;
1424
+ out vec4 fragColor;
1425
+
1426
+ // This function determines the value for a single byte in the YUV stream
1427
+ float getByteValue(float byteOffset) {
1428
+ float width = u_resolution.x;
1429
+ float height = u_resolution.y;
1430
+
1431
+ float yPlaneSize = width * height;
1432
+
1433
+ if (byteOffset < yPlaneSize) {
1434
+ // This byte is in the luma plane. Find the corresponding pixel coordinates to sample from
1435
+ float y = floor(byteOffset / width);
1436
+ float x = mod(byteOffset, width);
1437
+
1438
+ // Add 0.5 to sample the center of the texel
1439
+ vec2 sampleCoord = (vec2(x, y) + 0.5) / u_resolution;
1440
+
1441
+ // The luma value is the alpha from the source texture
1442
+ return texture(u_sourceTexture, sampleCoord).a;
1443
+ } else {
1444
+ // Write a fixed value for chroma and beyond
1445
+ return 128.0 / 255.0;
1446
+ }
1447
+ }
1448
+
1449
+ void main() {
1450
+ // Each fragment writes 4 bytes (R, G, B, A)
1451
+ float pixelIndex = floor(gl_FragCoord.y) * u_resolution.x + floor(gl_FragCoord.x);
1452
+ float baseByteOffset = pixelIndex * 4.0;
1453
+
1454
+ vec4 result;
1455
+ for (int i = 0; i < 4; i++) {
1456
+ float currentByteOffset = baseByteOffset + float(i);
1457
+ result[i] = getByteValue(currentByteOffset);
1458
+ }
1459
+
1460
+ fragColor = result;
1461
+ }
1462
+ `),n=this.gl.createProgram();return this.gl.attachShader(n,e),this.gl.attachShader(n,t),this.gl.linkProgram(n),n}createShader(e,t){let n=this.gl.createShader(e);return this.gl.shaderSource(n,t),this.gl.compileShader(n),this.gl.getShaderParameter(n,this.gl.COMPILE_STATUS)||console.error(`Shader compile error:`,this.gl.getShaderInfoLog(n)),n}createVAO(){let e=this.gl.createVertexArray();this.gl.bindVertexArray(e);let t=new Float32Array([-1,-1,0,1,1,-1,1,1,-1,1,0,0,1,1,1,0]),n=this.gl.createBuffer();this.gl.bindBuffer(this.gl.ARRAY_BUFFER,n),this.gl.bufferData(this.gl.ARRAY_BUFFER,t,this.gl.STATIC_DRAW);let r=this.gl.getAttribLocation(this.colorProgram,`a_position`),i=this.gl.getAttribLocation(this.colorProgram,`a_texCoord`);return this.gl.enableVertexAttribArray(r),this.gl.vertexAttribPointer(r,2,this.gl.FLOAT,!1,16,0),this.gl.enableVertexAttribArray(i),this.gl.vertexAttribPointer(i,2,this.gl.FLOAT,!1,16,8),e}createTexture(){let e=this.gl.createTexture();return this.gl.bindTexture(this.gl.TEXTURE_2D,e),this.gl.texParameteri(this.gl.TEXTURE_2D,this.gl.TEXTURE_WRAP_S,this.gl.CLAMP_TO_EDGE),this.gl.texParameteri(this.gl.TEXTURE_2D,this.gl.TEXTURE_WRAP_T,this.gl.CLAMP_TO_EDGE),this.gl.texParameteri(this.gl.TEXTURE_2D,this.gl.TEXTURE_MIN_FILTER,this.gl.LINEAR),this.gl.texParameteri(this.gl.TEXTURE_2D,this.gl.TEXTURE_MAG_FILTER,this.gl.LINEAR),e}updateTexture(e){this.lastFrame!==e&&((e.displayWidth!==this.canvas.width||e.displayHeight!==this.canvas.height)&&(this.canvas.width=e.displayWidth,this.canvas.height=e.displayHeight),this.gl.activeTexture(this.gl.TEXTURE0),this.gl.bindTexture(this.gl.TEXTURE_2D,this.sourceTexture),this.gl.texImage2D(this.gl.TEXTURE_2D,0,this.gl.RGBA,this.gl.RGBA,this.gl.UNSIGNED_BYTE,e),this.lastFrame=e)}extractColor(e){return this.updateTexture(e),this.gl.useProgram(this.colorProgram),this.gl.viewport(0,0,this.canvas.width,this.canvas.height),this.gl.clear(this.gl.COLOR_BUFFER_BIT),this.gl.bindVertexArray(this.vao),this.gl.drawArrays(this.gl.TRIANGLE_STRIP,0,4),new VideoFrame(this.canvas,{timestamp:e.timestamp,duration:e.duration??void 0,alpha:`discard`})}extractAlpha(e){this.updateTexture(e),this.gl.useProgram(this.alphaProgram),this.gl.uniform2f(this.alphaResolutionLocation,this.canvas.width,this.canvas.height),this.gl.viewport(0,0,this.canvas.width,this.canvas.height),this.gl.clear(this.gl.COLOR_BUFFER_BIT),this.gl.bindVertexArray(this.vao),this.gl.drawArrays(this.gl.TRIANGLE_STRIP,0,4);let{width:t,height:n}=this.canvas,r=Math.ceil(t/2)*Math.ceil(n/2),i=t*n+r*2,a=Math.ceil(i/(t*4)),o=new Uint8Array(4*t*a);this.gl.readPixels(0,0,t,a,this.gl.RGBA,this.gl.UNSIGNED_BYTE,o),o=o.subarray(0,i),I(o[t*n]===128),I(o[o.length-1]===128);let s={format:`I420`,codedWidth:t,codedHeight:n,timestamp:e.timestamp,duration:e.duration??void 0,transfer:[o.buffer]};return new VideoFrame(o,s)}close(){this.gl.getExtension(`WEBGL_lose_context`)?.loseContext(),this.gl=null}},vf=class extends mf{constructor(e){ef(e),super(e.codec),this._encoder=new gf(this,e)}add(e,t){if(!(e instanceof Bo))throw TypeError(`videoSample must be a VideoSample.`);return this._encoder.add(e,!1,t)}_flushAndClose(e){return this._encoder.flushAndClose(e)}},yf=class extends pf{constructor(e){if(super(),this._connectedTrack=null,!Ji.includes(e))throw TypeError(`Invalid audio codec '${e}'. Must be one of: ${Ji.join(`, `)}.`);this._codec=e}},bf=class extends yf{constructor(e){super(e)}add(e,t){if(!(e instanceof H))throw TypeError(`packet must be an EncodedPacket.`);if(e.isMetadataOnly)throw TypeError(`Metadata-only packets cannot be added.`);if(t!==void 0&&(!t||typeof t!=`object`))throw TypeError(`meta, when provided, must be an object.`);return this._ensureValidAdd(),this._connectedTrack.output._muxer.addEncodedAudioPacket(this._connectedTrack,e,t)}},xf=class{constructor(e,t){this.source=e,this.encodingConfig=t,this.ensureEncoderPromise=null,this.encoderInitialized=!1,this.encoder=null,this.muxer=null,this.lastNumberOfChannels=null,this.lastSampleRate=null,this.isPcmEncoder=!1,this.outputSampleSize=null,this.writeOutputValue=null,this.customEncoder=null,this.customEncoderCallSerializer=new yi,this.customEncoderQueueSize=0,this.lastEndSampleIndex=null,this.error=null}async add(e,t){try{if(this.checkForEncoderError(),this.source._ensureValidAdd(),this.lastNumberOfChannels!==null&&this.lastSampleRate!==null){if(e.numberOfChannels!==this.lastNumberOfChannels||e.sampleRate!==this.lastSampleRate)throw Error(`Audio parameters must remain constant. Expected ${this.lastNumberOfChannels} channels at ${this.lastSampleRate} Hz, got ${e.numberOfChannels} channels at ${e.sampleRate} Hz.`)}else this.lastNumberOfChannels=e.numberOfChannels,this.lastSampleRate=e.sampleRate;this.encoderInitialized||(this.ensureEncoderPromise||this.ensureEncoder(e),this.encoderInitialized||await this.ensureEncoderPromise),I(this.encoderInitialized);{let t=Math.round(e.timestamp*e.sampleRate),n=Math.round((e.timestamp+e.duration)*e.sampleRate);if(this.lastEndSampleIndex===null)this.lastEndSampleIndex=n;else{let n=t-this.lastEndSampleIndex;if(n>=64){let t=new Yo({data:new Float32Array(n*e.numberOfChannels),format:`f32-planar`,sampleRate:e.sampleRate,numberOfChannels:e.numberOfChannels,numberOfFrames:n,timestamp:this.lastEndSampleIndex/e.sampleRate});await this.add(t,!0)}this.lastEndSampleIndex+=e.numberOfFrames}}if(this.customEncoder){this.customEncoderQueueSize++;let t=e.clone(),n=this.customEncoderCallSerializer.call(()=>this.customEncoder.encode(t)).then(()=>this.customEncoderQueueSize--).catch(e=>this.error??=e).finally(()=>{t.close()});this.customEncoderQueueSize>=4&&await n,await this.muxer.mutex.currentPromise}else if(this.isPcmEncoder)await this.doPcmEncoding(e,t);else{I(this.encoder);let n=e.toAudioData();this.encoder.encode(n),n.close(),t&&e.close(),this.encoder.encodeQueueSize>=4&&await new Promise(e=>this.encoder.addEventListener(`dequeue`,e,{once:!0})),await this.muxer.mutex.currentPromise}}finally{t&&e.close()}}async doPcmEncoding(e,t){I(this.outputSampleSize),I(this.writeOutputValue);let{numberOfChannels:n,numberOfFrames:r,sampleRate:i,timestamp:a}=e,o=2048,s=[];for(let t=0;t<r;t+=o){let r=Math.min(o,e.numberOfFrames-t),i=r*n*this.outputSampleSize,a=new ArrayBuffer(i),c=new DataView(a);s.push({frameCount:r,view:c})}let c=e.allocationSize({planeIndex:0,format:`f32-planar`}),l=new Float32Array(c/Float32Array.BYTES_PER_ELEMENT);for(let t=0;t<n;t++){e.copyTo(l,{planeIndex:t,format:`f32-planar`});for(let e=0;e<s.length;e++){let{frameCount:r,view:i}=s[e];for(let a=0;a<r;a++)this.writeOutputValue(i,(a*n+t)*this.outputSampleSize,l[e*o+a])}}t&&e.close();let u={decoderConfig:{codec:this.encodingConfig.codec,numberOfChannels:n,sampleRate:i}};for(let e=0;e<s.length;e++){let{frameCount:t,view:n}=s[e],r=n.buffer,c=e*o,l=new H(new Uint8Array(r),`key`,a+c/i,t/i);this.encodingConfig.onEncodedPacket?.(l,u),await this.muxer.addEncodedAudioPacket(this.source._connectedTrack,l,u)}}ensureEncoder(e){this.ensureEncoderPromise=(async()=>{let{numberOfChannels:t,sampleRate:n}=e,r=of({numberOfChannels:t,sampleRate:n,...this.encodingConfig});this.encodingConfig.onEncoderConfig?.(r);let i=ko.find(e=>e.supports(this.encodingConfig.codec,r));if(i)this.customEncoder=new i,this.customEncoder.codec=this.encodingConfig.codec,this.customEncoder.config=r,this.customEncoder.onPacket=(e,t)=>{if(!(e instanceof H))throw TypeError(`The first argument passed to onPacket must be an EncodedPacket.`);if(t!==void 0&&(!t||typeof t!=`object`))throw TypeError(`The second argument passed to onPacket must be an object or undefined.`);this.encodingConfig.onEncodedPacket?.(e,t),this.muxer.addEncodedAudioPacket(this.source._connectedTrack,e,t).catch(e=>{this.error??=e})},await this.customEncoder.init();else if(Ki.includes(this.encodingConfig.codec))this.initPcmEncoder();else{if(typeof AudioEncoder>`u`)throw Error(`AudioEncoder is not supported by this browser.`);if(!(await AudioEncoder.isConfigSupported(r)).supported)throw Error(`This specific encoder configuration (${r.codec}, ${r.bitrate} bps, ${r.numberOfChannels} channels, ${r.sampleRate} Hz) is not supported by this browser. Consider using another codec or changing your audio parameters.`);let e=Error(`Encoding error`).stack;this.encoder=new AudioEncoder({output:(e,t)=>{if(this.encodingConfig.codec===`aac`&&t?.decoderConfig){let e=!1;if(e=!t.decoderConfig.description||t.decoderConfig.description.byteLength<2?!0:Ui(Ir(t.decoderConfig.description)).objectType===0,e){let e=Number(L(r.codec.split(`.`)));t.decoderConfig.description=Wi({objectType:e,numberOfChannels:t.decoderConfig.numberOfChannels,sampleRate:t.decoderConfig.sampleRate})}}let n=H.fromEncodedChunk(e);this.encodingConfig.onEncodedPacket?.(n,t),this.muxer.addEncodedAudioPacket(this.source._connectedTrack,n,t).catch(e=>{this.error??=e})},error:t=>{t.stack=e,this.error??=t}}),this.encoder.configure(r)}I(this.source._connectedTrack),this.muxer=this.source._connectedTrack.output._muxer,this.encoderInitialized=!0})()}initPcmEncoder(){this.isPcmEncoder=!0;let e=this.encodingConfig.codec,{dataType:t,sampleSize:n,littleEndian:r}=la(e);switch(this.outputSampleSize=n,n){case 1:t===`unsigned`?this.writeOutputValue=(e,t,n)=>e.setUint8(t,ui((n+1)*127.5,0,255)):t===`signed`?this.writeOutputValue=(e,t,n)=>{e.setInt8(t,ui(Math.round(n*128),-128,127))}:t===`ulaw`?this.writeOutputValue=(e,t,n)=>{let r=ui(Math.floor(n*32767),-32768,32767);e.setUint8(t,jo(r))}:t===`alaw`?this.writeOutputValue=(e,t,n)=>{let r=ui(Math.floor(n*32767),-32768,32767);e.setUint8(t,No(r))}:I(!1);break;case 2:t===`unsigned`?this.writeOutputValue=(e,t,n)=>e.setUint16(t,ui((n+1)*32767.5,0,65535),r):t===`signed`?this.writeOutputValue=(e,t,n)=>e.setInt16(t,ui(Math.round(n*32767),-32768,32767),r):I(!1);break;case 3:t===`unsigned`?this.writeOutputValue=(e,t,n)=>si(e,t,ui((n+1)*8388607.5,0,16777215),r):t===`signed`?this.writeOutputValue=(e,t,n)=>ci(e,t,ui(Math.round(n*8388607),-8388608,8388607),r):I(!1);break;case 4:t===`unsigned`?this.writeOutputValue=(e,t,n)=>e.setUint32(t,ui((n+1)*2147483647.5,0,4294967295),r):t===`signed`?this.writeOutputValue=(e,t,n)=>e.setInt32(t,ui(Math.round(n*2147483647),-2147483648,2147483647),r):t===`float`?this.writeOutputValue=(e,t,n)=>e.setFloat32(t,n,r):I(!1);break;case 8:t===`float`?this.writeOutputValue=(e,t,n)=>e.setFloat64(t,n,r):I(!1);break;default:ii(n),I(!1)}}async flushAndClose(e){e||this.checkForEncoderError(),this.customEncoder?(e||this.customEncoderCallSerializer.call(()=>this.customEncoder.flush()),await this.customEncoderCallSerializer.call(()=>this.customEncoder.close())):this.encoder&&(e||await this.encoder.flush(),this.encoder.state!==`closed`&&this.encoder.close()),e||this.checkForEncoderError()}getQueueSize(){return this.customEncoder?this.customEncoderQueueSize:this.isPcmEncoder?0:this.encoder?.encodeQueueSize??0}checkForEncoderError(){if(this.error)throw this.error}},Sf=class extends yf{constructor(e){rf(e),super(e.codec),this._encoder=new xf(this,e)}add(e){if(!(e instanceof Yo))throw TypeError(`audioSample must be an AudioSample.`);return this._encoder.add(e,!1)}_flushAndClose(e){return this._encoder.flushAndClose(e)}},Cf=class extends pf{constructor(e){if(super(),this._connectedTrack=null,!Yi.includes(e))throw TypeError(`Invalid subtitle codec '${e}'. Must be one of: ${Yi.join(`, `)}.`);this._codec=e}},wf=[`video`,`audio`,`subtitle`],Tf=e=>{if(!e||typeof e!=`object`)throw TypeError(`metadata must be an object.`);if(e.languageCode!==void 0&&!gi(e.languageCode))throw TypeError(`metadata.languageCode, when provided, must be a three-letter, ISO 639-2/T language code.`);if(e.name!==void 0&&typeof e.name!=`string`)throw TypeError(`metadata.name, when provided, must be a string.`);if(e.disposition!==void 0&&Bi(e.disposition),e.maximumPacketCount!==void 0&&(!Number.isInteger(e.maximumPacketCount)||e.maximumPacketCount<0))throw TypeError(`metadata.maximumPacketCount, when provided, must be a non-negative integer.`)},Ef=class{constructor(e){if(this.state=`pending`,this._tracks=[],this._startPromise=null,this._cancelPromise=null,this._finalizePromise=null,this._mutex=new Jr,this._metadataTags={},!e||typeof e!=`object`)throw TypeError(`options must be an object.`);if(!(e.format instanceof Xd))throw TypeError(`options.format must be an OutputFormat.`);if(!(e.target instanceof Hd))throw TypeError(`options.target must be a Target.`);if(e.target._output)throw Error(`Target is already used for another output.`);e.target._output=this,this.format=e.format,this.target=e.target,this._writer=e.target._createWriter(),this._muxer=e.format._createMuxer(this)}addVideoTrack(e,t={}){if(!(e instanceof mf))throw TypeError(`source must be a VideoSource.`);if(Tf(t),t.rotation!==void 0&&![0,90,180,270].includes(t.rotation))throw TypeError(`Invalid video rotation: ${t.rotation}. Has to be 0, 90, 180 or 270.`);if(!this.format.supportsVideoRotationMetadata&&t.rotation)throw Error(`${this.format._name} does not support video rotation metadata.`);if(t.frameRate!==void 0&&(!Number.isFinite(t.frameRate)||t.frameRate<=0))throw TypeError(`Invalid video frame rate: ${t.frameRate}. Must be a positive number.`);this._addTrack(`video`,e,t)}addAudioTrack(e,t={}){if(!(e instanceof yf))throw TypeError(`source must be an AudioSource.`);Tf(t),this._addTrack(`audio`,e,t)}addSubtitleTrack(e,t={}){if(!(e instanceof Cf))throw TypeError(`source must be a SubtitleSource.`);Tf(t),this._addTrack(`subtitle`,e,t)}setMetadataTags(e){if(Ri(e),this.state!==`pending`)throw Error(`Cannot set metadata tags after output has been started or canceled.`);this._metadataTags=e}_addTrack(e,t,n){if(this.state!==`pending`)throw Error(`Cannot add track after output has been started or canceled.`);if(t._connectedTrack)throw Error(`Source is already used for a track.`);let r=this.format.getSupportedTrackCounts(),i=this._tracks.reduce((t,n)=>t+(n.type===e?1:0),0),a=r[e].max;if(i===a)throw Error(a===0?`${this.format._name} does not support ${e} tracks.`:`${this.format._name} does not support more than ${a} ${e} track${a===1?``:`s`}.`);let o=r.total.max;if(this._tracks.length===o)throw Error(`${this.format._name} does not support more than ${o} tracks${o===1?``:`s`} in total.`);let s={id:this._tracks.length+1,output:this,type:e,source:t,metadata:n};if(s.type===`video`){let e=this.format.getSupportedVideoCodecs();if(e.length===0)throw Error(`${this.format._name} does not support video tracks.`+this.format._codecUnsupportedHint(s.source._codec));if(!e.includes(s.source._codec))throw Error(`Codec '${s.source._codec}' cannot be contained within ${this.format._name}. Supported video codecs are: ${e.map(e=>`'${e}'`).join(`, `)}.`+this.format._codecUnsupportedHint(s.source._codec))}else if(s.type===`audio`){let e=this.format.getSupportedAudioCodecs();if(e.length===0)throw Error(`${this.format._name} does not support audio tracks.`+this.format._codecUnsupportedHint(s.source._codec));if(!e.includes(s.source._codec))throw Error(`Codec '${s.source._codec}' cannot be contained within ${this.format._name}. Supported audio codecs are: ${e.map(e=>`'${e}'`).join(`, `)}.`+this.format._codecUnsupportedHint(s.source._codec))}else if(s.type===`subtitle`){let e=this.format.getSupportedSubtitleCodecs();if(e.length===0)throw Error(`${this.format._name} does not support subtitle tracks.`+this.format._codecUnsupportedHint(s.source._codec));if(!e.includes(s.source._codec))throw Error(`Codec '${s.source._codec}' cannot be contained within ${this.format._name}. Supported subtitle codecs are: ${e.map(e=>`'${e}'`).join(`, `)}.`+this.format._codecUnsupportedHint(s.source._codec))}this._tracks.push(s),t._connectedTrack=s}async start(){let e=this.format.getSupportedTrackCounts();for(let t of wf){let n=this._tracks.reduce((e,n)=>e+(n.type===t?1:0),0),r=e[t].min;if(n<r)throw Error(r===e[t].max?`${this.format._name} requires exactly ${r} ${t} track${r===1?``:`s`}.`:`${this.format._name} requires at least ${r} ${t} track${r===1?``:`s`}.`)}let t=e.total.min;if(this._tracks.length<t)throw Error(t===e.total.max?`${this.format._name} requires exactly ${t} track${t===1?``:`s`}.`:`${this.format._name} requires at least ${t} track${t===1?``:`s`}.`);if(this.state===`canceled`)throw Error(`Output has been canceled.`);return this._startPromise?(console.warn(`Output has already been started.`),this._startPromise):this._startPromise=(async()=>{this.state=`started`,this._writer.start();let e=await this._mutex.acquire();await this._muxer.start();let t=this._tracks.map(e=>e.source._start());await Promise.all(t),e()})()}getMimeType(){return this._muxer.getMimeType()}async cancel(){if(this._cancelPromise)return console.warn(`Output has already been canceled.`),this._cancelPromise;if(this.state===`finalizing`||this.state===`finalized`){console.warn(`Output has already been finalized.`);return}return this._cancelPromise=(async()=>{this.state=`canceled`;let e=await this._mutex.acquire(),t=this._tracks.map(e=>e.source._flushOrWaitForOngoingClose(!0));await Promise.all(t),await this._writer.close(),e()})()}async finalize(){if(this.state===`pending`)throw Error(`Cannot finalize before starting.`);if(this.state===`canceled`)throw Error(`Cannot finalize after canceling.`);return this._finalizePromise?(console.warn(`Output has already been finalized.`),this._finalizePromise):this._finalizePromise=(async()=>{this.state=`finalizing`;let e=await this._mutex.acquire(),t=this._tracks.map(e=>e.source._flushOrWaitForOngoingClose(!1));await Promise.all(t),await this._muxer.finalize(),await this._writer.flush(),await this._writer.finalize(),this.state=`finalized`,e()})()}},Df=e=>{if(e!==void 0&&(!e||typeof e!=`object`))throw TypeError(`options.video, when provided, must be an object.`);if(e?.discard!==void 0&&typeof e.discard!=`boolean`)throw TypeError(`options.video.discard, when provided, must be a boolean.`);if(e?.forceTranscode!==void 0&&typeof e.forceTranscode!=`boolean`)throw TypeError(`options.video.forceTranscode, when provided, must be a boolean.`);if(e?.codec!==void 0&&!Gi.includes(e.codec))throw TypeError(`options.video.codec, when provided, must be one of: ${Gi.join(`, `)}.`);if(e?.bitrate!==void 0&&!(e.bitrate instanceof sf)&&(!Number.isInteger(e.bitrate)||e.bitrate<=0))throw TypeError(`options.video.bitrate, when provided, must be a positive integer or a quality.`);if(e?.width!==void 0&&(!Number.isInteger(e.width)||e.width<=0))throw TypeError(`options.video.width, when provided, must be a positive integer.`);if(e?.height!==void 0&&(!Number.isInteger(e.height)||e.height<=0))throw TypeError(`options.video.height, when provided, must be a positive integer.`);if(e?.fit!==void 0&&![`fill`,`contain`,`cover`].includes(e.fit))throw TypeError(`options.video.fit, when provided, must be one of 'fill', 'contain', or 'cover'.`);if(e?.width!==void 0&&e.height!==void 0&&e.fit===void 0)throw TypeError(`When both options.video.width and options.video.height are provided, options.video.fit must also be provided.`);if(e?.rotate!==void 0&&![0,90,180,270].includes(e.rotate))throw TypeError(`options.video.rotate, when provided, must be 0, 90, 180 or 270.`);if(e?.allowRotationMetadata!==void 0&&typeof e.allowRotationMetadata!=`boolean`)throw TypeError(`options.video.allowRotationMetadata, when provided, must be a boolean.`);if(e?.crop!==void 0&&Wo(e.crop,`options.video.`),e?.frameRate!==void 0&&(!Number.isFinite(e.frameRate)||e.frameRate<=0))throw TypeError(`options.video.frameRate, when provided, must be a finite positive number.`);if(e?.alpha!==void 0&&![`discard`,`keep`].includes(e.alpha))throw TypeError(`options.video.alpha, when provided, must be either 'discard' or 'keep'.`);if(e?.keyFrameInterval!==void 0&&(!Number.isFinite(e.keyFrameInterval)||e.keyFrameInterval<0))throw TypeError(`options.video.keyFrameInterval, when provided, must be a non-negative number.`);if(e?.process!==void 0&&typeof e.process!=`function`)throw TypeError(`options.video.process, when provided, must be a function.`);if(e?.processedWidth!==void 0&&(!Number.isInteger(e.processedWidth)||e.processedWidth<=0))throw TypeError(`options.video.processedWidth, when provided, must be a positive integer.`);if(e?.processedHeight!==void 0&&(!Number.isInteger(e.processedHeight)||e.processedHeight<=0))throw TypeError(`options.video.processedHeight, when provided, must be a positive integer.`);if(e?.hardwareAcceleration!==void 0&&![`no-preference`,`prefer-hardware`,`prefer-software`].includes(e.hardwareAcceleration))throw TypeError(`options.video.hardwareAcceleration, when provided, must be 'no-preference', 'prefer-hardware' or 'prefer-software'.`)},Of=e=>{if(e!==void 0&&(!e||typeof e!=`object`))throw TypeError(`options.audio, when provided, must be an object.`);if(e?.discard!==void 0&&typeof e.discard!=`boolean`)throw TypeError(`options.audio.discard, when provided, must be a boolean.`);if(e?.forceTranscode!==void 0&&typeof e.forceTranscode!=`boolean`)throw TypeError(`options.audio.forceTranscode, when provided, must be a boolean.`);if(e?.codec!==void 0&&!Ji.includes(e.codec))throw TypeError(`options.audio.codec, when provided, must be one of: ${Ji.join(`, `)}.`);if(e?.bitrate!==void 0&&!(e.bitrate instanceof sf)&&(!Number.isInteger(e.bitrate)||e.bitrate<=0))throw TypeError(`options.audio.bitrate, when provided, must be a positive integer or a quality.`);if(e?.numberOfChannels!==void 0&&(!Number.isInteger(e.numberOfChannels)||e.numberOfChannels<=0))throw TypeError(`options.audio.numberOfChannels, when provided, must be a positive integer.`);if(e?.sampleRate!==void 0&&(!Number.isInteger(e.sampleRate)||e.sampleRate<=0))throw TypeError(`options.audio.sampleRate, when provided, must be a positive integer.`);if(e?.process!==void 0&&typeof e.process!=`function`)throw TypeError(`options.audio.process, when provided, must be a function.`);if(e?.processedNumberOfChannels!==void 0&&(!Number.isInteger(e.processedNumberOfChannels)||e.processedNumberOfChannels<=0))throw TypeError(`options.audio.processedNumberOfChannels, when provided, must be a positive integer.`);if(e?.processedSampleRate!==void 0&&(!Number.isInteger(e.processedSampleRate)||e.processedSampleRate<=0))throw TypeError(`options.audio.processedSampleRate, when provided, must be a positive integer.`)},kf=2,Af=48e3,jf=class e{static async init(t){let n=new e(t);return await n._init(),n}constructor(e){if(this._addedCounts={video:0,audio:0,subtitle:0},this._totalTrackCount=0,this._trackPromises=[],this._executed=!1,this._synchronizer=new Pf,this._totalDuration=null,this._maxTimestamps=new Map,this._canceled=!1,this.onProgress=void 0,this._computeProgress=!1,this._lastProgress=0,this.isValid=!1,this.utilizedTracks=[],this.discardedTracks=[],!e||typeof e!=`object`)throw TypeError(`options must be an object.`);if(!(e.input instanceof wl))throw TypeError(`options.input must be an Input.`);if(!(e.output instanceof Ef))throw TypeError(`options.output must be an Output.`);if(e.output._tracks.length>0||Object.keys(e.output._metadataTags).length>0||e.output.state!==`pending`)throw TypeError(`options.output must be fresh: no tracks or metadata tags added and not started.`);if(typeof e.video!=`function`&&Df(e.video),typeof e.audio!=`function`&&Of(e.audio),e.trim!==void 0&&(!e.trim||typeof e.trim!=`object`))throw TypeError(`options.trim, when provided, must be an object.`);if(e.trim?.start!==void 0&&!Number.isFinite(e.trim.start))throw TypeError(`options.trim.start, when provided, must be a finite number.`);if(e.trim?.end!==void 0&&!Number.isFinite(e.trim.end))throw TypeError(`options.trim.end, when provided, must be a finite number.`);if(e.trim?.start!==void 0&&e.trim.end!==void 0&&e.trim.start>=e.trim.end)throw TypeError(`options.trim.start must be less than options.trim.end.`);if(e.tags!==void 0&&(typeof e.tags!=`object`||!e.tags)&&typeof e.tags!=`function`)throw TypeError(`options.tags, when provided, must be an object or a function.`);if(typeof e.tags==`object`&&Ri(e.tags),e.showWarnings!==void 0&&typeof e.showWarnings!=`boolean`)throw TypeError(`options.showWarnings, when provided, must be a boolean.`);this._options=e,this.input=e.input,this.output=e.output;let{promise:t,resolve:n}=$r();this._started=t,this._start=n}async _init(){this._startTimestamp=this._options.trim?.start??Math.max(await this.input.getFirstTimestamp(),0),this._endTimestamp=Math.max(this._options.trim?.end??1/0,this._startTimestamp);let e=await this.input.getTracks(),t=this.output.format.getSupportedTrackCounts(),n=1,r=1;for(let i of e){let e;if(i.isVideoTrack()?this._options.video&&(typeof this._options.video==`function`?(e=await this._options.video(i,n),Df(e),n++):e=this._options.video):i.isAudioTrack()?this._options.audio&&(typeof this._options.audio==`function`?(e=await this._options.audio(i,r),Of(e),r++):e=this._options.audio):I(!1),e?.discard){this.discardedTracks.push({track:i,reason:`discarded_by_user`});continue}if(this._totalTrackCount===t.total.max){this.discardedTracks.push({track:i,reason:`max_track_count_reached`});continue}if(this._addedCounts[i.type]===t[i.type].max){this.discardedTracks.push({track:i,reason:`max_track_count_of_type_reached`});continue}i.isVideoTrack()?await this._processVideoTrack(i,e??{}):i.isAudioTrack()&&await this._processAudioTrack(i,e??{})}let i=await this.input.getMetadataTags(),a;if(this._options.tags){let e=typeof this._options.tags==`function`?await this._options.tags(i):this._options.tags;Ri(e),a=e}else a=i;let o=(await this.input.getFormat()).mimeType===this.output.format.mimeType,s=i.raw===a.raw;if(i.raw&&s&&!o&&delete a.raw,this.output.setMetadataTags(a),this.isValid=this._totalTrackCount>=t.total.min&&this._addedCounts.video>=t.video.min&&this._addedCounts.audio>=t.audio.min&&this._addedCounts.subtitle>=t.subtitle.min,this._options.showWarnings??!0){let e=[],t=this.discardedTracks.filter(e=>e.reason!==`discarded_by_user`);t.length>0&&e.push(`Some tracks had to be discarded from the conversion:`,t),this.isValid||e.push(`
1463
+
1464
+ `+this._getInvalidityExplanation().join(``)),e.length>0&&console.warn(...e)}}_getInvalidityExplanation(){let e=[];if(this.discardedTracks.length===0)e.push(`Due to missing tracks, this conversion cannot be executed.`);else{let t=this.discardedTracks.every(e=>e.reason===`discarded_by_user`||e.reason===`no_encodable_target_codec`);if(e.push(`Due to discarded tracks, this conversion cannot be executed.`),t){let t=this.discardedTracks.flatMap(e=>e.reason===`discarded_by_user`?[]:e.track.type===`video`?this.output.format.getSupportedVideoCodecs():e.track.type===`audio`?this.output.format.getSupportedAudioCodecs():this.output.format.getSupportedSubtitleCodecs());t.length===1?e.push(`\nTracks were discarded because your environment is not able to encode '${t[0]}'.`):e.push(`
1465
+ Tracks were discarded because your environment is not able to encode any of the following codecs: ${t.map(e=>`'${e}'`).join(`, `)}.`),t.includes(`mp3`)&&e.push(`
1466
+ The @mediabunny/mp3-encoder extension package provides support for encoding MP3.`),t.includes(`aac`)&&e.push(`
1467
+ The @mediabunny/aac-encoder extension package provides support for encoding AAC.`),(t.includes(`ac3`)||t.includes(`eac3`))&&e.push(`
1468
+ The @mediabunny/ac3 extension package provides support for encoding and decoding AC-3/E-AC-3.`),t.includes(`flac`)&&e.push(`
1469
+ The @mediabunny/flac-encoder extension package provides support for encoding FLAC.`)}else e.push(`
1470
+ Check the discardedTracks field for more info.`)}return e}async execute(){if(!this.isValid)throw Error(`Cannot execute this conversion because its output configuration is invalid. Make sure to always check the isValid field before executing a conversion.
1471
+ `+this._getInvalidityExplanation().join(``));if(this._executed)throw Error(`Conversion cannot be executed twice.`);if(this._executed=!0,this.onProgress){let e=this.utilizedTracks.map(e=>e.computeDuration()),t=Math.max(0,...await Promise.all(e));this._computeProgress=!0,this._totalDuration=Math.min(t-this._startTimestamp,this._endTimestamp-this._startTimestamp);for(let e of this.utilizedTracks)this._maxTimestamps.set(e.id,0);this.onProgress?.(0)}await this.output.start(),this._start();try{await Promise.all(this._trackPromises)}catch(e){throw this._canceled||this.cancel(),e}if(this._canceled)throw new Mf;await this.output.finalize(),this._computeProgress&&this.onProgress?.(1)}async cancel(){if(!(this.output.state===`finalizing`||this.output.state===`finalized`)){if(this._canceled){console.warn(`Conversion already canceled.`);return}this._canceled=!0,await this.output.cancel()}}async _processVideoTrack(e,t){let n=e.codec;if(!n){this.discardedTracks.push({track:e,reason:`unknown_source_codec`});return}let r,i=Nr(e.rotation+(t.rotate??0)),a=i,o=this.output.format.supportsVideoRotationMetadata&&(t.allowRotationMetadata??!0),[s,c]=i%180==0?[e.squarePixelWidth,e.squarePixelHeight]:[e.squarePixelHeight,e.squarePixelWidth],l=t.crop;l&&Uo(l,s,c);let[u,d]=l?[l.width,l.height]:[s,c],f=u,p=d,m=f/p,h=e=>Math.ceil(e/2)*2;t.width!==void 0&&t.height===void 0?(f=h(t.width),p=h(Math.round(f/m))):t.width===void 0&&t.height!==void 0?(p=h(t.height),f=h(Math.round(p*m))):t.width!==void 0&&t.height!==void 0&&(f=h(t.width),p=h(t.height));let g=await e.getFirstTimestamp(),_=this.output.format.getSupportedVideoCodecs(),v=!!t.forceTranscode||g<this._startTimestamp||!!t.frameRate||t.keyFrameInterval!==void 0||t.process!==void 0||t.bitrate!==void 0||!_.includes(n)||t.codec&&t.codec!==n||f!==u||p!==d||i!==0&&!o||!!l,y=t.alpha??`discard`;if(v){if(!await e.canDecode()){this.discardedTracks.push({track:e,reason:`undecodable_source_codec`});return}t.codec&&(_=_.filter(e=>e===t.codec));let n=t.bitrate??cf,s=await ff(_,{width:t.process&&t.processedWidth?t.processedWidth:f,height:t.process&&t.processedHeight?t.processedHeight:p,bitrate:n});if(!s){this.discardedTracks.push({track:e,reason:`no_encodable_target_codec`});return}let c={codec:s,bitrate:n,keyFrameInterval:t.keyFrameInterval,sizeChangeBehavior:t.fit??`passThrough`,alpha:y,hardwareAcceleration:t.hardwareAcceleration},m=new vf(c);r=m;let h=f!==u||p!==d||i!==0&&(!o||t.process!==void 0)||!!l||e.squarePixelWidth!==e.codedWidth||e.squarePixelHeight!==e.codedHeight;if(!h){let t=new Ef({format:new Qd,target:new Wd}),n=new vf(c);t.addVideoTrack(n),await t.start();let r=await new ds(e).getSample(g);if(r)try{await n.add(r),r.close(),await t.finalize()}catch(e){console.info(`Error when probing encoder support. Falling back to rerender path.`,e),h=!0,t.cancel()}else await t.cancel()}h?this._trackPromises.push((async()=>{await this._started;let n=new fs(e,{width:f,height:p,fit:t.fit??`fill`,rotation:i,crop:t.crop,poolSize:1,alpha:y===`keep`}).canvases(this._startTimestamp,this._endTimestamp),r=t.frameRate;a=0;let o=null,s=null,c=null,l=async n=>{I(o),I(r!==void 0);let i=Math.round((n-s)*r);for(let n=1;n<i;n++){let i=new Bo(o,{timestamp:s+n/r,duration:1/r});await this._registerVideoSample(e,t,m,i),i.close()}};for await(let{canvas:i,timestamp:a,duration:u}of n){if(this._canceled)return;let n=Math.max(a-this._startTimestamp,0);if(c=n+u,r!==void 0){let e=Math.floor(n*r)/r;if(o!==null)if(e<=s){o=i,s=e;continue}else await l(e);n=e}let d=new Bo(i,{timestamp:n,duration:r===void 0?u:1/r});await this._registerVideoSample(e,t,m,d),d.close(),r!==void 0&&(o=i,s=n)}o&&(I(c!==null),I(r!==void 0),await l(Math.floor(c*r)/r)),m.close(),this._synchronizer.closeTrack(e.id)})()):this._trackPromises.push((async()=>{await this._started;let n=new ds(e),r=t.frameRate,i=null,a=null,o=null,s=async n=>{I(i),I(r!==void 0);let o=Math.round((n-a)*r);for(let n=1;n<o;n++)i.setTimestamp(a+n/r),i.setDuration(1/r),await this._registerVideoSample(e,t,m,i);i.close()};for await(let c of n.samples(this._startTimestamp,this._endTimestamp)){if(this._canceled){c.close(),i?.close();return}let n=Math.max(c.timestamp-this._startTimestamp,0);if(o=n+c.duration,r!==void 0){let e=Math.floor(n*r)/r;if(i!==null)if(e<=a){i.close(),i=c,a=e;continue}else await s(e);n=e,c.setDuration(1/r)}c.setTimestamp(n),await this._registerVideoSample(e,t,m,c),r===void 0?c.close():(i=c,a=n)}i&&(I(o!==null),I(r!==void 0),await s(Math.floor(o*r)/r)),m.close(),this._synchronizer.closeTrack(e.id)})())}else{let t=new hf(n);r=t,this._trackPromises.push((async()=>{await this._started;let n=new as(e),r={decoderConfig:await e.getDecoderConfig()??void 0},i=Number.isFinite(this._endTimestamp)?await n.getPacket(this._endTimestamp,{metadataOnly:!0})??void 0:void 0;for await(let a of n.packets(void 0,i,{verifyKeyPackets:!0})){if(this._canceled)return;let n=a.clone({timestamp:a.timestamp-this._startTimestamp,sideData:y===`discard`?{}:a.sideData});I(n.timestamp>=0),this._reportProgress(e.id,n.timestamp),await t.add(n,r),this._synchronizer.shouldWait(e.id,n.timestamp)&&await this._synchronizer.wait(n.timestamp)}t.close(),this._synchronizer.closeTrack(e.id)})())}this.output.addVideoTrack(r,{frameRate:t.frameRate,languageCode:gi(e.languageCode)?e.languageCode:void 0,name:e.name??void 0,disposition:e.disposition,rotation:a}),this._addedCounts.video++,this._totalTrackCount++,this.utilizedTracks.push(e)}async _registerVideoSample(e,t,n,r){if(this._canceled)return;this._reportProgress(e.id,r.timestamp);let i;if(!t.process)i=[r];else{let e=t.process(r);e instanceof Promise&&(e=await e),Array.isArray(e)||(e=e===null?[]:[e]),i=e.map(e=>e instanceof Bo?e:typeof VideoFrame<`u`&&e instanceof VideoFrame?new Bo(e):new Bo(e,{timestamp:r.timestamp,duration:r.duration}))}for(let t of i){if(this._canceled)break;await n.add(t),this._synchronizer.shouldWait(e.id,t.timestamp)&&await this._synchronizer.wait(t.timestamp)}for(let e of i)e!==r&&e.close()}async _processAudioTrack(e,t){let n=e.codec;if(!n){this.discardedTracks.push({track:e,reason:`unknown_source_codec`});return}let r,i=e.numberOfChannels,a=e.sampleRate,o=await e.getFirstTimestamp(),s=t.numberOfChannels??i,c=t.sampleRate??a,l=s!==i||c!==a||o<this._startTimestamp||o>this._startTimestamp&&!this.output.format.supportsTimestampedMediaData,u=this.output.format.getSupportedAudioCodecs();if(!t.forceTranscode&&!t.bitrate&&!l&&u.includes(n)&&(!t.codec||t.codec===n)&&!t.process){let t=new bf(n);r=t,this._trackPromises.push((async()=>{await this._started;let n=new as(e),r={decoderConfig:await e.getDecoderConfig()??void 0},i=Number.isFinite(this._endTimestamp)?await n.getPacket(this._endTimestamp,{metadataOnly:!0})??void 0:void 0;for await(let a of n.packets(void 0,i)){if(this._canceled)return;let n=a.clone({timestamp:a.timestamp-this._startTimestamp});I(n.timestamp>=0),this._reportProgress(e.id,n.timestamp),await t.add(n,r),this._synchronizer.shouldWait(e.id,n.timestamp)&&await this._synchronizer.wait(n.timestamp)}t.close(),this._synchronizer.closeTrack(e.id)})())}else{if(!await e.canDecode()){this.discardedTracks.push({track:e,reason:`undecodable_source_codec`});return}let n=null;t.codec&&(u=u.filter(e=>e===t.codec));let i=t.bitrate??cf,a=await df(u,{numberOfChannels:t.process&&t.processedNumberOfChannels?t.processedNumberOfChannels:s,sampleRate:t.process&&t.processedSampleRate?t.processedSampleRate:c,bitrate:i});if(!a.some(e=>qi.includes(e))&&u.some(e=>qi.includes(e))&&(s!==kf||c!==Af)){let e=(await df(u,{numberOfChannels:kf,sampleRate:Af,bitrate:i})).find(e=>qi.includes(e));e&&(l=!0,n=e,s=kf,c=Af)}else n=a[0]??null;if(n===null){this.discardedTracks.push({track:e,reason:`no_encodable_target_codec`});return}if(l)r=this._resampleAudio(e,t,n,s,c,i);else{let a=new Sf({codec:n,bitrate:i});r=a,this._trackPromises.push((async()=>{await this._started;let n=new hs(e);for await(let r of n.samples(void 0,this._endTimestamp)){if(this._canceled){r.close();return}r.setTimestamp(r.timestamp-this._startTimestamp),await this._registerAudioSample(e,t,a,r),r.close()}a.close(),this._synchronizer.closeTrack(e.id)})())}}this.output.addAudioTrack(r,{languageCode:gi(e.languageCode)?e.languageCode:void 0,name:e.name??void 0,disposition:e.disposition}),this._addedCounts.audio++,this._totalTrackCount++,this.utilizedTracks.push(e)}async _registerAudioSample(e,t,n,r){if(this._canceled)return;this._reportProgress(e.id,r.timestamp);let i;if(!t.process)i=[r];else{let e=t.process(r);if(e instanceof Promise&&(e=await e),Array.isArray(e)||(e=e===null?[]:[e]),!e.every(e=>e instanceof Yo))throw TypeError(`The audio process function must return an AudioSample, null, or an array of AudioSamples.`);i=e}for(let t of i){if(this._canceled)break;await n.add(t),this._synchronizer.shouldWait(e.id,t.timestamp)&&await this._synchronizer.wait(t.timestamp)}for(let e of i)e!==r&&e.close()}_resampleAudio(e,t,n,r,i,a){let o=new Sf({codec:n,bitrate:a});return this._trackPromises.push((async()=>{await this._started;let n=new Ff({targetNumberOfChannels:r,targetSampleRate:i,startTime:this._startTimestamp,endTime:this._endTimestamp,onSample:async n=>{await this._registerAudioSample(e,t,o,n),n.close()}}),a=new hs(e).samples(this._startTimestamp,this._endTimestamp);for await(let e of a){if(this._canceled){e.close();return}await n.add(e),e.close()}await n.finalize(),o.close(),this._synchronizer.closeTrack(e.id)})()),o}_reportProgress(e,t){if(!this._computeProgress)return;I(this._totalDuration!==null),this._maxTimestamps.set(e,Math.max(t,this._maxTimestamps.get(e)));let n=ui(Math.min(...this._maxTimestamps.values())/this._totalDuration,0,1);n!==this._lastProgress&&(this._lastProgress=n,this.onProgress?.(n))}},Mf=class extends Error{constructor(e=`Conversion has been canceled.`){super(e),this.name=`ConversionCanceledError`}},Nf=5,Pf=class{constructor(){this.maxTimestamps=new Map,this.resolvers=[]}computeMinAndMaybeResolve(){let e=1/0;for(let[,t]of this.maxTimestamps)e=Math.min(e,t);for(let t=0;t<this.resolvers.length;t++){let n=this.resolvers[t];n.timestamp-e<Nf&&(n.resolve(),this.resolvers.splice(t,1),t--)}return e}shouldWait(e,t){return this.maxTimestamps.set(e,Math.max(t,this.maxTimestamps.get(e)??-1/0)),t-this.computeMinAndMaybeResolve()>=Nf}wait(e){let{promise:t,resolve:n}=$r();return this.resolvers.push({timestamp:e,resolve:n}),t}closeTrack(e){this.maxTimestamps.delete(e),this.computeMinAndMaybeResolve()}},Ff=class{constructor(e){this.sourceSampleRate=null,this.sourceNumberOfChannels=null,this.targetSampleRate=e.targetSampleRate,this.targetNumberOfChannels=e.targetNumberOfChannels,this.startTime=e.startTime,this.endTime=e.endTime,this.onSample=e.onSample,this.bufferSizeInFrames=Math.floor(this.targetSampleRate*5),this.bufferSizeInSamples=this.bufferSizeInFrames*this.targetNumberOfChannels,this.outputBuffer=new Float32Array(this.bufferSizeInSamples),this.bufferStartFrame=0,this.maxWrittenFrame=-1}doChannelMixerSetup(){I(this.sourceNumberOfChannels!==null);let e=this.sourceNumberOfChannels,t=this.targetNumberOfChannels;e===1&&t===2?this.channelMixer=(t,n)=>t[n*e]:e===1&&t===4?this.channelMixer=(t,n,r)=>t[n*e]*+(r<2):e===1&&t===6?this.channelMixer=(t,n,r)=>t[n*e]*+(r===2):e===2&&t===1?this.channelMixer=(t,n)=>{let r=n*e;return .5*(t[r]+t[r+1])}:e===2&&t===4||e===2&&t===6?this.channelMixer=(t,n,r)=>t[n*e+r]*+(r<2):e===4&&t===1?this.channelMixer=(t,n)=>{let r=n*e;return .25*(t[r]+t[r+1]+t[r+2]+t[r+3])}:e===4&&t===2?this.channelMixer=(t,n,r)=>{let i=n*e;return .5*(t[i+r]+t[i+r+2])}:e===4&&t===6?this.channelMixer=(t,n,r)=>{let i=n*e;return r<2?t[i+r]:r===2||r===3?0:t[i+r-2]}:e===6&&t===1?this.channelMixer=(t,n)=>{let r=n*e;return Math.SQRT1_2*(t[r]+t[r+1])+t[r+2]+.5*(t[r+4]+t[r+5])}:e===6&&t===2?this.channelMixer=(t,n,r)=>{let i=n*e;return t[i+r]+Math.SQRT1_2*(t[i+2]+t[i+r+4])}:e===6&&t===4?this.channelMixer=(t,n,r)=>{let i=n*e;return r<2?t[i+r]+Math.SQRT1_2*t[i+2]:t[i+r+2]}:this.channelMixer=(t,n,r)=>r<e?t[n*e+r]:0}ensureTempBufferSize(e){let t=this.tempSourceBuffer.length;for(;t<e;)t*=2;if(t!==this.tempSourceBuffer.length){let e=new Float32Array(t);e.set(this.tempSourceBuffer),this.tempSourceBuffer=e}}async add(e){this.sourceSampleRate===null&&(this.sourceSampleRate=e.sampleRate,this.sourceNumberOfChannels=e.numberOfChannels,this.tempSourceBuffer=new Float32Array(this.sourceSampleRate*this.sourceNumberOfChannels),this.doChannelMixerSetup());let t=e.numberOfFrames*e.numberOfChannels;this.ensureTempBufferSize(t);let n=e.allocationSize({planeIndex:0,format:`f32`}),r=new Float32Array(this.tempSourceBuffer.buffer,0,n/4);e.copyTo(r,{planeIndex:0,format:`f32`});let i=e.timestamp-this.startTime,a=e.numberOfFrames/this.sourceSampleRate,o=Math.min(i+a,this.endTime-this.startTime),s=Math.floor(i*this.targetSampleRate),c=Math.ceil(o*this.targetSampleRate);for(let t=s;t<c;t++){if(t<this.bufferStartFrame)continue;for(;t>=this.bufferStartFrame+this.bufferSizeInFrames;)await this.finalizeCurrentBuffer(),this.bufferStartFrame+=this.bufferSizeInFrames;let n=t-this.bufferStartFrame;I(n<this.bufferSizeInFrames);let a=(t/this.targetSampleRate-i)*this.sourceSampleRate,o=Math.floor(a),s=Math.ceil(a),c=a-o;for(let t=0;t<this.targetNumberOfChannels;t++){let i=0,a=0;o>=0&&o<e.numberOfFrames&&(i=this.channelMixer(r,o,t)),s>=0&&s<e.numberOfFrames&&(a=this.channelMixer(r,s,t));let l=i+c*(a-i),u=n*this.targetNumberOfChannels+t;this.outputBuffer[u]+=l}this.maxWrittenFrame=Math.max(this.maxWrittenFrame,n)}}async finalizeCurrentBuffer(){if(this.maxWrittenFrame<0)return;let e=(this.maxWrittenFrame+1)*this.targetNumberOfChannels,t=new Float32Array(e);t.set(this.outputBuffer.subarray(0,e));let n=this.bufferStartFrame/this.targetSampleRate,r=new Yo({format:`f32`,sampleRate:this.targetSampleRate,numberOfChannels:this.targetNumberOfChannels,timestamp:n,data:t});await this.onSample(r),this.outputBuffer.fill(0),this.maxWrittenFrame=-1}finalize(){return this.finalizeCurrentBuffer()}};function If(){return typeof AudioEncoder<`u`}async function Lf(e,t){let n=new wl({source:new bl(e),formats:vl}),r=new Ud,i=new Ef({format:new Qd({fastStart:`in-memory`}),target:r});try{let a=await jf.init({input:n,output:i,video:{discard:!0},audio:{codec:`aac`,bitrate:cf}});t&&(a.onProgress=t),await a.execute();let o=r.buffer;if(!o)throw Error(`Audio processing produced no output`);let s=e.name.replace(/\.[^.]+$/,``);return{file:new File([o],`${s}.m4a`,{type:`audio/mp4`})}}finally{n.dispose()}}var Rf={isSupported:If,processToFile:Lf},zf=1920,Bf=1080,Vf=640,Hf=32;function Uf(){return typeof VideoEncoder<`u`}async function Wf(e){let t=new wl({source:new bl(e),formats:vl});try{let e=await t.getPrimaryVideoTrack();if(!e)return{};let n=e.displayWidth,r=e.displayHeight,i=await t.computeDuration(),a=Math.min(i*.1,3),o=await new fs(e).getCanvas(a);if(!o)return{sourceWidth:n,sourceHeight:r};let s=o.canvas,c=s.width,l=s.height,u=Math.min(Vf/c,1),d=Math.round(c*u),p=Math.round(l*u),m=document.createElement(`canvas`);m.width=d,m.height=p;let h=m.getContext(`2d`);if(!h)return{sourceWidth:n,sourceHeight:r};h.drawImage(s,0,0,d,p);let g=await new Promise(e=>{m.toBlob(t=>e(t??void 0),`image/webp`,.8)}),_=Math.min(Hf/c,Hf/l,1),v=Math.max(Math.round(c*_),1),y=Math.max(Math.round(l*_),1),b=document.createElement(`canvas`);b.width=v,b.height=y;let x=b.getContext(`2d`);return x?(x.drawImage(s,0,0,v,y),{poster:g,blurhash:f(x.getImageData(0,0,v,y).data,v,y,4,3),sourceWidth:n,sourceHeight:r}):{poster:g,sourceWidth:n,sourceHeight:r}}catch{return{}}finally{t.dispose()}}async function Gf(e,t){let{poster:n,blurhash:r,sourceWidth:i,sourceHeight:a}=await Wf(e),o=zf,s=Bf;if(i&&a){let e=Math.min(zf/i,Bf/a,1);o=Math.round(i*e),s=Math.round(a*e)}o+=o%2,s+=s%2;let c=new wl({source:new bl(e),formats:vl}),l=new Ud,u=new Ef({format:new Qd({fastStart:`in-memory`}),target:l});try{let i=await jf.init({input:c,output:u,video:{codec:`avc`,width:o,height:s,fit:`contain`,bitrate:cf},audio:{codec:`aac`}});t&&(i.onProgress=t),await i.execute();let a=l.buffer;if(!a)throw Error(`Video processing produced no output`);let d=e.name.replace(/\.[^.]+$/,``);return{file:new File([a],`${d}.mp4`,{type:`video/mp4`}),width:o,height:s,poster:n,blurhash:r}}finally{c.dispose()}}var Kf={isSupported:Uf,processToFile:Gf};function qf(){return document.querySelector(`jant-compose-dialog`)}function Jf(){return document.querySelector(`[data-page='collection'][data-collection-id]`)?.dataset.collectionId||void 0}function Yf(e=document){return e.querySelector(`[data-post-current] article[data-post]`)||e.querySelector(`[data-post-view] article[data-post]`)}function Xf(e){let t=e.closest(`[data-post-view]`)?.dataset.postViewId;if(t)return{kind:`post-view`,id:t};let n=e.closest(`[data-page]`)?.dataset.page,r=e.dataset.threadRootId??e.dataset.postId;if(n===`home`&&r)return{kind:`timeline-item`,id:r};let i=e.dataset.postId;return i?{kind:`post-card`,id:i}:null}function Zf(e){let t=e.cloneNode(!0);t.querySelector(`[data-post-meta]`)?.remove(),t.querySelector(`.post-status-badges`)?.remove();let n=e.querySelector(`time.dt-published`);return{contentHtml:t.innerHTML,dateText:n?.textContent?.trim()??``}}async function Qf(e){await qf()?.openNew(e)}async function $f(e){let t=e.dataset.postId;if(!t)return;let n=qf();if(!n)return;let r=e.dataset.threadRootId??t;await n.openReply(t,Zf(e),r,Xf(e)??void 0)}function ep(e){try{let t=JSON.parse(e);return t.type===`doc`?tp(t.content??[]).trimEnd():``}catch{return``}}function tp(e,t=``){let n=[];for(let r of e){let e=np(r,t);e!==null&&n.push(e)}return n.join(`
1472
+
1473
+ `)}function np(e,n){switch(e.type){case`paragraph`:return n+op(e.content??[]);case`heading`:{let t=Math.min(Math.max(Number(e.attrs?.level??1),1),6);return`${n}${`#`.repeat(t)} ${op(e.content??[])}`}case`bulletList`:return ip(e.content??[],n,`bullet`);case`orderedList`:{let t=Number(e.attrs?.start??1);return ip(e.content??[],n,`ordered`,t)}case`blockquote`:return tp(e.content??[]).split(`
1474
+ `).map(e=>n+(e?`> ${e}`:`>`)).join(`
1475
+ `);case`codeBlock`:{let t=e.attrs?.language?String(e.attrs.language):``,r=lp(e.content??[]),i=up(r);return`${n}${i}${t}\n${r}\n${n}${i}`}case`table`:return ap(e.content??[],n);case`horizontalRule`:return`${n}---`;case`hardBreak`:return null;case`image`:{let r=String(e.attrs?.src??``),i=e.attrs?.alt?String(e.attrs.alt):``,a=e.attrs?.title?String(e.attrs.title):``,o=e.attrs?.caption?String(e.attrs.caption):``,s=e.attrs?.layout&&String(e.attrs.layout)!==`regular`?String(e.attrs.layout):``,c=e.attrs?.href?t(String(e.attrs.href)):``;return o||s||c?`${n}${rp({src:r,alt:i,title:a,caption:o,href:c,layout:s})}`:`${n}![${i}](${r}${a?` "${a}"`:``})`}case`moreBreak`:return`${n}<!--more-->`;default:return e.content?tp(e.content,n):null}}function rp(e){let t=[`data-jant-node="image"`];e.layout&&t.push(`data-jant-layout="${g(e.layout)}"`);let n=[`src="${g(e.src)}"`];e.alt&&n.push(`alt="${g(e.alt)}"`),e.title&&n.push(`title="${g(e.title)}"`);let r=`<img ${n.join(` `)}>`,i=e.href?`<a href="${g(e.href)}">${r}</a>`:r,a=e.caption?`<figcaption>${g(e.caption)}</figcaption>`:``;return`<figure ${t.join(` `)}>${i}${a}</figure>`}function ip(e,t,n,r=1){let i=[];for(let a=0;a<e.length;a++){let o=e[a],s=n===`bullet`?`-`:`${(r+a).toString()}.`,c=o.content??[];for(let e=0;e<c.length;e++){let n=c[e];if(e===0)if(n.type===`bulletList`||n.type===`orderedList`){let e=np(n,t+` `);e!==null&&i.push(`${t}${s} \n${e}`)}else{let e=op(n.content??[]);i.push(`${t}${s} ${e}`)}else{let e=t+` `.repeat(s.length+1);if(n.type===`bulletList`||n.type===`orderedList`){let t=np(n,e);t!==null&&i.push(t)}else if(n.type===`paragraph`){let t=op(n.content??[]);i.push(``),i.push(`${e}${t}`)}else{let t=np(n,e);t!==null&&(i.push(``),i.push(t))}}}}return i.join(`
1476
+ `)}function ap(e,t){if(e.length===0)return``;let n=[];for(let t of e){let e=[];for(let n of t.content??[]){let t=[];for(let e of n.content??[])t.push(op(e.content??[]));e.push(t.join(` `))}n.push(e)}let r=Math.max(...n.map(e=>e.length)),i=[];for(let e=0;e<r;e++)i.push(Math.max(3,...n.map(t=>(t[e]??``).length)));let a=[],o=n[0]??[];a.push(t+`| `+i.map((e,t)=>(o[t]??``).padEnd(e)).join(` | `)+` |`),a.push(t+`| `+i.map(e=>`-`.repeat(e)).join(` | `)+` |`);for(let e=1;e<n.length;e++){let r=n[e];a.push(t+`| `+i.map((e,t)=>(r[t]??``).padEnd(e)).join(` | `)+` |`)}return a.join(`
1477
+ `)}function op(e){return e.map(sp).join(``)}function sp(e){switch(e.type){case`text`:{let t=e.text??``;return e.marks&&e.marks.length>0&&(t=cp(t,e.marks)),t}case`hardBreak`:return`
1478
+ `;case`image`:{let t=String(e.attrs?.src??``),n=e.attrs?.alt?String(e.attrs.alt):``,r=e.attrs?.title?String(e.attrs.title):``;return`![${n}](${t}${r?` "${r}"`:``})`}default:return e.content?op(e.content):``}}function cp(e,t){let n=e;for(let e of t)switch(e.type){case`bold`:n=`**${n}**`;break;case`italic`:n=`*${n}*`;break;case`strike`:n=`~~${n}~~`;break;case`code`:n=`\`${n}\``;break;case`link`:{let t=String(e.attrs?.href??``);n=`[${n}](${t})`;break}}return n}function lp(e){return e.map(e=>e.text??``).join(``)}function up(e){let t=3,n=/(`{3,})/g,r;for(;(r=n.exec(e))!==null;){let e=r[1]??``;e.length>=t&&(t=e.length+1)}return"`".repeat(t)}function dp(e){return e instanceof globalThis.Element?e.closest(`jant-compose-editor`):null}function fp(e){return e instanceof globalThis.Element?e.closest(`jant-compose-dialog`):null}async function pp(e){let t=await fetch(e,{headers:{Accept:`text/html`}});return t.ok?t.text():null}async function mp(e){try{let t=document.querySelector(`[data-timeline-item][data-thread-root-id="${e}"]`)?.querySelector(`[data-timeline-item-content]`);if(!t)return!1;let n=await pp(`/_/timeline-item/${encodeURIComponent(e)}`);return n?(t.innerHTML=n,ee(t),!0):!1}catch{return!1}}async function hp(e){try{let t=document.querySelector(`article[data-post-id="${e}"]`)?.closest(`[data-timeline-item]`),n=await pp(`/_/post-card/${encodeURIComponent(e)}`);if(!n)return!1;if(t){let e=t.querySelector(`[data-timeline-item-content]`);return e?(e.innerHTML=n,ee(e),!0):!1}let r=document.querySelector(`article[data-post-id="${e}"]`);if(!r)return!1;r.outerHTML=n;let i=document.querySelector(`article[data-post-id="${e}"]`);return i&&ee(i),!0}catch{return!1}}async function gp(e){try{let t=document.querySelector(`[data-post-view][data-post-view-id="${e}"]`);if(!t)return!1;let n=await pp(`/_/post-view/${encodeURIComponent(e)}`);if(!n)return!1;t.outerHTML=n;let r=document.querySelector(`[data-post-view][data-post-view-id="${e}"]`);return r&&ee(r),!0}catch{return!1}}async function _p(e){return!e.replyRefreshKind||!e.replyRefreshId?!1:e.replyRefreshKind===`timeline-item`?mp(e.replyThreadRootId??e.replyRefreshId):e.replyRefreshKind===`post-view`?gp(e.replyRefreshId):hp(e.replyRefreshId)}var vp=new Map,yp=new Set;async function bp(e,t,n){try{let r,i,a,o,s,c;if(e.type.startsWith(`video/`)){if(!Kf.isSupported())return n?.updateAttachmentStatus(t,`error`,null,`Your browser doesn't support video processing. Use Chrome or Edge to upload videos.`),null;n?.updateAttachmentStatus(t,`processing`,null,null);let s=await Kf.processToFile(e,e=>{n?.updateAttachmentProgress(t,e)});r=s.file,i=s.width,a=s.height,o=s.blurhash,c=s.poster}else if(e.type.startsWith(`audio/`)){if(!Rf.isSupported())return n?.updateAttachmentStatus(t,`error`,null,`Your browser doesn't support audio processing. Use Chrome or Edge to upload audio.`),null;try{s=await _(e)}catch{}n?.updateAttachmentStatus(t,`processing`,null,null),r=(await Rf.processToFile(e,e=>{n?.updateAttachmentProgress(t,e)})).file}else if(e.type.startsWith(`image/`)||/\.heic$/i.test(e.name)||/\.heif$/i.test(e.name)){let o=e;try{let{isHeic:s,heicTo:c}=await Dr(async()=>{let{isHeic:e,heicTo:t}=await import(`./chunks/heic-to-XcUDQvtx.js`);return{isHeic:e,heicTo:t}},[]);if(await s(e)){n?.updateAttachmentStatus(t,`processing`,null,null);let r=await c({blob:e,type:`image/jpeg`,quality:.92});o=new File([r],e.name.replace(/\.heic$/i,`.jpg`),{type:`image/jpeg`}),n?.updateAttachmentPreview(t,o)}let l=await p.processToFile(o);r=l.file,i=l.width,a=l.height}catch{return n?.removeAttachment(t),m(`Image format not supported.`,`error`),null}}else r=e;if(n?.updateAttachmentStatus(t,`uploading`,null,null),!e.type.startsWith(`video/`)){let e=await te(r);i??=e.width,a??=e.height,o??=e.blurhash,s??=e.waveform,c??=e.poster}let u,d;if(Ne(e.type)===`text`&&e.type!==`text/x-tiptap+json`)try{let e=await r.text(),t=e.replace(/\s+/g,` `).trim();d=e.length,u=t.length<=100?t:t.slice(0,100)+`…`}catch{}else if(e.type===`text/x-tiptap+json`)try{d=xp(await r.text())}catch{}let f=await l(r,{width:i,height:a,blurhash:o,waveform:s,poster:c,summary:u,chars:d},e=>{n?.updateAttachmentProgress(t,e)});return n?.updateAttachmentStatus(t,`done`,f.id,null),f.id}catch(e){let r=e instanceof Error?e.message:`Upload failed`;return n?.updateAttachmentStatus(t,`error`,null,r),m(r,`error`),null}}function xp(e){let t=JSON.parse(e);if(!t.json)return;let n=``,r=e=>{if(typeof e.text==`string`&&(n+=e.text),Array.isArray(e.content))for(let t of e.content)t&&typeof t==`object`&&r(t)};return r(t.json),n.length}document.addEventListener(`jant:attachment-removed`,e=>{let{clientId:t,mediaId:n}=e.detail;n?fetch(`/api/upload/${n}`,{method:`DELETE`}).catch(()=>{}):yp.add(t)}),document.addEventListener(`jant:files-selected`,e=>{let t=e,n=dp(t.target);for(let{file:e,clientId:r}of t.detail.files){let t=bp(e,r,n).then(e=>yp.has(r)?(yp.delete(r),e&&fetch(`/api/upload/${e}`,{method:`DELETE`}).catch(()=>{}),null):e);vp.set(r,t),t.finally(()=>vp.delete(r))}}),document.addEventListener(`click`,e=>{let t=e.target.closest(`[data-reply-trigger]`);if(!t)return;let n=t.closest(`article[data-post]`);n&&$f(n)});function Sp(e,t){let n=e.format===`quote`,r=e.format===`link`;return{format:e.format,title:n?void 0:e.title||void 0,body:e.body||void 0,url:r&&e.url||void 0,sourceName:n&&e.quoteAuthor||void 0,sourceUrl:n&&e.url||void 0,quoteText:e.quoteText||void 0,slug:e.slug||void 0,status:e.status,visibility:e.visibility||void 0,rating:e.rating||void 0,collectionIds:e.collectionIds,attachments:t.length>0?t:void 0,replyToId:e.replyToId||void 0}}function Cp(e){return JSON.stringify(e.bodyJson)!==JSON.stringify(e.originalBodyJson??null)}function wp(e,t){let n=[];for(let r of e.attachments){if(r.type===`media`){let e=r.mediaId??t.get(r.clientId);if(!e)continue;n.push({type:`media`,mediaId:e,alt:r.alt});continue}if(r.mediaId&&!Cp(r)){n.push({type:`media`,mediaId:r.mediaId});continue}n.push({type:`text`,contentFormat:`markdown`,content:ep(JSON.stringify(r.bodyJson)),summary:r.summary})}return n}document.addEventListener(`jant:compose-submit-deferred`,async e=>{let t=e,n=t.detail,r=fp(t.target)??document.querySelector(`jant-compose-dialog`),i=!!r?.pageMode,o=r?.labels,s=o?.uploading??`Uploading...`,c=n.pendingAttachments.length>0,l=o?.published??`Published!`,u=o?.view??`View`;c&&h(`compose-deferred`,s);let f=(e,t=`success`)=>{c?v(`compose-deferred`,e,t):m(e,t)},p=()=>{!i||!r||(r.reset(),r.updateComplete.then(()=>{r.querySelector(`jant-compose-editor`)?.focusInput()}))},g=()=>{!i||!r||(r.loading=!1)},_=async()=>{await r?.refreshCollections()},y=(e,t)=>{x(e,`success`,t)},b=()=>!i||!r||!r.consumePageLeaveRequest()?!1:(r.preparePageLeave(),globalThis.location.assign(r.closeHref||a(`/`)),!0),S=!!n.editPostId,ee=null;try{let e=n.pendingAttachments.map(e=>e.clientId),t=e.map(e=>vp.get(e)).filter(e=>e!==void 0),a=await Promise.all(t);if(a.filter(e=>e===null).length>0)if(n.status===`published`&&!S)ee=`upload`;else{g(),f(`Upload failed. Post not created.`,`error`);return}let s=new Map;for(let t of n.pendingAttachments){let n=a[e.indexOf(t.clientId)];n&&s.set(t.clientId,n)}let c=wp(n,s),m=S?`/api/posts/${n.editPostId}`:`/compose`,h=S?`PUT`:`POST`,v=Sp({...n,status:ee?`draft`:n.status},c),x=await fetch(m,{method:h,headers:{"Content-Type":`application/json`,Accept:`application/json`},body:JSON.stringify(v)});if(!x.ok){if(n.status===`published`&&!S&&!ee){let e={...v,status:`draft`},t=await fetch(m,{method:h,headers:{"Content-Type":`application/json`,Accept:`application/json`},body:JSON.stringify(e)});if(t.ok){ee=`server`;let e=await d(t),n=o?.publishFailedDraft??`Couldn't publish. Saved as draft.`;await _(),b()||p(),f(n);let r=C(e,`toast`);r&&f(r);return}}let e=await d(x);g(),f(C(e,`error`)??`Something went wrong`,`error`);return}if(S){y(`Post updated.`),i?globalThis.location.assign(globalThis.location.pathname):globalThis.location.reload();return}if(ee===`upload`){let e=o?.uploadFailedDraft??`Some uploads failed. Saved as draft.`;await _(),p(),f(e);return}let te=await d(x),ne=C(te,`status`),re=C(te,`permalink`),ie=C(te,`toast`);if(ne===`published`){if(i&&re)y(l),r?.preparePageLeave?.(),globalThis.location.assign(re);else if(n.replyToId){if(await _(),!await _p(n)){y(l,re?{label:u,href:re}:void 0),globalThis.location.reload();return}f(l)}else y(l,re?{label:u,href:re}:void 0),globalThis.location.reload();return}else await _(),b()||p(),f(ie??`Draft saved.`)}catch{g(),f(`Something went wrong`,`error`)}});var Tp=`.compose-prompt`,Ep=`.compose-prompt-trigger`,Dp=`jant.composeOpenShortcutDiscovery`,Op=`/api/settings/discovery/compose-open-shortcut`,kp=350,Ap=1800,jp=3,Mp=`compose-prompt-discovery-visible`,Np=!1,Pp=null,Fp=null,Ip=null;function Lp(){try{return globalThis.localStorage!==void 0}catch{return!1}}function Rp(){if(!Lp())return{shownCount:0,completed:!1};let e=globalThis.localStorage.getItem(Dp);if(!e)return{shownCount:0,completed:!1};try{let t=JSON.parse(e);return{shownCount:typeof t.shownCount==`number`&&t.shownCount>=0?t.shownCount:0,completed:t.completed===!0}}catch{return globalThis.localStorage.removeItem(Dp),{shownCount:0,completed:!1}}}function zp(e){if(Lp())try{globalThis.localStorage.setItem(Dp,JSON.stringify(e))}catch{}}function Bp(){Pp!==null&&(clearTimeout(Pp),Pp=null)}function Vp(){Fp!==null&&(clearTimeout(Fp),Fp=null)}function Hp(){return typeof globalThis.matchMedia==`function`&&globalThis.matchMedia(`(min-width: 700px)`).matches}function Up(e){return Rp().completed?!0:e?.dataset.composeOpenShortcutDiscovered===`true`}function Wp(e){e&&(e.dataset.composeOpenShortcutDiscovered=`true`,e.classList.remove(Mp)),document.querySelectorAll(Tp).forEach(e=>{e.dataset.composeOpenShortcutDiscovered=`true`,e.classList.remove(Mp)})}function Gp(){let e=Rp();e.completed||Np||e.shownCount>=jp||(Np=!0,zp({...e,shownCount:e.shownCount+1}))}function Kp(e){return!Hp()||Up(e)?!1:Rp().shownCount<jp||Np}function qp(e){Bp(),Vp(),e?e.classList.remove(Mp):Ip&&Ip.classList.remove(Mp),(!e||e===Ip)&&(Ip=null)}function Jp(e){Kp(e)&&(qp(Ip),Ip=e,e.classList.add(Mp),Gp(),Fp=setTimeout(()=>{qp(e)},Ap))}function Yp(e){Kp(e)&&(e.classList.contains(Mp)||(Bp(),Pp=setTimeout(()=>{Jp(e)},kp)))}function Xp(e){if(e.dataset.composeOpenShortcutDiscoveryBound===`true`)return;let t=e.querySelector(Ep);t&&(e.dataset.composeOpenShortcutDiscoveryBound=`true`,t.addEventListener(`pointerenter`,()=>{Yp(e)}),t.addEventListener(`pointerleave`,()=>{qp(e)}),t.addEventListener(`focusin`,()=>{Yp(e)}),t.addEventListener(`focusout`,()=>{qp(e)}))}function Zp(e=document){e.querySelectorAll(Tp).forEach(e=>Xp(e))}function Qp(){let e=Rp();e.completed||zp({shownCount:Math.max(e.shownCount,jp),completed:!0}),Wp(Ip),qp(Ip),typeof globalThis.fetch==`function`&&globalThis.fetch(Op,{method:`POST`,headers:{Accept:`application/json`},credentials:`same-origin`}).catch(()=>{})}document.readyState===`loading`?document.addEventListener(`DOMContentLoaded`,()=>{Zp()}):Zp();var $p=[`input`,`textarea`,`select`,`button`,`a[href]`,`[contenteditable='']`,`[contenteditable='true']`,`[role='textbox']`,`.ProseMirror`].join(`, `);function em(e){return e instanceof globalThis.Element&&e.closest($p)!==null}function tm(e){if(e.defaultPrevented||e.isComposing||e.repeat||e.metaKey||e.ctrlKey||e.altKey||!qf()||document.querySelector(`[data-page="compose"]`)||document.querySelector(`dialog[open]`))return!0;let t=document.activeElement;return em(e.target)||t!==e.target&&em(t)}document.addEventListener(`keydown`,e=>{let t=e.key.toLowerCase();if(t!==`n`&&t!==`r`||tm(e))return;if(t===`n`){e.preventDefault(),Qp();let t=Jf();Qf(t?{collectionId:t}:void 0);return}let n=Yf();n&&(e.preventDefault(),$f(n))});var nm=class extends o{static properties={labels:{type:Object},timezones:{type:Array},languages:{type:Array},siteNameFallback:{type:String,attribute:`sitename-fallback`},siteDescriptionFallback:{type:String,attribute:`sitedescription-fallback`},demoMode:{type:Boolean,attribute:`demo-mode`},mainFeedUrl:{type:String,attribute:`main-feed-url`},latestFeedUrl:{type:String,attribute:`latest-feed-url`},featuredFeedUrl:{type:String,attribute:`featured-feed-url`},_siteName:{state:!0},_siteDescription:{state:!0},_siteFooter:{state:!0},_origSite:{state:!0},_siteDirty:{state:!0},_siteLoading:{state:!0},_siteLanguage:{state:!0},_timeZone:{state:!0},_origLocale:{state:!0},_localeDirty:{state:!0},_localeLoading:{state:!0},_mainRssFeed:{state:!0},_origMainRssFeed:{state:!0},_feedDirty:{state:!0},_feedLoading:{state:!0},_showJantBrandingOnHome:{state:!0},_origShowJantBrandingOnHome:{state:!0},_homeLoading:{state:!0},_noindex:{state:!0},_origNoindex:{state:!0},_searchLoading:{state:!0}};createRenderRoot(){return this.innerHTML=``,this}constructor(){super(),this.labels={},this.timezones=[],this.languages=[],this.siteNameFallback=``,this.siteDescriptionFallback=``,this.demoMode=!1,this.mainFeedUrl=`/feed`,this.latestFeedUrl=`/feed/latest`,this.featuredFeedUrl=`/feed/featured`,this._siteName=``,this._siteDescription=``,this._siteFooter=``,this._origSite={siteName:``,siteDescription:``,siteFooter:``},this._siteDirty=!1,this._siteLoading=!1,this._siteLanguage=`en`,this._timeZone=`UTC`,this._origLocale={siteLanguage:`en`,timeZone:`UTC`},this._localeDirty=!1,this._localeLoading=!1,this._mainRssFeed=`featured`,this._origMainRssFeed=`featured`,this._feedDirty=!1,this._feedLoading=!1,this._noindex=!1,this._origNoindex=!1,this._showJantBrandingOnHome=!1,this._origShowJantBrandingOnHome=!1,this._homeLoading=!1,this._searchLoading=!1}initData(e){this._siteName=e.siteName,this._siteDescription=e.siteDescription,this._siteFooter=e.siteFooter,this._origSite={siteName:e.siteName,siteDescription:e.siteDescription,siteFooter:e.siteFooter},this._siteLanguage=e.siteLanguage,this._timeZone=e.timeZone,this._origLocale={siteLanguage:e.siteLanguage,timeZone:e.timeZone},this._mainRssFeed=e.mainRssFeed,this._origMainRssFeed=e.mainRssFeed,this._showJantBrandingOnHome=e.showJantBrandingOnHome,this._origShowJantBrandingOnHome=e.showJantBrandingOnHome,this._noindex=e.noindex,this._origNoindex=e.noindex}sectionSaved(e){e===`site`?(this._origSite={siteName:this._siteName,siteDescription:this._siteDescription,siteFooter:this._siteFooter},this._siteDirty=!1,this._siteLoading=!1):e===`language-time`?(this._origLocale={siteLanguage:this._siteLanguage,timeZone:this._timeZone},this._localeDirty=!1,this._localeLoading=!1):e===`feeds`?(this._origMainRssFeed=this._mainRssFeed,this._feedDirty=!1,this._feedLoading=!1):e===`home`?(this._origShowJantBrandingOnHome=this._showJantBrandingOnHome,this._homeLoading=!1):e===`search`&&(this._origNoindex=this._noindex,this._searchLoading=!1)}sectionError(e){e===`site`?this._siteLoading=!1:e===`language-time`?this._localeLoading=!1:e===`feeds`?this._feedLoading=!1:e===`home`?(this._showJantBrandingOnHome=this._origShowJantBrandingOnHome,this._homeLoading=!1):e===`search`&&(this._noindex=this._origNoindex,this._searchLoading=!1)}_syncSiteDirty(){this._siteDirty=this._siteName!==this._origSite.siteName||this._siteDescription!==this._origSite.siteDescription||this._siteFooter!==this._origSite.siteFooter}_saveSite(){this._siteLoading||!this._siteDirty||(this._siteLoading=!0,this.dispatchEvent(new CustomEvent(`jant:settings-save`,{bubbles:!0,detail:{endpoint:`/settings/general`,data:{siteName:this._siteName,siteDescription:this._siteDescription,siteFooter:this._siteFooter},section:`site`}})))}_syncLocaleDirty(){this._localeDirty=this._siteLanguage!==this._origLocale.siteLanguage||this._timeZone!==this._origLocale.timeZone}_saveLocale(){this._localeLoading||!this._localeDirty||(this._localeLoading=!0,this.dispatchEvent(new CustomEvent(`jant:settings-save`,{bubbles:!0,detail:{endpoint:`/settings/general/language-time`,data:{siteLanguage:this._siteLanguage,timeZone:this._timeZone},section:`language-time`}})))}_syncFeedDirty(){this._feedDirty=this._mainRssFeed!==this._origMainRssFeed}_saveFeeds(){this._feedLoading||!this._feedDirty||(this._feedLoading=!0,this.dispatchEvent(new CustomEvent(`jant:settings-save`,{bubbles:!0,detail:{endpoint:`/settings/general/feeds`,data:{mainRssFeed:this._mainRssFeed},section:`feeds`}})))}_saveHomeToggle(e){this._homeLoading||(this._showJantBrandingOnHome=e,this._homeLoading=!0,this.dispatchEvent(new CustomEvent(`jant:settings-save`,{bubbles:!0,detail:{endpoint:`/settings/general/home`,data:{showJantBrandingOnHome:e},section:`home`}})))}_saveSearchToggle(e){this.demoMode||this._searchLoading||(this._noindex=!e,this._searchLoading=!0,this.dispatchEvent(new CustomEvent(`jant:settings-save`,{bubbles:!0,detail:{endpoint:`/settings/general/search`,data:{allowIndexing:e},section:`search`}})))}_onKeydown(e,t,n,r){e.key===`Enter`&&!r&&n&&!(e.target instanceof HTMLTextAreaElement)&&(e.preventDefault(),t())}_renderSaveAction(e,t,n){return s`
1479
+ <div class="flex mt-4">
1480
+ <button
1481
+ type="button"
1482
+ class="btn"
1483
+ ?disabled=${e||!t}
1484
+ @click=${n}
1485
+ >
1486
+ ${e?s`<svg
1487
+ class="animate-spin size-4"
1488
+ xmlns="http://www.w3.org/2000/svg"
1489
+ viewBox="0 0 24 24"
1490
+ fill="none"
1491
+ stroke="currentColor"
1492
+ stroke-width="2"
1493
+ stroke-linecap="round"
1494
+ stroke-linejoin="round"
1495
+ role="status"
1496
+ >
1497
+ <path d="M21 12a9 9 0 1 1-6.219-8.56" />
1498
+ </svg>`:i}
1499
+ ${this.labels.save}
1500
+ </button>
1501
+ </div>
1502
+ `}_renderSectionTitle(e){return s`<h3 class="text-sm font-semibold tracking-[0.01em]">
1503
+ ${e}
1504
+ </h3>`}_renderMainRssFeedOption(e,t,n){let r=this._mainRssFeed===e;return s`
1505
+ <label
1506
+ class=${`flex items-start gap-3 rounded-xl border p-3 cursor-pointer transition-colors ${r?`border-primary`:`border-border`}`}
1507
+ >
1508
+ <input
1509
+ type="radio"
1510
+ name="main-rss-feed"
1511
+ value=${e}
1512
+ class="mt-1"
1513
+ .checked=${r}
1514
+ @change=${()=>{this._mainRssFeed=e,this._syncFeedDirty()}}
1515
+ />
1516
+ <div>
1517
+ <div class="font-medium">${t}</div>
1518
+ <div class="text-sm text-muted-foreground">${n}</div>
1519
+ </div>
1520
+ </label>
1521
+ `}async _copyFeedUrl(e){try{if(!globalThis.navigator.clipboard?.writeText)throw Error(`Clipboard unavailable`);await globalThis.navigator.clipboard.writeText(e),m(this.labels.feedUrlCopied)}catch{m(this.labels.copyFailed,`error`)}}_renderFeedInfoRow(e,t){return s`
1522
+ <div class="flex min-w-0 flex-col gap-1">
1523
+ <p class="text-sm font-medium">${e}</p>
1524
+ <div class="relative">
1525
+ <input
1526
+ type="text"
1527
+ class="input w-full pr-20 font-mono text-sm"
1528
+ .value=${t}
1529
+ readonly
1530
+ aria-label=${e}
1531
+ @click=${e=>e.currentTarget.select()}
1532
+ @focus=${e=>e.currentTarget.select()}
1533
+ />
1534
+ <button
1535
+ type="button"
1536
+ class="btn-sm-outline absolute right-2 top-1/2 h-7 -translate-y-1/2 px-2.5 text-xs"
1537
+ data-copy-feed-url
1538
+ @click=${()=>void this._copyFeedUrl(t)}
1539
+ >
1540
+ ${this.labels.copy}
1541
+ </button>
1542
+ </div>
1543
+ </div>
1544
+ `}_renderGeneralForm(){return s`
1545
+ <div class="flex flex-col gap-8">
1546
+ <div>
1547
+ <h2 class="text-lg font-semibold">${this.labels.general}</h2>
1548
+ </div>
1549
+
1550
+ <section
1551
+ class="flex flex-col gap-4"
1552
+ @keydown=${e=>this._onKeydown(e,()=>this._saveSite(),this._siteDirty,this._siteLoading)}
1553
+ >
1554
+ ${this._renderSectionTitle(this.labels.site)}
1555
+ <div class="field">
1556
+ <label class="label">${this.labels.siteName}</label>
1557
+ <input
1558
+ type="text"
1559
+ class="input"
1560
+ maxlength=${120}
1561
+ .value=${this._siteName}
1562
+ placeholder=${this.siteNameFallback}
1563
+ @input=${e=>{this._siteName=e.target.value,this._syncSiteDirty()}}
1564
+ />
1565
+ </div>
1566
+
1567
+ <div class="field">
1568
+ <label class="label">${this.labels.aboutBlog}</label>
1569
+ <textarea
1570
+ class="textarea"
1571
+ rows="2"
1572
+ maxlength=${300}
1573
+ .value=${this._siteDescription}
1574
+ placeholder=${this.siteDescriptionFallback}
1575
+ @input=${e=>{this._siteDescription=e.target.value,this._syncSiteDirty()}}
1576
+ ></textarea>
1577
+ <p class="text-sm text-muted-foreground mt-1">
1578
+ ${this.labels.aboutBlogHelp}
1579
+ </p>
1580
+ </div>
1581
+
1582
+ <div class="field">
1583
+ <label class="label">${this.labels.siteFooter}</label>
1584
+ <textarea
1585
+ class="textarea font-mono text-sm"
1586
+ rows="4"
1587
+ maxlength=${Le}
1588
+ .value=${this._siteFooter}
1589
+ placeholder=${this.labels.markdownSupported}
1590
+ @input=${e=>{this._siteFooter=e.target.value,this._syncSiteDirty()}}
1591
+ ></textarea>
1592
+ <p class="text-sm text-muted-foreground mt-1">
1593
+ ${this.labels.footerHelp}
1594
+ </p>
1595
+ </div>
1596
+
1597
+ ${this._renderSaveAction(this._siteLoading,this._siteDirty,()=>this._saveSite())}
1598
+ </section>
1599
+
1600
+ <section
1601
+ class="flex flex-col gap-4 border-t pt-8"
1602
+ @keydown=${e=>this._onKeydown(e,()=>this._saveLocale(),this._localeDirty,this._localeLoading)}
1603
+ >
1604
+ ${this._renderSectionTitle(this.labels.languageAndTime)}
1605
+ <div class="field">
1606
+ <label class="label">${this.labels.language}</label>
1607
+ <select
1608
+ class="select"
1609
+ @change=${e=>{this._siteLanguage=e.target.value,this._syncLocaleDirty()}}
1610
+ >
1611
+ ${this.languages.map(e=>s`
1612
+ <option
1613
+ value=${e.value}
1614
+ ?selected=${this._siteLanguage===e.value}
1615
+ >
1616
+ ${e.label}
1617
+ </option>
1618
+ `)}
1619
+ </select>
1620
+ </div>
1621
+
1622
+ <div class="field">
1623
+ <label class="label">${this.labels.timeZone}</label>
1624
+ <select
1625
+ class="select"
1626
+ @change=${e=>{this._timeZone=e.target.value,this._syncLocaleDirty()}}
1627
+ >
1628
+ ${this.timezones.map(e=>s`
1629
+ <option
1630
+ value=${e.value}
1631
+ ?selected=${this._timeZone===e.value}
1632
+ >
1633
+ ${e.label}
1634
+ </option>
1635
+ `)}
1636
+ </select>
1637
+ </div>
1638
+
1639
+ ${this._renderSaveAction(this._localeLoading,this._localeDirty,()=>this._saveLocale())}
1640
+ </section>
1641
+
1642
+ <section
1643
+ class="flex flex-col gap-4 border-t pt-8"
1644
+ @keydown=${e=>this._onKeydown(e,()=>this._saveFeeds(),this._feedDirty,this._feedLoading)}
1645
+ >
1646
+ ${this._renderSectionTitle(this.labels.feeds)}
1647
+ <div class="field">
1648
+ <p class="label">${this.labels.mainRssFeed}</p>
1649
+ <p class="text-sm text-muted-foreground mt-1">
1650
+ ${this.labels.mainRssFeedHelp}
1651
+ </p>
1652
+ <div class="mt-3 flex flex-col gap-2">
1653
+ ${this._renderMainRssFeedOption(`featured`,this.labels.featuredFeedOption,this.labels.featuredFeedOptionDescription)}
1654
+ ${this._renderMainRssFeedOption(`latest`,this.labels.latestFeedOption,this.labels.latestFeedOptionDescription)}
1655
+ </div>
1656
+ <p class="text-sm text-muted-foreground mt-2">
1657
+ ${this.labels.mainRssFeedWarning}
1658
+ </p>
1659
+ </div>
1660
+
1661
+ <div class="rounded-xl border border-border/70 bg-muted/30 p-4">
1662
+ <div class="flex flex-col gap-4">
1663
+ <div class="flex flex-col gap-1">
1664
+ <p class="text-sm font-medium">
1665
+ ${this.labels.availableFeedUrls}
1666
+ </p>
1667
+ <p class="text-sm text-muted-foreground">
1668
+ ${this.labels.availableFeedUrlsHelp}
1669
+ </p>
1670
+ </div>
1671
+
1672
+ ${this._renderFeedInfoRow(this.labels.mainFeedUrl,this.mainFeedUrl)}
1673
+ ${this._renderFeedInfoRow(this.labels.latestFeedUrl,this.latestFeedUrl)}
1674
+ ${this._renderFeedInfoRow(this.labels.featuredFeedUrl,this.featuredFeedUrl)}
1675
+ </div>
1676
+ </div>
1677
+
1678
+ ${this._renderSaveAction(this._feedLoading,this._feedDirty,()=>this._saveFeeds())}
1679
+ </section>
1680
+
1681
+ <section class="flex flex-col gap-4 border-t pt-8 pb-6">
1682
+ ${this._renderSectionTitle(this.labels.home)}
1683
+ <label class="flex items-center gap-2 cursor-pointer">
1684
+ <input
1685
+ type="checkbox"
1686
+ class="checkbox"
1687
+ .checked=${this._showJantBrandingOnHome}
1688
+ ?disabled=${this._homeLoading}
1689
+ @change=${e=>this._saveHomeToggle(e.target.checked)}
1690
+ />
1691
+ <span>${this.labels.showJantBrandingOnHome}</span>
1692
+ </label>
1693
+ </section>
1694
+ </div>
1695
+ `}_renderSearchForm(){return s`
1696
+ <section class="flex flex-col gap-4 border-t pt-8">
1697
+ ${this._renderSectionTitle(this.labels.search)}
1698
+ <label class="flex items-center gap-2 cursor-pointer">
1699
+ <input
1700
+ type="checkbox"
1701
+ class="checkbox"
1702
+ .checked=${!this._noindex}
1703
+ ?disabled=${this.demoMode||this._searchLoading}
1704
+ @change=${e=>this._saveSearchToggle(e.target.checked)}
1705
+ />
1706
+ <span>${this.labels.allowIndexing}</span>
1707
+ </label>
1708
+ ${this.demoMode?s`<p class="text-sm text-muted-foreground">
1709
+ ${this.labels.demoSeoLocked}
1710
+ </p>`:i}
1711
+ </section>
1712
+ `}render(){return s`
1713
+ <div class="flex flex-col">
1714
+ ${this._renderGeneralForm()} ${this._renderSearchForm()}
1715
+ </div>
1716
+ `}};customElements.define(`jant-settings-general`,nm);var rm=class extends o{static properties={avatarUrl:{type:String,attribute:`avatar-url`},showInHeader:{type:Boolean,attribute:`show-in-header`},labels:{type:Object},_showInHeader:{state:!0},_origShowInHeader:{state:!0},_dirty:{state:!0},_loading:{state:!0},_removeLoading:{state:!0}};createRenderRoot(){return this.innerHTML=``,this}constructor(){super(),this.avatarUrl=``,this.showInHeader=!1,this.labels={},this._showInHeader=!1,this._origShowInHeader=!1,this._dirty=!1,this._loading=!1,this._removeLoading=!1}connectedCallback(){super.connectedCallback(),this._showInHeader=this.showInHeader,this._origShowInHeader=this.showInHeader}saved(){this._origShowInHeader=this._showInHeader,this._dirty=!1,this._loading=!1}saveError(){this._loading=!1}_toggleDisplay(){this._showInHeader=!this._showInHeader,this._dirty=this._showInHeader!==this._origShowInHeader}_cancelDisplay(){this._showInHeader=this._origShowInHeader,this._dirty=!1}_saveDisplay(){this._loading||!this._dirty||(this._loading=!0,this.dispatchEvent(new CustomEvent(`jant:settings-save`,{bubbles:!0,detail:{endpoint:`/settings/avatar/display`,data:{showHeaderAvatar:this._showInHeader?`true`:``},section:`avatar-display`}})))}_removeAvatar(){this._removeLoading||(this._removeLoading=!0,this.dispatchEvent(new CustomEvent(`jant:avatar-remove`,{bubbles:!0,detail:{endpoint:`/settings/avatar/remove`}})))}_renderPreview(){let e=`rounded-full size-16 overflow-hidden border border-border/70 bg-muted/40 flex items-center justify-center shrink-0`;return this.avatarUrl?s`
1717
+ <div class=${e}>
1718
+ <img
1719
+ src=${this.avatarUrl}
1720
+ alt=""
1721
+ class="w-full h-full object-cover"
1722
+ />
1723
+ </div>
1724
+ `:s`
1725
+ <div class="${e} text-muted-foreground">
1726
+ <svg
1727
+ xmlns="http://www.w3.org/2000/svg"
1728
+ width="24"
1729
+ height="24"
1730
+ viewBox="0 0 24 24"
1731
+ fill="none"
1732
+ stroke="currentColor"
1733
+ stroke-width="2"
1734
+ stroke-linecap="round"
1735
+ stroke-linejoin="round"
1736
+ >
1737
+ <rect width="18" height="18" x="3" y="3" rx="2" ry="2" />
1738
+ <circle cx="9" cy="9" r="2" />
1739
+ <path d="m21 15-3.086-3.086a2 2 0 0 0-2.828 0L6 21" />
1740
+ </svg>
1741
+ </div>
1742
+ `}render(){return s`
1743
+ <div>
1744
+ <h2 class="text-lg font-semibold mb-4">${this.labels.blogAvatar}</h2>
1745
+ <div class="flex flex-col gap-4">
1746
+ <div class="flex items-center gap-4">
1747
+ ${this._renderPreview()}
1748
+ <div class="flex flex-col gap-2">
1749
+ <form
1750
+ action=${a(`/settings/avatar`)}
1751
+ method="post"
1752
+ enctype="multipart/form-data"
1753
+ class="inline"
1754
+ >
1755
+ <label class="btn text-sm cursor-pointer">
1756
+ ${this.labels.uploadAvatar}
1757
+ <input
1758
+ type="file"
1759
+ name="file"
1760
+ accept="image/jpeg,image/png,image/gif,image/webp,image/svg+xml"
1761
+ class="hidden"
1762
+ data-avatar-upload
1763
+ data-text-processing=${this.labels.processing}
1764
+ data-text-uploading=${this.labels.uploading}
1765
+ data-text-error=${this.labels.uploadError}
1766
+ />
1767
+ </label>
1768
+ </form>
1769
+ ${this.avatarUrl?s`
1770
+ <button
1771
+ type="button"
1772
+ class="btn-outline text-sm"
1773
+ ?disabled=${this._removeLoading}
1774
+ @click=${this._removeAvatar}
1775
+ >
1776
+ ${this.labels.remove}
1777
+ </button>
1778
+ `:i}
1779
+ </div>
1780
+ </div>
1781
+ <p class="text-sm text-muted-foreground">${this.labels.avatarHelp}</p>
1782
+ <label class="flex items-center gap-2 cursor-pointer">
1783
+ <input
1784
+ type="checkbox"
1785
+ class="checkbox"
1786
+ .checked=${this._showInHeader}
1787
+ @change=${this._toggleDisplay}
1788
+ />
1789
+ <span>${this.labels.displayInHeader}</span>
1790
+ </label>
1791
+ <div class="flex gap-2 mt-4">
1792
+ <button
1793
+ type="button"
1794
+ class="btn"
1795
+ ?disabled=${this._loading||!this._dirty}
1796
+ @click=${this._saveDisplay}
1797
+ >
1798
+ ${this._loading?s`<svg
1799
+ class="animate-spin size-4"
1800
+ xmlns="http://www.w3.org/2000/svg"
1801
+ viewBox="0 0 24 24"
1802
+ fill="none"
1803
+ stroke="currentColor"
1804
+ stroke-width="2"
1805
+ stroke-linecap="round"
1806
+ stroke-linejoin="round"
1807
+ role="status"
1808
+ >
1809
+ <path d="M21 12a9 9 0 1 1-6.219-8.56" />
1810
+ </svg>`:i}
1811
+ ${this.labels.save}
1812
+ </button>
1813
+ <button
1814
+ type="button"
1815
+ class="btn-outline"
1816
+ ?disabled=${this._loading||!this._dirty}
1817
+ @click=${this._cancelDisplay}
1818
+ >
1819
+ ${this.labels.cancel}
1820
+ </button>
1821
+ </div>
1822
+ </div>
1823
+ </div>
1824
+ `}};customElements.define(`jant-settings-avatar`,rm);function im(e){let t=C(e,`siteName`),n=C(e,`siteDescription`),r=C(e,`siteLanguage`),i=C(e,`mainRssFeed`),a=C(e,`timeZone`),o=C(e,`siteFooter`),s=b(e,`showJantBrandingOnHome`),c=b(e,`noindex`);return t===void 0||n===void 0||r===void 0||i===void 0||a===void 0||o===void 0||s===void 0||c===void 0?null:{siteName:t,siteDescription:n,siteLanguage:r,mainRssFeed:i,timeZone:a,siteFooter:o,showJantBrandingOnHome:s,noindex:c}}document.addEventListener(`jant:settings-save`,async e=>{let{endpoint:t,data:n,section:r}=e.detail,i=document.querySelector(`jant-settings-general`),a=document.querySelector(`jant-settings-avatar`);try{let e=await fetch(t,{method:`POST`,headers:{"Content-Type":`application/json`,Accept:`application/json`},body:JSON.stringify(n)});if(!e.ok)throw Error(`HTTP ${e.status}`);let o=await d(e),s=C(o,`status`),c=C(o,`url`),l=C(o,`toast`);if(s===`redirect`&&c){window.location.href=c;return}l&&m(l),r===`avatar-display`?a?.saved():i?.sectionSaved(r)}catch{m(`Failed to save. Please try again.`,`error`),r===`avatar-display`?a?.saveError():i?.sectionError(r)}}),document.addEventListener(`jant:avatar-remove`,async e=>{let{endpoint:t}=e.detail;try{let e=await fetch(t,{method:`POST`,headers:{"Content-Type":`application/json`,Accept:`application/json`}});if(!e.ok)throw Error(`HTTP ${e.status}`);let n=await d(e),r=C(n,`status`),i=C(n,`url`);if(r===`redirect`&&i){window.location.href=i;return}}catch{m(`Failed to remove avatar. Please try again.`,`error`)}});function am(){let e=document.querySelector(`jant-settings-general`);if(!e)return;let t=document.getElementById(`settings-initial-data`);if(t?.textContent)try{let n=im(JSON.parse(t.textContent));n&&e.initData(n)}catch{}}document.readyState===`loading`?document.addEventListener(`DOMContentLoaded`,am):queueMicrotask(am);var om,sm;function cm(){return om?Promise.resolve(om):(sm||=Dr(()=>import(`./chunks/url-CG0eolsk.js`).then(e=>e.i).then(e=>(om=e.slugify,e.slugify)),[]),sm)}async function lm(e){return(await cm())(e)}var um=class extends o{static properties={labels:{type:Object},initial:{type:Object},action:{type:String},cancelHref:{type:String,attribute:`cancel-href`},isEdit:{type:Boolean,attribute:`is-edit`},variant:{type:String},_title:{state:!0},_slug:{state:!0},_description:{state:!0},_sortOrder:{state:!0},_showSlugEditor:{state:!0},_slugEdited:{state:!0},_suggestedSlug:{state:!0},_loading:{state:!0}};#e=!1;createRenderRoot(){return this.innerHTML=``,this}constructor(){super(),this.labels={},this.initial={title:``,slug:``,description:``,sortOrder:`newest`},this.action=``,this.cancelHref=`/`,this.isEdit=!1,this.variant=`full`,this._title=``,this._slug=``,this._description=``,this._sortOrder=`newest`,this._showSlugEditor=!1,this._slugEdited=!1,this._suggestedSlug=``,this._loading=!1}update(e){(!this.#e||e.has(`initial`))&&this.#t(),super.update(e)}set loading(e){this._loading=e}get loading(){return this._loading}#t(){this.initial&&(this.#e=!0,this._title=this.initial.title??``,this._slug=this.initial.slug??``,this._suggestedSlug=this.initial.slug??``,this._description=this.initial.description??``,this._sortOrder=this.initial.sortOrder??`newest`,this._slugEdited=this.isEdit||!!this._slug.trim(),this._showSlugEditor=this.variant!==`quick`)}async#n(e){let t=e.target;if(this._title=t.value,this.isEdit||this._slugEdited)return;let n=t.value,r=We(await lm(n),200);this._title===n&&(this._suggestedSlug=r,this._slugEdited||(this._slug=r))}#r(e){this._slug=e.target.value.toLowerCase(),this._slugEdited=!0}#i(){let e=Ge(this._slug,{maxLength:200,additionalReservedValues:Be});return e===`too_long`?this.labels.slugTooLongHelp??`Keep this link under 200 characters.`:e===`invalid`?this.labels.slugInvalidHelp:e===`reserved`?this.labels.slugReservedHelp:null}#a(){this._showSlugEditor||(this._showSlugEditor=!0,this.updateComplete.then(()=>{let e=this.querySelector(`[data-collection-slug-input]`);e?.focus(),e?.select()}))}#o(){this._suggestedSlug&&(this._slug=this._suggestedSlug,this._slugEdited=!1,this.variant===`quick`&&(this._showSlugEditor=!1))}#s(){let e=this._slug.trim(),t=a(e?`/c/${e}`:`/c/`),n=globalThis.location?.origin&&globalThis.location.origin!==`null`?globalThis.location.origin:`http://localhost`;return new URL(t,`${n}/`).toString()}#c(){let e=this.#i();return e?s`<p
1825
+ class="text-xs text-destructive mt-1"
1826
+ data-collection-slug-error
1827
+ >
1828
+ ${e}
1829
+ </p>`:this._slug.trim()?s`<p class="text-xs text-muted-foreground mt-1 break-all">
1830
+ ${this.#s()}
1831
+ </p>`:s`<p class="text-xs text-muted-foreground mt-1">
1832
+ ${this.labels.slugHelp}
1833
+ </p>`}#l(){let e=!!this._slug.trim(),t=this._showSlugEditor&&!!this._suggestedSlug&&this._slug.trim()!==this._suggestedSlug;return!e&&!this._showSlugEditor?i:this._showSlugEditor?s`
1834
+ <div class="collection-quick-link-editor">
1835
+ <div class="field">
1836
+ <div class="collection-quick-link-row">
1837
+ <label class="label mb-0">${this.labels.slugLabel}</label>
1838
+ ${t?s`
1839
+ <button
1840
+ type="button"
1841
+ class="collection-quick-link-action"
1842
+ @click=${()=>this.#o()}
1843
+ >
1844
+ ${this.labels.resetSlugLabel}
1845
+ </button>
1846
+ `:i}
1847
+ </div>
1848
+ <input
1849
+ type="text"
1850
+ class="input"
1851
+ data-collection-slug-input
1852
+ required
1853
+ pattern="[a-z0-9]+(?:-[a-z0-9]+)*"
1854
+ maxlength=${200}
1855
+ .value=${this._slug}
1856
+ aria-invalid=${this.#i()?`true`:`false`}
1857
+ placeholder="my-collection"
1858
+ @input=${e=>this.#r(e)}
1859
+ />
1860
+ ${this.#c()}
1861
+ </div>
1862
+ </div>
1863
+ `:s`
1864
+ <div class="collection-quick-link-box">
1865
+ <div class="collection-quick-link-row">
1866
+ <p
1867
+ class="collection-quick-link-preview text-xs text-muted-foreground"
1868
+ aria-live="polite"
1869
+ >
1870
+ ${this.#s()}
1871
+ </p>
1872
+ <button
1873
+ type="button"
1874
+ class="collection-quick-link-action"
1875
+ @click=${()=>this.#a()}
1876
+ >
1877
+ ${this.labels.editSlugLabel}
1878
+ </button>
1879
+ </div>
1880
+ </div>
1881
+ `}async#u(e){if(e.preventDefault(),this._loading)return;let t=this._title.trim(),n=this._slug.trim();if(!t){this.querySelector(`[data-collection-title-input]`)?.focus();return}if(!n&&!this._slugEdited&&(n=We(await lm(t),200),this._slug=n,this._suggestedSlug=n),!n||this.#i()){this.variant===`quick`&&!this._showSlugEditor&&this.#a(),this.updateComplete.then(()=>{this.querySelector(`[data-collection-slug-input]`)?.focus()});return}let r={endpoint:this.action,isEdit:this.isEdit,data:{title:t,slug:n,description:this.variant===`quick`?void 0:this._description.trim()||void 0,sortOrder:this.variant===`quick`?void 0:this._sortOrder||void 0}};this.dispatchEvent(new CustomEvent(`jant:collection-submit`,{bubbles:!0,detail:r}))}render(){let e=this.variant===`quick`;return s`
1882
+ <form
1883
+ class=${e?`flex flex-col gap-4`:`collection-editor-form`}
1884
+ @submit=${e=>void this.#u(e)}
1885
+ >
1886
+ ${e?s`
1887
+ <div class="field">
1888
+ <label class="label">${this.labels.titleLabel}</label>
1889
+ <input
1890
+ type="text"
1891
+ class="input"
1892
+ data-collection-title-input
1893
+ required
1894
+ maxlength=${120}
1895
+ .value=${this._title}
1896
+ placeholder=${this.isEdit?i:this.labels.titlePlaceholder}
1897
+ @input=${e=>void this.#n(e)}
1898
+ />
1899
+ </div>
1900
+
1901
+ ${this.#l()}
1902
+ `:s`
1903
+ <div class="collection-editor-primary-grid">
1904
+ <div class="field collection-editor-title-field">
1905
+ <label class="label">${this.labels.titleLabel}</label>
1906
+ <input
1907
+ type="text"
1908
+ class="input"
1909
+ data-collection-title-input
1910
+ required
1911
+ maxlength=${120}
1912
+ .value=${this._title}
1913
+ placeholder=${this.isEdit?i:this.labels.titlePlaceholder}
1914
+ @input=${e=>void this.#n(e)}
1915
+ />
1916
+ </div>
1917
+
1918
+ <div class="field collection-editor-slug-field">
1919
+ <label class="label">${this.labels.slugLabel}</label>
1920
+ <input
1921
+ type="text"
1922
+ class="input"
1923
+ data-collection-slug-input
1924
+ required
1925
+ pattern="[a-z0-9]+(?:-[a-z0-9]+)*"
1926
+ maxlength=${200}
1927
+ .value=${this._slug}
1928
+ aria-invalid=${this.#i()?`true`:`false`}
1929
+ placeholder=${this.isEdit?i:`my-collection`}
1930
+ @input=${e=>this.#r(e)}
1931
+ />
1932
+ ${this.#c()}
1933
+ </div>
1934
+ </div>
1935
+
1936
+ <div class="collection-editor-secondary-grid">
1937
+ <div class="field collection-editor-description-field">
1938
+ <label class="label">${this.labels.descriptionLabel}</label>
1939
+ <textarea
1940
+ class="textarea"
1941
+ rows="4"
1942
+ maxlength=${500}
1943
+ .value=${this._description}
1944
+ placeholder=${this.isEdit?i:this.labels.descriptionPlaceholder}
1945
+ @input=${e=>{this._description=e.target.value}}
1946
+ ></textarea>
1947
+ </div>
1948
+
1949
+ <div class="field collection-editor-sort-field">
1950
+ <label class="label">${this.labels.sortOrderLabel}</label>
1951
+ <select
1952
+ class="select"
1953
+ .value=${this._sortOrder}
1954
+ @change=${e=>{this._sortOrder=e.target.value}}
1955
+ >
1956
+ <option value="newest">${this.labels.sortNewest}</option>
1957
+ <option value="oldest">${this.labels.sortOldest}</option>
1958
+ <option value="rating_desc">
1959
+ ${this.labels.sortRatingDesc}
1960
+ </option>
1961
+ </select>
1962
+ </div>
1963
+ </div>
1964
+ `}
1965
+ ${e?s`
1966
+ <button type="submit" class="sr-only">
1967
+ ${this.labels.quickSubmitLabel}
1968
+ </button>
1969
+ `:s`
1970
+ <div class="collection-editor-actions">
1971
+ <button
1972
+ type="submit"
1973
+ class="btn collection-editor-submit"
1974
+ ?disabled=${this._loading}
1975
+ >
1976
+ ${this._loading?s`<svg
1977
+ class="animate-spin size-4"
1978
+ xmlns="http://www.w3.org/2000/svg"
1979
+ viewBox="0 0 24 24"
1980
+ fill="none"
1981
+ stroke="currentColor"
1982
+ stroke-width="2"
1983
+ stroke-linecap="round"
1984
+ stroke-linejoin="round"
1985
+ role="status"
1986
+ >
1987
+ <path d="M21 12a9 9 0 1 1-6.219-8.56" />
1988
+ </svg>`:i}
1989
+ ${this.labels.submitLabel}
1990
+ </button>
1991
+ <a
1992
+ href=${this.cancelHref}
1993
+ class="btn-outline collection-editor-cancel"
1994
+ >
1995
+ ${this.labels.cancelLabel}
1996
+ </a>
1997
+ </div>
1998
+ `}
1999
+ </form>
2000
+ `}};customElements.define(`jant-collection-form`,um);function dm(e,t){let n=e[t];if(!n||n.type!==`divider`||!n.label)return null;let r=[];for(let n=t+1;n<e.length;n+=1){let t=e[n];if(!t||t.type===`divider`)break;let i=t.collection?.slug;i&&r.push(i)}return r.length<2?null:{slugExpression:r.join(`+`),collectionCount:r.length}}function fm(){return Math.floor(Date.now()/1e3)}function pm(e){return new Date(e*1e3).toISOString()}function mm(e,t=`UTC`){let n=fm()-e;if(n<60)return`1m`;let r=Math.floor(n/60);if(r<60)return`${r}m`;let i=Math.floor(n/3600);if(i<24)return`${i}h`;let a=Math.floor(n/86400);return a<=7?`${a}d`:new Date(e*1e3).toLocaleDateString(`en-US`,{month:`short`,day:`numeric`,timeZone:t})}function hm(e,t=`UTC`){let n=mm(e,t);return/^[0-9]+[mhd]$/.test(n)?`${n} ago`:n}var gm=class extends o{static properties={items:{type:Array},labels:{type:Object},_items:{state:!0},_reorderMode:{state:!0},_editingDividerId:{state:!0},_showMoreMenu:{state:!0},_hoveringId:{state:!0},_showItemMenuId:{state:!0}};#e=null;#t=!1;#n=null;#r=null;#i=()=>{this._showMoreMenu=!1,document.removeEventListener(`click`,this.#i)};#a=()=>{this._showItemMenuId=null,document.removeEventListener(`click`,this.#a)};#o=e=>{let t=e.target;if(!t)return;t.closest(`[data-collections-more-menu]`)&&e.stopPropagation();let n=t.closest(`[data-collections-action]`);if(!n||!this.#r?.contains(n))return;let r=n.dataset.collectionsAction;if(r)switch(e.preventDefault(),e.stopPropagation(),r!==`toggle-menu`&&this._showMoreMenu&&(this._showMoreMenu=!1,document.removeEventListener(`click`,this.#i)),r){case`done`:this.#v();break;case`toggle-menu`:this._showMoreMenu=!this._showMoreMenu,this._showMoreMenu?setTimeout(()=>{document.addEventListener(`click`,this.#i)}):document.removeEventListener(`click`,this.#i);break;case`organize`:this.#_();break;case`divider`:this.#y();break;default:break}};createRenderRoot(){return this.innerHTML=``,this}connectedCallback(){super.connectedCallback(),this.#d()}constructor(){super(),this.items=[],this.labels={},this._items=[],this._reorderMode=!1,this._editingDividerId=null,this._showMoreMenu=!1,this._hoveringId=null,this._showItemMenuId=null}update(e){(!this.#t||e.has(`items`))&&(this._items=[...this.items??[]],this.#t=!0),super.update(e)}disconnectedCallback(){super.disconnectedCallback(),this.#e?.destroy(),this.#e=null,this.#r?.removeEventListener(`click`,this.#o),this.#r=null,document.removeEventListener(`click`,this.#i),document.removeEventListener(`click`,this.#a)}#s(){return this._items.some(e=>e.type===`collection`&&e.collection)}#c(){return this._items.filter(e=>e.type===`collection`&&e.collection).length}#l(){let e=this.#c();return`${e} ${e===1?this.labels.collectionSingular:this.labels.collectionPlural}`}#u(e){return`${e} ${e===1?this.labels.entrySingular:this.labels.entryPlural}`}#d(){let e=this.closest(`[data-collections-manager-root]`);e!==this.#r&&(this.#r?.removeEventListener(`click`,this.#o),this.#r=e,this.#r?.addEventListener(`click`,this.#o))}#f(e){return this.#r?.querySelector(e)??null}#p(){let e=this.#f(`[data-collections-count]`);e&&(e.textContent=this.#l(),e.hidden=!1);let t=this.#f(`[data-collections-action="done"]`);t&&(t.hidden=!this._reorderMode);let n=this.#f(`[data-collections-reorder-actions]`);n&&(n.hidden=!this._reorderMode);let r=this.#f(`[data-collections-toolbar]`);r&&(r.hidden=this._reorderMode);let i=this.#f(`[data-collections-hint]`);i&&(i.hidden=!this._reorderMode);let a=this.#f(`[data-collections-more-menu]`);a&&(a.hidden=!this._showMoreMenu||this._reorderMode);let o=this.#f(`[data-collections-action="toggle-menu"]`);o&&o.setAttribute(`aria-expanded`,String(this._showMoreMenu&&!this._reorderMode))}#m(e){let t=e.collections??[],n=e.sidebarItems??[],r=new Map;for(let e of t)r.set(e.id,{id:e.id,slug:e.slug,title:e.title,description:e.description,sortOrder:e.sortOrder,postCount:e.postCount??0,recentActivityAt:e.recentActivityAt});let i=new Set,a=[];for(let e of n){let t=e.collectionId==null?void 0:r.get(e.collectionId);e.type===`collection`&&!t||(t&&i.add(t.id),a.push({id:e.id,type:e.type,collectionId:e.collectionId,label:e.label,position:e.position,collection:t}))}for(let e of t)i.has(e.id)||a.push({id:`collection-${e.id}`,type:`collection`,collectionId:e.id,position:``,collection:r.get(e.id)});return a}async#h(){try{let e=await fetch(`/api/collections`);if(!e.ok)return;let t=await e.json();this._items=this.#m(t)}catch{}}#g(){let e=this.querySelector(`#collections-manager-list`);!e||this.#e||(this.#e=P.create(e,{...vr,chosenClass:`collection-directory-chosen`,dragClass:`collection-directory-drag`,ghostClass:`collection-directory-ghost`,handle:`[data-drag-handle]`,scroll:!0,onChoose:()=>{Sr(e,!0)},onStart:e=>{this.#n=br(e)},onUnchoose:()=>{Sr(e,!1)},onEnd:t=>{let n=yr(e,`[data-sidebar-item]`,`sidebarItem`);xr(e,t,this.#n),this.#n=null,Sr(e,!1),this.#e?.destroy(),this.#e=null;let{movedId:r,afterId:i,beforeId:a}=Cr(n,t.newIndex);if(!r)return;let o=new Map(this._items.map(e=>[e.id,e]));this._items=n.map(e=>o.get(e)).filter(e=>e!==void 0),fetch(`/api/collections/sidebar-items/${r}/move`,{method:`PUT`,headers:{"Content-Type":`application/json`},body:JSON.stringify({after:i??null,before:a??null})}).then(e=>{e.ok?m(this.labels.orderSaved):m(this.labels.saveFailed,`error`)})}}))}#_(){this._reorderMode=!0,this._showMoreMenu=!1,document.removeEventListener(`click`,this.#i)}#v(){this._reorderMode=!1,this._editingDividerId=null,this.#e?.destroy(),this.#e=null}updated(){if(this.#d(),this.#p(),this._reorderMode&&this.#g(),this._editingDividerId){let e=this.querySelector(`[data-divider-input-for="${this._editingDividerId}"]`);e&&(e.focus(),e.select(),e.scrollIntoView({block:`nearest`}),this._editingDividerId=null)}}async#y(){this._showMoreMenu=!1,document.removeEventListener(`click`,this.#i);try{let e=await fetch(`/api/collections/sidebar-items`,{method:`POST`,headers:{"Content-Type":`application/json`}});if(!e.ok)throw Error(`HTTP ${e.status}`);let t=await e.json();this._reorderMode=!0,await this.#h(),this._editingDividerId=t.id}catch{m(this.labels.saveFailed,`error`)}}async#b(e){try{let t=await fetch(`/api/collections/sidebar-items/${e}`,{method:`DELETE`});if(!t.ok)throw Error(`HTTP ${t.status}`);this._items=this._items.filter(t=>t.id!==e)}catch{m(this.labels.saveFailed,`error`)}}async#x(e,t){let n=t.trim();if(n!==(this._items.find(t=>t.id===e)?.label??``))try{let t=await fetch(`/api/collections/sidebar-items/${e}`,{method:`PUT`,headers:{"Content-Type":`application/json`},body:JSON.stringify({label:n||null})});if(!t.ok)throw Error(`HTTP ${t.status}`);let r=await t.json();this._items=this._items.map(t=>t.id===e?{...t,label:r.label??null}:t)}catch{m(this.labels.saveFailed,`error`),await this.#h()}}async#S(e){if(await ve({message:this.labels.confirmDelete,confirmLabel:this.labels.deleteCollection,cancelLabel:this.labels.cancel,tone:`danger`})){this._showItemMenuId=null,document.removeEventListener(`click`,this.#a);try{let t=await fetch(`/api/collections/${e.id}`,{method:`DELETE`});if(!t.ok)throw Error(`HTTP ${t.status}`);m(this.labels.deleted),await this.#h()}catch{m(this.labels.saveFailed,`error`)}}}#C(e,t){let n=e.collection;if(!n)return i;let r=s`
2001
+ <div class="collection-directory-main">
2002
+ <span class="collection-directory-sequence" aria-hidden="true">
2003
+ ${String(t).padStart(2,`0`)}
2004
+ </span>
2005
+ <div class="collection-directory-title-row">
2006
+ <span class="collection-directory-title">${n.title}</span>
2007
+ </div>
2008
+ <p class="collection-directory-summary">
2009
+ <span class="collection-directory-meta"
2010
+ >${this.#u(n.postCount)}</span
2011
+ >
2012
+ <span class="collection-directory-meta-separator" aria-hidden="true"
2013
+ >/</span
2014
+ >
2015
+ <time
2016
+ class="collection-directory-updated"
2017
+ datetime=${pm(n.recentActivityAt)}
2018
+ >
2019
+ ${hm(n.recentActivityAt)}
2020
+ </time>
2021
+ </p>
2022
+ </div>
2023
+ `;return this._reorderMode?s`
2024
+ <div
2025
+ data-sidebar-item=${e.id}
2026
+ class="collection-directory-item collection-directory-item-reorder"
2027
+ >
2028
+ <div class="collection-directory-handle" data-drag-handle>
2029
+ <svg
2030
+ xmlns="http://www.w3.org/2000/svg"
2031
+ width="16"
2032
+ height="16"
2033
+ viewBox="0 0 24 24"
2034
+ fill="none"
2035
+ stroke="currentColor"
2036
+ stroke-width="2"
2037
+ stroke-linecap="round"
2038
+ stroke-linejoin="round"
2039
+ >
2040
+ <circle cx="9" cy="12" r="1" />
2041
+ <circle cx="9" cy="5" r="1" />
2042
+ <circle cx="9" cy="19" r="1" />
2043
+ <circle cx="15" cy="12" r="1" />
2044
+ <circle cx="15" cy="5" r="1" />
2045
+ <circle cx="15" cy="19" r="1" />
2046
+ </svg>
2047
+ </div>
2048
+ <div class="collection-directory-reorder-main" data-drag-handle>
2049
+ ${r}
2050
+ </div>
2051
+ </div>
2052
+ `:s`
2053
+ <div
2054
+ class=${w({"group relative":!0,"z-50":this._showItemMenuId===e.id})}
2055
+ @mouseenter=${()=>{this._hoveringId=e.id}}
2056
+ @mouseleave=${()=>{this._hoveringId===e.id&&(this._hoveringId=null)}}
2057
+ >
2058
+ <a
2059
+ href=${a(`/c/${n.slug}`)}
2060
+ class="collection-directory-item collection-directory-item-manageable"
2061
+ >
2062
+ ${r}
2063
+ </a>
2064
+ ${this._hoveringId===e.id||this._showItemMenuId===e.id?this.#w(e):i}
2065
+ </div>
2066
+ `}#w(e){let t=e.collection;if(!t)return i;let n=this._showItemMenuId===e.id;return s`
2067
+ <div class="collection-directory-item-menu">
2068
+ <button
2069
+ type="button"
2070
+ class="collections-page-icon-button"
2071
+ aria-label=${this.labels.moreActions}
2072
+ @click=${t=>{t.preventDefault(),t.stopPropagation(),n?(this._showItemMenuId=null,document.removeEventListener(`click`,this.#a)):(this._showItemMenuId=e.id,setTimeout(()=>{document.addEventListener(`click`,this.#a)}))}}
2073
+ >
2074
+ <svg
2075
+ xmlns="http://www.w3.org/2000/svg"
2076
+ width="14"
2077
+ height="14"
2078
+ viewBox="0 0 24 24"
2079
+ fill="currentColor"
2080
+ >
2081
+ <circle cx="5" cy="12" r="2" />
2082
+ <circle cx="12" cy="12" r="2" />
2083
+ <circle cx="19" cy="12" r="2" />
2084
+ </svg>
2085
+ </button>
2086
+ ${n?s`
2087
+ <div
2088
+ class="collections-page-menu"
2089
+ @click=${e=>e.stopPropagation()}
2090
+ >
2091
+ <a
2092
+ href=${a(`/c/${t.slug}/edit?returnTo=${encodeURIComponent(a(`/c`))}`)}
2093
+ class="collections-page-menu-item"
2094
+ >
2095
+ ${this.labels.edit}
2096
+ </a>
2097
+ <button
2098
+ type="button"
2099
+ class="collections-page-menu-item collections-page-menu-item-danger"
2100
+ @click=${()=>this.#S(t)}
2101
+ >
2102
+ ${this.labels.deleteCollection}
2103
+ </button>
2104
+ </div>
2105
+ `:i}
2106
+ </div>
2107
+ `}#T(e,t){if(this._reorderMode)return s`
2108
+ <div
2109
+ data-sidebar-item=${e.id}
2110
+ class="collection-directory-divider-row"
2111
+ >
2112
+ <div class="collection-directory-handle" data-drag-handle>
2113
+ <svg
2114
+ xmlns="http://www.w3.org/2000/svg"
2115
+ width="16"
2116
+ height="16"
2117
+ viewBox="0 0 24 24"
2118
+ fill="none"
2119
+ stroke="currentColor"
2120
+ stroke-width="2"
2121
+ stroke-linecap="round"
2122
+ stroke-linejoin="round"
2123
+ >
2124
+ <circle cx="9" cy="12" r="1" />
2125
+ <circle cx="9" cy="5" r="1" />
2126
+ <circle cx="9" cy="19" r="1" />
2127
+ <circle cx="15" cy="12" r="1" />
2128
+ <circle cx="15" cy="5" r="1" />
2129
+ <circle cx="15" cy="19" r="1" />
2130
+ </svg>
2131
+ </div>
2132
+ <div class="collection-directory-divider-body">
2133
+ <input
2134
+ type="text"
2135
+ class="collection-directory-divider-input"
2136
+ data-divider-input-for=${e.id}
2137
+ placeholder=${this.labels.dividerLabelPlaceholder}
2138
+ .value=${e.label??``}
2139
+ aria-label=${this.labels.dividerLabelPlaceholder}
2140
+ @blur=${t=>this.#x(e.id,t.currentTarget.value)}
2141
+ @keydown=${t=>{let n=t.currentTarget;t.key===`Enter`&&(t.preventDefault(),n.blur()),t.key===`Escape`&&(n.value=e.label??``,n.blur())}}
2142
+ />
2143
+ <hr class="collection-directory-divider-line" />
2144
+ </div>
2145
+ <button
2146
+ type="button"
2147
+ class="collections-page-icon-button"
2148
+ title=${this.labels.deleteDivider}
2149
+ aria-label=${this.labels.deleteDivider}
2150
+ @click=${()=>this.#b(e.id)}
2151
+ >
2152
+ <svg
2153
+ xmlns="http://www.w3.org/2000/svg"
2154
+ width="12"
2155
+ height="12"
2156
+ viewBox="0 0 24 24"
2157
+ fill="none"
2158
+ stroke="currentColor"
2159
+ stroke-width="2"
2160
+ stroke-linecap="round"
2161
+ stroke-linejoin="round"
2162
+ >
2163
+ <path d="M18 6 6 18" />
2164
+ <path d="m6 6 12 12" />
2165
+ </svg>
2166
+ </button>
2167
+ </div>
2168
+ `;let n=!!e.label,r=dm(this._items,t);return s`
2169
+ <div class="collection-directory-divider">
2170
+ <div
2171
+ class="collection-directory-divider-row"
2172
+ aria-hidden=${n?i:`true`}
2173
+ >
2174
+ ${n?s`
2175
+ ${r?s`
2176
+ <a
2177
+ href=${a(`/c/${r.slugExpression}`)}
2178
+ class="collection-directory-divider-link collection-directory-divider-text"
2179
+ >
2180
+ ${e.label}
2181
+ </a>
2182
+ `:s`
2183
+ <span class="collection-directory-divider-text">
2184
+ ${e.label}
2185
+ </span>
2186
+ `}
2187
+ <hr class="collection-directory-divider-line" />
2188
+ `:s`<hr class="collection-directory-divider-line" />`}
2189
+ </div>
2190
+ </div>
2191
+ `}render(){return s`
2192
+ ${this.#s()?s`
2193
+ <div id="collections-manager-list" class="collection-directory">
2194
+ ${(()=>{let e=0;return this._items.map((t,n)=>t.type===`collection`?(e+=1,this.#C(t,e)):this.#T(t,n))})()}
2195
+ </div>
2196
+ `:s`<p class="text-muted-foreground">${this.labels.emptyState}</p>`}
2197
+ `}};customElements.define(`jant-collections-manager`,gm),document.addEventListener(`jant:collection-submit`,async e=>{let t=e,n=t.detail,r=t.target instanceof HTMLElement?t.target:document.querySelector(`jant-collection-form`),i=r?.closest(`[data-collection-editor-page]`);if(!(!n?.endpoint||!r||!i)){r.loading=!0;try{let e=await fetch(n.endpoint,{method:n.isEdit?`PUT`:`POST`,headers:{"Content-Type":`application/json`,Accept:`application/json`},body:JSON.stringify(n.data)}),t=await e.json().catch(()=>null);if(!e.ok)throw Error(t?.error||i.dataset.collectionEditorSaveFailed||`Couldn't save. Try again in a moment.`);let o=n.isEdit&&typeof t?.slug==`string`&&t.slug.length>0?a(`/c/${t.slug}`):r.cancelHref||a(`/c`);window.location.href=o;return}catch(e){m(e instanceof Error?e.message:i.dataset.collectionEditorSaveFailed||`Couldn't save. Try again in a moment.`,`error`)}finally{r.loading=!1}}});function _m(e){let t;if(e===`application/pdf`)t=`<text x="12" y="16.5" text-anchor="middle" fill="currentColor" stroke="none" font-size="6" font-weight="700" font-family="system-ui, sans-serif">PDF</text>`;else if(e===`text/markdown`)t=`<text x="12" y="16.5" text-anchor="middle" fill="currentColor" stroke="none" font-size="10" font-weight="700" font-family="system-ui, sans-serif">#</text>`;else if(e===`text/csv`)t=`<line x1="8" y1="12" x2="16" y2="12"/><line x1="8" y1="15" x2="16" y2="15"/><line x1="8" y1="18" x2="16" y2="18"/><line x1="10.7" y1="12" x2="10.7" y2="18"/><line x1="13.3" y1="12" x2="13.3" y2="18"/>`;else if(Ne(e)===`archive`)t=`<line x1="12" y1="10" x2="12" y2="11.5"/><line x1="12" y1="13" x2="12" y2="14.5"/><line x1="12" y1="16" x2="12" y2="17.5"/>`;else if(e.startsWith(`audio/`))return s`<svg
2198
+ width="24"
2199
+ height="24"
2200
+ viewBox="0 0 24 24"
2201
+ fill="none"
2202
+ stroke="currentColor"
2203
+ stroke-width="1.5"
2204
+ stroke-linecap="round"
2205
+ stroke-linejoin="round"
2206
+ >
2207
+ ${be(`<path d="M9 18V5l12-2v13"/><circle cx="6" cy="18" r="3"/><circle cx="18" cy="16" r="3"/>`)}
2208
+ </svg>`;else if(e.startsWith(`video/`))return s`<svg
2209
+ width="24"
2210
+ height="24"
2211
+ viewBox="0 0 24 24"
2212
+ fill="none"
2213
+ stroke="currentColor"
2214
+ stroke-width="1.5"
2215
+ stroke-linecap="round"
2216
+ stroke-linejoin="round"
2217
+ >
2218
+ ${be(`<polygon points="23 7 16 12 23 17 23 7"/><rect x="1" y="5" width="15" height="14" rx="2" ry="2"/>`)}
2219
+ </svg>`;else t=`<line x1="16" y1="13" x2="8" y2="13"/><line x1="16" y1="17" x2="8" y2="17"/><line x1="10" y1="9" x2="8" y2="9"/>`;return s`<svg
2220
+ width="24"
2221
+ height="24"
2222
+ viewBox="0 0 24 24"
2223
+ fill="none"
2224
+ stroke="currentColor"
2225
+ stroke-width="1.5"
2226
+ stroke-linecap="round"
2227
+ stroke-linejoin="round"
2228
+ >
2229
+ ${be(`<path d="M14 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V8z"/><polyline points="14 2 14 8 20 8"/>`+t)}
2230
+ </svg>`}function vm(e){return Ne(e.mimeType)===`image`?s`<img
2231
+ src=${e.thumbUrl}
2232
+ alt=${e.alt}
2233
+ class="w-full h-full object-cover rounded-lg border"
2234
+ loading="lazy"
2235
+ />`:s`<div
2236
+ class="w-full h-full rounded-lg border bg-muted flex flex-col items-center justify-center gap-1 p-1 text-muted-foreground"
2237
+ >
2238
+ ${_m(e.mimeType)}
2239
+ <span class="text-[10px] leading-tight text-center truncate w-full px-1"
2240
+ >${e.originalName}</span
2241
+ >
2242
+ </div>`}function ym(e){let{media:t,labels:n,_mediaIds:r}=e;if(r.length===0)return s`<p class="text-sm text-muted-foreground">
2243
+ ${n.mediaEmptyLabel}
2244
+ </p>`;let i=new Map(t.map(e=>[e.id,e]));return s`<div class="grid grid-cols-4 sm:grid-cols-6 gap-2 mb-2">
2245
+ ${r.map(t=>{let r=i.get(t);return r?s`<div class="relative group aspect-square" data-media-id=${t}>
2246
+ ${vm(r)}
2247
+ <button
2248
+ type="button"
2249
+ class="absolute top-1 right-1 w-5 h-5 flex items-center justify-center bg-black/60 text-white rounded-full text-xs opacity-0 group-hover:opacity-100 transition-opacity cursor-pointer"
2250
+ @click=${()=>e.removeMedia(t)}
2251
+ aria-label=${n.mediaRemoveButton}
2252
+ >
2253
+ &times;
2254
+ </button>
2255
+ </div>`:s`<div
2256
+ class="relative group aspect-square rounded-lg border bg-muted flex items-center justify-center text-xs text-muted-foreground"
2257
+ >
2258
+ ${t}
2259
+ <button
2260
+ type="button"
2261
+ class="absolute top-1 right-1 w-5 h-5 flex items-center justify-center bg-black/60 text-white rounded-full text-xs opacity-0 group-hover:opacity-100 transition-opacity cursor-pointer"
2262
+ @click=${()=>e.removeMedia(t)}
2263
+ aria-label=${n.mediaRemoveButton}
2264
+ >
2265
+ &times;
2266
+ </button>
2267
+ </div>`})}
2268
+ </div>`}function bm(e){return e.collections.length?s`<div class="field">
2269
+ <label class="label">${e.labels.collectionsLabel}</label>
2270
+ <div class="flex flex-col gap-1">
2271
+ ${e.collections.map(t=>s`<label class="flex items-center gap-2 text-sm">
2272
+ <input
2273
+ type="checkbox"
2274
+ class="checkbox"
2275
+ .checked=${e._collectionIds.includes(t.id)}
2276
+ @change=${()=>e.toggleCollection(t.id)}
2277
+ />
2278
+ <span>${t.title}</span>
2279
+ </label>`)}
2280
+ </div>
2281
+ </div>`:i}function xm(e){return s`<form
2282
+ class="flex flex-col gap-4 max-w-2xl"
2283
+ @submit=${t=>e.handleSubmit(t)}
2284
+ >
2285
+ <div class="field">
2286
+ <label class="label">${e.labels.formatLabel}</label>
2287
+ <select
2288
+ class="select"
2289
+ .value=${e._format}
2290
+ @change=${t=>{e._format=t.target.value??`note`}}
2291
+ >
2292
+ <option value="note">${e.labels.noteOption}</option>
2293
+ <option value="link">${e.labels.linkOption}</option>
2294
+ <option value="quote">${e.labels.quoteOption}</option>
2295
+ </select>
2296
+ </div>
2297
+
2298
+ <div class="field">
2299
+ <label class="label">${e.labels.titleLabel}</label>
2300
+ <input
2301
+ type="text"
2302
+ class="input"
2303
+ placeholder=${e.labels.titlePlaceholder}
2304
+ .value=${e._title}
2305
+ @input=${t=>e.handleTitleInput(t)}
2306
+ />
2307
+ </div>
2308
+
2309
+ <div class="field">
2310
+ <label class="label">${e.labels.slugLabel}</label>
2311
+ <input
2312
+ type="text"
2313
+ class="input"
2314
+ placeholder=${e.labels.slugPlaceholder}
2315
+ .value=${e._slug}
2316
+ @input=${t=>e.handleSlugInput(t)}
2317
+ />
2318
+ ${e._slug?s`<p class="text-xs text-muted-foreground mt-1">
2319
+ ${e.siteUrl}/${e._slug}
2320
+ </p>`:s`<p class="text-xs text-muted-foreground mt-1">
2321
+ ${e.labels.slugHelp}
2322
+ </p>`}
2323
+ </div>
2324
+
2325
+ <div class="field">
2326
+ <label class="label">${e.labels.bodyLabel}</label>
2327
+ <div
2328
+ class="post-form-tiptap-body compose-tiptap-body border rounded-lg p-3 min-h-32"
2329
+ ></div>
2330
+ </div>
2331
+
2332
+ <div class="field">
2333
+ <label class="label">${e.labels.urlLabel}</label>
2334
+ <input
2335
+ type="url"
2336
+ class="input"
2337
+ placeholder=${e.labels.urlPlaceholder}
2338
+ .value=${e._url}
2339
+ @input=${t=>e.handleInput(`_url`,t)}
2340
+ />
2341
+ </div>
2342
+
2343
+ ${e._format===`quote`?s`<div class="field">
2344
+ <label class="label">${e.labels.quoteTextLabel}</label>
2345
+ <textarea
2346
+ class="textarea"
2347
+ rows="3"
2348
+ placeholder=${e.labels.quoteTextPlaceholder}
2349
+ .value=${e._quoteText}
2350
+ @input=${t=>e.handleInput(`_quoteText`,t)}
2351
+ ></textarea>
2352
+ </div>`:i}
2353
+
2354
+ <div class="field">
2355
+ <label class="label">${e.labels.mediaLabel}</label>
2356
+ ${ym(e)}
2357
+ <button
2358
+ type="button"
2359
+ class="btn-outline text-sm"
2360
+ @click=${()=>e.openMediaPicker()}
2361
+ >
2362
+ ${e.labels.mediaAddButton}
2363
+ </button>
2364
+ </div>
2365
+
2366
+ <div class="field">
2367
+ <label class="label">${e.labels.statusLabel}</label>
2368
+ <select
2369
+ class="select"
2370
+ .value=${e._status}
2371
+ @change=${t=>{e._status=t.target.value??`published`}}
2372
+ >
2373
+ <option value="published">${e.labels.statusPublished}</option>
2374
+ <option value="draft">${e.labels.statusDraft}</option>
2375
+ </select>
2376
+ </div>
2377
+
2378
+ <div class="field">
2379
+ <label class="label">${e.labels.visibilityLabel}</label>
2380
+ <select
2381
+ class="select"
2382
+ .value=${e._visibility}
2383
+ @change=${t=>{e._visibility=t.target.value??`public`}}
2384
+ >
2385
+ <option value="public">${e.labels.visibilityPublic}</option>
2386
+ <option value="latest_hidden">
2387
+ ${e.labels.visibilityHiddenFromLatest}
2388
+ </option>
2389
+ </select>
2390
+ </div>
2391
+
2392
+ <label class="flex items-center gap-2 text-sm">
2393
+ <input
2394
+ type="checkbox"
2395
+ class="checkbox"
2396
+ .checked=${e._pinned}
2397
+ @change=${t=>{e._pinned=t.target.checked}}
2398
+ />
2399
+ ${e.labels.pinnedLabel}
2400
+ </label>
2401
+
2402
+ ${bm(e)}
2403
+
2404
+ <div class="flex gap-2">
2405
+ <button type="submit" class="btn" ?disabled=${e._loading}>
2406
+ ${e._loading?s`<svg
2407
+ class="animate-spin size-4"
2408
+ xmlns="http://www.w3.org/2000/svg"
2409
+ viewBox="0 0 24 24"
2410
+ fill="none"
2411
+ stroke="currentColor"
2412
+ stroke-width="2"
2413
+ stroke-linecap="round"
2414
+ stroke-linejoin="round"
2415
+ role="status"
2416
+ >
2417
+ <path d="M21 12a9 9 0 1 1-6.219-8.56" />
2418
+ </svg>`:i}
2419
+ ${e.labels.submitLabel}
2420
+ </button>
2421
+ <a href=${e.cancelHref} class="btn-outline"
2422
+ >${e.labels.cancelLabel}</a
2423
+ >
2424
+ </div>
2425
+ </form>
2426
+
2427
+ <dialog
2428
+ id="post-media-picker"
2429
+ class="p-6 rounded-lg max-w-2xl w-full backdrop:bg-black/50"
2430
+ @click=${t=>{t.target===t.currentTarget&&e.closeMediaPicker()}}
2431
+ >
2432
+ <div class="flex items-center justify-between mb-4">
2433
+ <h2 class="text-lg font-semibold">
2434
+ ${e.labels.mediaDialogTitle}
2435
+ </h2>
2436
+ <button
2437
+ type="button"
2438
+ class="btn-outline text-sm"
2439
+ @click=${()=>e.closeMediaPicker()}
2440
+ >
2441
+ ${e.labels.mediaDialogDone}
2442
+ </button>
2443
+ </div>
2444
+ <div
2445
+ id="post-media-grid"
2446
+ class="grid grid-cols-4 gap-2 max-h-96 overflow-y-auto"
2447
+ >
2448
+ <p class="text-muted-foreground text-sm col-span-4">
2449
+ ${e.labels.mediaDialogLoading}
2450
+ </p>
2451
+ </div>
2452
+ </dialog>`}var Sm={format:`note`,title:``,slug:``,body:``,url:``,quoteText:``,status:`published`,visibility:`public`,pinned:!1,rating:0,collectionIds:[],mediaIds:[]},Cm={formatLabel:``,noteOption:``,linkOption:``,quoteOption:``,titleLabel:``,titlePlaceholder:``,slugLabel:``,slugPlaceholder:``,slugHelp:``,bodyLabel:``,bodyPlaceholder:``,urlLabel:``,urlPlaceholder:``,quoteTextLabel:``,quoteTextPlaceholder:``,mediaLabel:``,mediaAddButton:``,mediaRemoveButton:``,mediaEmptyLabel:``,statusLabel:``,statusPublished:``,statusDraft:``,visibilityLabel:``,visibilityPublic:``,visibilityHiddenFromLatest:``,pinnedLabel:``,collectionsLabel:``,submitLabel:``,cancelLabel:``,mediaDialogTitle:``,mediaDialogDone:``,mediaDialogLoading:``,submitSuccessMessage:``,submitErrorMessage:``,draftFallbackMessage:``};function wm(e,t){if(typeof e==`string`)try{return JSON.parse(e)}catch{return t}return e&&typeof e==`object`?e:t}var Tm=class e extends o{static properties={labels:{type:Object},initial:{type:Object},collections:{type:Array},media:{type:Array},action:{type:String},cancelHref:{type:String,attribute:`cancel-href`},mediaPickerUrl:{type:String,attribute:`media-picker-url`},siteUrl:{type:String,attribute:`site-url`},isEdit:{type:Boolean,attribute:`is-edit`},_format:{state:!0},_title:{state:!0},_slug:{state:!0},_slugManuallyEdited:{state:!0},_body:{state:!0},_url:{state:!0},_quoteText:{state:!0},_status:{state:!0},_visibility:{state:!0},_pinned:{state:!0},_rating:{state:!0},_collectionIds:{state:!0},_mediaIds:{state:!0},_loading:{state:!0}};_editor=null;_bodyJson=null;#e=!1;#t=!1;#n=e=>{this.#t&&(e.preventDefault(),e.returnValue=``)};createRenderRoot(){return this.innerHTML=``,this}constructor(){super(),this.labels={...Cm},this.initial={...Sm},this.collections=[],this.media=[],this.action=``,this.cancelHref=`/`,this.mediaPickerUrl=``,this.siteUrl=``,this.isEdit=!1,this._format=`note`,this._title=``,this._slug=``,this._slugManuallyEdited=!1,this._body=``,this._url=``,this._quoteText=``,this._status=`published`,this._visibility=`public`,this._pinned=!1,this._rating=0,this._collectionIds=[],this._mediaIds=[],this._loading=!1}willUpdate(e){typeof this.labels==`string`&&(this.labels=wm(this.labels,{...Cm})),typeof this.initial==`string`&&(this.initial=wm(this.initial,{...Sm})),typeof this.collections==`string`&&(this.collections=wm(this.collections,[])),typeof this.media==`string`&&(this.media=wm(this.media,[])),(!this.#e||e.has(`initial`))&&this.#i()}set loading(e){this._loading=e}get loading(){return this._loading}set mediaIds(e){this._mediaIds=[...e]}get mediaIds(){return[...this._mediaIds]}get#r(){return this.querySelector(`#post-media-picker`)}connectedCallback(){super.connectedCallback(),window.addEventListener(`beforeunload`,this.#n)}disconnectedCallback(){super.disconnectedCallback(),window.removeEventListener(`beforeunload`,this.#n),this._editor?.destroy(),this._editor=null,this.closeMediaPicker()}#i(){let e=this.initial??Sm;if(this._format=e.format??`note`,this._title=e.title??``,this._slug=e.slug??``,this._slugManuallyEdited=!!e.slug,this._body=e.body??``,this._url=e.url??``,this._quoteText=e.quoteText??``,this._status=e.status??`published`,this._visibility=e.visibility??`public`,this._pinned=!!e.pinned,this._rating=e.rating??0,this._collectionIds=[...e.collectionIds??[]],this._mediaIds=[...e.mediaIds??[]],this.#e=!0,this._body&&this._body.startsWith(`{`))try{this._bodyJson=JSON.parse(this._body)}catch{this._bodyJson=null}else this._bodyJson=null}initEditor(){if(this._editor)return;let e=this.querySelector(`.post-form-tiptap-body`);e&&(this._editor=y({element:e,placeholder:this.labels.bodyPlaceholder??`Write something…`,content:this._bodyJson,onUpdate:e=>{this._bodyJson=e,this._body=JSON.stringify(e)},pasteMedia:{shouldInsertInline:e=>e.type.startsWith(`image/`)}}))}static#a=new Set([`_format`,`_title`,`_slug`,`_body`,`_url`,`_quoteText`,`_status`,`_visibility`,`_pinned`,`_rating`,`_collectionIds`,`_mediaIds`]);updated(t){if(super.updated(t),this._editor||this.initEditor(),this.#e&&!t.has(`initial`)){for(let n of t.keys())if(e.#a.has(n)){this.#t=!0;break}}}clearDirty(){this.#t=!1}handleInput(e,t){this[e]=t.target.value}handleTitleInput(e){let t=e.target;this._title=t.value,this._slugManuallyEdited||(this._slug=t.value.toLowerCase().replace(/[^a-z0-9]+/g,`-`).replace(/^-|-$/g,``))}handleSlugInput(e){this._slug=e.target.value,this._slugManuallyEdited=!0}toggleCollection(e){this._collectionIds=this._collectionIds.includes(e)?this._collectionIds.filter(t=>t!==e):[...this._collectionIds,e]}removeMedia(e){this._mediaIds=this._mediaIds.filter(t=>t!==e)}openMediaPicker(){let e=this.#r;e&&(e.showModal(),this.dispatchEvent(new CustomEvent(`jant:post-load-media`,{bubbles:!0,detail:{endpoint:this.mediaPickerUrl,selectedIds:[...this._mediaIds]}})))}closeMediaPicker(){this.#r?.close()}handleSubmit(e){if(e.preventDefault(),this._loading||!this.action)return;let t=this._bodyJson?JSON.stringify(this._bodyJson):this._body,n={endpoint:this.action,isEdit:this.isEdit,data:{format:this._format,title:this._title.trim(),slug:this._slug.trim()||void 0,body:t,status:this._status,visibility:this._visibility,pinned:this._pinned,url:this._url.trim(),quoteText:this._quoteText.trim(),rating:this._rating,collectionIds:[...this._collectionIds],mediaIds:[...this._mediaIds]},messages:{success:this.labels.submitSuccessMessage,error:this.labels.submitErrorMessage}};this.dispatchEvent(new CustomEvent(`jant:post-submit`,{bubbles:!0,detail:n}))}render(){return xm(this)}};customElements.define(`jant-post-form`,Tm);function Em(e){return e instanceof HTMLElement&&e.tagName===`JANT-POST-FORM`?e:e instanceof HTMLElement?e.closest(`jant-post-form`):document.querySelector(`jant-post-form`)}function Dm(e,t){e.classList.toggle(`ring-2`,t),e.classList.toggle(`ring-primary`,t),e.classList.toggle(`border-primary`,t)}async function Om(e){let t=e,n=t.detail;if(!n)return;let r=Em(t.target);if(!(!r||!n.endpoint)){r.loading=!0;try{let e=await fetch(n.endpoint,{method:`POST`,headers:{"Content-Type":`application/json`,Accept:`application/json`},body:JSON.stringify(n.data)});if(!e.ok){let t=n.messages.error;try{let n=await d(e);t=C(n,`error`)??C(n,`message`)??t}catch{}if(n.data.status===`published`&&!n.isEdit)try{let e=await fetch(n.endpoint,{method:`POST`,headers:{"Content-Type":`application/json`,Accept:`application/json`},body:JSON.stringify({...n.data,status:`draft`})});if(e.ok){let t=await d(e),n=r.getAttribute(`labels`),i=`Couldn't publish. Saved as draft.`;if(n)try{let e=JSON.parse(n);e.draftFallbackMessage&&(i=e.draftFallbackMessage)}catch{}let a=C(t,`status`),o=C(t,`url`);if(a===`redirect`&&o){r.clearDirty(),x(i),window.location.href=o;return}m(i),r.clearDirty();return}}catch{}throw Error(t)}let t=await d(e),i=C(t,`status`),a=C(t,`url`);if(i===`redirect`&&a){r.clearDirty(),x(n.messages.success),window.location.href=a;return}r.clearDirty(),m(n.messages.success)}catch(e){m(e instanceof Error&&e.message?e.message:n.messages.error,`error`)}finally{r.loading=!1}}}async function km(e){let t=e,n=t.detail;if(!n?.endpoint)return;let r=document.getElementById(`post-media-grid`),i=Em(t.target);if(!r||!i)return;try{r.innerHTML=`<p class="text-muted-foreground text-sm col-span-4">Loading...</p>`,r.innerHTML=await(await fetch(n.endpoint,{headers:{Accept:`text/html`}})).text()}catch{r.innerHTML=`<p class="text-red-500 text-sm col-span-4">Failed to load media.</p>`;return}let a=new Set(n.selectedIds);r.querySelectorAll(`[data-media-id]`).forEach(e=>{let t=e.dataset.mediaId;t&&Dm(e,a.has(t))}),r.onclick=e=>{let t=e.target.closest(`[data-media-id]`);if(!t)return;let n=t.dataset.mediaId;if(!n)return;let r=new Set(i.mediaIds);r.has(n)?(r.delete(n),Dm(t,!1)):(r.add(n),Dm(t,!0)),i.mediaIds=[...r]}}document.addEventListener(`jant:post-submit`,Om),document.addEventListener(`jant:post-load-media`,km);var Am=class extends o{static properties={items:{type:Array},labels:{type:Object},systemNavItems:{type:Array,attribute:`system-nav-items`},siteName:{type:String,attribute:`site-name`},maxVisible:{type:Number,attribute:`max-visible`},homeDefaultView:{type:String,attribute:`home-default-view`},_items:{state:!0},_editingId:{state:!0},_editLabel:{state:!0},_editUrl:{state:!0},_togglingKeys:{state:!0},_showOverflow:{state:!0},_showLinkForm:{state:!0},_newLinkLabel:{state:!0},_newLinkUrl:{state:!0},_addingLink:{state:!0}};#e=null;#t=!1;#n=()=>{this._showOverflow=!1,document.removeEventListener(`click`,this.#n)};#r=()=>{this._showLinkForm=!1,document.removeEventListener(`click`,this.#r)};createRenderRoot(){return this.innerHTML=``,this}constructor(){super(),this.items=[],this.labels={},this.systemNavItems=[],this.siteName=``,this.maxVisible=2,this.homeDefaultView=`latest`,this._items=[],this._editingId=null,this._editLabel=``,this._editUrl=``,this._togglingKeys=new Set,this._showOverflow=!1,this._showLinkForm=!1,this._newLinkLabel=``,this._newLinkUrl=``,this._addingLink=!1}update(e){(!this.#t||e.has(`items`))&&(this._items=[...this.items??[]],this.#t=!0),super.update(e)}updated(){this.#i()}disconnectedCallback(){super.disconnectedCallback(),this.#e?.destroy(),this.#e=null,document.removeEventListener(`click`,this.#n),document.removeEventListener(`click`,this.#r)}#i(){let e=this.querySelector(`#nav-items-list`);!e||this.#e||(this.#e=P.create(e,{...vr,animation:150,handle:`[data-drag-handle]`,onEnd:t=>{let n=yr(e,`[data-nav-id]`,`navId`);xr(e,t),this.#e?.destroy(),this.#e=null;let{movedId:r,afterId:i,beforeId:a}=Cr(n,t.newIndex);if(!r)return;let o=new Map(this._items.map(e=>[e.id,e]));this._items=n.map(e=>o.get(e)).filter(e=>e!==void 0),fetch(`/api/nav-items/${r}/move`,{method:`PUT`,headers:{"Content-Type":`application/json`},body:JSON.stringify({after:i??null,before:a??null})}).then(e=>{e.ok?m(this.labels.orderSaved):m(this.labels.saveFailed,`error`)})}}))}#a(e){e.type!==`system`&&(this._editingId===e.id?this._editingId=null:(this._editingId=e.id,this._editLabel=e.label,this._editUrl=e.url))}#o(e){let t=this._editLabel.trim();if(!t){m(this.labels.labelRequired,`error`);return}let n={id:e.id,label:t,...e.type===`link`&&{url:this._editUrl.trim()}};this.dispatchEvent(new CustomEvent(`jant:nav-update`,{bubbles:!0,detail:n}))}#s(e){this.dispatchEvent(new CustomEvent(`jant:nav-delete`,{bubbles:!0,detail:{id:e.id}}))}async#c(e){let t=Math.max(0,Math.min(5,e));this.maxVisible=t;try{(await fetch(`/settings/navigation/nav-max-visible`,{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify({value:t})})).ok?m(this.labels.maxVisibleSaved):m(this.labels.saveFailed,`error`)}catch{m(this.labels.saveFailed,`error`)}}async#l(e){this.homeDefaultView=e?`featured`:`latest`;try{(await fetch(`/settings/navigation/home-default-view`,{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify({value:this.homeDefaultView})})).ok?m(this.labels.homeViewSaved):m(this.labels.saveFailed,`error`)}catch{m(this.labels.saveFailed,`error`)}}async#u(){let e=this._newLinkLabel.trim(),t=this._newLinkUrl.trim();if(!e||!t){m(this.labels.labelAndUrlRequired,`error`);return}this._addingLink=!0;try{let n=await fetch(`/api/nav-items`,{method:`POST`,headers:{"Content-Type":`application/json`,Accept:`application/json`},body:JSON.stringify({type:`link`,label:e,url:t})});if(!n.ok)throw Error(`HTTP ${n.status}`);let r=await n.json();this.#e?.destroy(),this.#e=null,this._items=[...this._items,r],this._newLinkLabel=``,this._newLinkUrl=``,this._showLinkForm=!1,document.removeEventListener(`click`,this.#r)}catch{m(this.labels.saveFailed,`error`)}finally{this._addingLink=!1}}#d(e){return this._items.some(t=>t.type===`system`&&t.systemKey===e.key)}async#f(e,t){this._togglingKeys=new Set([...this._togglingKeys,e.key]);try{if(t){let t=await fetch(`/api/nav-items`,{method:`POST`,headers:{"Content-Type":`application/json`,Accept:`application/json`},body:JSON.stringify({type:`system`,systemKey:e.key})});if(!t.ok)throw Error(`HTTP ${t.status}`);let n=await t.json();this.#e?.destroy(),this.#e=null,this._items=[...this._items,{...n,displayLabel:e.label}]}else{let t=this._items.find(t=>t.type===`system`&&t.systemKey===e.key);if(t){let e=await fetch(`/api/nav-items/${t.id}`,{method:`DELETE`,headers:{Accept:`application/json`}});if(!e.ok)throw Error(`HTTP ${e.status}`);this.#e?.destroy(),this.#e=null,this._items=this._items.filter(e=>e.id!==t.id)}}}catch{m(this.labels.saveFailed,`error`),this.requestUpdate()}finally{let t=new Set(this._togglingKeys);t.delete(e.key),this._togglingKeys=t}}#p(){let e=this._items.slice(0,this.maxVisible),t=this._items.slice(this.maxVisible),n=t.length>0;return s`
2453
+ <div class="nav-preview">
2454
+ <div class="nav-preview-chrome">
2455
+ <div class="nav-preview-dots">
2456
+ <span></span><span></span><span></span>
2457
+ </div>
2458
+ <span class="nav-preview-label">${this.labels.preview}</span>
2459
+ </div>
2460
+ <div class="nav-preview-content">
2461
+ <div class="site-header-top">
2462
+ <a href=${a(`/`)} class="site-logo">${this.siteName}</a>
2463
+ <div class="site-header-right">
2464
+ ${e.length>0||n?s`<nav class="site-header-nav">
2465
+ ${e.map(e=>s`<a
2466
+ href=${a(e.url)}
2467
+ class="site-header-link"
2468
+ >
2469
+ ${e.displayLabel??e.label}
2470
+ </a>`)}
2471
+ ${n?s`<div class="dropdown-menu site-header-more">
2472
+ <button
2473
+ type="button"
2474
+ class="site-header-more-btn"
2475
+ aria-haspopup="menu"
2476
+ aria-expanded=${this._showOverflow}
2477
+ @click=${e=>{e.stopPropagation(),this._showOverflow=!this._showOverflow,this._showOverflow?setTimeout(()=>{document.addEventListener(`click`,this.#n)}):document.removeEventListener(`click`,this.#n)}}
2478
+ >
2479
+ <svg
2480
+ xmlns="http://www.w3.org/2000/svg"
2481
+ width="16"
2482
+ height="16"
2483
+ viewBox="0 0 24 24"
2484
+ fill="currentColor"
2485
+ >
2486
+ <circle cx="5" cy="12" r="2" />
2487
+ <circle cx="12" cy="12" r="2" />
2488
+ <circle cx="19" cy="12" r="2" />
2489
+ </svg>
2490
+ </button>
2491
+ ${this._showOverflow?s`<div
2492
+ data-popover
2493
+ data-align="end"
2494
+ aria-hidden="false"
2495
+ >
2496
+ <div role="menu">
2497
+ ${t.map(e=>s`<a
2498
+ href=${a(e.url)}
2499
+ role="menuitem"
2500
+ >
2501
+ ${e.displayLabel??e.label}
2502
+ </a>`)}
2503
+ </div>
2504
+ </div>`:i}
2505
+ </div>`:i}
2506
+ </nav>`:i}
2507
+ <span class="site-header-search" aria-hidden="true">
2508
+ <svg
2509
+ xmlns="http://www.w3.org/2000/svg"
2510
+ width="16"
2511
+ height="16"
2512
+ viewBox="0 0 24 24"
2513
+ fill="none"
2514
+ stroke="currentColor"
2515
+ stroke-width="2"
2516
+ stroke-linecap="round"
2517
+ stroke-linejoin="round"
2518
+ >
2519
+ <circle cx="11" cy="11" r="8" />
2520
+ <path d="m21 21-4.35-4.35" />
2521
+ </svg>
2522
+ </span>
2523
+ </div>
2524
+ </div>
2525
+ <nav class="site-browse-nav">
2526
+ <span class="site-browse-link site-browse-link-active">
2527
+ ${this.homeDefaultView===`featured`?this.labels.featured:this.labels.latest}
2528
+ </span>
2529
+ <span class="site-browse-sep" aria-hidden="true">/</span>
2530
+ <span class="site-browse-link">
2531
+ ${this.homeDefaultView===`featured`?this.labels.latest:this.labels.featured}
2532
+ </span>
2533
+ </nav>
2534
+ </div>
2535
+ </div>
2536
+ `}#m(e){return s`<span class="badge-secondary">${e===`system`?this.labels.system:this.labels.link}</span>`}#h(e){return this._editingId===e.id&&e.type===`link`?s`
2537
+ <div class="nav-item-edit">
2538
+ <div class="field">
2539
+ <label class="label">${this.labels.label}</label>
2540
+ <input
2541
+ type="text"
2542
+ class="input"
2543
+ required
2544
+ .value=${this._editLabel}
2545
+ @input=${e=>{this._editLabel=e.target.value}}
2546
+ />
2547
+ </div>
2548
+ <div class="field">
2549
+ <label class="label">${this.labels.url}</label>
2550
+ <input
2551
+ type="text"
2552
+ class="input"
2553
+ required
2554
+ .value=${this._editUrl}
2555
+ @input=${e=>{this._editUrl=e.target.value}}
2556
+ />
2557
+ </div>
2558
+ <div class="flex items-center justify-between">
2559
+ <button
2560
+ type="button"
2561
+ class="btn-sm-ghost text-destructive"
2562
+ @click=${()=>this.#s(e)}
2563
+ >
2564
+ ${this.labels.delete}
2565
+ </button>
2566
+ <button
2567
+ type="button"
2568
+ class="btn-sm"
2569
+ @click=${()=>this.#o(e)}
2570
+ >
2571
+ ${this.labels.save}
2572
+ </button>
2573
+ </div>
2574
+ </div>
2575
+ `:i}#g(e){let t=this._editingId===e.id;return s`
2576
+ <div
2577
+ data-nav-id=${e.id}
2578
+ class="nav-item${t?` nav-item-editing`:``}"
2579
+ >
2580
+ <div class="nav-item-row">
2581
+ <div class="nav-item-handle" data-drag-handle>
2582
+ <svg
2583
+ xmlns="http://www.w3.org/2000/svg"
2584
+ width="14"
2585
+ height="14"
2586
+ viewBox="0 0 24 24"
2587
+ fill="none"
2588
+ stroke="currentColor"
2589
+ stroke-width="2"
2590
+ stroke-linecap="round"
2591
+ stroke-linejoin="round"
2592
+ class="text-muted-foreground shrink-0"
2593
+ >
2594
+ <circle cx="9" cy="12" r="1" />
2595
+ <circle cx="9" cy="5" r="1" />
2596
+ <circle cx="9" cy="19" r="1" />
2597
+ <circle cx="15" cy="12" r="1" />
2598
+ <circle cx="15" cy="5" r="1" />
2599
+ <circle cx="15" cy="19" r="1" />
2600
+ </svg>
2601
+ </div>
2602
+ <div
2603
+ class="nav-item-info"
2604
+ @click=${e.type===`link`?()=>this.#a(e):void 0}
2605
+ >
2606
+ <div class="flex items-center gap-2 min-w-0">
2607
+ <span class="text-sm font-medium truncate"
2608
+ >${e.displayLabel??e.label}</span
2609
+ >
2610
+ ${this.#m(e.type)}
2611
+ </div>
2612
+ <span class="text-xs text-muted-foreground truncate"
2613
+ >${e.url}</span
2614
+ >
2615
+ </div>
2616
+ ${e.type===`link`?s`<button
2617
+ type="button"
2618
+ class="nav-item-toggle"
2619
+ @click=${()=>this.#a(e)}
2620
+ aria-label=${this.labels.toggleEdit}
2621
+ >
2622
+ <svg
2623
+ xmlns="http://www.w3.org/2000/svg"
2624
+ width="14"
2625
+ height="14"
2626
+ viewBox="0 0 24 24"
2627
+ fill="none"
2628
+ stroke="currentColor"
2629
+ stroke-width="2"
2630
+ stroke-linecap="round"
2631
+ stroke-linejoin="round"
2632
+ style="transition: transform 0.15s; ${t?`transform: rotate(180deg);`:``}"
2633
+ >
2634
+ <path d="m6 9 6 6 6-6" />
2635
+ </svg>
2636
+ </button>`:i}
2637
+ </div>
2638
+ ${this.#h(e)}
2639
+ </div>
2640
+ `}#_(){return s`
2641
+ <section class="mt-8">
2642
+ <h2 class="text-lg font-semibold mb-3">
2643
+ ${this.labels.addCustomLinkToNavigation}
2644
+ </h2>
2645
+ <div id="nav-link-popover" class="popover">
2646
+ <button
2647
+ id="nav-link-popover-trigger"
2648
+ type="button"
2649
+ aria-expanded=${this._showLinkForm}
2650
+ aria-controls="nav-link-popover-content"
2651
+ class="btn-outline"
2652
+ @click=${e=>{e.stopPropagation(),this._showLinkForm=!this._showLinkForm,this._showLinkForm?setTimeout(()=>{document.addEventListener(`click`,this.#r)}):document.removeEventListener(`click`,this.#r)}}
2653
+ >
2654
+ ${this.labels.addLink}
2655
+ </button>
2656
+ ${this._showLinkForm?s`
2657
+ <div
2658
+ id="nav-link-popover-content"
2659
+ data-popover
2660
+ data-side="top"
2661
+ aria-hidden="false"
2662
+ class="w-80"
2663
+ style="bottom: 100%; margin-bottom: 0.5rem;"
2664
+ @click=${e=>e.stopPropagation()}
2665
+ >
2666
+ <div class="grid gap-4">
2667
+ <header class="grid gap-1.5">
2668
+ <h4 class="leading-none font-medium">
2669
+ ${this.labels.addLink}
2670
+ </h4>
2671
+ <p class="text-muted-foreground text-sm">
2672
+ ${this.labels.addLinkDescription}
2673
+ </p>
2674
+ </header>
2675
+ <form
2676
+ class="form grid gap-2"
2677
+ @submit=${e=>{e.preventDefault(),this.#u()}}
2678
+ >
2679
+ <div class="grid grid-cols-3 items-center gap-4">
2680
+ <label for="nav-link-label">${this.labels.label}</label>
2681
+ <input
2682
+ type="text"
2683
+ id="nav-link-label"
2684
+ class="col-span-2 h-8"
2685
+ placeholder="Home"
2686
+ required
2687
+ .value=${this._newLinkLabel}
2688
+ @input=${e=>{this._newLinkLabel=e.target.value}}
2689
+ autofocus
2690
+ />
2691
+ </div>
2692
+ <div class="grid grid-cols-3 items-center gap-4">
2693
+ <label for="nav-link-url">${this.labels.url}</label>
2694
+ <input
2695
+ type="text"
2696
+ id="nav-link-url"
2697
+ class="col-span-2 h-8"
2698
+ placeholder=${this.labels.urlPlaceholder}
2699
+ required
2700
+ .value=${this._newLinkUrl}
2701
+ @input=${e=>{this._newLinkUrl=e.target.value}}
2702
+ />
2703
+ </div>
2704
+ <button
2705
+ type="submit"
2706
+ class="btn-sm mt-2"
2707
+ ?disabled=${this._addingLink}
2708
+ >
2709
+ ${this.labels.addLink}
2710
+ </button>
2711
+ </form>
2712
+ </div>
2713
+ </div>
2714
+ `:i}
2715
+ </div>
2716
+ </section>
2717
+ `}#v(){return this.systemNavItems?.length?s`
2718
+ <section class="mt-8">
2719
+ <h2 class="text-lg font-semibold mb-1">${this.labels.systemLinks}</h2>
2720
+ <p class="text-sm text-muted-foreground mb-3">
2721
+ ${this.labels.systemLinksDescription}
2722
+ </p>
2723
+ <div class="flex flex-col divide-y">
2724
+ ${this.systemNavItems.map(e=>{let t=this.#d(e),n=this._togglingKeys.has(e.key);return s`
2725
+ <label class=${n?`flex items-center justify-between gap-4 py-3 opacity-60 cursor-not-allowed`:`flex items-center justify-between gap-4 py-3 cursor-pointer`}>
2726
+ <div>
2727
+ <p class="font-medium">${e.label}</p>
2728
+ <p class="text-sm text-muted-foreground">
2729
+ ${e.description}
2730
+ </p>
2731
+ </div>
2732
+ <input
2733
+ type="checkbox"
2734
+ role="switch"
2735
+ class="input"
2736
+ .checked=${t}
2737
+ ?disabled=${n}
2738
+ @change=${t=>{let n=t.target.checked;this.#f(e,n)}}
2739
+ />
2740
+ </label>
2741
+ `})}
2742
+ </div>
2743
+ </section>
2744
+ `:i}render(){return s`
2745
+ ${this.#p()}
2746
+
2747
+ <div class="flex flex-col gap-4 mt-3">
2748
+ <div class="flex items-start justify-between gap-4">
2749
+ <div class="flex flex-col gap-0.5">
2750
+ <label class="text-sm font-medium" for="nav-max-visible">
2751
+ ${this.labels.maxVisibleLinks}
2752
+ </label>
2753
+ <p class="text-xs text-muted-foreground">
2754
+ ${this.labels.maxVisibleLinksDescription}
2755
+ </p>
2756
+ </div>
2757
+ <input
2758
+ type="number"
2759
+ id="nav-max-visible"
2760
+ class="input w-16 h-8 shrink-0"
2761
+ min="0"
2762
+ max="5"
2763
+ .value=${String(this.maxVisible)}
2764
+ @change=${e=>{let t=parseInt(e.target.value,10);isNaN(t)||this.#c(t)}}
2765
+ />
2766
+ </div>
2767
+ <label class="flex items-start justify-between gap-4 cursor-pointer">
2768
+ <div class="flex flex-col gap-0.5">
2769
+ <span class="text-sm font-medium">
2770
+ ${this.labels.useFeaturedAsDefault}
2771
+ </span>
2772
+ <p class="text-xs text-muted-foreground">
2773
+ ${this.labels.useFeaturedAsDefaultDescription}
2774
+ </p>
2775
+ </div>
2776
+ <input
2777
+ type="checkbox"
2778
+ role="switch"
2779
+ id="nav-home-view"
2780
+ class="input shrink-0"
2781
+ .checked=${this.homeDefaultView===`featured`}
2782
+ @change=${e=>{this.#l(e.target.checked)}}
2783
+ />
2784
+ </label>
2785
+ </div>
2786
+
2787
+ <section class="mt-8">
2788
+ <h2 class="text-lg font-semibold mb-3">
2789
+ ${this.labels.navigationItems}
2790
+ </h2>
2791
+ ${this._items.length===0?s`<p class="text-sm text-muted-foreground py-4">
2792
+ ${this.labels.emptyState}
2793
+ </p>`:s`
2794
+ <div id="nav-items-list" class="nav-items-list">
2795
+ ${this._items.map(e=>this.#g(e))}
2796
+ </div>
2797
+ `}
2798
+ </section>
2799
+
2800
+ ${this.#_()} ${this.#v()}
2801
+ `}};customElements.define(`jant-nav-manager`,Am),document.addEventListener(`jant:nav-update`,async e=>{let{detail:t}=e;if(t?.id)try{let e=await fetch(`/api/nav-items/${t.id}`,{method:`PUT`,headers:{"Content-Type":`application/json`,Accept:`application/json`},body:JSON.stringify({label:t.label,...t.url!==void 0&&{url:t.url}})});if(!e.ok)throw Error(`HTTP ${e.status}`);window.location.reload()}catch{m(`Failed to save. Please try again.`,`error`)}}),document.addEventListener(`jant:nav-delete`,async e=>{let{detail:t}=e;if(t?.id)try{let e=await fetch(`/api/nav-items/${t.id}`,{method:`DELETE`,headers:{Accept:`application/json`}});if(!e.ok)throw Error(`HTTP ${e.status}`);window.location.reload()}catch{m(`Failed to delete. Please try again.`,`error`)}});var jm=`M12 3 10.1 10.1 3 12l7.1 1.9L12 21l1.9-7.1L21 12l-7.1-1.9Z`,Mm=`M4 4 20 20`,Nm=360,Pm=12;function Fm(e){let t=window.innerHeight-e.bottom-Pm,n=e.top-Pm;return t<Nm&&n>t}function Im(e){let t=Array.from(e?.children??[]).find(e=>e instanceof HTMLElement&&e.classList.contains(`feed-item`));Array.from(t?.children??[]).find(e=>e instanceof HTMLElement&&e.classList.contains(`feed-divider`))?.remove()}var Lm=class extends o{static properties={_open:{state:!0},_data:{state:!0},_x:{state:!0},_y:{state:!0},_openAbove:{state:!0},_view:{state:!0},_collections:{state:!0},_collectionsLoading:{state:!0},_collectionSearch:{state:!0},_postCollectionIds:{state:!0},_addCollectionPanelOpen:{state:!0}};#e=!1;createRenderRoot(){return this.innerHTML=``,this}constructor(){super(),this._open=!1,this._data=null,this._x=0,this._y=0,this._openAbove=!0,this._view=`menu`,this._collections=null,this._collectionsLoading=!1,this._collectionSearch=``,this._postCollectionIds=[],this._addCollectionPanelOpen=!1,this._triggerEl=null}connectedCallback(){super.connectedCallback(),document.addEventListener(`click`,this.#i),document.addEventListener(`keydown`,this.#r),window.addEventListener(`resize`,this.#n)}disconnectedCallback(){super.disconnectedCallback(),document.removeEventListener(`click`,this.#i),document.removeEventListener(`keydown`,this.#r),window.removeEventListener(`resize`,this.#n)}#t(){let e=this._triggerEl;if(!e?.isConnected){this._open&&this.#c({restoreFocus:!1});return}let t=e.getBoundingClientRect();this._openAbove=Fm(t),this._x=window.scrollX+t.right,this._y=window.scrollY+(this._openAbove?t.top-6:t.bottom+6)}#n=()=>{!this._open||this._addCollectionPanelOpen||this.#t()};#r=e=>{if(e.key===`Escape`){if(this._addCollectionPanelOpen){this.#_();return}let e=document.querySelector(`[data-collection-popover].open`);if(e){e.classList.remove(`open`);return}if(this._open){if(this._view!==`menu`){this.#o();return}this.#c()}}};#i=e=>{let t=e.target,n=t.closest(`[data-collection-popover-trigger]`);if(n){e.preventDefault(),e.stopPropagation();let t=n.parentElement?.querySelector(`[data-collection-popover]`);t&&t.classList.toggle(`open`);return}if(t.closest(`[data-collection-popover]`)||t.closest(`[data-collection-quick-dialog]`)||t.classList.contains(`collection-quick-dialog-backdrop`))return;let r=document.querySelector(`[data-collection-popover].open`);r&&r.classList.remove(`open`);let i=t.closest(`[data-post-menu-trigger]`);if(i){e.preventDefault(),e.stopPropagation();let t=i.closest(`article[data-post]`);if(!t)return;let n=t.dataset.postId;if(!n)return;if(this._open&&this._data?.id===n){this.#c();return}this._data={id:n,pinned:t.hasAttribute(`data-post-pinned`),featured:t.hasAttribute(`data-post-featured`),visibility:t.dataset.postVisibility??`public`,isReply:t.hasAttribute(`data-post-reply`)},this._triggerEl=i,this.#t(),i.setAttribute(`aria-expanded`,`true`),this._view=`menu`,this._open=!0,this.#a(`[data-post-menu-item-primary]`);return}this._open&&t.closest?.(`[role='menu'], [data-collection-picker], [data-visibility-panel]`)||this._open&&this.#c({restoreFocus:!1})};#a(e){this.updateComplete.then(()=>{this.querySelector(e)?.focus()})}#o(e=`[data-post-menu-item-primary]`){this._view=`menu`,this.#a(e)}#s(){this._data?.isReply||(this._view=`visibility`,this.#a(`[data-post-menu-visibility-current='true'], [data-post-menu-visibility-option]`))}#c(e={}){let{restoreFocus:t=!0}=e,n=this._triggerEl;if(n?.setAttribute(`aria-expanded`,`false`),this._triggerEl=null,this._open=!1,this._view=`menu`,this._addCollectionPanelOpen=!1,this._collectionSearch=``,this.#e){this.#e=!1,window.location.reload();return}t&&n?.focus()}async#l(){if(!this._data)return;let e=this._data.id;this.#c({restoreFocus:!1});let t=document.getElementById(`compose-dialog`)?.querySelector(`jant-compose-dialog`);t&&await t.openEdit(e)}async#u(e){if(this._data){try{if(!(await fetch(`/api/posts/${this._data.id}`,{method:`PUT`,headers:{"Content-Type":`application/json`},body:JSON.stringify({visibility:e})})).ok)throw Error();let t=document.querySelector(`article[data-post-id="${this._data.id}"]`);t&&(t.dataset.postVisibility=e),this._data={...this._data,visibility:e},m({public:`Post made public.`,latest_hidden:`Hidden from Latest.`,private:`Post made private.`}[e]??`Visibility updated.`)}catch{m(`Could not update post. Try again.`,`error`)}this.#c()}}async#d(e){if(this._data){try{if(!(await fetch(`/api/posts/${this._data.id}`,{method:`PUT`,headers:{"Content-Type":`application/json`},body:JSON.stringify({featured:e})})).ok)throw Error();let t=document.querySelector(`article[data-post-id="${this._data.id}"]`);t&&(e?t.setAttribute(`data-post-featured`,``):t.removeAttribute(`data-post-featured`)),this._data={...this._data,featured:e},m(e?`Added to Featured.`:`Removed from Featured.`)}catch{m(`Could not update post. Try again.`,`error`)}this.#c()}}async#f(){if(!this._data)return;let e=!this._data.pinned;try{if(!(await fetch(`/api/posts/${this._data.id}`,{method:`PUT`,headers:{"Content-Type":`application/json`},body:JSON.stringify({pinned:e})})).ok)throw Error();let t=document.querySelector(`article[data-post-id="${this._data.id}"]`);t&&(e?t.setAttribute(`data-post-pinned`,``):t.removeAttribute(`data-post-pinned`)),this._data={...this._data,pinned:e},m(e?`Post pinned.`:`Post unpinned.`)}catch{m(`Could not update post. Try again.`,`error`)}this.#c()}async#p(){if(!this._data)return;let e=this._triggerEl;if(this.#c({restoreFocus:!1}),!await ve({message:`Delete this post permanently? This can't be undone.`,confirmLabel:`Delete`,cancelLabel:`Cancel`,tone:`danger`})){e?.focus();return}try{if(!(await fetch(`/api/posts/${this._data.id}`,{method:`DELETE`})).ok)throw Error();let e=document.querySelector(`article[data-post-id="${this._data.id}"]`),t=e?.closest(`.feed-item`),n=t?.parentElement;(t??e)?.remove(),Im(n),m(`Post deleted.`)}catch{m(`Could not delete post. Try again.`,`error`),e?.focus()}}async#m(){if(!this._data)return;let e=this._data.id;this._view=`collections`,this._collectionSearch=``,this._collectionsLoading=!0,this.#a(`.post-menu-picker-search input, .post-menu-picker-option, [data-post-menu-add-collection]`);try{let[t,n]=await Promise.all([fetch(`/api/collections`),fetch(`/api/posts/${e}`)]);if(!t.ok)throw Error();this._collections=(await t.json()).collections??[],n.ok&&(this._postCollectionIds=(await n.json()).collectionIds??[])}catch{this._collections=this._collections??[],m(`Could not load collections.`,`error`)}this._collectionsLoading=!1,this.#a(`.post-menu-picker-search input, .post-menu-picker-option, [data-post-menu-add-collection]`)}async#h(e){if(!this._data)return;let t=this._postCollectionIds.includes(e);try{if(t){if(!(await fetch(`/api/collections/${e}/posts/${this._data.id}`,{method:`DELETE`})).ok)throw Error();this._postCollectionIds=this._postCollectionIds.filter(t=>t!==e),this.#e=!0,m(`Removed from collection.`)}else{let t=await fetch(`/api/collections/${e}/posts`,{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify({postId:this._data.id})});if(!t.ok){let n=await t.json().catch(()=>null);if(t.status===409||n?.error?.includes(`already`)){this._postCollectionIds.includes(e)||(this._postCollectionIds=[...this._postCollectionIds,e]);return}throw Error()}this._postCollectionIds=[...this._postCollectionIds,e],this.#e=!0,m(`Added to collection.`)}}catch{m(t?`Could not remove from collection. Try again.`:`Could not add to collection. Try again.`,`error`)}}#g(){this._addCollectionPanelOpen=!0,this.updateComplete.then(()=>{let e=this.querySelector(`[data-collection-quick-dialog] [data-collection-title-input]`);e?.focus(),e?.select()})}#_(){this._addCollectionPanelOpen=!1,this.#t(),this.updateComplete.then(()=>{(this.querySelector(`[data-post-menu-add-collection]`)??this._triggerEl)?.focus()})}async#v(e){let t=e;t.stopPropagation();let n=t.detail;if(!n)return;let r=this.querySelector(`jant-collection-form`);r&&(r.loading=!0);try{let e=await fetch(`/api/collections`,{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify(n.data)}),t=await e.json().catch(()=>null);if(!e.ok)throw Error(t?.error||`Could not create collection. Try again.`);if(!t?.id||!t.title||!t.slug)throw Error(`Could not create collection. Try again.`);let r={id:t.id,title:t.title,slug:t.slug};this._collections=[...this._collections??[],r],this._data&&(await fetch(`/api/collections/${t.id}/posts`,{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify({postId:this._data.id})}),this._postCollectionIds=[...this._postCollectionIds,t.id]),this.#e=!0,this.#_(),m(this.#y()?.createdLabel??`Collection created.`)}catch(e){m(e instanceof Error?e.message:`Could not create collection. Try again.`,`error`)}finally{r&&(r.loading=!1)}}#y(){return document.querySelector(`jant-compose-dialog`)?.labels?.collectionFormLabels??null}#b(){return document.querySelector(`jant-compose-dialog`)?.labels?.addCollection??`Add Collection`}#x(e){switch(e){case`private`:return`Private`;case`latest_hidden`:return`Hidden from Latest`;default:return`Public`}}#S(){return s`<svg
2802
+ xmlns="http://www.w3.org/2000/svg"
2803
+ viewBox="0 0 24 24"
2804
+ fill="none"
2805
+ stroke="currentColor"
2806
+ stroke-width="1.75"
2807
+ stroke-linecap="round"
2808
+ stroke-linejoin="round"
2809
+ >
2810
+ <path d="M12 20h9" />
2811
+ <path d="M16.5 3.5a2.12 2.12 0 1 1 3 3L7 19l-4 1 1-4Z" />
2812
+ </svg>`}#C(){return s`<svg
2813
+ xmlns="http://www.w3.org/2000/svg"
2814
+ viewBox="0 0 24 24"
2815
+ fill="none"
2816
+ stroke="currentColor"
2817
+ stroke-width="1.75"
2818
+ stroke-linecap="round"
2819
+ stroke-linejoin="round"
2820
+ >
2821
+ <path d=${jm} />
2822
+ </svg>`}#w(){return s`<svg
2823
+ xmlns="http://www.w3.org/2000/svg"
2824
+ viewBox="0 0 24 24"
2825
+ fill="none"
2826
+ stroke="currentColor"
2827
+ stroke-width="1.75"
2828
+ style="--icon-stroke: 1.5"
2829
+ stroke-linecap="round"
2830
+ stroke-linejoin="round"
2831
+ >
2832
+ <path d=${jm} />
2833
+ <path d=${Mm} />
2834
+ </svg>`}#T(){return s`<svg
2835
+ xmlns="http://www.w3.org/2000/svg"
2836
+ viewBox="0 0 24 24"
2837
+ fill="none"
2838
+ stroke="currentColor"
2839
+ stroke-width="1.75"
2840
+ stroke-linecap="round"
2841
+ stroke-linejoin="round"
2842
+ >
2843
+ <line x1="12" x2="12" y1="17" y2="22" />
2844
+ <path
2845
+ d="M5 17h14v-1.76a2 2 0 0 0-1.11-1.79l-1.78-.9A2 2 0 0 1 15 10.76V6h1a2 2 0 0 0 0-4H8a2 2 0 0 0 0 4h1v4.76a2 2 0 0 1-1.11 1.79l-1.78.9A2 2 0 0 0 5 15.24Z"
2846
+ />
2847
+ </svg>`}#E(){return s`<svg
2848
+ xmlns="http://www.w3.org/2000/svg"
2849
+ viewBox="0 0 24 24"
2850
+ fill="none"
2851
+ stroke="currentColor"
2852
+ stroke-width="1.75"
2853
+ stroke-linecap="round"
2854
+ stroke-linejoin="round"
2855
+ >
2856
+ <line x1="2" x2="22" y1="2" y2="22" />
2857
+ <line x1="12" x2="12" y1="17" y2="22" />
2858
+ <path d="M9 9v1.76a2 2 0 0 1-1.11 1.79l-1.78.9A2 2 0 0 0 5 15.24V17h12" />
2859
+ <path d="M15 9.34V6h1a2 2 0 0 0 0-4H8a2 2 0 0 0-1.4.6" />
2860
+ </svg>`}#D(){return s`<svg
2861
+ xmlns="http://www.w3.org/2000/svg"
2862
+ viewBox="0 0 24 24"
2863
+ fill="none"
2864
+ stroke="currentColor"
2865
+ stroke-width="1.75"
2866
+ stroke-linecap="round"
2867
+ stroke-linejoin="round"
2868
+ >
2869
+ <path d="M3 6h18" />
2870
+ <path d="M19 6v14c0 1-1 2-2 2H7c-1 0-2-1-2-2V6" />
2871
+ <path d="M8 6V4c0-1 1-2 2-2h4c1 0 2 1 2 2v2" />
2872
+ </svg>`}#O(){return s`<svg
2873
+ xmlns="http://www.w3.org/2000/svg"
2874
+ viewBox="0 0 24 24"
2875
+ fill="none"
2876
+ stroke="currentColor"
2877
+ stroke-width="1.9"
2878
+ stroke-linecap="round"
2879
+ stroke-linejoin="round"
2880
+ >
2881
+ <path d="m15 18-6-6 6-6" />
2882
+ </svg>`}#k(){return s`<svg
2883
+ xmlns="http://www.w3.org/2000/svg"
2884
+ viewBox="0 0 24 24"
2885
+ fill="none"
2886
+ stroke="currentColor"
2887
+ stroke-width="1.9"
2888
+ stroke-linecap="round"
2889
+ stroke-linejoin="round"
2890
+ >
2891
+ <path d="m9 18 6-6-6-6" />
2892
+ </svg>`}#A(){return s`<svg
2893
+ xmlns="http://www.w3.org/2000/svg"
2894
+ viewBox="0 0 24 24"
2895
+ fill="none"
2896
+ stroke="currentColor"
2897
+ stroke-width="2.3"
2898
+ stroke-linecap="round"
2899
+ stroke-linejoin="round"
2900
+ >
2901
+ <path d="M20 6 9 17l-5-5" />
2902
+ </svg>`}#j(){let e=this._collections??[],t=this._collectionSearch.toLowerCase(),n=t?e.filter(e=>e.title.toLowerCase().includes(t)):e;return s`
2903
+ <div
2904
+ data-collection-picker
2905
+ class="post-menu-view post-menu-collection-picker"
2906
+ >
2907
+ <div class="post-menu-panel-header">
2908
+ <button
2909
+ type="button"
2910
+ class="post-menu-panel-back"
2911
+ aria-label="Back"
2912
+ @click=${()=>this.#o(`[data-post-menu-open-collections]`)}
2913
+ >
2914
+ ${this.#O()}
2915
+ </button>
2916
+ <div class="post-menu-panel-heading">
2917
+ <span>Collections</span>
2918
+ </div>
2919
+ </div>
2920
+ ${e.length>0?s`<div class="post-menu-picker-search">
2921
+ <svg
2922
+ width="14"
2923
+ height="14"
2924
+ viewBox="0 0 24 24"
2925
+ fill="none"
2926
+ stroke="currentColor"
2927
+ stroke-width="2"
2928
+ stroke-linecap="round"
2929
+ stroke-linejoin="round"
2930
+ >
2931
+ <circle cx="11" cy="11" r="8" />
2932
+ <path d="m21 21-4.3-4.3" />
2933
+ </svg>
2934
+ <input
2935
+ type="text"
2936
+ placeholder="Search collections..."
2937
+ autocomplete="off"
2938
+ autocorrect="off"
2939
+ spellcheck="false"
2940
+ .value=${this._collectionSearch}
2941
+ @input=${e=>{this._collectionSearch=e.target.value}}
2942
+ />
2943
+ </div>`:i}
2944
+ <div
2945
+ class="post-menu-picker-list"
2946
+ role="listbox"
2947
+ aria-multiselectable="true"
2948
+ >
2949
+ ${this._collectionsLoading?s`<div class="post-menu-picker-empty">Loading...</div>`:n.length>0?n.map(e=>{let t=this._postCollectionIds.includes(e.id);return s`
2950
+ <button
2951
+ type="button"
2952
+ role="option"
2953
+ aria-selected=${t?`true`:`false`}
2954
+ class=${`post-menu-picker-option${t?` post-menu-picker-option-selected`:``}`}
2955
+ @click=${()=>this.#h(e.id)}
2956
+ >
2957
+ <span class="post-menu-picker-title">${e.title}</span>
2958
+ ${t?s`<span
2959
+ class="post-menu-picker-marker post-menu-picker-marker-selected"
2960
+ >
2961
+ <svg
2962
+ xmlns="http://www.w3.org/2000/svg"
2963
+ viewBox="0 0 24 24"
2964
+ fill="none"
2965
+ aria-hidden="true"
2966
+ >
2967
+ <circle
2968
+ cx="12"
2969
+ cy="12"
2970
+ r="10"
2971
+ fill="currentColor"
2972
+ />
2973
+ <path
2974
+ d="M8 12.5 10.7 15.2 16.4 9.5"
2975
+ stroke="var(--site-page-bg)"
2976
+ stroke-width="2.3"
2977
+ stroke-linecap="round"
2978
+ stroke-linejoin="round"
2979
+ />
2980
+ </svg>
2981
+ </span>`:s`<span
2982
+ class="post-menu-picker-marker post-menu-picker-marker-add"
2983
+ >
2984
+ <svg
2985
+ xmlns="http://www.w3.org/2000/svg"
2986
+ viewBox="0 0 24 24"
2987
+ fill="none"
2988
+ aria-hidden="true"
2989
+ >
2990
+ <circle
2991
+ cx="12"
2992
+ cy="12"
2993
+ r="9"
2994
+ stroke="currentColor"
2995
+ stroke-width="1.8"
2996
+ />
2997
+ <path
2998
+ d="M12 8v8M8 12h8"
2999
+ stroke="currentColor"
3000
+ stroke-width="1.9"
3001
+ stroke-linecap="round"
3002
+ />
3003
+ </svg>
3004
+ </span>`}
3005
+ </button>
3006
+ `}):s`<div class="post-menu-picker-empty">
3007
+ ${t?`No matching collections`:`No collections yet`}
3008
+ </div>`}
3009
+ </div>
3010
+ <div class="post-menu-picker-footer">
3011
+ <button
3012
+ type="button"
3013
+ class="post-menu-picker-add"
3014
+ data-post-menu-add-collection
3015
+ @click=${()=>this.#g()}
3016
+ >
3017
+ <svg
3018
+ width="14"
3019
+ height="14"
3020
+ viewBox="0 0 16 16"
3021
+ fill="none"
3022
+ stroke="currentColor"
3023
+ stroke-width="1.5"
3024
+ stroke-linecap="round"
3025
+ stroke-linejoin="round"
3026
+ >
3027
+ <path d="M8 3v10M3 8h10" />
3028
+ </svg>
3029
+ Add Collection
3030
+ </button>
3031
+ </div>
3032
+ </div>
3033
+ `}#M(){if(!this._data||this._data.isReply)return i;let e=this._data.visibility;return s`
3034
+ <div
3035
+ data-visibility-panel
3036
+ class="post-menu-view post-menu-visibility-panel"
3037
+ >
3038
+ <div class="post-menu-panel-header">
3039
+ <button
3040
+ type="button"
3041
+ class="post-menu-panel-back"
3042
+ aria-label="Back"
3043
+ @click=${()=>this.#o(`[data-post-menu-open-visibility]`)}
3044
+ >
3045
+ ${this.#O()}
3046
+ </button>
3047
+ <div class="post-menu-panel-heading">
3048
+ <span>Visibility</span>
3049
+ </div>
3050
+ </div>
3051
+ <div role="menu" class="post-menu-list">
3052
+ <div class="post-menu-section">
3053
+ <button
3054
+ type="button"
3055
+ role="menuitemradio"
3056
+ aria-checked=${e===`public`?`true`:`false`}
3057
+ data-post-menu-visibility-option
3058
+ data-post-menu-visibility-current=${e===`public`?`true`:`false`}
3059
+ class=${`post-menu-item${e===`public`?` post-menu-item-active`:``}`}
3060
+ @click=${()=>e===`public`?this.#o(`[data-post-menu-open-visibility]`):this.#u(`public`)}
3061
+ >
3062
+ <span class="post-menu-item-label">Public</span>
3063
+ ${e===`public`?s`<span
3064
+ class="post-menu-item-trailing post-menu-item-check"
3065
+ >${this.#A()}</span
3066
+ >`:i}
3067
+ </button>
3068
+
3069
+ <button
3070
+ type="button"
3071
+ role="menuitemradio"
3072
+ aria-checked=${e===`latest_hidden`?`true`:`false`}
3073
+ data-post-menu-visibility-option
3074
+ data-post-menu-visibility-current=${e===`latest_hidden`?`true`:`false`}
3075
+ class=${`post-menu-item${e===`latest_hidden`?` post-menu-item-active`:``}`}
3076
+ @click=${()=>e===`latest_hidden`?this.#o(`[data-post-menu-open-visibility]`):this.#u(`latest_hidden`)}
3077
+ >
3078
+ <span class="post-menu-item-label">Hidden from Latest</span>
3079
+ ${e===`latest_hidden`?s`<span
3080
+ class="post-menu-item-trailing post-menu-item-check"
3081
+ >${this.#A()}</span
3082
+ >`:i}
3083
+ </button>
3084
+
3085
+ <button
3086
+ type="button"
3087
+ role="menuitemradio"
3088
+ aria-checked=${e===`private`?`true`:`false`}
3089
+ data-post-menu-visibility-option
3090
+ data-post-menu-visibility-current=${e===`private`?`true`:`false`}
3091
+ class=${`post-menu-item${e===`private`?` post-menu-item-active`:``}`}
3092
+ @click=${()=>e===`private`?this.#o(`[data-post-menu-open-visibility]`):this.#u(`private`)}
3093
+ >
3094
+ <span class="post-menu-item-label">Private</span>
3095
+ ${e===`private`?s`<span
3096
+ class="post-menu-item-trailing post-menu-item-check"
3097
+ >${this.#A()}</span
3098
+ >`:i}
3099
+ </button>
3100
+ </div>
3101
+ </div>
3102
+ </div>
3103
+ `}#N(){let e=this.#y();return e?s`
3104
+ <div
3105
+ class="collection-quick-dialog-backdrop"
3106
+ @click=${()=>this.#_()}
3107
+ ></div>
3108
+ <div
3109
+ class="collection-quick-dialog"
3110
+ data-collection-quick-dialog
3111
+ role="dialog"
3112
+ aria-modal="true"
3113
+ aria-label=${this.#b()}
3114
+ @click=${e=>e.stopPropagation()}
3115
+ >
3116
+ <div class="collection-quick-dialog-header">
3117
+ <div class="collection-quick-dialog-title-block">
3118
+ <h2 class="collection-quick-dialog-title">
3119
+ ${this.#b()}
3120
+ </h2>
3121
+ <p class="collection-quick-dialog-note">${e.quickHint}</p>
3122
+ </div>
3123
+ <button
3124
+ type="button"
3125
+ class="collection-quick-dialog-cancel"
3126
+ @click=${()=>this.#_()}
3127
+ >
3128
+ ${e.cancelLabel}
3129
+ </button>
3130
+ </div>
3131
+ <div class="collection-quick-dialog-body">
3132
+ <jant-collection-form
3133
+ variant="quick"
3134
+ .labels=${e}
3135
+ .initial=${{title:``,slug:``,description:``,sortOrder:`newest`,icon:``}}
3136
+ action=${a(`/api/collections`)}
3137
+ cancel-href="javascript:void(0)"
3138
+ @jant:collection-submit=${e=>this.#v(e)}
3139
+ ></jant-collection-form>
3140
+ </div>
3141
+ <div class="collection-quick-dialog-footer">
3142
+ <button
3143
+ type="button"
3144
+ class="compose-post-btn collection-quick-dialog-submit"
3145
+ @click=${()=>{this.querySelector(`[data-collection-quick-dialog] form`)?.requestSubmit()}}
3146
+ >
3147
+ ${e.quickSubmitLabel}
3148
+ </button>
3149
+ </div>
3150
+ </div>
3151
+ `:i}#P(){if(!this._data)return i;let e=this._data.visibility,t=this._data.pinned,n=this._data.featured;return s`
3152
+ <div class="post-menu-view post-menu-main">
3153
+ <div role="menu" class="post-menu-list">
3154
+ <div class="post-menu-section">
3155
+ <button
3156
+ type="button"
3157
+ role="menuitem"
3158
+ class="post-menu-item"
3159
+ data-post-menu-item-primary
3160
+ @click=${()=>this.#l()}
3161
+ >
3162
+ <span class="post-menu-item-label">Edit</span>
3163
+ <span class="post-menu-item-trailing">${this.#S()}</span>
3164
+ </button>
3165
+
3166
+ <button
3167
+ type="button"
3168
+ role="menuitem"
3169
+ class="post-menu-item"
3170
+ data-post-menu-open-collections
3171
+ @click=${()=>this.#m()}
3172
+ >
3173
+ <span class="post-menu-item-label">Add to collection</span>
3174
+ <span class="post-menu-item-trailing post-menu-item-chevron"
3175
+ >${this.#k()}</span
3176
+ >
3177
+ </button>
3178
+
3179
+ ${this._data.isReply?i:s`
3180
+ <button
3181
+ type="button"
3182
+ role="menuitem"
3183
+ class="post-menu-item"
3184
+ data-post-menu-open-visibility
3185
+ @click=${()=>this.#s()}
3186
+ >
3187
+ <span class="post-menu-item-label">Visibility</span>
3188
+ <span class="post-menu-item-meta"
3189
+ >${this.#x(e)}</span
3190
+ >
3191
+ <span class="post-menu-item-trailing post-menu-item-chevron"
3192
+ >${this.#k()}</span
3193
+ >
3194
+ </button>
3195
+ `}
3196
+ </div>
3197
+
3198
+ <div class="post-menu-section">
3199
+ <button
3200
+ type="button"
3201
+ role="menuitem"
3202
+ class="post-menu-item"
3203
+ @click=${()=>this.#d(!n)}
3204
+ >
3205
+ <span class="post-menu-item-label"
3206
+ >${n?`Remove from Featured`:`Add to Featured`}</span
3207
+ >
3208
+ <span class="post-menu-item-trailing"
3209
+ >${n?this.#w():this.#C()}</span
3210
+ >
3211
+ </button>
3212
+
3213
+ ${this._data.isReply?i:s`
3214
+ <button
3215
+ type="button"
3216
+ role="menuitem"
3217
+ class="post-menu-item"
3218
+ @click=${()=>this.#f()}
3219
+ >
3220
+ <span class="post-menu-item-label"
3221
+ >${t?`Unpin`:`Pin this post`}</span
3222
+ >
3223
+ <span class="post-menu-item-trailing"
3224
+ >${t?this.#E():this.#T()}</span
3225
+ >
3226
+ </button>
3227
+ `}
3228
+ </div>
3229
+
3230
+ <div class="post-menu-section post-menu-section-danger">
3231
+ <button
3232
+ type="button"
3233
+ role="menuitem"
3234
+ class="post-menu-item post-menu-item-danger"
3235
+ @click=${()=>this.#p()}
3236
+ >
3237
+ <span class="post-menu-item-label">Delete</span>
3238
+ <span class="post-menu-item-trailing">${this.#D()}</span>
3239
+ </button>
3240
+ </div>
3241
+ </div>
3242
+ </div>
3243
+ `}render(){if(!this._open||!this._data)return i;let e=this._openAbove?`transform:translate(-100%, -100%);`:`transform:translateX(-100%);`,t=`position:absolute;z-index:100;left:${Math.round(this._x)}px;top:${Math.round(this._y)}px;${e}`;return s`
3244
+ ${this._addCollectionPanelOpen?i:s`
3245
+ <div
3246
+ class="post-menu-backdrop"
3247
+ @click=${()=>this.#c({restoreFocus:!1})}
3248
+ ></div>
3249
+ <div class="dropdown-menu" style=${t}>
3250
+ <div
3251
+ data-popover
3252
+ aria-hidden="false"
3253
+ class="!static post-menu-panel"
3254
+ >
3255
+ ${this._view===`collections`?this.#j():this._view===`visibility`?this.#M():this.#P()}
3256
+ </div>
3257
+ </div>
3258
+ `}
3259
+ ${this._addCollectionPanelOpen?this.#N():i}
3260
+ `}};customElements.define(`jant-post-menu`,Lm);var Rm=e=>{if(!e)return{edit:``,moreActions:``,deleteCollection:``,confirmDelete:``,cancel:``,saveFailed:``,deleted:``};try{return JSON.parse(e)}catch{return{edit:``,moreActions:``,deleteCollection:``,confirmDelete:``,cancel:``,saveFailed:``,deleted:``}}};document.querySelectorAll(`[data-collection-page-actions]`).forEach(e=>{if(e.dataset.collectionPageActionsInitialized===`true`)return;let t=Rm(e.dataset.collectionPageLabels),n=e.dataset.collectionId,r=e.dataset.collectionPageRedirectUrl||`/c`,i=e.querySelector(`[data-collection-page-action='toggle-menu']`),a=e.querySelector(`[data-collection-page-menu]`);if(!n||!i||!a)return;let o=(e=!1)=>{a.hidden||(a.hidden=!0,i.setAttribute(`aria-expanded`,`false`),e&&i.focus())},s=(e=!1)=>{a.hidden=!1,i.setAttribute(`aria-expanded`,`true`),e&&a.querySelector(`[role='menuitem']`)?.focus()},c=async()=>{if(o(!1),await ve({message:t.confirmDelete,confirmLabel:t.deleteCollection,cancelLabel:t.cancel,tone:`danger`}))try{let e=await fetch(`/api/collections/${n}`,{method:`DELETE`});if(!e.ok)throw Error(`HTTP ${e.status}`);m(t.deleted),window.location.href=r}catch{m(t.saveFailed,`error`)}};i.addEventListener(`click`,e=>{if(e.preventDefault(),e.stopPropagation(),a.hidden){s(!1);return}o(!1)}),i.addEventListener(`keydown`,e=>{(e.key===`Enter`||e.key===` `||e.key===`ArrowDown`)&&(e.preventDefault(),a.hidden?s(!0):o(!1)),e.key===`Escape`&&(e.preventDefault(),o(!0))}),a.addEventListener(`keydown`,e=>{e.key===`Escape`&&(e.preventDefault(),o(!0))}),e.addEventListener(`click`,t=>{let n=t.target;if(!n)return;let r=n.closest(`[data-collection-page-action]`);!r||!e.contains(r)||r.dataset.collectionPageAction===`delete`&&(t.preventDefault(),c())}),document.addEventListener(`click`,t=>{t.target instanceof Node&&(e.contains(t.target)||o(!1))}),e.dataset.collectionPageActionsInitialized=`true`});function zm(e=document){e.querySelectorAll(`[data-custom-url-actions]`).forEach(e=>{if(e.dataset.customUrlActionsInitialized===`true`)return;let t=e.querySelector(`[data-custom-url-action='toggle-menu']`),n=e.querySelector(`[data-custom-url-menu]`);if(!(t instanceof HTMLButtonElement)||!n)return;let r=(e=!1)=>{n.hidden||(n.hidden=!0,t.setAttribute(`aria-expanded`,`false`),e&&t.focus())},i=(r=!1)=>{document.dispatchEvent(new CustomEvent(`jant:custom-url-menu`,{detail:{source:e}})),n.hidden=!1,t.setAttribute(`aria-expanded`,`true`),r&&n.querySelector(`[role='menuitem']`)?.focus()};t.addEventListener(`click`,e=>{if(e.preventDefault(),e.stopPropagation(),n.hidden){i(!1);return}r(!1)}),t.addEventListener(`keydown`,e=>{if(e.key===`Enter`||e.key===` `||e.key===`ArrowDown`){e.preventDefault(),n.hidden?i(!0):r(!1);return}e.key===`Escape`&&(e.preventDefault(),r(!0))}),n.addEventListener(`keydown`,e=>{e.key===`Escape`&&(e.preventDefault(),r(!0))}),e.addEventListener(`click`,t=>{let n=t.target;if(!n)return;let i=n.closest(`[data-custom-url-action]`);!i||!e.contains(i)||i.dataset.customUrlAction===`delete`&&r(!1)}),document.addEventListener(`click`,t=>{t.target instanceof Node&&(e.contains(t.target)||r(!1))}),document.addEventListener(`jant:custom-url-menu`,t=>{t.detail?.source!==e&&r(!1)}),e.dataset.customUrlActionsInitialized=`true`})}zm(),document.querySelector(`jant-compose-fullscreen`)||document.body.appendChild(document.createElement(`jant-compose-fullscreen`)),_e();