react-native-audio-browser 1.0.0-next.1 → 1.0.0-next.3

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 (147) hide show
  1. package/android/src/main/java/com/audiobrowser/AudioBrowser.kt +19 -2
  2. package/android/src/main/java/com/audiobrowser/browser/BrowserManager.kt +29 -8
  3. package/android/src/main/java/com/audiobrowser/http/RequestConfigBuilder.kt +8 -10
  4. package/android/src/main/java/com/audiobrowser/model/PlayerSetupOptions.kt +2 -2
  5. package/android/src/main/java/com/audiobrowser/player/AutomaticBufferManager.kt +17 -16
  6. package/android/src/main/java/com/audiobrowser/player/InterceptingPlayer.kt +11 -0
  7. package/android/src/main/java/com/audiobrowser/player/Player.kt +8 -4
  8. package/android/src/test/java/com/audiobrowser/ContentRefreshNavigationErrorTest.kt +236 -0
  9. package/android/src/test/java/com/audiobrowser/browser/BrowserManagerUnparsableResponseTest.kt +82 -0
  10. package/android/src/test/java/com/audiobrowser/browser/BrowserUrlResolutionTest.kt +15 -0
  11. package/android/src/test/java/com/audiobrowser/http/RequestConfigBuilderTest.kt +26 -0
  12. package/android/src/test/java/com/audiobrowser/model/PlayerSetupOptionsTest.kt +19 -2
  13. package/android/src/test/java/com/audiobrowser/player/AutomaticBufferManagerTest.kt +17 -0
  14. package/android/src/test/java/com/audiobrowser/player/SessionQueueShuffleOrderTest.kt +38 -0
  15. package/ios/Browser/BrowserError.swift +8 -0
  16. package/ios/Browser/BrowserManager.swift +29 -28
  17. package/ios/Browser/BrowserPathHelper.swift +26 -24
  18. package/ios/Browser/FavoriteSet.swift +16 -8
  19. package/ios/Browser/Favorites.swift +66 -0
  20. package/ios/Browser/JsonModels.swift +27 -7
  21. package/ios/Browser/NavigationErrorState.swift +18 -1
  22. package/ios/Browser/PageResolver.swift +2 -2
  23. package/ios/Browser/RequestLayer.swift +11 -4
  24. package/ios/Browser/RequestPipeline.swift +8 -4
  25. package/ios/Browser/TabBarEntries.swift +7 -0
  26. package/ios/CarPlay/CarPlayImageLoader.swift +3 -7
  27. package/ios/CarPlay/CarPlaySession+Navigator.swift +3 -1
  28. package/ios/CarPlay/IntentHandlers.swift +1 -7
  29. package/ios/CarPlay/MediaIntentCriteria.swift +4 -4
  30. package/ios/Extension/CGSize+AspectFit.swift +11 -0
  31. package/ios/Extension/Dictionary+Headers.swift +8 -0
  32. package/ios/Extension/NavigationError+Conversion.swift +4 -3
  33. package/ios/Extension/ResolvedTrack+Copying.swift +15 -0
  34. package/ios/Http/HttpClient.swift +37 -11
  35. package/ios/HybridAudioBrowser+Browser.swift +9 -16
  36. package/ios/HybridAudioBrowser+Options.swift +1 -0
  37. package/ios/HybridAudioBrowser+Player.swift +24 -23
  38. package/ios/HybridAudioBrowser+PlayerCallbacks.swift +1 -2
  39. package/ios/Model/NitroTypeStubs.swift +39 -0
  40. package/ios/Model/TrackPlayerError.swift +21 -2
  41. package/ios/Player/AudioSessionController.swift +2 -2
  42. package/ios/Player/MediaLoader.swift +1 -1
  43. package/ios/Player/PlaybackStateMachine.swift +13 -12
  44. package/ios/Player/Player.swift +60 -21
  45. package/ios/Player/PlayerEngine.swift +5 -0
  46. package/ios/Player/QueueManager.swift +21 -4
  47. package/ios/Tests/BrowserErrorTests.swift +21 -0
  48. package/ios/Tests/BrowserPathHelperTests.swift +18 -0
  49. package/ios/Tests/CGSizeAspectFitTests.swift +36 -0
  50. package/ios/Tests/ClampedVolumeTests.swift +26 -0
  51. package/ios/Tests/FavoriteSetTests.swift +68 -3
  52. package/ios/Tests/FavoritesTests.swift +102 -0
  53. package/ios/Tests/HttpClientUserAgentTests.swift +45 -0
  54. package/ios/Tests/JsonModelsTests.swift +74 -6
  55. package/ios/Tests/MediaIntentCriteriaTests.swift +11 -1
  56. package/ios/Tests/MediaLoaderAssetOptionsTests.swift +7 -0
  57. package/ios/Tests/NavigationErrorStateTests.swift +73 -0
  58. package/ios/Tests/PlaybackStateMachineTests.swift +21 -12
  59. package/ios/Tests/PlayerPolicyTests.swift +103 -0
  60. package/ios/Tests/PlayerProgressTests.swift +109 -0
  61. package/ios/Tests/PlayerTests.swift +106 -0
  62. package/ios/Tests/QueueIndexTests.swift +43 -0
  63. package/ios/Tests/QueueManagerTests.swift +79 -15
  64. package/ios/Tests/RequestLayerTests.swift +22 -3
  65. package/ios/Tests/TabBarEntriesTests.swift +19 -0
  66. package/ios/Tests/TrackSelectorTests.swift +154 -0
  67. package/ios/Tests/UnparsableResponseTests.swift +91 -0
  68. package/ios/TrackSelector.swift +28 -8
  69. package/ios/Util/ArtworkImageFetcher.swift +9 -8
  70. package/ios/Util/SVGProcessor.swift +6 -17
  71. package/lib/commonjs/features/browser-config.js +6 -3
  72. package/lib/commonjs/features/browser-config.js.map +1 -1
  73. package/lib/commonjs/features/errors.js +12 -7
  74. package/lib/commonjs/features/errors.js.map +1 -1
  75. package/lib/commonjs/features/nowPlaying.js +9 -3
  76. package/lib/commonjs/features/nowPlaying.js.map +1 -1
  77. package/lib/commonjs/features/playback/trackPlaybackTime.js +2 -1
  78. package/lib/commonjs/features/playback/trackPlaybackTime.js.map +1 -1
  79. package/lib/commonjs/features/player/setup.js +2 -2
  80. package/lib/commonjs/features/queue/activeTrack.js +4 -2
  81. package/lib/commonjs/features/queue/activeTrack.js.map +1 -1
  82. package/lib/commonjs/features/sleepTimer.js +6 -5
  83. package/lib/commonjs/features/sleepTimer.js.map +1 -1
  84. package/lib/commonjs/utils/LazyNativeEmitter.js +2 -1
  85. package/lib/commonjs/utils/LazyNativeEmitter.js.map +1 -1
  86. package/lib/commonjs/utils/NativeUpdatedValue.js +2 -1
  87. package/lib/commonjs/utils/NativeUpdatedValue.js.map +1 -1
  88. package/lib/commonjs/utils/callListener.js +23 -0
  89. package/lib/commonjs/utils/callListener.js.map +1 -0
  90. package/lib/module/features/browser-config.js +6 -3
  91. package/lib/module/features/browser-config.js.map +1 -1
  92. package/lib/module/features/errors.js +12 -7
  93. package/lib/module/features/errors.js.map +1 -1
  94. package/lib/module/features/nowPlaying.js +9 -3
  95. package/lib/module/features/nowPlaying.js.map +1 -1
  96. package/lib/module/features/playback/trackPlaybackTime.js +2 -1
  97. package/lib/module/features/playback/trackPlaybackTime.js.map +1 -1
  98. package/lib/module/features/player/setup.js +2 -2
  99. package/lib/module/features/queue/activeTrack.js +4 -2
  100. package/lib/module/features/queue/activeTrack.js.map +1 -1
  101. package/lib/module/features/sleepTimer.js +6 -5
  102. package/lib/module/features/sleepTimer.js.map +1 -1
  103. package/lib/module/utils/LazyNativeEmitter.js +2 -1
  104. package/lib/module/utils/LazyNativeEmitter.js.map +1 -1
  105. package/lib/module/utils/NativeUpdatedValue.js +2 -1
  106. package/lib/module/utils/NativeUpdatedValue.js.map +1 -1
  107. package/lib/module/utils/callListener.js +19 -0
  108. package/lib/module/utils/callListener.js.map +1 -0
  109. package/lib/typescript/src/features/browser-config.d.ts.map +1 -1
  110. package/lib/typescript/src/features/errors.d.ts +8 -6
  111. package/lib/typescript/src/features/errors.d.ts.map +1 -1
  112. package/lib/typescript/src/features/nowPlaying.d.ts +2 -1
  113. package/lib/typescript/src/features/nowPlaying.d.ts.map +1 -1
  114. package/lib/typescript/src/features/playback/trackPlaybackTime.d.ts.map +1 -1
  115. package/lib/typescript/src/features/player/setup.d.ts +2 -2
  116. package/lib/typescript/src/features/queue/activeTrack.d.ts +2 -1
  117. package/lib/typescript/src/features/queue/activeTrack.d.ts.map +1 -1
  118. package/lib/typescript/src/features/sleepTimer.d.ts +2 -1
  119. package/lib/typescript/src/features/sleepTimer.d.ts.map +1 -1
  120. package/lib/typescript/src/types/browser.d.ts +3 -2
  121. package/lib/typescript/src/types/browser.d.ts.map +1 -1
  122. package/lib/typescript/src/utils/LazyNativeEmitter.d.ts.map +1 -1
  123. package/lib/typescript/src/utils/NativeUpdatedValue.d.ts.map +1 -1
  124. package/lib/typescript/src/utils/callListener.d.ts +7 -0
  125. package/lib/typescript/src/utils/callListener.d.ts.map +1 -0
  126. package/package.json +1 -1
  127. package/src/features/browser-config.test.ts +15 -0
  128. package/src/features/browser-config.ts +6 -3
  129. package/src/features/errors.test.ts +83 -0
  130. package/src/features/errors.ts +12 -7
  131. package/src/features/hook-wiring.test.ts +11 -10
  132. package/src/features/nowPlaying.ts +9 -3
  133. package/src/features/playback/trackPlaybackTime.test.ts +24 -1
  134. package/src/features/playback/trackPlaybackTime.ts +2 -1
  135. package/src/features/player/setup.ts +2 -2
  136. package/src/features/queue/activeTrack.test.ts +32 -0
  137. package/src/features/queue/activeTrack.ts +8 -2
  138. package/src/features/sleepTimer.test.ts +24 -0
  139. package/src/features/sleepTimer.ts +6 -5
  140. package/src/types/browser.ts +3 -2
  141. package/src/utils/LazyNativeEmitter.test.ts +32 -0
  142. package/src/utils/LazyNativeEmitter.ts +3 -1
  143. package/src/utils/NativeUpdatedValue.test.ts +32 -0
  144. package/src/utils/NativeUpdatedValue.ts +3 -1
  145. package/src/utils/callListener.ts +17 -0
  146. package/website/guide/configuration.md +3 -3
  147. package/website/guide/errors.md +3 -1
