react-native-audio-browser 0.2.0-next.53 → 0.2.0-next.54

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 (329) hide show
  1. package/android/src/cast/java/com/audiobrowser/cast/CastSupport.kt +8 -10
  2. package/android/src/main/java/com/audiobrowser/AudioBrowser.kt +96 -243
  3. package/android/src/main/java/com/audiobrowser/AudioBrowserLifecycleModule.kt +8 -12
  4. package/android/src/main/java/com/audiobrowser/AudioBrowserPackage.kt +1 -3
  5. package/android/src/main/java/com/audiobrowser/Callbacks.kt +1 -10
  6. package/android/src/main/java/com/audiobrowser/ForegroundStart.kt +13 -18
  7. package/android/src/main/java/com/audiobrowser/HeadlessTaskService.kt +3 -7
  8. package/android/src/main/java/com/audiobrowser/RemoteOutputs.kt +8 -10
  9. package/android/src/main/java/com/audiobrowser/Service.kt +20 -61
  10. package/android/src/main/java/com/audiobrowser/ServiceBinding.kt +9 -17
  11. package/android/src/main/java/com/audiobrowser/browser/ArtworkResolutionRegistry.kt +10 -9
  12. package/android/src/main/java/com/audiobrowser/browser/BrowseArtworkRegistry.kt +11 -8
  13. package/android/src/main/java/com/audiobrowser/browser/BrowserManager.kt +117 -448
  14. package/android/src/main/java/com/audiobrowser/browser/BrowserUrlResolution.kt +21 -60
  15. package/android/src/main/java/com/audiobrowser/browser/InertStyleDiagnostic.kt +20 -80
  16. package/android/src/main/java/com/audiobrowser/browser/JsonArtwork.kt +6 -10
  17. package/android/src/main/java/com/audiobrowser/browser/JsonModels.kt +7 -24
  18. package/android/src/main/java/com/audiobrowser/browser/RouteMatch.kt +2 -4
  19. package/android/src/main/java/com/audiobrowser/browser/SectionScope.kt +13 -31
  20. package/android/src/main/java/com/audiobrowser/browser/SimpleRouter.kt +12 -40
  21. package/android/src/main/java/com/audiobrowser/browser/StyleResolver.kt +15 -26
  22. package/android/src/main/java/com/audiobrowser/browser/TrackLoadHandler.kt +5 -15
  23. package/android/src/main/java/com/audiobrowser/extension/EnumExtensions.kt +1 -0
  24. package/android/src/main/java/com/audiobrowser/extension/NumberExt.kt +2 -0
  25. package/android/src/main/java/com/audiobrowser/extension/ResolvedTrackExt.kt +4 -8
  26. package/android/src/main/java/com/audiobrowser/extension/TappedTrack.kt +4 -6
  27. package/android/src/main/java/com/audiobrowser/extension/TrackIdentity.kt +3 -7
  28. package/android/src/main/java/com/audiobrowser/http/HttpClient.kt +13 -22
  29. package/android/src/main/java/com/audiobrowser/http/RequestConfigBuilder.kt +17 -38
  30. package/android/src/main/java/com/audiobrowser/model/IcyTitle.kt +5 -6
  31. package/android/src/main/java/com/audiobrowser/model/PlaybackMetadata.kt +4 -9
  32. package/android/src/main/java/com/audiobrowser/model/PlayerSetupOptions.kt +18 -29
  33. package/android/src/main/java/com/audiobrowser/model/PlayerUpdateOptions.kt +6 -16
  34. package/android/src/main/java/com/audiobrowser/player/AutomaticBufferManager.kt +15 -45
  35. package/android/src/main/java/com/audiobrowser/player/CapabilityControls.kt +23 -59
  36. package/android/src/main/java/com/audiobrowser/player/CrossOriginHeaderStripper.kt +14 -26
  37. package/android/src/main/java/com/audiobrowser/player/DynamicLoadControl.kt +15 -43
  38. package/android/src/main/java/com/audiobrowser/player/EnginePlayback.kt +4 -4
  39. package/android/src/main/java/com/audiobrowser/player/EqualizerController.kt +15 -21
  40. package/android/src/main/java/com/audiobrowser/player/InterceptingPlayer.kt +14 -31
  41. package/android/src/main/java/com/audiobrowser/player/LocalEngine.kt +8 -8
  42. package/android/src/main/java/com/audiobrowser/player/MediaFactory.kt +16 -27
  43. package/android/src/main/java/com/audiobrowser/player/MediaSessionCallback.kt +119 -237
  44. package/android/src/main/java/com/audiobrowser/player/MediaSessionCommandManager.kt +48 -145
  45. package/android/src/main/java/com/audiobrowser/player/NowPlayingUpdater.kt +39 -100
  46. package/android/src/main/java/com/audiobrowser/player/PlaybackErrorClassifier.kt +16 -26
  47. package/android/src/main/java/com/audiobrowser/player/PlaybackStateMachine.kt +22 -28
  48. package/android/src/main/java/com/audiobrowser/player/PlaybackStateStore.kt +28 -64
  49. package/android/src/main/java/com/audiobrowser/player/PlaybackTimer.kt +8 -4
  50. package/android/src/main/java/com/audiobrowser/player/Player.kt +117 -405
  51. package/android/src/main/java/com/audiobrowser/player/PlayerCapabilitiesExt.kt +1 -1
  52. package/android/src/main/java/com/audiobrowser/player/PlayerEngineFactory.kt +11 -19
  53. package/android/src/main/java/com/audiobrowser/player/PlayerListener.kt +30 -96
  54. package/android/src/main/java/com/audiobrowser/player/RetryLoadErrorHandlingPolicy.kt +39 -95
  55. package/android/src/main/java/com/audiobrowser/player/ShuffleOrderLedBy.kt +7 -13
  56. package/android/src/main/java/com/audiobrowser/player/SleepTimer.kt +13 -30
  57. package/android/src/main/java/com/audiobrowser/player/SleepTimerManager.kt +7 -11
  58. package/android/src/main/java/com/audiobrowser/player/StuckRecoveryPolicy.kt +9 -22
  59. package/android/src/main/java/com/audiobrowser/player/TransformingDataSource.kt +22 -54
  60. package/android/src/main/java/com/audiobrowser/player/VolumeFader.kt +8 -15
  61. package/android/src/main/java/com/audiobrowser/remote/RemoteItem.kt +9 -8
  62. package/android/src/main/java/com/audiobrowser/remote/RemoteOutputsController.kt +13 -10
  63. package/android/src/main/java/com/audiobrowser/remote/RemotePlayback.kt +8 -8
  64. package/android/src/main/java/com/audiobrowser/remote/RemoteQueue.kt +12 -5
  65. package/android/src/main/java/com/audiobrowser/remote/RemoteSwitchingPlayer.kt +28 -48
  66. package/android/src/main/java/com/audiobrowser/sonos/DeviceDescriptionParser.kt +11 -19
  67. package/android/src/main/java/com/audiobrowser/sonos/DidlLite.kt +2 -2
  68. package/android/src/main/java/com/audiobrowser/sonos/SoapClient.kt +6 -6
  69. package/android/src/main/java/com/audiobrowser/sonos/SoapEnvelopes.kt +8 -9
  70. package/android/src/main/java/com/audiobrowser/sonos/SoapResponseParser.kt +11 -18
  71. package/android/src/main/java/com/audiobrowser/sonos/SonosDiscoverer.kt +10 -10
  72. package/android/src/main/java/com/audiobrowser/sonos/SonosOutputs.kt +10 -10
  73. package/android/src/main/java/com/audiobrowser/sonos/SonosPlayer.kt +21 -33
  74. package/android/src/main/java/com/audiobrowser/sonos/SonosRemote.kt +4 -6
  75. package/android/src/main/java/com/audiobrowser/sonos/SonosRouteProviderService.kt +9 -10
  76. package/android/src/main/java/com/audiobrowser/sonos/SonosStreamUri.kt +7 -7
  77. package/android/src/main/java/com/audiobrowser/sonos/SonosTransport.kt +5 -4
  78. package/android/src/main/java/com/audiobrowser/sonos/SsdpDiscovery.kt +8 -3
  79. package/android/src/main/java/com/audiobrowser/sonos/SsdpMessages.kt +4 -6
  80. package/android/src/main/java/com/audiobrowser/sonos/ZoneGroupState.kt +13 -11
  81. package/android/src/main/java/com/audiobrowser/tls/AiaCertChaser.kt +34 -71
  82. package/android/src/main/java/com/audiobrowser/tls/AiaChasingExtendedTrustManager.kt +20 -37
  83. package/android/src/main/java/com/audiobrowser/tls/AiaChasingTrustManager.kt +18 -27
  84. package/android/src/main/java/com/audiobrowser/tls/AiaTls.kt +14 -29
  85. package/android/src/main/java/com/audiobrowser/tls/CachingCertificateFetcher.kt +68 -133
  86. package/android/src/main/java/com/audiobrowser/util/ArtworkContentProvider.kt +10 -22
  87. package/android/src/main/java/com/audiobrowser/util/ArtworkRoutes.kt +6 -6
  88. package/android/src/main/java/com/audiobrowser/util/ArtworkUris.kt +4 -3
  89. package/android/src/main/java/com/audiobrowser/util/ArtworkVariant.kt +2 -13
  90. package/android/src/main/java/com/audiobrowser/util/Automotive.kt +2 -4
  91. package/android/src/main/java/com/audiobrowser/util/BatteryOptimizationHelper.kt +3 -9
  92. package/android/src/main/java/com/audiobrowser/util/BatteryWarningStore.kt +4 -14
  93. package/android/src/main/java/com/audiobrowser/util/BrowserPathHelper.kt +21 -85
  94. package/android/src/main/java/com/audiobrowser/util/CoilArtworkLoader.kt +7 -7
  95. package/android/src/main/java/com/audiobrowser/util/CoilArtworkLoaderHolder.kt +5 -8
  96. package/android/src/main/java/com/audiobrowser/util/CoilBitmapLoader.kt +8 -24
  97. package/android/src/main/java/com/audiobrowser/util/EqualizerManager.kt +7 -39
  98. package/android/src/main/java/com/audiobrowser/util/MediaExtrasBuilder.kt +10 -14
  99. package/android/src/main/java/com/audiobrowser/util/MetadataAdapter.kt +5 -9
  100. package/android/src/main/java/com/audiobrowser/util/NetworkConnectivityMonitor.kt +5 -9
  101. package/android/src/main/java/com/audiobrowser/util/OutputMonitor.kt +21 -50
  102. package/android/src/main/java/com/audiobrowser/util/OutputSwitcher.kt +7 -20
  103. package/android/src/main/java/com/audiobrowser/util/PlayingStateFactory.kt +3 -5
  104. package/android/src/main/java/com/audiobrowser/util/RatingFavorites.kt +4 -5
  105. package/android/src/main/java/com/audiobrowser/util/StyleWire.kt +5 -5
  106. package/android/src/main/java/com/audiobrowser/util/SvgArtworkRenderer.kt +5 -9
  107. package/android/src/main/java/com/audiobrowser/util/SystemVolumeMonitor.kt +6 -9
  108. package/android/src/main/java/com/audiobrowser/util/TrackFactory.kt +25 -47
  109. package/android/src/nocast/java/com/audiobrowser/cast/CastSupport.kt +0 -2
  110. package/android/src/test/java/com/audiobrowser/ForegroundStartTest.kt +1 -2
  111. package/android/src/test/java/com/audiobrowser/LegacyRatingTest.kt +3 -3
  112. package/android/src/test/java/com/audiobrowser/ServiceBindingTest.kt +0 -13
  113. package/android/src/test/java/com/audiobrowser/ServiceTaskRemovedTest.kt +2 -3
  114. package/android/src/test/java/com/audiobrowser/TestFixtures.kt +5 -14
  115. package/android/src/test/java/com/audiobrowser/browser/BrowseArtworkRegistryTest.kt +1 -1
  116. package/android/src/test/java/com/audiobrowser/browser/BrowserManagerBuildApiRequestTest.kt +2 -8
  117. package/android/src/test/java/com/audiobrowser/browser/BrowserManagerFavoritesTest.kt +2 -12
  118. package/android/src/test/java/com/audiobrowser/browser/BrowserManagerLayerResolutionTest.kt +5 -28
  119. package/android/src/test/java/com/audiobrowser/browser/BrowserManagerTest.kt +11 -43
  120. package/android/src/test/java/com/audiobrowser/browser/BrowserUrlResolutionTest.kt +4 -13
  121. package/android/src/test/java/com/audiobrowser/browser/InertStyleDiagnosticTest.kt +2 -11
  122. package/android/src/test/java/com/audiobrowser/browser/JsonArtworkTest.kt +0 -2
  123. package/android/src/test/java/com/audiobrowser/browser/JsonStyleTest.kt +3 -8
  124. package/android/src/test/java/com/audiobrowser/browser/SectionScopeTest.kt +2 -14
  125. package/android/src/test/java/com/audiobrowser/browser/SimpleRouterTest.kt +1 -5
  126. package/android/src/test/java/com/audiobrowser/browser/StyleResolverTest.kt +2 -13
  127. package/android/src/test/java/com/audiobrowser/extension/TappedTrackTest.kt +1 -7
  128. package/android/src/test/java/com/audiobrowser/extension/TrackIdentityTest.kt +0 -5
  129. package/android/src/test/java/com/audiobrowser/http/RequestConfigBuilderTest.kt +8 -16
  130. package/android/src/test/java/com/audiobrowser/model/IcyTitleTest.kt +1 -1
  131. package/android/src/test/java/com/audiobrowser/player/BrowseTilesTest.kt +12 -29
  132. package/android/src/test/java/com/audiobrowser/player/CapabilityControlsTest.kt +3 -12
  133. package/android/src/test/java/com/audiobrowser/player/CrossOriginHeaderStripperTest.kt +0 -7
  134. package/android/src/test/java/com/audiobrowser/player/DynamicLoadControlTest.kt +0 -1
  135. package/android/src/test/java/com/audiobrowser/player/EqualizerControllerTest.kt +0 -9
  136. package/android/src/test/java/com/audiobrowser/player/LiveSeekCommandTest.kt +1 -2
  137. package/android/src/test/java/com/audiobrowser/player/MediaSessionSlotMappingTest.kt +0 -9
  138. package/android/src/test/java/com/audiobrowser/player/NowPlayingUpdaterTest.kt +15 -22
  139. package/android/src/test/java/com/audiobrowser/player/PlaybackErrorClassifierTest.kt +1 -24
  140. package/android/src/test/java/com/audiobrowser/player/PlaybackStateMachineTest.kt +0 -20
  141. package/android/src/test/java/com/audiobrowser/player/PlaybackStateStoreTrackJsonTest.kt +1 -6
  142. package/android/src/test/java/com/audiobrowser/player/PlaybackTimerTest.kt +2 -4
  143. package/android/src/test/java/com/audiobrowser/player/PlayerCastTest.kt +2 -2
  144. package/android/src/test/java/com/audiobrowser/player/PlayerEngineFactoryTest.kt +0 -3
  145. package/android/src/test/java/com/audiobrowser/player/PlayerInvalidTrackTest.kt +0 -1
  146. package/android/src/test/java/com/audiobrowser/player/PlayerSetupTest.kt +3 -2
  147. package/android/src/test/java/com/audiobrowser/player/PlayerSonosTest.kt +5 -1
  148. package/android/src/test/java/com/audiobrowser/player/PlayerSuppressionTest.kt +5 -7
  149. package/android/src/test/java/com/audiobrowser/player/RetryLoadErrorHandlingPolicyTest.kt +4 -35
  150. package/android/src/test/java/com/audiobrowser/player/SessionErrorMaskTest.kt +0 -5
  151. package/android/src/test/java/com/audiobrowser/player/ShuffleOrderLedByTest.kt +1 -8
  152. package/android/src/test/java/com/audiobrowser/player/StandardSkipTest.kt +4 -6
  153. package/android/src/test/java/com/audiobrowser/player/StuckRecoveryPolicyTest.kt +11 -11
  154. package/android/src/test/java/com/audiobrowser/player/TransformingDataSourceTest.kt +2 -23
  155. package/android/src/test/java/com/audiobrowser/remote/FakeRemote.kt +9 -10
  156. package/android/src/test/java/com/audiobrowser/remote/RemoteSwitchingPlayerTest.kt +0 -1
  157. package/android/src/test/java/com/audiobrowser/sonos/DeviceDescriptionParserTest.kt +1 -3
  158. package/android/src/test/java/com/audiobrowser/sonos/DidlLiteTest.kt +0 -1
  159. package/android/src/test/java/com/audiobrowser/sonos/SoapClientTest.kt +0 -3
  160. package/android/src/test/java/com/audiobrowser/sonos/SoapEnvelopesTest.kt +0 -1
  161. package/android/src/test/java/com/audiobrowser/sonos/SoapResponseParserTest.kt +0 -1
  162. package/android/src/test/java/com/audiobrowser/sonos/SonosDiscovererTest.kt +2 -0
  163. package/android/src/test/java/com/audiobrowser/sonos/SonosPlayerTest.kt +0 -1
  164. package/android/src/test/java/com/audiobrowser/sonos/SonosRemoteTest.kt +1 -1
  165. package/android/src/test/java/com/audiobrowser/sonos/SonosRoutesTest.kt +2 -0
  166. package/android/src/test/java/com/audiobrowser/sonos/SonosTransportTest.kt +2 -6
  167. package/android/src/test/java/com/audiobrowser/sonos/SsdpMessagesTest.kt +0 -2
  168. package/android/src/test/java/com/audiobrowser/tls/AiaCertChaserTest.kt +13 -37
  169. package/android/src/test/java/com/audiobrowser/tls/AiaChasingTrustManagerTest.kt +10 -24
  170. package/android/src/test/java/com/audiobrowser/tls/CachingCertificateFetcherCallSiteTest.kt +15 -39
  171. package/android/src/test/java/com/audiobrowser/tls/CachingCertificateFetcherTest.kt +4 -10
  172. package/android/src/test/java/com/audiobrowser/util/ArtworkContentProviderTest.kt +2 -11
  173. package/android/src/test/java/com/audiobrowser/util/ArtworkUrisTest.kt +0 -1
  174. package/android/src/test/java/com/audiobrowser/util/BrowserPathHelperTest.kt +0 -4
  175. package/android/src/test/java/com/audiobrowser/util/CoilArtworkLoaderHolderTest.kt +1 -1
  176. package/android/src/test/java/com/audiobrowser/util/CoilArtworkLoaderTest.kt +0 -5
  177. package/android/src/test/java/com/audiobrowser/util/FakeImageLoader.kt +2 -2
  178. package/android/src/test/java/com/audiobrowser/util/MediaExtrasBuilderTest.kt +4 -12
  179. package/android/src/test/java/com/audiobrowser/util/OutputMonitorTest.kt +1 -1
  180. package/android/src/test/java/com/audiobrowser/util/PlayingStateFactoryTest.kt +0 -4
  181. package/android/src/test/java/com/audiobrowser/util/TrackFactoryBrowseTest.kt +1 -1
  182. package/android/src/test/java/com/audiobrowser/util/TrackFactoryMediaIdTest.kt +4 -6
  183. package/android/src/testCast/java/com/audiobrowser/cast/CastEndsTest.kt +1 -1
  184. package/android/src/testCast/java/com/audiobrowser/cast/SendingMediaItemConverterTest.kt +1 -0
  185. package/ios/AVPlayerEngine.swift +13 -21
  186. package/ios/AVPlayerEngineCallbacks.swift +2 -4
  187. package/ios/Browser/BrowseGate.swift +7 -8
  188. package/ios/Browser/BrowserConfig.swift +19 -34
  189. package/ios/Browser/BrowserError.swift +0 -1
  190. package/ios/Browser/BrowserManager.swift +29 -75
  191. package/ios/Browser/BrowserPathHelper.swift +13 -93
  192. package/ios/Browser/FavoriteSet.swift +7 -10
  193. package/ios/Browser/InertStyleDiagnostic.swift +17 -82
  194. package/ios/Browser/JsonModels.swift +11 -51
  195. package/ios/Browser/NavigationErrorState.swift +3 -2
  196. package/ios/Browser/PageResolver.swift +13 -23
  197. package/ios/Browser/RequestLayer.swift +16 -20
  198. package/ios/Browser/RequestPipeline.swift +33 -43
  199. package/ios/Browser/SearchDrillIn.swift +7 -13
  200. package/ios/Browser/SectionScope.swift +14 -26
  201. package/ios/Browser/SimpleRouter.swift +8 -15
  202. package/ios/Browser/StyleResolver.swift +12 -29
  203. package/ios/Browser/TabBarEntries.swift +6 -11
  204. package/ios/Browser/TrackIdTemplate.swift +6 -14
  205. package/ios/CarPlay/CPInterfaceController+Safe.swift +19 -28
  206. package/ios/CarPlay/CarPlayArtworkResolver.swift +5 -9
  207. package/ios/CarPlay/CarPlayController.swift +4 -4
  208. package/ios/CarPlay/CarPlayImageLoader.swift +11 -26
  209. package/ios/CarPlay/CarPlayListItemFactory.swift +30 -80
  210. package/ios/CarPlay/CarPlayNowPlayingManager.swift +19 -54
  211. package/ios/CarPlay/CarPlaySession+Navigator.swift +10 -10
  212. package/ios/CarPlay/CarPlaySession+PageLoader.swift +6 -5
  213. package/ios/CarPlay/CarPlaySession+Refresher.swift +2 -2
  214. package/ios/CarPlay/CarPlaySession+TabBar.swift +19 -26
  215. package/ios/CarPlay/CarPlaySession.swift +13 -17
  216. package/ios/CarPlay/CarPlayTemplates.swift +6 -7
  217. package/ios/CarPlay/IntentHandlers.swift +3 -5
  218. package/ios/CarPlay/MediaIntentCriteria.swift +15 -29
  219. package/ios/CarPlay/MediaIntentHandler.swift +4 -7
  220. package/ios/CarPlay/MediaIntentPlayback.swift +9 -8
  221. package/ios/CarPlay/NowPlayingButtonRules.swift +3 -4
  222. package/ios/CarPlay/SectionPresentation.swift +18 -28
  223. package/ios/CarPlay/TopTemplateReplacer.swift +8 -9
  224. package/ios/Extension/Capability+RemoteCommand.swift +3 -3
  225. package/ios/Extension/ChapterMetadata+AVFoundation.swift +2 -5
  226. package/ios/Extension/CxxVectorConformances.swift +4 -16
  227. package/ios/Extension/NavigationError+Conversion.swift +4 -7
  228. package/ios/Extension/PlayerCapabilities+Favorite.swift +0 -1
  229. package/ios/Extension/RequestConfig+Copying.swift +2 -6
  230. package/ios/Extension/ResolvedTrack+Copying.swift +2 -8
  231. package/ios/Extension/SearchParams+Query.swift +4 -4
  232. package/ios/Extension/Section+Copying.swift +3 -6
  233. package/ios/Extension/String+IcyCharset.swift +5 -5
  234. package/ios/Extension/TimedMetadata+AVFoundation.swift +6 -12
  235. package/ios/Extension/Track+AVPlayer.swift +1 -2
  236. package/ios/Extension/Track+Copying.swift +2 -8
  237. package/ios/Extension/Track+Identity.swift +4 -9
  238. package/ios/Extension/TrackMetadata+AVFoundation.swift +10 -13
  239. package/ios/Extension/UIApplication+ActiveScene.swift +6 -14
  240. package/ios/Extension/Variant+Artwork.swift +8 -22
  241. package/ios/Http/HttpClient.swift +3 -3
  242. package/ios/HybridAudioBrowser+Browser.swift +10 -16
  243. package/ios/HybridAudioBrowser+Options.swift +6 -9
  244. package/ios/HybridAudioBrowser+Player.swift +8 -16
  245. package/ios/HybridAudioBrowser+PlayerCallbacks.swift +4 -5
  246. package/ios/HybridAudioBrowser+Stubs.swift +5 -7
  247. package/ios/HybridAudioBrowser.swift +54 -79
  248. package/ios/Model/NitroTypeStubs.swift +15 -22
  249. package/ios/Model/PlayerUpdateOptions.swift +6 -21
  250. package/ios/Model/RemoteCommand.swift +2 -2
  251. package/ios/Model/TrackPlayerError.swift +9 -22
  252. package/ios/NowPlayingInfo/NowPlayingInfoController.swift +21 -40
  253. package/ios/NowPlayingInfo/SilentAudioPrimer.swift +10 -16
  254. package/ios/Observer/ItemObserver.swift +7 -5
  255. package/ios/Observer/PlayerObserver.swift +5 -5
  256. package/ios/PlaybackEvent.swift +2 -2
  257. package/ios/Player/AirPlayStallJudgement.swift +7 -9
  258. package/ios/Player/AudioSessionController.swift +14 -15
  259. package/ios/Player/DeferredSeek.swift +2 -2
  260. package/ios/Player/EndOfTrackJudgement.swift +6 -13
  261. package/ios/Player/ErrorStatus.swift +8 -7
  262. package/ios/Player/MediaLoader.swift +20 -24
  263. package/ios/Player/NowPlayingLines.swift +1 -4
  264. package/ios/Player/NowPlayingUpdater.swift +35 -61
  265. package/ios/Player/PersistedPlaybackState.swift +1 -2
  266. package/ios/Player/PlaybackFailure.swift +20 -24
  267. package/ios/Player/PlaybackPersistence.swift +5 -6
  268. package/ios/Player/PlaybackStateMachine.swift +8 -11
  269. package/ios/Player/PlaybackTimer.swift +8 -11
  270. package/ios/Player/Player.swift +6 -13
  271. package/ios/Player/PlayerEngine.swift +20 -20
  272. package/ios/Player/PlayerStatusTypes.swift +1 -2
  273. package/ios/Player/QueueManager.swift +23 -67
  274. package/ios/Player/RetryLoop.swift +39 -50
  275. package/ios/Player/ShuffleOrder.swift +17 -57
  276. package/ios/Player/SleepTimerManager.swift +13 -28
  277. package/ios/Player/VolumeFader.swift +16 -16
  278. package/ios/RemoteCommand/RemoteCommandCallbacks.swift +6 -16
  279. package/ios/RemoteCommand/RemoteCommandController.swift +8 -10
  280. package/ios/Tests/AirPlayStallJudgementTests.swift +4 -4
  281. package/ios/Tests/BrowserPathHelperTests.swift +3 -6
  282. package/ios/Tests/DeferredSeekTests.swift +1 -3
  283. package/ios/Tests/EmitterTests.swift +0 -1
  284. package/ios/Tests/EndOfTrackJudgementTests.swift +1 -6
  285. package/ios/Tests/FavoriteSetTests.swift +1 -0
  286. package/ios/Tests/GenerationMemoTests.swift +2 -2
  287. package/ios/Tests/InertStyleDiagnosticTests.swift +4 -10
  288. package/ios/Tests/JsonModelsTests.swift +5 -12
  289. package/ios/Tests/LRUCacheTests.swift +1 -5
  290. package/ios/Tests/MediaIntentCriteriaTests.swift +2 -7
  291. package/ios/Tests/MediaLoaderTests.swift +3 -12
  292. package/ios/Tests/ObserverTests.swift +3 -3
  293. package/ios/Tests/PlaybackErrorTests.swift +7 -9
  294. package/ios/Tests/PlaybackFailureTests.swift +9 -17
  295. package/ios/Tests/PlaybackPersistenceTests.swift +1 -0
  296. package/ios/Tests/PlaybackStateMachineTests.swift +1 -16
  297. package/ios/Tests/PlaybackTimerTests.swift +2 -3
  298. package/ios/Tests/PlayerPolicyTests.swift +10 -26
  299. package/ios/Tests/PlayerTests.swift +53 -88
  300. package/ios/Tests/PlayingStateTests.swift +0 -1
  301. package/ios/Tests/QueueManagerTests.swift +30 -80
  302. package/ios/Tests/RemoteCommandControllerTests.swift +5 -13
  303. package/ios/Tests/ResolvedTrackCopyingTests.swift +0 -2
  304. package/ios/Tests/RetryLoopTests.swift +12 -35
  305. package/ios/Tests/SearchDrillInTests.swift +4 -5
  306. package/ios/Tests/SectionPresentationTests.swift +3 -16
  307. package/ios/Tests/SectionScopeTests.swift +3 -6
  308. package/ios/Tests/SimpleRouterTests.swift +1 -5
  309. package/ios/Tests/SleepTimerManagerTests.swift +8 -11
  310. package/ios/Tests/StyleResolverTests.swift +4 -13
  311. package/ios/Tests/Support/ManualSleepTimerScheduler.swift +3 -8
  312. package/ios/Tests/Support/TestTypes.swift +5 -15
  313. package/ios/Tests/TabBarEntriesTests.swift +0 -2
  314. package/ios/Tests/TimedMetadataAVFoundationTests.swift +2 -3
  315. package/ios/Tests/TopTemplateReplacerTests.swift +1 -1
  316. package/ios/Tests/TrackIdTemplateTests.swift +2 -6
  317. package/ios/Tests/TrackMetadataAVFoundationTests.swift +1 -4
  318. package/ios/Tests/TrackSelectorTests.swift +3 -15
  319. package/ios/TrackSelector.swift +13 -25
  320. package/ios/Util/ArtworkFreshness.swift +6 -6
  321. package/ios/Util/ArtworkImageFetcher.swift +19 -20
  322. package/ios/Util/ConcurrentMap.swift +2 -2
  323. package/ios/Util/Emitter.swift +8 -13
  324. package/ios/Util/NetworkMonitor.swift +4 -6
  325. package/ios/Util/OutputPicker.swift +1 -1
  326. package/ios/Util/ReadyValue.swift +3 -2
  327. package/ios/Util/SFSymbolRenderer.swift +17 -30
  328. package/ios/Util/SVGProcessor.swift +5 -9
  329. package/package.json +1 -1
@@ -33,15 +33,6 @@ import kotlinx.coroutines.withContext
33
33
  import kotlinx.serialization.json.Json
34
34
  import timber.log.Timber
35
35
 
36
- /**
37
- * Core browser manager that handles navigation, search, and media browsing.
38
- *
39
- * This class contains the main business logic for:
40
- * - Route resolution and path matching with parameter extraction
41
- * - HTTP API requests and response processing
42
- * - JavaScript callback invocation
43
- * - Fallback handling and error management
44
- */
45
36
  class BrowserManager {
46
37
  private val router = SimpleRouter()
47
38
  private val httpClient = HttpClient()
@@ -78,7 +69,6 @@ class BrowserManager {
78
69
  set(value) {
79
70
  val previous = field
80
71
  field = value
81
- // Arrays need contentEquals for comparison
82
72
  if (value != null && !value.contentEquals(previous)) {
83
73
  onTabsChanged?.invoke(value)
84
74
  } else if (value == null && previous != null) {
@@ -86,61 +76,47 @@ class BrowserManager {
86
76
  }
87
77
  }
88
78
 
89
- // LRU cache for individual tracks - keyed by both path and src for O(1) lookup
79
+ // Keyed by id, path and src (see cacheTrack), so one track takes up to three entries.
90
80
  private val trackCache = LruCache<String, Track>(3000)
91
81
 
92
- // LRU cache for resolved content - keyed by path
93
- // Keeps recently visited paths cached for fast back navigation and tab switching
94
- // Invalidated via invalidateContentCache() when content changes
95
82
  private val contentCache = LruCache<String, ResolvedTrack>(20)
96
83
 
97
- // Cache for the most recent search - the query string and its results stored as one pair, so a
98
- // concurrent reader never sees one query matched with another query's results.
84
+ // Query and results stored as one pair, so a concurrent reader never matches one query with
85
+ // another query's results.
99
86
  @Volatile private var lastSearch: Pair<String, Array<Track>>? = null
100
87
 
101
- // Set of favorited track identities (id when non-blank, else src — see Track.identity)
88
+ // Track identities: id when non-blank, else src (ADR 0008).
102
89
  private var favoriteIds = setOf<String>()
103
90
 
104
- // Whether favoriting is enabled, propagated from the player's `favorite` capability.
105
- // false = favoriting disabled (no row hearts). Set via setFavoriteEnabled.
106
91
  private var favoriteEnabled: Boolean = false
107
92
 
108
- // Navigation tracking to prevent race conditions
109
93
  @Volatile private var currentNavigationId = 0
110
94
 
111
95
  /**
112
- * Browser configuration containing routes, search, tabs, and request settings. This can be
113
- * updated dynamically when the configuration changes.
114
- *
115
- * Setting a new config bumps [layerGeneration] so the cached request/browse resolver layers are
116
- * re-resolved on the next request (the resolvers may close over config-derived state).
96
+ * Setting a new config re-resolves the request/browse resolver layers and the "view more" title
97
+ * on the next request, and clears the artwork registries: their registrations pin the previous
98
+ * config's JS callback handles.
117
99
  */
118
100
  var config: BrowserConfig = BrowserConfig()
119
101
  set(value) {
120
102
  field = value
121
103
  layerGeneration += 1
122
- // Registered artwork resolutions pin configs (and their JS callback handles)
123
- // from the previous configuration — never resolve through them again.
124
104
  artworkResolutions.clear()
125
105
  onArtworkRegistriesCleared?.invoke()
126
106
  }
127
107
 
128
- // Resolver-layer caching. The request/browse layers may be resolver thunks
129
- // (config.requestResolver / config.browseResolver) resolved once per *content generation*:
130
- // re-resolved when content is invalidated (clearContentCache, from invalidateAllContent) or when
131
- // a new config is set, cached, and merged per request.
108
+ // Request/browse resolver layers, resolved once per generation and merged per request. The
109
+ // generation moves on a new config or clearContentCache (invalidateAllContent).
132
110
  private var layerGeneration = 0
133
111
  private var resolvedLayerGeneration = -1
134
112
  private var resolvedRequestLayer: TransformableRequestConfig? = null
135
113
  private var resolvedBrowseLayer: TransformableRequestConfig? = null
136
114
 
137
- // The "view more" row title, cached on the same generation as the layers above — see
138
- // viewMoreTitle(). Kept separate from them because it is resolved lazily (only a browse that
139
- // actually appends a row asks for it), not eagerly alongside every request.
115
+ // Cached on the same generation, but resolved lazily: only a browse that appends a "view more"
116
+ // row asks for it.
140
117
  private var resolvedViewMoreTitleGeneration = -1
141
118
  private var resolvedViewMoreTitle = DEFAULT_VIEW_MORE_TITLE
142
119
 
143
- /** Test-only accessors for the resolver-layer cache state (see ensureLayersResolved). */
144
120
  internal val layerGenerationForTest: Int
145
121
  get() = layerGeneration
146
122
 
@@ -154,32 +130,22 @@ class BrowserManager {
154
130
  get() = resolvedBrowseLayer
155
131
 
156
132
  /**
157
- * Maps produced artwork URIs back to (Track, artwork-config kind) so display-time bitmap loading
158
- * can re-resolve Track-first. See [ArtworkResolutionRegistry].
133
+ * Maps produced artwork URIs back to the track and config that made them, so display-time loading
134
+ * (which gets only a URI from Media3) can re-resolve with a size. See
135
+ * [ArtworkResolutionRegistry].
159
136
  */
160
137
  val artworkResolutions = ArtworkResolutionRegistry()
161
138
 
162
- /**
163
- * Sets the favorited track identities (id when non-blank, else src). Tracks will have their
164
- * favorited field hydrated based on this list during browsing.
165
- */
139
+ /** Sets the favorited track identities (id when non-blank, else src). */
166
140
  fun setFavorites(favorites: List<String>) {
167
141
  favoriteIds = favorites.toSet()
168
142
  Timber.d("Set ${favoriteIds.size} favorite IDs")
169
143
  }
170
144
 
171
- /**
172
- * Enables or disables favoriting (propagated from the `favorite` capability). false disables
173
- * row-heart hydration.
174
- */
175
145
  fun setFavoriteEnabled(enabled: Boolean) {
176
146
  favoriteEnabled = enabled
177
147
  }
178
148
 
179
- /**
180
- * Updates the favorite state for a single track identity (id when non-blank, else src). Called
181
- * when the heart button is tapped in media controllers.
182
- */
183
149
  fun updateFavorite(identity: String, favorited: Boolean) {
184
150
  favoriteIds =
185
151
  if (favorited) {
@@ -191,29 +157,21 @@ class BrowserManager {
191
157
  }
192
158
 
193
159
  /**
194
- * Hydrates the favorited field on a track based on the favoriteIds set. No-op unless favoriting
195
- * is enabled (the `favorite` capability). Only tracks with an identity (id or src) are
196
- * favoritable; the flag is set to true OR false so non-favorited tracks still show an (empty)
197
- * heart. Doesn't overwrite API-provided values.
160
+ * Sets `favorited` to true or false, so a track that isn't a favorite still shows an empty heart.
161
+ * A value the source already set wins; a track without an identity is left unset.
198
162
  */
199
163
  private fun hydrateFavorite(track: Track): Track {
200
164
  if (!favoriteEnabled) return track
201
- // Don't overwrite API-provided favorites
202
165
  if (track.favorited != null) return track
203
- // Only identity-bearing tracks are favoritable
204
166
  if (track.identity == null) return track
205
167
 
206
168
  return track.copy(favorited = isFavorite(track))
207
169
  }
208
170
 
209
- /** Whether [track]'s identity is in the favorites set. */
210
171
  private fun isFavorite(track: Track): Boolean =
211
172
  track.identity?.let { favoriteIds.contains(it) } == true
212
173
 
213
- /**
214
- * Hydrates favorites on all tracks of a resolved page. Pages reach hydration normalized (ADR
215
- * 0010), so `sections` is the only structure to walk.
216
- */
174
+ // Pages arrive normalized (ADR 0010): `sections` is the only structure to walk.
217
175
  private fun hydrateChildren(resolvedTrack: ResolvedTrack): ResolvedTrack {
218
176
  val sections = resolvedTrack.sections ?: return resolvedTrack
219
177
  return resolvedTrack.copy(
@@ -226,7 +184,6 @@ class BrowserManager {
226
184
  )
227
185
  }
228
186
 
229
- /** Cache a track by id, path, and src for O(1) lookup from any mediaId form. */
230
187
  private fun cacheTrack(track: Track) {
231
188
  track.id?.takeUnless { it.isBlank() }?.let { trackCache.put(it, track) }
232
189
  track.path?.let { trackCache.put(it, track) }
@@ -237,27 +194,21 @@ class BrowserManager {
237
194
  resolvedTrack.flattenedChildren?.forEach { cacheTrack(it) }
238
195
  }
239
196
 
240
- // Pages already warned about by warnIfGridPageLacksPromise — the mismatch
241
- // re-observes on every onGetChildren serve, and once is a diagnostic while
242
- // every-scroll is noise. Concurrent: onGetChildren serves run on the IO
243
- // pool, several in flight at once.
197
+ // Warns once per page: the check runs again on every onGetChildren serve. Concurrent: those
198
+ // serves run several at once on the IO pool.
244
199
  private val promiseWarnedPaths = java.util.concurrent.ConcurrentHashMap.newKeySet<String>()
245
200
 
246
201
  /**
247
- * Dev diagnostic (ADR 0011): a page serving grid sections under a browsable handle that declared
248
- * no `style.display` promise still renders its parent-level layout as a list on Android Auto —
249
- * the parent hint is emitted only when declared, never derived from resolved pages and never
250
- * back-filled. Warns at the one site where the mismatch is observable; a cache miss for the
251
- * handle (cold start straight into the page) just skips the check.
252
- *
253
- * Only an all-grid page warns: the parent-level hint lays out the WHOLE page, so on a mixed page
254
- * (a teaser shelf above list sections) there is no correct promise to advise — grid would tile
255
- * the list sections too.
202
+ * Dev diagnostic (ADR 0011): an all-grid page under a browsable handle that declares no
203
+ * `style.display` renders as a list on Android Auto, which takes the layout from the parent-level
204
+ * hint, emitted only when the handle declares it. A handle missing from the cache (cold start
205
+ * straight into the page) skips the check. A mixed page never warns: the parent hint lays out the
206
+ * whole page, so grid would tile its list sections too.
256
207
  */
257
208
  fun warnIfGridPageLacksPromise(path: String, sections: List<Section>) {
258
209
  if (sections.isEmpty() || !sections.all { it.style?.display == StyleDisplay.GRID }) return
259
210
  val handle = trackCache.get(path) ?: return
260
- if (handle.src != null) return // rendered playable — opens no page, promises nothing
211
+ if (handle.src != null) return // rendered playable: opens no page
261
212
  if (handle.style?.display == null && promiseWarnedPaths.add(path)) {
262
213
  Timber.w(
263
214
  "Page '%s' serves grid sections, but its browsable handle declares no style.display — " +
@@ -269,20 +220,16 @@ class BrowserManager {
269
220
  }
270
221
 
271
222
  /**
272
- * Get a cached Track by mediaId (stable id, path, or src), or null if not cached. Used by Media3
273
- * to rehydrate MediaItem shells with full track metadata. Re-hydrates favorites in case
274
- * setFavoriteStates was called after caching.
223
+ * Returns the cached track for a mediaId (id, path or src, or a contextual path's trackId), with
224
+ * favorites re-hydrated, or null when it isn't cached.
275
225
  */
276
226
  fun getCachedTrack(mediaId: String): Track? {
277
- // Try direct lookup first (matches path or src)
278
227
  trackCache.get(mediaId)?.let { track ->
279
228
  val hydratedTrack = hydrateFavorite(track)
280
229
  Timber.d("Cache HIT for mediaId='$mediaId' → '${track.title}'")
281
230
  return hydratedTrack
282
231
  }
283
232
 
284
- // Try extracting the track identity (id when non-blank, else src) from a contextual path —
285
- // the cache is keyed by id AND src, so either identity form resolves.
286
233
  val trackId = BrowserPathHelper.extractTrackId(mediaId)
287
234
  if (trackId != null) {
288
235
  trackCache.get(trackId)?.let { track ->
@@ -297,11 +244,9 @@ class BrowserManager {
297
244
  }
298
245
 
299
246
  /**
300
- * Resolves a tapped mediaId to the contextual path to expand a queue from, or null when there is
301
- * none. A contextual mediaId is its own; a stable-id mediaId (see TrackFactory.buildMediaItem)
302
- * resolves through the track cache to the contextual path of the container it was most recently
303
- * browsed in — a legacy car controller round-trips only the mediaId, so the cache is what
304
- * remembers which list the row came from.
247
+ * The contextual path to expand a queue from, or null. A stable-id mediaId resolves through the
248
+ * track cache to the container it was most recently browsed in: a legacy car controller
249
+ * round-trips only the mediaId, so the cache is what remembers which list the row came from.
305
250
  */
306
251
  fun contextualPathFor(mediaId: String): String? {
307
252
  if (BrowserPathHelper.isContextual(mediaId)) return mediaId
@@ -309,16 +254,12 @@ class BrowserManager {
309
254
  }
310
255
 
311
256
  /**
312
- * Resolves a single Media3 MediaItem to a Track. Prefers the track cache (keyed by id, path, and
313
- * src).
314
- *
315
- * A cache miss is legitimately reachable: a controller can replay a mediaId this process never
316
- * browsed — e.g. a search-result track after process death. When the mediaId is a playable URL,
317
- * or the item's requestMetadata carries the playable uri (stamped by TrackFactory for stable-id
318
- * mediaIds, and round-tripped by Media3 controllers), fall back to a minimal track built from the
319
- * item's own metadata instead of failing playback.
257
+ * A cache miss is reachable: a controller can replay a mediaId this process never browsed (a
258
+ * search result after process death). When the mediaId is a playable URL, or the item's
259
+ * requestMetadata carries the playable uri (stamped by TrackFactory), it builds a minimal track
260
+ * from the item's metadata.
320
261
  *
321
- * @throws IllegalStateException if the mediaId is not cached and no playable URL is available
262
+ * @throws IllegalStateException when the mediaId is not cached and no playable URL is available
322
263
  */
323
264
  private fun resolveMediaItemToTrack(mediaItem: MediaItem): Track {
324
265
  val mediaId = mediaItem.mediaId
@@ -339,8 +280,8 @@ class BrowserManager {
339
280
  val metadata = mediaItem.mediaMetadata
340
281
  return hydrateFavorite(
341
282
  Track(
342
- // A mediaId distinct from the playable uri is the track's stable id —
343
- // keep it so the item's identity (car now-playing row match) survives.
283
+ // A mediaId distinct from the playable uri is the stable id; keeping it lets the car's
284
+ // now-playing row match.
344
285
  id = mediaId.takeIf { it != fallbackSrc },
345
286
  path = null,
346
287
  src = fallbackSrc,
@@ -368,44 +309,31 @@ class BrowserManager {
368
309
  }
369
310
 
370
311
  /**
371
- * **Media3/Android Auto Integration Entry Point**
372
- *
373
- * Resolves Media3 MediaItems for playback, with special handling for Android Auto queue
374
- * expansion. Called exclusively from `MediaSessionCallback.onSetMediaItems()`.
312
+ * Resolves the items `MediaSessionCallback.onSetMediaItems()` receives. A single item with a
313
+ * search query plays the search results from that item; a single contextual item expands to the
314
+ * tapped section's queue. Otherwise each item resolves through the track cache. Disabled tracks
315
+ * are dropped and the start index shifts to match.
375
316
  *
376
- * Behavior:
377
- * - Single item: Attempts queue expansion (Android Auto album/playlist restoration)
378
- * - Multiple items OR expansion fails: Falls back to cache resolution
379
- *
380
- * @param mediaItems List of Media3 MediaItems requested for playback
381
- * @param startIndex Index of the item to start playing
382
- * @param startPositionMs Position within the start item to begin playback
383
- * @return MediaSession.MediaItemsWithStartPosition ready for Media3
384
- * @throws IllegalStateException if a mediaId is neither cached nor a playable URL
317
+ * @throws IllegalStateException when the start track is disabled, every track is disabled, or a
318
+ * mediaId is neither cached nor a playable URL
385
319
  */
386
320
  suspend fun resolveMediaItemsForPlayback(
387
321
  mediaItems: List<MediaItem>,
388
322
  startIndex: Int,
389
323
  startPositionMs: Long,
390
324
  ): MediaSession.MediaItemsWithStartPosition {
391
- // Android Auto queue expansion: single track → full album/playlist
392
325
  if (mediaItems.size == 1) {
393
326
  val mediaItem = mediaItems[0]
394
327
 
395
- // Handle search query - user initiated playback from search results
396
328
  val searchQuery = mediaItem.requestMetadata.searchQuery
397
329
  if (searchQuery != null) {
398
330
  Timber.d("Handling search playback request for query: $searchQuery")
399
331
 
400
- // Execute search (will hit cache if already performed). Disabled
401
- // tracks never play, so they never enter a search-built queue.
402
332
  val searchResults = search(searchQuery)
403
333
  val searchTracks =
404
334
  searchResults.flattenedChildren?.filterNot { it.disabled == true }?.toTypedArray()
405
335
 
406
336
  if (searchTracks != null && searchTracks.isNotEmpty()) {
407
- // Find the selected track in search results (mediaId is the stable id
408
- // when the track has one, else path/src — see TrackFactory)
409
337
  val mediaId = mediaItem.mediaId
410
338
  val selectedIndex =
411
339
  searchTracks.indexOfFirst { track ->
@@ -417,7 +345,6 @@ class BrowserManager {
417
345
  "Playing search result at index $selectedIndex of ${searchTracks.size} results"
418
346
  )
419
347
 
420
- // Convert to Media3 MediaItems
421
348
  val searchMediaItems = searchTracks.map { track -> TrackFactory.toMedia3(track) }
422
349
 
423
350
  return MediaSession.MediaItemsWithStartPosition(
@@ -433,9 +360,9 @@ class BrowserManager {
433
360
  }
434
361
  }
435
362
 
363
+ // A failed search match falls through to plain resolution, never to browse expansion: the
364
+ // user asked for that one result, not a browsed list.
436
365
  val mediaId = mediaItems[0].mediaId
437
- // A failed search match falls through to plain resolution, never to browse
438
- // expansion — the user asked for that one result, not a browsed list.
439
366
  val contextualPath = if (searchQuery == null) contextualPathFor(mediaId) else null
440
367
 
441
368
  if (contextualPath != null) {
@@ -446,7 +373,6 @@ class BrowserManager {
446
373
  if (expanded != null) {
447
374
  val (tracks, selectedIndex) = expanded
448
375
 
449
- // Convert to Media3 MediaItems
450
376
  val expandedMediaItems = tracks.map { track -> TrackFactory.toMedia3(track) }
451
377
 
452
378
  return MediaSession.MediaItemsWithStartPosition(
@@ -458,18 +384,12 @@ class BrowserManager {
458
384
  }
459
385
  }
460
386
 
461
- // No expansion - resolve from cache (with a minimal-track fallback for replayed mediaIds)
462
387
  val resolvedTracks = mediaItems.map { resolveMediaItemToTrack(it) }
463
388
 
464
- // A disabled track is unavailable — it never plays, even by a stale or
465
- // replayed mediaId (Track.disabled). Refusal fails the future: Media3
466
- // surfaces an error to the controller and the current playback stays
467
- // untouched (an empty item list would clear the live timeline instead).
468
- //
469
- // Media3's legacy path — how Android Auto and Assistant actually request
470
- // playback (onPlayFromMediaId et al.) — passes C.INDEX_UNSET, meaning
471
- // "the default item", i.e. the first. Normalize before the guard, or the
472
- // refusal is dead on exactly the path that serves cars.
389
+ // Refusal fails the future: Media3 surfaces an error to the controller and current playback
390
+ // stays untouched, where an empty item list would clear the timeline. Android Auto and
391
+ // Assistant request playback through Media3's legacy path, which passes C.INDEX_UNSET for
392
+ // "the first item": normalize before the guard, or the refusal misses the cars.
473
393
  val effectiveStartIndex = if (startIndex == C.INDEX_UNSET) 0 else startIndex
474
394
  val startTrack = resolvedTracks.getOrNull(effectiveStartIndex)
475
395
  if (startTrack != null && startTrack.disabled == true) {
@@ -478,14 +398,10 @@ class BrowserManager {
478
398
  }
479
399
  val playableTracks = resolvedTracks.filterNot { it.disabled == true }
480
400
  if (playableTracks.isEmpty()) {
481
- // Belt over the start-item guard: never hand Media3 an empty timeline.
482
401
  Timber.w("Refusing playback: every requested track is disabled")
483
402
  throw IllegalStateException("Refusing playback: every requested track is disabled")
484
403
  }
485
- // Positional, not indexOf: value equality would alias a duplicated track
486
- // (the same station twice in a queue) to its first copy. An unset index
487
- // stays unset — Media3's "default item" semantics pass through as they
488
- // did before the filter existed.
404
+ // Positional, not indexOf: value equality would map a duplicated track to its first copy.
489
405
  val adjustedStartIndex =
490
406
  when {
491
407
  startIndex == C.INDEX_UNSET -> C.INDEX_UNSET
@@ -493,7 +409,6 @@ class BrowserManager {
493
409
  else -> resolvedTracks.take(effectiveStartIndex).count { it.disabled != true }
494
410
  }
495
411
 
496
- // Convert to Media3 MediaItems
497
412
  val resolvedMediaItems = playableTracks.map { track -> TrackFactory.toMedia3(track) }
498
413
 
499
414
  return MediaSession.MediaItemsWithStartPosition(
@@ -503,10 +418,6 @@ class BrowserManager {
503
418
  )
504
419
  }
505
420
 
506
- /**
507
- * Validates that a track has either path or src for stable identification. Throws
508
- * IllegalStateException if validation fails.
509
- */
510
421
  private fun validateTrack(track: Track, context: String) {
511
422
  if (track.path == null && track.src == null) {
512
423
  throw IllegalStateException(
@@ -515,27 +426,21 @@ class BrowserManager {
515
426
  }
516
427
  }
517
428
 
429
+ /** Resolves the page at [path]; a contextual path resolves its parent container. */
518
430
  suspend fun resolve(path: String, useCache: Boolean = true): ResolvedTrack {
519
431
  Timber.d("=== RESOLVE: path='$path' (useCache=$useCache) ===")
520
432
 
521
- // Strip __trackId from contextual paths (e.g., "/library/radio?__trackId=song.mp3" →
522
- // "/library/radio")
523
- // This allows resolving the parent container for tracks referenced by contextual path
524
433
  val normalizedPath = BrowserPathHelper.stripTrackId(path)
525
434
  if (normalizedPath != path) {
526
435
  Timber.d("Stripped __trackId from contextual path: '$normalizedPath'")
527
436
  }
528
437
 
529
- // Check content cache first
530
438
  if (useCache) {
531
439
  contentCache.get(normalizedPath)?.let { cached ->
532
440
  Timber.d("Content cache HIT for path='$normalizedPath'")
533
- // Re-key the track cache even on a hit: an id-keyed lookup (stable-id
534
- // mediaId → contextual path, see contextualPathFor) must reflect the
535
- // most recently *browsed* container, which a cached re-display
536
- // otherwise wouldn't re-register.
441
+ // Re-key the track cache on a hit too: contextualPathFor must see the most recently
442
+ // browsed container.
537
443
  cacheChildren(cached)
538
- // Re-hydrate favorites in case they changed since caching
539
444
  return hydrateChildren(cached)
540
445
  }
541
446
  Timber.d("Content cache MISS for path='$normalizedPath'")
@@ -543,22 +448,14 @@ class BrowserManager {
543
448
 
544
449
  val resolvedTrack = resolveUncached(normalizedPath)
545
450
 
546
- // Cache the resolved content for future navigation
547
451
  contentCache.put(normalizedPath, resolvedTrack)
548
452
 
549
- // Cache children for Media3 track lookups (getCachedTrack)
550
453
  cacheChildren(resolvedTrack)
551
454
 
552
455
  return hydrateChildren(resolvedTrack)
553
456
  }
554
457
 
555
- /**
556
- * Invalidates the content cache for a specific path. Called when content at that path has changed
557
- * (e.g., via notifyContentChanged).
558
- *
559
- * @param path The container path to invalidate (e.g., "/library/radio")
560
- * @throws IllegalArgumentException if passed a contextual path (contains __trackId)
561
- */
458
+ /** @throws IllegalArgumentException when [path] is contextual rather than a container path */
562
459
  fun invalidateContentCache(path: String) {
563
460
  require(!BrowserPathHelper.isContextual(path)) {
564
461
  "invalidateContentCache() expects a container path, not a contextual path: $path"
@@ -567,26 +464,21 @@ class BrowserManager {
567
464
  Timber.d("Invalidated content cache for path='$path'")
568
465
  }
569
466
 
570
- /** Clears all cached content. */
467
+ /**
468
+ * Clears every cached page and the last search, which nothing else evicts, and re-resolves the
469
+ * resolver layers and "view more" title on the next request.
470
+ */
571
471
  fun clearContentCache() {
572
472
  contentCache.evictAll()
573
- // The search slot is content too: a locale switch or a re-auth changes titles, src, artwork
574
- // and availability, and nothing else ever evicts it, so a repeated query returned
575
- // pre-invalidation results forever. (Matches the Swift twin's clearContentCache.)
576
473
  lastSearch = null
577
- // Bump the layer generation so request/browse resolver thunks are re-resolved on the next
578
- // request (invalidateAllContent → clearContentCache is the documented re-resolve trigger).
579
474
  layerGeneration += 1
580
- // Invalidated content's artwork resolutions go with it (same staleness rule as the
581
- // config setter).
582
475
  artworkResolutions.clear()
583
476
  onArtworkRegistriesCleared?.invoke()
584
477
  Timber.d("Cleared all content cache")
585
478
  }
586
479
 
587
480
  private suspend fun resolveUncached(path: String): ResolvedTrack {
588
- // Match an explicit route (or the '*' default). With no match, fall back to
589
- // the implicit default: fetch the path via the request + browse config.
481
+ // With no route matched, the implicit default fetches the path via the request + browse config.
590
482
  val match = config.routes?.let { findBestRouteMatch(path, it) }
591
483
 
592
484
  val resolvedTrack: ResolvedTrack
@@ -602,20 +494,13 @@ class BrowserManager {
602
494
  effectiveArtworkConfig = config.artwork
603
495
  }
604
496
 
605
- // Normalize to the canonical sectioned shape (children sugar → one untitled
606
- // section — ADR 0010), then generate contextual paths and transform artwork
607
- // URLs. The output never carries `children`.
608
497
  val sections = resolvedTrack.normalizedSections ?: return resolvedTrack
609
- // Dev diagnostic (ADR 0011) — before the blocks are folded, while each level is
610
- // still attributable. Every page passes here whatever its source, and only on a
611
- // cache miss. No-op outside debug builds.
498
+ // Before the sections are folded, while each level is still attributable.
612
499
  InertStyleDiagnostic.warn(path, resolvedTrack.style, sections)
613
- // The contextual index is the flat page position — children concatenated in
614
- // section order (ADR 0009/0010).
500
+ // The contextual index is the flat page position: children in section order (ADR 0009).
615
501
  var flatIndex = 0
616
- // One scope for the whole page: every child's transform (which can suspend
617
- // on artwork resolution) launches up front across all sections, then the
618
- // sections reassemble — a slow section doesn't serialize the ones after it.
502
+ // One scope for the page: every child's artwork transform launches up front, so a slow section
503
+ // doesn't hold up the ones after it.
619
504
  val transformedSections = coroutineScope {
620
505
  sections
621
506
  .map { section ->
@@ -625,18 +510,13 @@ class BrowserManager {
625
510
  section.children.mapIndexed { offset, track ->
626
511
  async {
627
512
  val index = base + offset
628
- // Validate that track has stable identifier.
629
513
  validateTrack(track, "Child track")
630
514
 
631
515
  var transformedTrack = track
632
516
 
633
- // Generate contextual paths for playable tracks
634
- // Always regenerate to reflect the current browsing context, not the original
635
- // context
636
- // (e.g., a track favorited from an album should use /favorites context when browsed
637
- // there)
638
- // The flat page position rides along as a duplicate-identity tie-breaker.
639
517
  val trackIdentity = track.identity
518
+ // Regenerated on every browse so the path names the container it was browsed in;
519
+ // the flat position breaks ties between duplicate identities.
640
520
  if (track.src != null && trackIdentity != null) {
641
521
  val contextualPath = BrowserPathHelper.build(path, trackIdentity, index)
642
522
  transformedTrack = transformedTrack.copy(path = contextualPath)
@@ -650,7 +530,7 @@ class BrowserManager {
650
530
  )
651
531
  }
652
532
 
653
- // Transform artwork URL. At browse-time there is no display size info.
533
+ // No display size at browse time.
654
534
  transformArtworkUrl(
655
535
  transformedTrack,
656
536
  effectiveArtworkConfig,
@@ -669,13 +549,6 @@ class BrowserManager {
669
549
  return resolvedTrack.copy(sections = transformedSections.toTypedArray(), children = null)
670
550
  }
671
551
 
672
- /**
673
- * Transforms a track's artwork via [resolveArtworkUrl]. Populates artworkSource with the
674
- * transformed ImageSource, keeping artwork unchanged. Handles all edge cases: undefined returns,
675
- * errors, missing artwork.
676
- *
677
- * @param imageContext Optional size context for CDN URL generation (null at browse-time)
678
- */
679
552
  private suspend fun transformArtworkUrl(
680
553
  track: Track,
681
554
  artworkConfig: ArtworkRequestConfig?,
@@ -683,7 +556,6 @@ class BrowserManager {
683
556
  index: Int,
684
557
  imageContext: ImageContext? = null,
685
558
  ): Track {
686
- // No artwork config and no track.artwork - nothing to transform
687
559
  if (artworkConfig == null && track.artwork == null) {
688
560
  return track
689
561
  }
@@ -692,20 +564,16 @@ class BrowserManager {
692
564
  val imageSource = resolveArtworkUrl(track, artworkConfig, imageContext)
693
565
 
694
566
  when {
695
- // resolve returned null → no artwork source
696
567
  imageSource == null -> {
697
568
  Timber.d(
698
569
  "[$path] Child[$index] '${track.title}': Artwork resolver returned null, no artworkSource"
699
570
  )
700
571
  track.copy(artworkSource = null)
701
572
  }
702
- // resolve returned ImageSource → set artworkSource
703
573
  else -> {
704
574
  Timber.d("[$path] Child[$index] '${track.title}': artworkSource set: ${imageSource.uri}")
705
- // Remember how this URI was produced so display-time loading (which only
706
- // gets a URI from Media3) can re-resolve Track-first with a size hint.
707
- // Register the per-route config only when it isn't the global fallback,
708
- // so display-time resolution reads the *current* config.artwork.
575
+ // Registers a per-route config only, so display-time resolution reads the current
576
+ // config.artwork rather than a stale global.
709
577
  artworkResolutions.register(
710
578
  imageSource.uri,
711
579
  track,
@@ -715,7 +583,6 @@ class BrowserManager {
715
583
  }
716
584
  }
717
585
  } catch (e: Exception) {
718
- // resolve threw → log error, clear artworkSource to avoid broken images
719
586
  Timber.e(
720
587
  e,
721
588
  "[$path] Child[$index] '${track.title}': Artwork transform failed, clearing artworkSource",
@@ -725,13 +592,10 @@ class BrowserManager {
725
592
  }
726
593
 
727
594
  /**
728
- * Expands a contextual path into a queue of playable tracks.
729
- *
730
- * Used when navigating to a track to load it with its full album/playlist context. Returns only
731
- * the selected track if singleTrack is true.
732
- *
733
- * @param contextualPath The contextual path (e.g., "/album?__trackId=song.mp3")
734
- * @return Pair of (tracks array, selected track index), or null if expansion fails
595
+ * Expands a contextual path into the playable, enabled tracks of the tapped section (ADR 0006)
596
+ * and the start index, or only the tapped track when `singleTrack` is set. Returns null when the
597
+ * path is not contextual, the tapped identity is no longer on the page or is disabled, or
598
+ * resolution fails; the caller then plays the stored single track.
735
599
  */
736
600
  suspend fun expandQueueFromContextualPath(contextualPath: String): Pair<Array<Track>, Int>? {
737
601
  val trackId = BrowserPathHelper.extractTrackId(contextualPath) ?: return null
@@ -739,7 +603,6 @@ class BrowserManager {
739
603
  Timber.d("Expanding queue from contextual path: $contextualPath (trackId=$trackId)")
740
604
 
741
605
  try {
742
- // Resolve the parent container to get all siblings
743
606
  val parentPath = BrowserPathHelper.stripTrackId(contextualPath)
744
607
  val parentResolvedTrack = resolve(parentPath)
745
608
  val sections = parentResolvedTrack.normalizedSections
@@ -749,21 +612,14 @@ class BrowserManager {
749
612
  return null
750
613
  }
751
614
 
752
- // Queue scope is the tapped section, not the whole page (ADR 0006). The
753
- // stamped flat index pins which section (and which copy) was tapped when
754
- // the same identity appears more than once; it is only a tie-breaker — a
755
- // stale index falls back to the first identity match. An id that no
756
- // longer appears on the page at all aborts the expansion — the caller
757
- // falls back to the stored single track; silently queueing the changed
758
- // list would resume the wrong station.
615
+ // The stamped flat index pins which section and which copy was tapped; a stale index falls
616
+ // back to the first identity match. A vanished identity aborts: queueing the changed list
617
+ // would resume the wrong station.
759
618
  val tappedIndex = BrowserPathHelper.extractIndex(contextualPath)
760
619
  val scoped = SectionScope.scoped(sections, trackId, tappedIndex) ?: return null
761
620
  val sectionTracks = scoped.section.children.toList()
762
621
  val tappedOffset = scoped.tappedOffset
763
622
 
764
- // Filter to only playable tracks (tracks with src). A disabled track is
765
- // unavailable — queue expansion excludes it, so auto-advance never meets
766
- // one.
767
623
  val playableTracks =
768
624
  sectionTracks.filter { track -> track.src != null && track.disabled != true }
769
625
 
@@ -772,8 +628,6 @@ class BrowserManager {
772
628
  return null
773
629
  }
774
630
 
775
- // Find the index of the selected track in the playable tracks array:
776
- // the pinned copy when the stamp survived, else the first identity match
777
631
  val selectedIndex =
778
632
  if (
779
633
  tappedOffset != null &&
@@ -790,7 +644,6 @@ class BrowserManager {
790
644
  return null
791
645
  }
792
646
 
793
- // Check singleTrack setting - if true, return only the selected track
794
647
  if (config.singleTrack) {
795
648
  Timber.d("singleTrack=true - returning single track at index $selectedIndex")
796
649
  return Pair(arrayOf(playableTracks[selectedIndex]), 0)
@@ -807,40 +660,26 @@ class BrowserManager {
807
660
  }
808
661
 
809
662
  /**
810
- * Navigate to a path and return browser content.
811
- *
812
- * Uses a navigation ID to prevent race conditions when multiple navigations overlap. Only the
813
- * most recent navigation's result is applied.
814
- *
815
- * @param path The path to navigate to (e.g., "/artists/123")
816
- * @return ResolvedTrack containing the navigation result
663
+ * Sets the path and clears the content at once, then resolves. Only the latest navigation or
664
+ * refresh publishes its content; an overtaken one still returns its result.
817
665
  */
818
666
  suspend fun navigate(path: String): ResolvedTrack {
819
667
  Timber.d("Navigating to path: $path")
820
668
 
821
- // Increment navigation ID and capture for this navigation
822
669
  val navigationId = ++currentNavigationId
823
670
 
824
671
  this.path = path
825
- this.content = null // Clear content immediately to show loading state
672
+ this.content = null
826
673
  val content = resolve(path)
827
674
 
828
- // Only apply result if this is still the current navigation
829
675
  if (navigationId == currentNavigationId) {
830
676
  this.content = content
831
677
  }
832
678
  return content
833
679
  }
834
680
 
835
- /**
836
- * Refresh the current path's content without changing navigation state. Used for background
837
- * refreshes (e.g., when content changes via notifyContentChanged). Bypasses content cache to
838
- * fetch fresh data. Errors are silently ignored.
839
- *
840
- * Uses navigation ID tracking to prevent race conditions.
841
- */
681
+ /** Re-resolves the current path, bypassing the cache. Errors are logged, never thrown. */
842
682
  suspend fun refresh() {
843
- // Increment navigation ID and capture for this refresh
844
683
  val navigationId = ++currentNavigationId
845
684
 
846
685
  val currentPath = path
@@ -850,7 +689,6 @@ class BrowserManager {
850
689
  contentCache.remove(currentPath)
851
690
  val content = resolve(currentPath, useCache = false)
852
691
 
853
- // Only apply result if this is still the current navigation
854
692
  if (navigationId == currentNavigationId) {
855
693
  this.content = content
856
694
  }
@@ -859,27 +697,13 @@ class BrowserManager {
859
697
  }
860
698
  }
861
699
 
862
- /**
863
- * Get cached search results for a query. Used by Media3 onGetSearchResult() callback to retrieve
864
- * previously executed search.
865
- *
866
- * @param query The search query string
867
- * @return Array of Track results, or null if not found
868
- */
700
+ /** Returns the results of the most recent search when [query] matches it, else null. */
869
701
  fun getCachedSearchResults(query: String): Array<Track>? {
870
702
  val (cachedQuery, cachedResults) = lastSearch ?: return null
871
703
  if (query != cachedQuery) return null
872
704
  return cachedResults.map { hydrateFavorite(it) }.toTypedArray()
873
705
  }
874
706
 
875
- /**
876
- * Search for tracks and return playable results.
877
- *
878
- * @param query The search query string
879
- * @return Array of playable tracks, or null if no results or search not configured
880
- * @throws Exception when the search itself fails — a zero-result page means "found nothing",
881
- * never "couldn't ask"
882
- */
883
707
  suspend fun searchPlayable(query: String): Array<Track>? {
884
708
  return searchPlayable(
885
709
  SearchParams(
@@ -896,20 +720,14 @@ class BrowserManager {
896
720
  }
897
721
 
898
722
  /**
899
- * Search for tracks and return playable results. If the first result is browsable, resolves it
900
- * and returns its children. If the first result is playable, returns it. Used for voice search
901
- * "play X" commands.
723
+ * Returns the playable results, or null when there are none. A browsable first result plays its
724
+ * children instead.
902
725
  *
903
- * @param params The structured search parameters
904
- * @return Array of playable tracks, or null if no results or search not configured
905
- * @throws Exception when the search itself fails — a zero-result page means "found nothing",
906
- * never "couldn't ask"
726
+ * @throws Exception when the search callback fails; a failed API search returns null
907
727
  */
908
728
  suspend fun searchPlayable(params: SearchParams): Array<Track>? {
909
729
  val searchResults = search(params)
910
- // Voice search never matches a disabled track (Track.disabled) — filtered
911
- // before the first result is picked, so an unavailable one can't capture
912
- // the play.
730
+ // Disabled tracks go before the first result is picked, so one can't capture the play.
913
731
  val tracks = searchResults.flattenedChildren?.filter { it.disabled != true }?.toTypedArray()
914
732
 
915
733
  if (tracks.isNullOrEmpty()) {
@@ -918,8 +736,6 @@ class BrowserManager {
918
736
 
919
737
  val firstResult = tracks[0]
920
738
 
921
- // Check if result is browsable-only (container/route) vs playable
922
- // If it's browsable but also playable (has src or playable=true), treat it as playable
923
739
  val firstResultPath = firstResult.path
924
740
  val tracksToFilter =
925
741
  if (firstResult.src == null && firstResultPath != null) {
@@ -936,14 +752,6 @@ class BrowserManager {
936
752
  return tracksToFilter.filter { it.src != null }.takeIf { it.isNotEmpty() }?.toTypedArray()
937
753
  }
938
754
 
939
- /**
940
- * Search for tracks using the configured search source.
941
- *
942
- * @param query The search query string
943
- * @return ResolvedTrack containing search results as children
944
- * @throws Exception when the search itself fails — a zero-result page means "found nothing",
945
- * never "couldn't ask"
946
- */
947
755
  suspend fun search(query: String): ResolvedTrack {
948
756
  return search(
949
757
  SearchParams(
@@ -960,14 +768,9 @@ class BrowserManager {
960
768
  }
961
769
 
962
770
  /**
963
- * Search for tracks using the configured search source. Returns a ResolvedTrack at the path
964
- * /__search?q=query with children containing results. Always executes a fresh search and caches
965
- * results for onGetSearchResult() retrieval.
771
+ * Runs a fresh search and keeps its results for [getCachedSearchResults].
966
772
  *
967
- * @param params The structured search parameters
968
- * @return ResolvedTrack containing search results as children
969
- * @throws Exception when the search itself fails — a zero-result page means "found nothing",
970
- * never "couldn't ask"
773
+ * @throws Exception when the search callback fails; a failed API search yields no results
971
774
  */
972
775
  suspend fun search(params: SearchParams): ResolvedTrack {
973
776
  Timber.d("Executing fresh search for: ${params.query} (mode=${params.mode})")
@@ -975,9 +778,8 @@ class BrowserManager {
975
778
  val searchPath = BrowserPathHelper.createSearchPath(params.query)
976
779
 
977
780
  try {
978
- // Execute search. Drop results without a stable identifier (path or src): search results come
979
- // from server/JS data that doesn't pass through validateTrack like browse children do, and
980
- // downstream conversion (TrackFactory.toMedia3) and browsable-result resolution require one.
781
+ // Search results skip validateTrack, so one without a path or src is dropped here:
782
+ // TrackFactory.toMedia3 needs one.
981
783
  val searchResults =
982
784
  resolveSearch(params)
983
785
  .filter { track ->
@@ -989,8 +791,6 @@ class BrowserManager {
989
791
  }
990
792
  .toTypedArray()
991
793
 
992
- // Search results are a flat list; as a resolved page they are one
993
- // untitled section (ADR 0010).
994
794
  val searchResolvedTrack =
995
795
  ResolvedTrack(
996
796
  id = null,
@@ -1017,10 +817,8 @@ class BrowserManager {
1017
817
  icyCharset = null,
1018
818
  )
1019
819
 
1020
- // Cache search results for getCachedSearchResults()
1021
820
  lastSearch = params.query to searchResults
1022
821
 
1023
- // Cache individual tracks for Media3 lookups
1024
822
  cacheChildren(searchResolvedTrack)
1025
823
  Timber.d(
1026
824
  "Cached search results for query: ${params.query} with ${searchResults.size} results"
@@ -1028,72 +826,46 @@ class BrowserManager {
1028
826
 
1029
827
  return searchResolvedTrack
1030
828
  } catch (e: Exception) {
1031
- // Propagates, like the iOS `search`: a caller that cannot tell a failed search from one
1032
- // that found nothing renders a server error as "No results found".
829
+ // Propagates, like iOS `search`: a caller must tell a failed search from an empty one.
1033
830
  Timber.e(e, "Error during search for query: ${params.query}")
1034
831
  throw e
1035
832
  }
1036
833
  }
1037
834
 
1038
- /**
1039
- * Get the current navigation path.
1040
- *
1041
- * @return Current path string
1042
- */
1043
835
  fun getPath(): String {
1044
836
  return path
1045
837
  }
1046
838
 
1047
- /**
1048
- * Get the current loaded content.
1049
- *
1050
- * @return Current ResolvedTrack content or null if none loaded
1051
- */
1052
839
  fun getContent(): ResolvedTrack? {
1053
840
  return content
1054
841
  }
1055
842
 
1056
- /**
1057
- * Get the current cached tabs.
1058
- *
1059
- * @return Current tabs array or null if none loaded
1060
- */
1061
843
  fun getTabs(): Array<Track>? {
1062
844
  return tabs
1063
845
  }
1064
846
 
1065
- /** Set callback for path changes. */
1066
847
  fun setOnPathChanged(callback: (String) -> Unit) {
1067
848
  onPathChanged = callback
1068
849
  }
1069
850
 
1070
- /** Set callback for content changes. */
1071
851
  fun setOnContentChanged(callback: (ResolvedTrack?) -> Unit) {
1072
852
  onContentChanged = callback
1073
853
  }
1074
854
 
1075
- /** Set callback for tabs changes. */
1076
855
  fun setOnTabsChanged(callback: (Array<Track>) -> Unit) {
1077
856
  onTabsChanged = callback
1078
857
  }
1079
858
 
1080
859
  /**
1081
- * Set callback invoked whenever both [artworkResolutions] and the browse-artwork registry are
1082
- * cleared (config swap or content invalidation). The caller should clear any parallel
1083
- * [com.audiobrowser.browser.BrowseArtworkRegistry] instance it owns.
860
+ * Called whenever [artworkResolutions] and the browse-artwork registry are cleared. The caller
861
+ * clears any [BrowseArtworkRegistry] it owns.
1084
862
  */
1085
863
  fun setOnArtworkRegistriesCleared(callback: () -> Unit) {
1086
864
  onArtworkRegistriesCleared = callback
1087
865
  }
1088
866
 
1089
- /**
1090
- * Query navigation tabs from the configured tabs source. This is an async operation that resolves
1091
- * the tabs configuration.
1092
- *
1093
- * @return Array of Track objects representing tabs
1094
- */
867
+ /** Resolves the tabs once; later calls return the first result. */
1095
868
  suspend fun queryTabs(): Array<Track> {
1096
- // Return cached tabs if available
1097
869
  this.tabs?.let {
1098
870
  return it
1099
871
  }
@@ -1102,7 +874,6 @@ class BrowserManager {
1102
874
 
1103
875
  val tabs = resolveTabs()
1104
876
 
1105
- // Validate tabs have stable identifiers
1106
877
  tabs.forEachIndexed { index, tab ->
1107
878
  validateTrack(tab, "Tab")
1108
879
  Timber.d("[TABS] Tab[$index] '${tab.title}': path=${tab.path}")
@@ -1113,42 +884,27 @@ class BrowserManager {
1113
884
  }
1114
885
 
1115
886
  companion object {
1116
- /** Internal path used for the default/root browse source */
1117
887
  internal const val DEFAULT_ROUTE_PATH = "__default__"
1118
888
 
1119
- /** Internal path used for navigation tabs */
1120
889
  internal const val TABS_ROUTE_PATH = "__tabs__"
1121
890
 
1122
- /** Internal path used for search */
1123
891
  internal const val SEARCH_ROUTE_PATH = "__search__"
1124
892
 
1125
- /**
1126
- * Title of the appended "view more" row when the consumer sets no
1127
- * [BrowserConfig.viewMoreTitle]. English in code, like [defaultFormattedError]'s error copy — a
1128
- * default that renders beats a section whose `path` is unreachable, and it still resolves when
1129
- * the JS runtime is gone.
1130
- */
893
+ // English, like defaultFormattedError's copy: it still resolves when the JS runtime is gone.
1131
894
  internal const val DEFAULT_VIEW_MORE_TITLE = "View more"
1132
895
  }
1133
896
 
1134
- /**
1135
- * Find the best matching route entry for a path. Uses SimpleRouter for pattern matching, with
1136
- * __default__ as lowest priority fallback.
1137
- */
1138
897
  private fun findBestRouteMatch(
1139
898
  path: String,
1140
899
  routes: Array<NativeRouteEntry>,
1141
900
  ): Pair<NativeRouteEntry, Map<String, String>>? {
1142
- // Convert to map for router compatibility, excluding default fallback
1143
901
  val routeMap = routes.filter { it.path != DEFAULT_ROUTE_PATH }.associateBy { it.path }
1144
902
 
1145
- // Try to find a specific route match
1146
903
  router.findBestMatch(path, routeMap)?.let { (routePattern, match) ->
1147
904
  val routeEntry = routeMap[routePattern]!!
1148
905
  return Pair(routeEntry, match.params)
1149
906
  }
1150
907
 
1151
- // Fall back to default route if present
1152
908
  routes
1153
909
  .find { it.path == DEFAULT_ROUTE_PATH }
1154
910
  ?.let { defaultRoute ->
@@ -1158,23 +914,15 @@ class BrowserManager {
1158
914
  return null
1159
915
  }
1160
916
 
1161
- /**
1162
- * Resolve a NativeRouteEntry into a ResolvedTrack. The entry has flattened browse options:
1163
- * callback, config, or static.
1164
- */
1165
917
  private suspend fun resolveRouteEntry(
1166
918
  entry: NativeRouteEntry,
1167
919
  path: String,
1168
920
  routeParams: Map<String, String>,
1169
921
  ): ResolvedTrack {
1170
- // Priority: callback > config > static
1171
922
  entry.browseCallback?.let { callback ->
1172
923
  Timber.d("Resolving route via callback")
1173
924
  val param = BrowserSourceCallbackParam(path, routeParams)
1174
- // BrowserSourceCallback may return a BrowseResult synchronously or via a
1175
- // Promise. Nitro flattens (ResolvedTrack | BrowseError) | Promise<BrowseResult>
1176
- // into a 3-arm variant: sync track, sync error, or a Promise resolving to a
1177
- // BrowseResult (which is itself a ResolvedTrack | BrowseError variant).
925
+ // Nitro flattens `(ResolvedTrack | BrowseError) | Promise<BrowseResult>` into three arms.
1178
926
  return callback
1179
927
  .invoke(param)
1180
928
  .await()
@@ -1205,13 +953,9 @@ class BrowserManager {
1205
953
  throw ContentNotFoundException(path)
1206
954
  }
1207
955
 
1208
- /**
1209
- * Resolve search via the __search__ route entry. The entry has searchCallback or searchConfig.
1210
- */
1211
956
  private suspend fun resolveSearch(params: SearchParams): Array<Track> {
1212
957
  val routes = config.routes ?: return emptyArray()
1213
958
 
1214
- // Find the __search__ route entry
1215
959
  val searchEntry = routes.find { it.path == SEARCH_ROUTE_PATH }
1216
960
  if (searchEntry == null) {
1217
961
  Timber.w("No search route configured")
@@ -1234,14 +978,9 @@ class BrowserManager {
1234
978
  return emptyArray()
1235
979
  }
1236
980
 
1237
- /**
1238
- * Resolve tabs via the __tabs__ route entry. Returns children of the resolved track, or empty
1239
- * array if no tabs configured.
1240
- */
1241
981
  private suspend fun resolveTabs(): Array<Track> {
1242
982
  val routes = config.routes ?: return emptyArray()
1243
983
 
1244
- // Find the __tabs__ route entry
1245
984
  val tabsEntry = routes.find { it.path == TABS_ROUTE_PATH }
1246
985
  if (tabsEntry == null) {
1247
986
  Timber.d("No tabs route configured")
@@ -1251,39 +990,25 @@ class BrowserManager {
1251
990
  Timber.d("Resolving tabs via route entry")
1252
991
  val resolvedTrack = resolveRouteEntry(tabsEntry, TABS_ROUTE_PATH, emptyMap())
1253
992
 
1254
- // Tabs are a flat list, not a page — a sectioned tabs source flattens.
1255
993
  return resolvedTrack.flattenedChildren?.toTypedArray() ?: emptyArray()
1256
994
  }
1257
995
 
1258
- /**
1259
- * Resolves a single request/browse layer. When a resolver thunk is present it is invoked and its
1260
- * result awaited. The resolver is Promise-only (the TS layer normalizes a sync-or-async thunk via
1261
- * Promise.resolve), so its native shape is `Promise<Promise<TransformableRequestConfig>>` — a
1262
- * double await. When there is no resolver the static layer config is returned as-is.
1263
- */
1264
996
  private suspend fun resolveLayer(
1265
997
  staticConfig: TransformableRequestConfig?,
1266
998
  resolver: Func_std__shared_ptr_Promise_std__shared_ptr_Promise_TransformableRequestConfig____?,
1267
999
  ): TransformableRequestConfig? {
1268
1000
  if (resolver == null) return staticConfig
1269
- // Promise-only resolver (the TS layer wraps a sync-or-async thunk in
1270
- // Promise.resolve) → double await: the bridge promise, then the JS promise.
1001
+ // The TS layer wraps the thunk in Promise.resolve: await the bridge promise, then the JS one.
1271
1002
  return resolver.invoke().await().await()
1272
1003
  }
1273
1004
 
1274
- /**
1275
- * Ensures the request/browse resolver layers are resolved for the current [layerGeneration],
1276
- * caching the result. Re-resolves when the generation changes (config set or content
1277
- * invalidation). Uses a simple generation guard with no in-flight cache: a benign idempotent
1278
- * double-resolve under concurrent first-requests is acceptable, and on a thrown resolver nothing
1279
- * is cached so the next request retries naturally.
1280
- */
1005
+ // No in-flight dedupe: concurrent first requests may both resolve, which is harmless, and a
1006
+ // resolver that throws caches nothing, so the next request retries.
1281
1007
  internal suspend fun ensureLayersResolved() {
1282
1008
  if (resolvedLayerGeneration == layerGeneration) return
1283
1009
  val generation = layerGeneration
1284
1010
  val req = resolveLayer(config.request, config.requestResolver)
1285
1011
  val brw = resolveLayer(config.browse, config.browseResolver)
1286
- // A newer generation started while we were awaiting — drop this stale result.
1287
1012
  if (generation != layerGeneration) return
1288
1013
  resolvedRequestLayer = req
1289
1014
  resolvedBrowseLayer = brw
@@ -1291,13 +1016,8 @@ class BrowserManager {
1291
1016
  }
1292
1017
 
1293
1018
  /**
1294
- * Ensures the request layer is resolved for the current generation and returns it (the resolver
1295
- * result when a [BrowserConfig.requestResolver] is configured, else the static
1296
- * [BrowserConfig.request]).
1297
- *
1298
- * Consumers outside the browse path (media URL building, artwork) must obtain the request layer
1299
- * through this accessor rather than reading the static `config.request`, so a resolver-only
1300
- * consumer still gets a baseUrl/headers/transform for media, artwork, and now-playing artwork.
1019
+ * The request layer for the current generation. Media URLs and artwork read it through here,
1020
+ * never `config.request`, which a resolver-only config leaves unset.
1301
1021
  */
1302
1022
  internal suspend fun resolvedRequestConfig(): TransformableRequestConfig? {
1303
1023
  ensureLayersResolved()
@@ -1305,14 +1025,9 @@ class BrowserManager {
1305
1025
  }
1306
1026
 
1307
1027
  /**
1308
- * The title for the "view more" row appended to a pathed section on a surface whose header cannot
1309
- * be tapped (Android Auto).
1310
- *
1311
- * Resolved from [BrowserConfig.viewMoreTitle] once per content generation — the same generation
1312
- * the resolver layers use, so `invalidateAllContent()` re-reads it and an app that switched
1313
- * language mid-drive gets the new copy without reconfiguring. Falls back to
1314
- * [DEFAULT_VIEW_MORE_TITLE] when unset, blank, or throwing: a row with the default copy still
1315
- * reaches the section's page, an untitled one does not.
1028
+ * The title of the "view more" row appended to a pathed section where the header can't be tapped
1029
+ * (Android Auto). Re-read once per generation, so invalidateAllContent picks up a new language.
1030
+ * Falls back to [DEFAULT_VIEW_MORE_TITLE] when unset, blank or throwing.
1316
1031
  */
1317
1032
  internal suspend fun viewMoreTitle(): String {
1318
1033
  val generation = layerGeneration
@@ -1324,7 +1039,6 @@ class BrowserManager {
1324
1039
  Timber.e(e, "viewMoreTitle callback failed; falling back to the default")
1325
1040
  null
1326
1041
  } ?: DEFAULT_VIEW_MORE_TITLE
1327
- // A newer generation started while awaiting — use this result, but don't cache it as current.
1328
1042
  if (generation != layerGeneration) return title
1329
1043
  resolvedViewMoreTitle = title
1330
1044
  resolvedViewMoreTitleGeneration = generation
@@ -1332,20 +1046,12 @@ class BrowserManager {
1332
1046
  }
1333
1047
 
1334
1048
  /**
1335
- * Builds the HTTP request for an API-backed path by layering request (shared) → kind
1336
- * (browse/search) → route configs. Each layer's transform receives the previous layer's output; a
1337
- * layer with no transform merges its static fields.
1049
+ * Layers request → kind (browse/search) → route; each transform receives the previous output.
1050
+ * [path] seeds the base because no layer's static path ever applies; [initialQuery] seeds it
1051
+ * because a layer with a transform receives only the base, so its static query never applies.
1052
+ * Mirrors iOS `buildApiRequest`.
1338
1053
  *
1339
- * `initialQuery` seeds query params onto the BASE the kind layer receives (e.g. search q/mode/…):
1340
- * a layer with a transform "wins completely" and is handed only the base, so params placed on a
1341
- * layer's own static query would be dropped before the transform runs. The same goes for `path`:
1342
- * it is carried from the base through every layer (only a transform may change it), so a kind
1343
- * whose config supplies the path (search) must seed it via the `path` parameter. Mirrors iOS
1344
- * `buildApiRequest`.
1345
- *
1346
- * @throws ContentNotFoundException when no layer supplies a baseUrl — there is nothing to fetch,
1347
- * so the path is genuinely "not found" rather than a network error (mirrors iOS's `guard let
1348
- * baseUrl`).
1054
+ * @throws ContentNotFoundException when no layer supplies a baseUrl
1349
1055
  */
1350
1056
  internal suspend fun buildApiRequest(
1351
1057
  kindConfig: TransformableRequestConfig?,
@@ -1354,7 +1060,6 @@ class BrowserManager {
1354
1060
  params: Map<String, String>,
1355
1061
  initialQuery: Map<String, String>? = null,
1356
1062
  ): HttpClient.HttpRequest {
1357
- // Resolve the request/browse resolver thunks once per content generation (cached).
1358
1063
  ensureLayersResolved()
1359
1064
 
1360
1065
  var merged =
@@ -1381,27 +1086,20 @@ class BrowserManager {
1381
1086
  return RequestConfigBuilder.buildHttpRequest(merged)
1382
1087
  }
1383
1088
 
1384
- /**
1385
- * Execute an API request for browser content. Request building (layering + transforms + baseUrl
1386
- * guard) lives in [buildApiRequest]; this adds the browse-specific response shape (a
1387
- * ResolvedTrack page object).
1388
- */
1389
1089
  private suspend fun executeApiRequest(
1390
1090
  apiConfig: TransformableRequestConfig?,
1391
1091
  path: String,
1392
1092
  routeParams: Map<String, String>,
1393
1093
  ): ResolvedTrack {
1394
1094
  return withContext(Dispatchers.IO) {
1395
- // request (shared) → browse (kind) → route. apiConfig is null for the
1396
- // implicit default (an unmatched browse path → fetch via request + browse + path).
1397
1095
  ensureLayersResolved()
1096
+ // apiConfig is null for the implicit default.
1398
1097
  val httpRequest = buildApiRequest(resolvedBrowseLayer, apiConfig, path, routeParams)
1399
1098
  val response = httpClient.request(httpRequest)
1400
1099
 
1401
1100
  response.fold(
1402
1101
  onSuccess = { httpResponse ->
1403
1102
  if (httpResponse.isSuccessful) {
1404
- // 3. Parse response as ResolvedTrack
1405
1103
  val jsonResolvedTrack = json.decodeFromString<JsonResolvedTrack>(httpResponse.body)
1406
1104
  jsonResolvedTrack.toNitro()
1407
1105
  } else {
@@ -1419,16 +1117,6 @@ class BrowserManager {
1419
1117
  }
1420
1118
  }
1421
1119
 
1422
- /**
1423
- * Execute an API request for search results. Automatically adds search parameters to request
1424
- * query:
1425
- * - q: The search query string (always included)
1426
- * - mode: The search mode (any, genre, artist, album, song, playlist) - omitted for unstructured
1427
- * search
1428
- * - genre, artist, album, title, playlist: Included only when non-null
1429
- *
1430
- * Transform callbacks can access and modify all parameters as needed.
1431
- */
1432
1120
  private suspend fun executeSearchApiRequest(
1433
1121
  apiConfig: TransformableRequestConfig,
1434
1122
  params: SearchParams,
@@ -1446,15 +1134,12 @@ class BrowserManager {
1446
1134
  params.playlist?.let { put("playlist", it) }
1447
1135
  }
1448
1136
 
1449
- // request (shared) → search (kind); no browse layer and no route — search
1450
- // is its own kind. The search params seed the base (see buildApiRequest
1451
- // docs), and so does the search config's path: a layer's static path
1452
- // never applies (the path is carried from the base), so the caller
1453
- // seeds it — mirrors the web stub's fetchSearchResults.
1137
+ // No browse layer and no route: search is its own kind.
1454
1138
  val httpRequest =
1455
1139
  buildApiRequest(
1456
1140
  kindConfig = apiConfig,
1457
1141
  routeConfig = null,
1142
+ // A layer's static path never applies, so the search config's path seeds the base.
1458
1143
  path = apiConfig.path,
1459
1144
  params = emptyMap(),
1460
1145
  initialQuery = searchQueryParams,
@@ -1464,8 +1149,7 @@ class BrowserManager {
1464
1149
  response.fold(
1465
1150
  onSuccess = { httpResponse ->
1466
1151
  if (httpResponse.isSuccessful) {
1467
- // The search endpoint returns a bare Track array (unlike browse,
1468
- // which returns a page object). iOS parses it the same way.
1152
+ // A bare Track array, unlike browse's page object.
1469
1153
  val jsonTracks = json.decodeFromString<List<JsonTrack>>(httpResponse.body)
1470
1154
  jsonTracks.map { it.toNitro() }.toTypedArray()
1471
1155
  } else {
@@ -1488,51 +1172,36 @@ class BrowserManager {
1488
1172
  }
1489
1173
  }
1490
1174
 
1491
- /** Exception thrown when no content is configured for a requested path. */
1492
1175
  class ContentNotFoundException(val path: String) : Exception("Content not found")
1493
1176
 
1494
- /** Exception thrown when an HTTP request fails with a non-2xx status code. */
1495
1177
  class HttpStatusException(val statusCode: Int, message: String) : Exception(message)
1496
1178
 
1497
- /** Exception thrown when a network request fails (connection error, timeout, etc). */
1498
1179
  class NetworkException(message: String, cause: Throwable? = null) : Exception(message, cause)
1499
1180
 
1500
- /** Exception thrown when a browse callback returns an error message. */
1501
1181
  class CallbackException(message: String) : Exception(message)
1502
1182
 
1503
- /**
1504
- * Configuration object that holds all browser settings. Uses flattened structure matching
1505
- * NativeBrowserConfiguration from JS.
1506
- */
1183
+ /** Mirrors NativeBrowserConfiguration from JS. */
1507
1184
  data class BrowserConfig(
1508
1185
  val request: TransformableRequestConfig? = null,
1509
- // Resolver thunk for the shared request layer. When set, it is resolved once per content
1510
- // generation (re-resolved after invalidateAllContent), cached, and merged per request — instead
1511
- // of carrying a static `request`. `request` and `requestResolver` are mutually exclusive in
1512
- // practice (the consumer sets one or the other), but both are merged if present.
1186
+ // Resolved once per content generation and merged per request. When set, it replaces `request`,
1187
+ // which is then ignored (the JS bridge sets only one of the two).
1513
1188
  val requestResolver:
1514
1189
  Func_std__shared_ptr_Promise_std__shared_ptr_Promise_TransformableRequestConfig____? =
1515
1190
  null,
1516
1191
  val browse: TransformableRequestConfig? = null,
1517
- // Resolver thunk for the browse layer. See `requestResolver`.
1518
1192
  val browseResolver:
1519
1193
  Func_std__shared_ptr_Promise_std__shared_ptr_Promise_TransformableRequestConfig____? =
1520
1194
  null,
1521
1195
  val media: MediaRequestConfig? = null,
1522
1196
  val artwork: ArtworkRequestConfig? = null,
1523
- // Now-playing-only artwork configuration (lock screen / notification / Android Auto now-playing).
1524
- // A distinct kind from `artwork`; the now-playing path falls back to `artwork` when this is null.
1197
+ // Falls back to `artwork` when null.
1525
1198
  val nowPlayingArtwork: ArtworkRequestConfig? = null,
1526
- // Routes as array with flattened entries (includes __tabs__, __search__, and __default__ special
1527
- // routes)
1199
+ // Includes the special __tabs__, __search__ and __default__ routes.
1528
1200
  val routes: Array<NativeRouteEntry>? = null,
1529
- // Behavior
1530
1201
  val singleTrack: Boolean = false,
1531
1202
  val androidControllerOfflineError: Boolean = true,
1532
- // Titles the "view more" row appended to a pathed section. See BrowserManager.viewMoreTitle.
1533
1203
  val viewMoreTitle: (() -> Promise<String>)? = null,
1534
1204
  ) {
1535
- /** Returns true if search functionality is configured (either callback or config). */
1536
1205
  val hasSearch: Boolean
1537
1206
  get() {
1538
1207
  val searchEntry = routes?.find { it.path == BrowserManager.SEARCH_ROUTE_PATH }