@@ -29,9 +29,9 @@ final class Player {
29
29
  guard let self, queue.currentIndex >= 0 else { return }
30
30
  let progressEvent = PlaybackProgressUpdatedEvent(
31
31
  track: Double(queue.currentIndex),
32
- position: engine.currentTime,
33
- duration: engine.duration,
34
- buffered: engine.bufferedPosition,
32
+ position: currentTime,
33
+ duration: duration,
34
+ buffered: bufferedPosition,
35
35
  )
36
36
  callbacks?.playerDidUpdateProgress(progressEvent)
37
37
  }
@@ -101,8 +101,7 @@ final class Player {
101
101
  ) { [unowned self] in
102
102
  currentTrack.map {
103
103
  PlaybackPersistence.snapshot(
104
- of: $0, state: state, position: deferredSeek.target ?? (enginePositionIsCurrent ? engine.currentTime : 0),
105
- repeatMode: repeatMode,
104
+ of: $0, state: state, position: currentTime, repeatMode: repeatMode,
106
105
  shuffleEnabled: shuffleEnabled, rate: rate,
107
106
  )
108
107
  }
@@ -120,6 +119,27 @@ final class Player {
120
119
  !awaitingItem && load?.itemPrepared == true
121
120
  }
122
121
 
122
+ /// Whether the engine's item is one of this Load's, which a reload of the track keeps until the
123
+ /// next is prepared.
124
+ private var engineItemIsCurrent: Bool {
125
+ load?.itemPrepared == true
126
+ }
127
+
128
+ /// The current track's position: a pending seek's target, and 0 before the engine reports it.
129
+ var currentTime: Double {
130
+ deferredSeek.target ?? (enginePositionIsCurrent ? engine.currentTime : 0)
131
+ }
132
+
133
+ /// The current track's duration, 0 until one of its items is in the engine.
134
+ var duration: Double {
135
+ engineItemIsCurrent ? engine.duration : 0
136
+ }
137
+
138
+ /// How far the current track is buffered, 0 until one of its items is in the engine.
139
+ var bufferedPosition: Double {
140
+ engineItemIsCurrent ? engine.bufferedPosition : 0
141
+ }
142
+
123
143
  private var resumePosition: TimeInterval? {
124
144
  deferredSeek.target ?? (enginePositionIsCurrent ? engine.resumePosition : nil)
125
145
  }
@@ -140,7 +160,6 @@ final class Player {
140
160
  var queueVersion: Int { queue.version }
141
161
  var queueSourcePath: String? { queue.queueSourcePath }
142
162
  var currentTrack: Track? { queue.currentTrack }
143
- var currentTime: Double { engine.currentTime }
144
163
  var nitroPlaybackError: PlaybackError? { errorStatus.nitroError }
145
164
 
146
165
  var repeatMode: RepeatMode {
@@ -188,7 +207,7 @@ final class Player {
188
207
  // A terminal state or a cancelled retry has no item to play, or one parked at its end: reload,
189
208
  // re-resolving a URL that may have expired since. Only .error and a cancelled retry resume where they failed.
190
209
  let resumes = state == .error || load?.reloadOnPlay == true
191
- if newValue, resumes || state == .stopped || state == .ended {
210
+ if newValue, resumes || state.isTerminal {
192
211
  reloadResolving(startFromCurrentTime: resumes)
193
212
  }
194
213
  // While loading, the engine may still hold the previous track's item: a play waits for the new one.
@@ -300,9 +319,7 @@ final class Player {
300
319
  state = newState
301
320
  applySideEffects(old: oldState, new: newState)
302
321
  publish()
303
- // While nothing plays, no periodic save runs: every transition rewrites the snapshot, so it
304
- // never keeps a position from before a track change or a seek.
305
- if !(playbackActive && playWhenReady) { persistence.save() }
322
+ saveSnapshotWhileNothingPlays()
306
323
  // Repeat modes never end the queue (matches web's endsQueue()): a repeat-track pause at the
307
324
  // track boundary (e.g. the end-of-track sleep timer) must not read as "playlist over".
308
325
  if newState == .ended, queue.isLastInPlaybackOrder, repeatMode == .off {
@@ -388,6 +405,8 @@ final class Player {
388
405
  // must not play it under the error.
389
406
  engine.pause()
390
407
  retry.cancel()
408
+ // The intent holds through .error: no pause follows to request the release.
409
+ if playWhenReady { evaluateSessionRelease() }
391
410
  default: break
392
411
  }
393
412
 
@@ -441,8 +460,9 @@ final class Player {
441
460
  /// iOS has already paused the AVPlayer, but that pause is swallowed while the intent holds, so
442
461
  /// the paused state is forced here.
443
462
  func handleInterruptionBegan() {
444
- // A nested interruption keeps the intent the first one captured.
445
- shouldResumeAfterInterruption = shouldResumeAfterInterruption || playWhenReady
463
+ // A nested interruption keeps what the first one captured. `.error` holds the intent with
464
+ // nothing playing: there is nothing to resume.
465
+ shouldResumeAfterInterruption = shouldResumeAfterInterruption || playingState.playing
446
466
  pause()
447
467
  if playbackActive, state != .loading, state != .paused {
448
468
  transition(.avPlayerPaused(hasAsset: engine.hasLoadedAsset))
@@ -462,14 +482,18 @@ final class Player {
462
482
  }
463
483
  }
464
484
 
465
- /// Requests a session release once playback is deliberately stopped: no intent, no
466
- /// interruption to resume from, and no retry pending, whose reconnect needs the session. The
467
- /// engine debounces it.
485
+ /// Whether nothing needs the audio session: playback is deliberately stopped or has failed for
486
+ /// good (`.error` keeps the intent), with no interruption to resume from and no retry pending,
487
+ /// whose reconnect needs the session.
488
+ var canReleaseAudioSession: Bool {
489
+ (!playWhenReady || state == .error)
490
+ && !shouldResumeAfterInterruption
491
+ && retry.pendingTask == nil
492
+ }
493
+
494
+ /// Requests a session release when nothing needs the session. The engine debounces it.
468
495
  private func evaluateSessionRelease() {
469
- guard !playWhenReady,
470
- !shouldResumeAfterInterruption,
471
- retry.pendingTask == nil
472
- else { return }
496
+ guard canReleaseAudioSession else { return }
473
497
  engine.scheduleAudioSessionRelease()
474
498
  }
475
499
 
@@ -521,6 +545,12 @@ final class Player {
521
545
  try afterQueueMutation(queue.replace(index, track))
522
546
  }
523
547
 
548
+ /// Replaces, in place, each track `transform` returns a track for; the current track keeps
549
+ /// playing.
550
+ func replaceEach(_ transform: (Track) -> Track?) {
551
+ afterQueueMutation(queue.replaceEach(transform))
552
+ }
553
+
524
554
  func setQueue(
525
555
  _ newTracks: [Track],
526
556
  initialIndex: Int = 0,
@@ -642,6 +672,8 @@ final class Player {
642
672
  defer { pushSkipAvailability() }
643
673
  sleepTimerManager.onTrackChanged()
644
674
 
675
+ // Read before the new Load replaces the one it belongs to.
676
+ let lastPosition = currentTime
645
677
  engine.cancelLoading()
646
678
  beginLoad()
647
679
  if let start { deferredSeek.capture(start) }
@@ -649,7 +681,6 @@ final class Player {
649
681
  // Published by the .trackLoading or .trackUnloaded transition below, even when it is a no-op.
650
682
  errorStatus = .none
651
683
 
652
- let lastPosition = engine.currentTime
653
684
  let shouldContinuePlayback = playWhenReady
654
685
  engine.nowPlayingTrackChanged()
655
686
  if let currentTrack {
@@ -688,6 +719,12 @@ final class Player {
688
719
  lastIndex = queue.currentIndex
689
720
  }
690
721
 
722
+ /// While nothing plays, no periodic save runs: every transition and every seek rewrites the
723
+ /// snapshot, so it never keeps a position from before a track change or a seek.
724
+ private func saveSnapshotWhileNothingPlays() {
725
+ if !(playbackActive && playWhenReady) { persistence.save() }
726
+ }
727
+
691
728
  // MARK: - Seeking
692
729
 
693
730
  /// Seeks the current item. While it awaits the next item, or in .error for the restart, the
@@ -698,6 +735,7 @@ final class Player {
698
735
  completion(false)
699
736
  } else if awaitingItem || state == .error {
700
737
  deferredSeek.capture(seconds)
738
+ saveSnapshotWhileNothingPlays()
701
739
  completion(false)
702
740
  } else if engine.hasItem {
703
741
  seekItem(to: seconds, completion: completion)
@@ -739,6 +777,7 @@ final class Player {
739
777
  return
740
778
  }
741
779
  seekDidLand(finished: finished)
780
+ if finished { saveSnapshotWhileNothingPlays() }
742
781
  completion(finished)
743
782
  }
744
783
  }
@@ -939,7 +978,7 @@ final class Player {
939
978
  recoverIfAirPlayStalled(transitioningTo: status, waitingForNoItem: waitingForNoItem)
940
979
  timeControlStatusDidChange(status)
941
980
  case .audioDidStart:
942
- if !awaitingItem { transition(.audioFrameDecoded) }
981
+ if !awaitingItem, playWhenReady { transition(.audioFrameDecoded) }
943
982
  case .playedToEnd:
944
983
  itemDidPlayToEnd()
945
984
  case .stalled:
@@ -28,6 +28,11 @@ enum EngineEvent {
28
28
  case timedMetadata(TimedMetadata)
29
29
  }
30
30
 
31
+ /// `level` clamped to the engine's 0–1 volume; nil for NaN, which is nearer neither end.
32
+ func clampedVolume(_ level: Double) -> Float? {
33
+ level.isNaN ? nil : Float(min(max(level, 0), 1))
34
+ }
35
+
31
36
  /// The media stack under the Player: the AVPlayer and its items, loading, now playing, remote
32
37
  /// commands and the audio session. It carries out what the Player decides and reports what it
33
38
  /// observes through `onEvent`; it holds no playback policy (ADR 0012). Tests use a mock.
@@ -138,12 +138,13 @@ class QueueManager {
138
138
 
139
139
  // MARK: - Navigation (returns QueueNavigationResult)
140
140
 
141
- // Shared by `next()` and `canNext` so the button and the navigation agree. Shuffle wraps
142
- // whatever the repeat mode, as Media3 does; sequential order wraps only on repeat-queue.
141
+ // Shared by `next()` and `canNext` so the button and the navigation agree. Wraps only on
142
+ // repeat-queue, shuffled or not, as Media3 does.
143
143
  private var nextIndex: Int? {
144
144
  guard currentTrack != nil, tracks.count > 1 else { return nil }
145
145
  let candidate: Int? = if shuffleEnabled {
146
- shuffleOrder.getNextIndex(after: currentIndex) ?? shuffleOrder.firstIndex
146
+ shuffleOrder.getNextIndex(after: currentIndex)
147
+ ?? (repeatMode == .queue ? shuffleOrder.firstIndex : nil)
147
148
  } else if currentIndex + 1 < tracks.count {
148
149
  currentIndex + 1
149
150
  } else {
@@ -156,7 +157,8 @@ class QueueManager {
156
157
  private var previousIndex: Int? {
157
158
  guard currentTrack != nil, tracks.count > 1 else { return nil }
158
159
  let candidate: Int? = if shuffleEnabled {
159
- shuffleOrder.getPreviousIndex(before: currentIndex) ?? shuffleOrder.lastIndex
160
+ shuffleOrder.getPreviousIndex(before: currentIndex)
161
+ ?? (repeatMode == .queue ? shuffleOrder.lastIndex : nil)
160
162
  } else if currentIndex - 1 >= 0 {
161
163
  currentIndex - 1
162
164
  } else {
@@ -305,6 +307,21 @@ class QueueManager {
305
307
  return .tracksOnly
306
308
  }
307
309
 
310
+ /// Replaces, in place, each track `transform` returns a track for.
311
+ @discardableResult
312
+ func replaceEach(_ transform: (Track) -> Track?) -> QueueChange {
313
+ var updated = tracks
314
+ var replaced = false
315
+ for (index, track) in tracks.enumerated() {
316
+ guard let replacement = transform(track) else { continue }
317
+ updated[index] = replacement
318
+ replaced = true
319
+ }
320
+ guard replaced else { return .none }
321
+ tracks = updated
322
+ return .tracksOnly
323
+ }
324
+
308
325
  /// Removes the tracks after the current one in queue order, not shuffle order.
309
326
  @discardableResult
310
327
  func removeUpcomingTracks() -> QueueChange {
@@ -0,0 +1,21 @@
1
+ import Testing
2
+
3
+ @testable import AudioBrowserTestable
4
+
5
+ @Suite("BrowserError")
6
+ struct BrowserErrorTests {
7
+ @Test func aPathNoRouteMatchesIsContentNotFoundWithoutABaseUrl() {
8
+ guard case let .contentNotFound(path) = BrowserError.missingBaseUrl(path: "/nowhere", routed: false) else {
9
+ Issue.record("expected contentNotFound")
10
+ return
11
+ }
12
+ #expect(path == "/nowhere")
13
+ }
14
+
15
+ @Test func aRoutesRequestIsInvalidConfigurationWithoutABaseUrl() {
16
+ guard case .invalidConfiguration = BrowserError.missingBaseUrl(path: "/library", routed: true) else {
17
+ Issue.record("expected invalidConfiguration")
18
+ return
19
+ }
20
+ }
21
+ }
@@ -107,6 +107,24 @@ import Testing
107
107
  #expect(BrowserPathHelper.stripTrackId(url) == "/library")
108
108
  }
109
109
 
110
+ @Test(arguments: [
111
+ "/genres/Hip Hop",
112
+ "/genres/Électro",
113
+ "/list?tag=c%2B%2B",
114
+ "/list?sort=a%2Fb",
115
+ "/list?ids=[1]",
116
+ "/sale/50%",
117
+ "/list?x=%E9",
118
+ "/page#top",
119
+ ])
120
+ func buildRoundTripsAParentThatIsNotACanonicalUrl(parent: String) {
121
+ let identity = "id 1/é"
122
+ let url = BrowserPathHelper.build(parentPath: parent, trackId: identity, index: 2)
123
+ #expect(BrowserPathHelper.stripTrackId(url) == parent)
124
+ #expect(BrowserPathHelper.extractTrackId(url) == identity)
125
+ #expect(BrowserPathHelper.extractIndex(url) == 2)
126
+ }
127
+
110
128
  // MARK: - extractIndex
111
129
 
112
130
  @Test func extractIndexReturnsNilWithoutAStampedIndex() {
@@ -0,0 +1,36 @@
1
+ import CoreGraphics
2
+ import Testing
3
+
4
+ @testable import AudioBrowserTestable
5
+
6
+ @Suite("CGSize.aspectFitted(in:)")
7
+ struct CGSizeAspectFitTests {
8
+ private let slot = CGSize(width: 40, height: 40)
9
+
10
+ @Test func aLargeCanvasShrinksToTheSlot() {
11
+ #expect(CGSize(width: 1024, height: 1024).aspectFitted(in: slot) == slot)
12
+ }
13
+
14
+ @Test func aSmallCanvasGrowsToTheSlot() {
15
+ #expect(CGSize(width: 24, height: 24).aspectFitted(in: slot) == slot)
16
+ }
17
+
18
+ @Test func aWideCanvasKeepsItsAspectRatio() {
19
+ #expect(CGSize(width: 200, height: 100).aspectFitted(in: slot) == CGSize(width: 40, height: 20))
20
+ }
21
+
22
+ @Test func aTallCanvasKeepsItsAspectRatio() {
23
+ #expect(CGSize(width: 100, height: 400).aspectFitted(in: slot) == CGSize(width: 10, height: 40))
24
+ }
25
+
26
+ @Test(arguments: [
27
+ CGSize.zero,
28
+ CGSize(width: 100, height: 0),
29
+ CGSize(width: -10, height: 10),
30
+ CGSize(width: CGFloat.infinity, height: 10),
31
+ CGSize(width: CGFloat.nan, height: 10),
32
+ ])
33
+ func aCanvasWithoutAnAspectRatioHasNoFit(_ canvas: CGSize) {
34
+ #expect(canvas.aspectFitted(in: slot) == nil)
35
+ }
36
+ }
@@ -0,0 +1,26 @@
1
+ import Testing
2
+
3
+ @testable import AudioBrowserTestable
4
+
5
+ @Suite("clampedVolume")
6
+ struct ClampedVolumeTests {
7
+ @Test func keepsALevelInRange() {
8
+ #expect(clampedVolume(0) == 0)
9
+ #expect(clampedVolume(0.25) == 0.25)
10
+ #expect(clampedVolume(1) == 1)
11
+ }
12
+
13
+ @Test func raisesALevelBelowZeroToSilence() {
14
+ #expect(clampedVolume(-0.5) == 0)
15
+ #expect(clampedVolume(-.infinity) == 0)
16
+ }
17
+
18
+ @Test func lowersALevelAboveOneToFull() {
19
+ #expect(clampedVolume(1.5) == 1)
20
+ #expect(clampedVolume(.infinity) == 1)
21
+ }
22
+
23
+ @Test func hasNoVolumeForNaN() {
24
+ #expect(clampedVolume(.nan) == nil)
25
+ }
26
+ }
@@ -10,10 +10,10 @@ struct FavoriteSetTests {
10
10
  return set
11
11
  }
12
12
 
13
- @Test func replaceReportsWhetherTheIdentitiesChanged() {
13
+ @Test func replaceReportsTheIdentitiesThatChanged() {
14
14
  var set = FavoriteSet()
15
- let changes = [["a", "b"], ["b", "a"], ["a", "b", "a"], []].map { set.replace(with: $0) }
16
- #expect(changes == [true, false, false, true])
15
+ let changes = [["a", "b"], ["b", "a"], ["a", "b", "a"], ["b", "c"], []].map { set.replace(with: $0) }
16
+ #expect(changes == [["a", "b"], [], [], ["a", "c"], ["b", "c"]])
17
17
  }
18
18
 
19
19
  @Test func hydratesTrueOrFalseByIdentity() {
@@ -58,4 +58,69 @@ struct FavoriteSetTests {
58
58
  let hydrated = favorites(["b"]).hydrate(page)
59
59
  #expect(hydrated.sections?.map { $0.children.map(\.favorited) } == [[false], [true]])
60
60
  }
61
+
62
+ @Test func aHydratedTrackFollowsALaterReplace() throws {
63
+ var set = favorites([])
64
+ let queued = set.hydrate(Track(src: "a"))
65
+ #expect(queued.favorited == false)
66
+
67
+ let added = set.replace(with: ["a"])
68
+ let favorited = try #require(set.restamp(queued, changed: added))
69
+ #expect(favorited.favorited == true)
70
+
71
+ let removed = set.replace(with: [])
72
+ #expect(set.restamp(favorited, changed: removed)?.favorited == false)
73
+ }
74
+
75
+ @Test func restampFillsAnUnsetFlag() {
76
+ var set = favorites([])
77
+ let changed = set.replace(with: ["a"])
78
+ #expect(set.restamp(Track(src: "a"), changed: changed)?.favorited == true)
79
+ }
80
+
81
+ @Test func restampLeavesATrackWhoseIdentityDidNotChange() {
82
+ var set = favorites(["a"])
83
+ let changed = set.replace(with: ["a", "c"])
84
+ // Carried by the tracks themselves, against the set: only a change to their identity moves them.
85
+ #expect(set.restamp(Track(src: "a", favorited: false), changed: changed) == nil)
86
+ #expect(set.restamp(Track(src: "b", favorited: true), changed: changed) == nil)
87
+ }
88
+
89
+ @Test func restampLeavesATrackThatAlreadyAgrees() {
90
+ var set = favorites([])
91
+ let changed = set.replace(with: ["a"])
92
+ #expect(set.restamp(Track(src: "a", favorited: true), changed: changed) == nil)
93
+ }
94
+
95
+ @Test func restampOverwritesAStampedTrackWhenDisabled() {
96
+ var set = favorites(["a"], enabled: false)
97
+ let changed = set.replace(with: [])
98
+ #expect(set.restamp(Track(src: "a", favorited: true), changed: changed)?.favorited == false)
99
+ }
100
+
101
+ @Test func restampLeavesATrackWithoutIdentityAlone() {
102
+ var set = favorites([])
103
+ let changed = set.replace(with: ["/browse"])
104
+ #expect(set.restamp(Track(path: "/browse"), changed: changed) == nil)
105
+ }
106
+
107
+ @Test func restampsTheChangedTracksOfAPage() {
108
+ var set = favorites(["b"])
109
+ let page = set.hydrate(ResolvedTrack(
110
+ path: "/p",
111
+ sections: [Section(children: [Track(src: "a")]), Section(children: [Track(src: "b"), Track(src: "c")])],
112
+ title: "P",
113
+ ))
114
+ let changed = set.replace(with: ["a", "c"])
115
+ let restamped = page.replacingEachTrack { set.restamp($0, changed: changed) }
116
+ #expect(restamped?.sections?.map { $0.children.map(\.favorited) } == [[true], [false, true]])
117
+ #expect(restamped?.path == "/p")
118
+ }
119
+
120
+ @Test func aPageWithNoChangedTrackIsNotRestamped() {
121
+ var set = favorites(["b"])
122
+ let page = set.hydrate(ResolvedTrack(path: "/p", sections: [Section(children: [Track(src: "b")])], title: "P"))
123
+ let changed = set.replace(with: ["b", "elsewhere"])
124
+ #expect(page.replacingEachTrack { set.restamp($0, changed: changed) } == nil)
125
+ }
61
126
  }
@@ -0,0 +1,102 @@
1
+ import Testing
2
+
3
+ @testable import AudioBrowserTestable
4
+
5
+ @MainActor
6
+ private final class Holder: FavoriteStamped {
7
+ var tracks: [Track]
8
+ let name: String
9
+ let log: Log
10
+
11
+ init(_ name: String, _ tracks: [Track], log: Log) {
12
+ self.name = name
13
+ self.tracks = tracks
14
+ self.log = log
15
+ }
16
+
17
+ func restampFavorites(_ restamp: (Track) -> Track?) {
18
+ log.entries.append(name)
19
+ tracks = tracks.map { restamp($0) ?? $0 }
20
+ }
21
+ }
22
+
23
+ private final class Log {
24
+ var entries: [String] = []
25
+ }
26
+
27
+ @MainActor
28
+ struct FavoritesTests {
29
+ private let log = Log()
30
+
31
+ private func makeFavorites(content: [Track] = [], queue: [Track] = []) -> (Favorites, Holder, Holder) {
32
+ let content = Holder("content", content, log: log)
33
+ let queue = Holder("queue", queue, log: log)
34
+ let favorites = Favorites(content: content)
35
+ favorites.enabled = true
36
+ favorites.queue = queue
37
+ favorites.changed.addListener { [log] in log.entries.append("changed") }
38
+ return (favorites, content, queue)
39
+ }
40
+
41
+ @Test func aReplaceRestampsTheContentThenTheQueueThenEmits() {
42
+ let (favorites, content, queue) = makeFavorites(
43
+ content: [Track(src: "a", favorited: false)],
44
+ queue: [Track(src: "a", favorited: false), Track(src: "b", favorited: false)],
45
+ )
46
+
47
+ favorites.replace(with: ["a"])
48
+
49
+ #expect(log.entries == ["content", "queue", "changed"])
50
+ #expect(content.tracks.map(\.favorited) == [true])
51
+ #expect(queue.tracks.map(\.favorited) == [true, false])
52
+ }
53
+
54
+ @Test func aReplaceThatChangesNothingRestampsNothing() {
55
+ let (favorites, _, _) = makeFavorites()
56
+ favorites.replace(with: [])
57
+ #expect(log.entries.isEmpty)
58
+ }
59
+
60
+ @Test func aToggleRestampsEveryCopyOfTheTrack() {
61
+ let a = Track(src: "a", favorited: false)
62
+ let (favorites, content, queue) = makeFavorites(content: [a], queue: [a, Track(src: "b"), a])
63
+
64
+ favorites.set("a", favorited: true)
65
+
66
+ #expect(log.entries == ["content", "queue", "changed"])
67
+ #expect(content.tracks.map(\.favorited) == [true])
68
+ #expect(queue.tracks.map(\.favorited) == [true, nil, true])
69
+ }
70
+
71
+ @Test func aToggleRestampsACopyThatDisagreesWithTheSet() {
72
+ let (favorites, _, queue) = makeFavorites(queue: [Track(src: "a", favorited: false)])
73
+ favorites.replace(with: ["a"])
74
+ queue.tracks = [Track(src: "a", favorited: false)]
75
+
76
+ favorites.set("a", favorited: true)
77
+
78
+ #expect(queue.tracks.map(\.favorited) == [true])
79
+ }
80
+
81
+ @Test func aReplaceWhileDisabledReachesAStampedCopy() {
82
+ let (favorites, _, queue) = makeFavorites(queue: [Track(src: "a", favorited: false)])
83
+ favorites.replace(with: ["a"])
84
+ favorites.enabled = false
85
+
86
+ favorites.replace(with: [])
87
+ favorites.enabled = true
88
+
89
+ #expect(queue.tracks.map(\.favorited) == [false])
90
+ }
91
+
92
+ @Test func theQueueIsThePlayer() throws {
93
+ let player = makePlayer()
94
+ let favorites = Favorites(content: Holder("content", [], log: log))
95
+ favorites.queue = player
96
+ try player.setQueue([Track(src: "a", favorited: false), Track(src: "a", favorited: false)])
97
+
98
+ favorites.set("a", favorited: true)
99
+
100
+ #expect(player.tracks.map(\.favorited) == [true, true])
101
+ }
102
+ }
@@ -0,0 +1,45 @@
1
+ @testable import AudioBrowserTestable
2
+ import Foundation
3
+ import Testing
4
+
5
+ /// Answers every request with the `User-Agent` it carries, as `{"userAgent": …}`.
6
+ private final class EchoUserAgentProtocol: URLProtocol {
7
+ override class func canInit(with _: URLRequest) -> Bool {
8
+ true
9
+ }
10
+
11
+ override class func canonicalRequest(for request: URLRequest) -> URLRequest {
12
+ request
13
+ }
14
+
15
+ override func startLoading() {
16
+ let body = ["userAgent": request.value(forHTTPHeaderField: "User-Agent") ?? ""]
17
+ let response = HTTPURLResponse(url: request.url!, statusCode: 200, httpVersion: "HTTP/1.1", headerFields: nil)!
18
+ client?.urlProtocol(self, didReceive: response, cacheStoragePolicy: .notAllowed)
19
+ client?.urlProtocol(self, didLoad: try! JSONEncoder().encode(body))
20
+ client?.urlProtocolDidFinishLoading(self)
21
+ }
22
+
23
+ override func stopLoading() {}
24
+ }
25
+
26
+ @Suite("The User-Agent an HTTP request carries")
27
+ struct HttpClientUserAgentTests {
28
+ /// The `User-Agent` sent for a request with `headers` and the default `userAgent`.
29
+ private func sentUserAgent(headers: [String: String]) async throws -> String? {
30
+ let configuration = URLSessionConfiguration.ephemeral
31
+ configuration.protocolClasses = [EchoUserAgentProtocol.self]
32
+ let request = HttpClient.HttpRequest(
33
+ url: "https://stub.invalid/", method: .get, headers: headers, body: nil,
34
+ contentType: HttpClient.defaultContentType, userAgent: HttpClient.defaultUserAgent,
35
+ )
36
+ let session = URLSession(configuration: configuration)
37
+ defer { session.finishTasksAndInvalidate() }
38
+ return try await HttpClient(session: session).requestJson(request, as: [String: String].self)["userAgent"]
39
+ }
40
+
41
+ @Test(arguments: ["user-agent", "USER-AGENT"])
42
+ func aHeaderWinsOverTheFieldInAnyCase(name: String) async throws {
43
+ #expect(try await sentUserAgent(headers: [name: "MyApp/1.0"]) == "MyApp/1.0")
44
+ }
45
+ }