@kesha-antonov/react-native-background-downloader 4.6.3 → 4.7.0

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 (41) hide show
  1. package/README.md +29 -7
  2. package/android/src/main/java/com/eko/DownloadConstants.kt +13 -2
  3. package/android/src/main/java/com/eko/DownloadResult.kt +3 -1
  4. package/android/src/main/java/com/eko/Downloader.kt +25 -4
  5. package/android/src/main/java/com/eko/ProgressReporter.kt +14 -35
  6. package/android/src/main/java/com/eko/RNBackgroundDownloaderModuleImpl.kt +162 -76
  7. package/android/src/main/java/com/eko/ResumableDownloadService.kt +2 -1
  8. package/android/src/main/java/com/eko/ResumableDownloader.kt +75 -3
  9. package/android/src/main/java/com/eko/UIDTDownloadJobService.kt +34 -8
  10. package/android/src/main/java/com/eko/Uploader.kt +15 -11
  11. package/android/src/main/java/com/eko/handlers/OnBegin.kt +6 -1
  12. package/android/src/main/java/com/eko/uidt/CancelDownloadReceiver.kt +3 -1
  13. package/android/src/main/java/com/eko/uidt/UIDTJobManager.kt +18 -2
  14. package/android/src/main/java/com/eko/utils/RedirectResolver.kt +5 -13
  15. package/android/src/main/java/com/eko/utils/StorageManager.kt +5 -0
  16. package/android/src/test/java/com/eko/DownloaderRecoveryTest.kt +78 -0
  17. package/android/src/test/java/com/eko/DownloaderResumeTest.kt +97 -0
  18. package/android/src/test/java/com/eko/ResumableDownloaderStallTest.kt +145 -0
  19. package/android/src/test/java/com/eko/UploaderMultipartTest.kt +84 -0
  20. package/android/src/test/java/com/eko/handlers/OnBeginTest.kt +51 -0
  21. package/android/src/test/java/com/eko/uidt/CancelDownloadReceiverTest.kt +84 -0
  22. package/android/src/test/java/com/eko/utils/RedirectResolverTest.kt +67 -0
  23. package/ios/RNBGDTaskConfig.h +2 -0
  24. package/ios/RNBGDTaskConfig.mm +6 -0
  25. package/ios/RNBackgroundDownloader.mm +640 -90
  26. package/lib/DownloadTask.d.ts +2 -0
  27. package/lib/DownloadTask.js +21 -1
  28. package/lib/UploadTask.d.ts +2 -0
  29. package/lib/UploadTask.js +25 -3
  30. package/lib/index.d.ts +1 -1
  31. package/lib/index.js +83 -70
  32. package/lib/tasks.d.ts +4 -0
  33. package/lib/tasks.js +7 -0
  34. package/package.json +14 -11
  35. package/plugin/build/index.d.ts +1 -0
  36. package/plugin/build/index.js +18 -10
  37. package/react-native-background-downloader.podspec +8 -0
  38. package/src/DownloadTask.ts +22 -1
  39. package/src/UploadTask.ts +25 -3
  40. package/src/index.ts +74 -43
  41. package/src/tasks.ts +7 -0
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@kesha-antonov/react-native-background-downloader",
3
- "version": "4.6.3",
3
+ "version": "4.7.0",
4
4
  "description": "Background file downloads and uploads for React Native and Expo. Large files keep transferring on iOS and Android while your app is in the background or terminated. Pause/resume, progress events, TurboModules, TypeScript.",
5
5
  "keywords": [
6
6
  "react-native",
@@ -71,6 +71,7 @@
71
71
  "src/",
72
72
  "lib/",
73
73
  "ios/",
74
+ "!ios/Tests/",
74
75
  "android/build.gradle",
75
76
  "android/src/",
76
77
  "plugin/build/"
@@ -78,20 +79,21 @@
78
79
  "scripts": {
79
80
  "bump": "npm version patch",
80
81
  "lint": "eslint .",
81
- "typecheck": "tsc src/*.ts --noEmit --strict --skipLibCheck",
82
+ "typecheck": "tsc src/*.ts types/*.d.ts --noEmit --strict --skipLibCheck --module node16 --moduleResolution node16",
82
83
  "build": "rm -rf lib && tsc -p tsconfig.build.json",
83
84
  "prepare": "npm run build && npm run build-plugin",
84
85
  "prepublishOnly": "npm run build-plugin && npm run build && npm run typecheck && jest && npm run lint",
85
86
  "build-plugin": "tsc plugin/src/index.ts --outDir plugin/build --target ES2018 --module commonjs --declaration --esModuleInterop --strict --skipLibCheck",
86
87
  "release": "npm publish",
87
88
  "test": "jest",
88
- "test:android": "cd example/android && ./gradlew :kesha-antonov_react-native-background-downloader:testDebugUnitTest"
89
+ "test:android": "cd example/android && ./gradlew :kesha-antonov_react-native-background-downloader:testDebugUnitTest",
90
+ "test:ios": "cd example/ios && xcodebuild test -workspace RNBDExample.xcworkspace -scheme react-native-background-downloader-Unit-Tests -destination \"platform=iOS Simulator,name=${IOS_SIMULATOR:-iPhone 17}\""
89
91
  },
90
92
  "lint-staged": {
91
93
  "*.js": "eslint --cache"
92
94
  },
93
95
  "jest": {
94
- "preset": "react-native",
96
+ "preset": "@react-native/jest-preset",
95
97
  "setupFiles": [
96
98
  "./__mocks__/RNBackgroundDownloader.js",
97
99
  "./__mocks__/NativeEventEmitter.js"
@@ -112,10 +114,11 @@
112
114
  "@babel/preset-env": "^7.28.5",
113
115
  "@babel/preset-typescript": "^7.28.5",
114
116
  "@babel/runtime": "^7.28.4",
115
- "@expo/config-plugins": "^54.0.2",
116
- "@react-native/babel-preset": "^0.81.5",
117
- "@react-native/eslint-config": "^0.81.5",
118
- "@react-native/metro-config": "^0.81.5",
117
+ "@expo/config-plugins": "^58.0.11",
118
+ "@react-native/babel-preset": "^0.88.1",
119
+ "@react-native/eslint-config": "^0.88.1",
120
+ "@react-native/jest-preset": "^0.88.1",
121
+ "@react-native/metro-config": "^0.88.1",
119
122
  "@typescript-eslint/eslint-plugin": "^8.46.1",
120
123
  "@typescript-eslint/parser": "^8.46.1",
121
124
  "babel-jest": "^29.7.0",
@@ -134,11 +137,11 @@
134
137
  "jest": "^29.7.0",
135
138
  "lint-staged": ">=16",
136
139
  "metro-react-native-babel-preset": "^0.77.0",
137
- "react": "19.1.0",
138
- "react-native": "0.81.5",
140
+ "react": "19.3.0",
141
+ "react-native": "0.88.1",
139
142
  "react-native-fs": "^2.20.0",
140
143
  "react-native-vector-icons": "^10.3.0",
141
- "react-test-renderer": "19.2.0",
144
+ "react-test-renderer": "19.3.0",
142
145
  "typescript": "5.9.3"
143
146
  },
144
147
  "peerDependencies": {
@@ -22,4 +22,5 @@ interface PluginOptions {
22
22
  skipMmkvDependency?: boolean;
23
23
  }
24
24
  declare const withRNBackgroundDownloader: ConfigPlugin<PluginOptions | void>;
25
+ export declare function addSwiftSupport(appDelegateContents: string): string;
25
26
  export default withRNBackgroundDownloader;
@@ -33,6 +33,7 @@ var __importStar = (this && this.__importStar) || (function () {
33
33
  };
34
34
  })();
35
35
  Object.defineProperty(exports, "__esModule", { value: true });
36
+ exports.addSwiftSupport = addSwiftSupport;
36
37
  const config_plugins_1 = require("@expo/config-plugins");
37
38
  const fs = __importStar(require("fs"));
38
39
  const path = __importStar(require("path"));
@@ -43,7 +44,7 @@ const withRNBackgroundDownloader = (config, options) => {
43
44
  const shouldSkipMmkv = skipMmkvDependency || hasReactNativeMmkv;
44
45
  // Handle iOS AppDelegate modifications
45
46
  config = (0, config_plugins_1.withAppDelegate)(config, (config) => {
46
- if (config.modResults.language === 'objc') {
47
+ if (config.modResults.language === 'objc' || config.modResults.language === 'objcpp') {
47
48
  // For Objective-C AppDelegate.m (React Native < 0.77)
48
49
  config.modResults.contents = addObjCSupport(config.modResults.contents);
49
50
  }
@@ -160,26 +161,33 @@ function addObjCSupport(appDelegateContents) {
160
161
  function addSwiftSupport(appDelegateContents) {
161
162
  // For Swift, we need to add the method to the AppDelegate class
162
163
  // The import should be handled by the bridging header
164
+ // Remove the method if an older version of this plugin added it outside the AppDelegate class.
165
+ // Only the exact one-line body it generated is matched, so hand-written methods are never touched
166
+ appDelegateContents = appDelegateContents.replace(/\n[ \t]*func application\(\s*_ application: UIApplication,\s*handleEventsForBackgroundURLSession identifier: String,\s*completionHandler: @escaping \(\) -> Void\s*\)\s*\{\s*RNBackgroundDownloader\.setCompletionHandlerWithIdentifier\(identifier, completionHandler: completionHandler\)\s*\}\n/g, '');
163
167
  // Add the handleEventsForBackgroundURLSession method if not already present
164
168
  if (!appDelegateContents.includes('handleEventsForBackgroundURLSession')) {
169
+ // ExpoAppDelegate already implements the method, so it must be overridden and other sessions passed to it
170
+ const isExpo = /\bExpoAppDelegate\b/.test(appDelegateContents);
171
+ const passOtherSessions = `
172
+ guard identifier.hasSuffix(".backgrounddownloadtask") else {
173
+ return super.application(application, handleEventsForBackgroundURLSession: identifier, completionHandler: completionHandler)
174
+ }`;
165
175
  const methodToAdd = `
166
- func application(
176
+ ${isExpo ? 'public override func' : 'func'} application(
167
177
  _ application: UIApplication,
168
178
  handleEventsForBackgroundURLSession identifier: String,
169
179
  completionHandler: @escaping () -> Void
170
- ) {
180
+ ) {${isExpo ? passOtherSessions : ''}
171
181
  RNBackgroundDownloader.setCompletionHandlerWithIdentifier(identifier, completionHandler: completionHandler)
172
182
  }
173
183
  `;
174
184
  // Find the end of the AppDelegate class but before the closing brace
175
- const classEndRegex = /^}$/gm;
176
- const matches = [...appDelegateContents.matchAll(classEndRegex)];
177
- if (matches.length > 0) {
178
- // Insert before the last closing brace (assuming it's the AppDelegate class)
179
- const lastMatch = matches[matches.length - 1];
180
- const insertPosition = lastMatch.index;
185
+ const classMatch = /^.*\bclass\s+AppDelegate\b.*$/m.exec(appDelegateContents);
186
+ const classEndMatch = classMatch ? /^}$/m.exec(appDelegateContents.slice(classMatch.index)) : null;
187
+ if (classMatch && classEndMatch) {
188
+ const insertPosition = classMatch.index + classEndMatch.index;
181
189
  appDelegateContents = appDelegateContents.slice(0, insertPosition) +
182
- methodToAdd + '\n' +
190
+ methodToAdd +
183
191
  appDelegateContents.slice(insertPosition);
184
192
  }
185
193
  }
@@ -16,6 +16,7 @@ Pod::Spec.new do |s|
16
16
  s.source = { git: 'https://github.com/kesha-antonov/react-native-background-downloader.git', tag: 'main' }
17
17
 
18
18
  s.source_files = 'ios/**/*.{h,m,mm,swift}'
19
+ s.exclude_files = 'ios/Tests/**/*'
19
20
  # React Native Core dependency
20
21
  install_modules_dependencies(s)
21
22
 
@@ -42,6 +43,13 @@ Pod::Spec.new do |s|
42
43
  # resolve to the broken 2.4.1 on its own.
43
44
  s.dependency 'MMKVCore', '!= 2.4.1'
44
45
 
46
+ # Unit tests, built only when a Podfile asks for them with `:testspecs => ['Tests']`
47
+ # (the example app does). They need C++20 for React's headers.
48
+ s.test_spec 'Tests' do |test_spec|
49
+ test_spec.source_files = 'ios/Tests/**/*.{h,m,mm}'
50
+ test_spec.pod_target_xcconfig = { 'CLANG_CXX_LANGUAGE_STANDARD' => 'c++20' }
51
+ end
52
+
45
53
  # Enable codegen for new architecture
46
54
  if ENV['RCT_NEW_ARCH_ENABLED'] == '1'
47
55
  s.compiler_flags = folly_compiler_flags + " -DRCT_NEW_ARCH_ENABLED=1"
@@ -18,6 +18,7 @@ import {
18
18
  } from './types'
19
19
  import { config } from './config'
20
20
  import { log } from './logger'
21
+ import { tasksMap } from './tasks'
21
22
 
22
23
  // Import shared native module getter to avoid duplicating TurboModule lookup
23
24
  // This is lazily imported to avoid circular dependency issues at module load time
@@ -48,6 +49,10 @@ export class DownloadTask {
48
49
  doneHandler?: DoneHandler
49
50
  errorHandler?: ErrorHandler
50
51
 
52
+ // begin fires once per task. Android sends it again for each new transfer (a resume in
53
+ // a new job, a reschedule by the system), which isn't a new beginning for the app.
54
+ private hasBegun = false
55
+
51
56
  constructor (taskParams: TaskInfo | TaskInfoNative, originalTask?: DownloadTaskType) {
52
57
  this.id = taskParams.id
53
58
 
@@ -62,6 +67,9 @@ export class DownloadTask {
62
67
 
63
68
  this.metadata = this.tryParseJson(taskParams.metadata) ?? {}
64
69
 
70
+ // A restored task that already has data has begun; so has one this replaces
71
+ this.hasBegun = (originalTask instanceof DownloadTask && originalTask.hasBegun) || this.bytesDownloaded > 0
72
+
65
73
  if (originalTask) {
66
74
  this.beginHandler = originalTask.beginHandler
67
75
  this.progressHandler = originalTask.progressHandler
@@ -106,13 +114,22 @@ export class DownloadTask {
106
114
 
107
115
  // event listeners
108
116
 
117
+ // Native can still deliver begin or progress that was in flight when the app paused
118
+ // or stopped the task, or when it ended. Those must not run handlers or change state.
119
+ private isInactive (): boolean {
120
+ return this.state === 'PAUSED' || this.state === 'STOPPED' || this.state === 'DONE' || this.state === 'FAILED'
121
+ }
122
+
109
123
  onBegin (params: BeginHandlerParams) {
124
+ if (this.isInactive() || this.hasBegun) return
125
+ this.hasBegun = true
110
126
  this.state = 'DOWNLOADING'
111
127
  this.bytesTotal = params.expectedBytes
112
128
  this.beginHandler?.(params)
113
129
  }
114
130
 
115
131
  onProgress (params: ProgressHandlerParams) {
132
+ if (this.isInactive()) return
116
133
  this.bytesDownloaded = params.bytesDownloaded
117
134
  this.bytesTotal = params.bytesTotal
118
135
  this.progressHandler?.(params)
@@ -127,6 +144,7 @@ export class DownloadTask {
127
144
 
128
145
  onError (params: ErrorHandlerParams) {
129
146
  this.state = 'FAILED'
147
+ this.errorCode = params.errorCode
130
148
  this.errorHandler?.(params)
131
149
  }
132
150
 
@@ -192,7 +210,7 @@ export class DownloadTask {
192
210
  ...this.downloadParams,
193
211
  headers: this.headersToUnsafeObject(this.downloadParams.headers),
194
212
  isAllowedOverRoaming: this.downloadParams.isAllowedOverRoaming ?? false,
195
- isAllowedOverMetered: this.downloadParams.isAllowedOverMetered ?? false,
213
+ isAllowedOverMetered: this.downloadParams.isAllowedOverMetered ?? config.allowsCellularAccess,
196
214
  // iOS-only; ignored on Android. Falls back to the global setConfig default.
197
215
  iosDataProtection: this.downloadParams.iosDataProtection ?? config.iosDataProtection,
198
216
  })
@@ -203,6 +221,9 @@ export class DownloadTask {
203
221
 
204
222
  this.state = 'STOPPED'
205
223
  await getNativeModule().stopTask(this.id)
224
+ // No event follows a stop, so nothing else would release the task
225
+ if (tasksMap.get(this.id) === this)
226
+ tasksMap.delete(this.id)
206
227
  }
207
228
 
208
229
  tryParseJson (metadata?: string | Metadata | object): Metadata | null {
package/src/UploadTask.ts CHANGED
@@ -18,6 +18,7 @@ import {
18
18
  } from './types'
19
19
  import { config } from './config'
20
20
  import { log } from './logger'
21
+ import { uploadTasksMap } from './tasks'
21
22
 
22
23
  // Import shared native module getter to avoid duplicating TurboModule lookup
23
24
  // This is lazily imported to avoid circular dependency issues at module load time
@@ -47,6 +48,10 @@ export class UploadTask {
47
48
  doneHandler?: UploadDoneHandler
48
49
  errorHandler?: UploadErrorHandler
49
50
 
51
+ // begin fires once per task. Android sends it again for each new transfer (a resume in
52
+ // a new job, a reschedule by the system), which isn't a new beginning for the app.
53
+ private hasBegun = false
54
+
50
55
  constructor (taskParams: UploadTaskInfo | UploadTaskInfoNative, originalTask?: UploadTaskType) {
51
56
  this.id = taskParams.id
52
57
 
@@ -58,6 +63,9 @@ export class UploadTask {
58
63
 
59
64
  this.metadata = this.tryParseJson(taskParams.metadata) ?? {}
60
65
 
66
+ // A restored task that already has data has begun; so has one this replaces
67
+ this.hasBegun = (originalTask instanceof UploadTask && originalTask.hasBegun) || this.bytesUploaded > 0
68
+
61
69
  if (originalTask) {
62
70
  this.beginHandler = originalTask.beginHandler
63
71
  this.progressHandler = originalTask.progressHandler
@@ -102,13 +110,22 @@ export class UploadTask {
102
110
 
103
111
  // event listeners
104
112
 
113
+ // Native can still deliver begin or progress that was in flight when the app paused
114
+ // or stopped the upload, or when it ended. Those must not run handlers or change state.
115
+ private isInactive (): boolean {
116
+ return this.state === 'PAUSED' || this.state === 'STOPPED' || this.state === 'DONE' || this.state === 'FAILED'
117
+ }
118
+
105
119
  onBegin (params: UploadBeginHandlerParams) {
120
+ if (this.isInactive() || this.hasBegun) return
121
+ this.hasBegun = true
106
122
  this.state = 'UPLOADING'
107
123
  this.bytesTotal = params.expectedBytes
108
124
  this.beginHandler?.(params)
109
125
  }
110
126
 
111
127
  onProgress (params: UploadProgressHandlerParams) {
128
+ if (this.isInactive()) return
112
129
  this.bytesUploaded = params.bytesUploaded
113
130
  this.bytesTotal = params.bytesTotal
114
131
  this.progressHandler?.(params)
@@ -123,6 +140,7 @@ export class UploadTask {
123
140
 
124
141
  onError (params: UploadErrorHandlerParams) {
125
142
  this.state = 'FAILED'
143
+ this.errorCode = params.errorCode
126
144
  this.errorHandler?.(params)
127
145
  }
128
146
 
@@ -185,7 +203,7 @@ export class UploadTask {
185
203
  method: this.uploadParams.method ?? 'POST',
186
204
  headers: this.headersToUnsafeObject(this.uploadParams.headers),
187
205
  isAllowedOverRoaming: this.uploadParams.isAllowedOverRoaming ?? false,
188
- isAllowedOverMetered: this.uploadParams.isAllowedOverMetered ?? false,
206
+ isAllowedOverMetered: this.uploadParams.isAllowedOverMetered ?? config.allowsCellularAccess,
189
207
  })
190
208
  }
191
209
 
@@ -194,10 +212,14 @@ export class UploadTask {
194
212
 
195
213
  this.state = 'STOPPED'
196
214
  const nativeModule = getNativeModule()
197
- if (nativeModule.stopUploadTask)
215
+ if (nativeModule.stopUploadTask) {
198
216
  await nativeModule.stopUploadTask(this.id)
199
- else
217
+ // No event follows a stop, so nothing else would release the task
218
+ if (uploadTasksMap.get(this.id) === this)
219
+ uploadTasksMap.delete(this.id)
220
+ } else {
200
221
  log('UploadTask: stop not supported - native implementation missing')
222
+ }
201
223
  }
202
224
 
203
225
  tryParseJson (metadata?: string | Metadata | object): Metadata | null {
package/src/index.ts CHANGED
@@ -1,10 +1,11 @@
1
- import { NativeModules, Platform, TurboModuleRegistry, NativeEventEmitter, NativeModule } from 'react-native'
1
+ import { NativeModules, Platform, TurboModuleRegistry, NativeEventEmitter } from 'react-native'
2
2
  import { DownloadTask } from './DownloadTask'
3
3
  import { UploadTask } from './UploadTask'
4
4
  import { Config, DownloadParams, Headers, Metadata, TaskInfo, TaskInfoNative, UploadParams, UploadTaskInfo, UploadTaskInfoNative } from './types'
5
- import { config, DEFAULT_PROGRESS_INTERVAL, DEFAULT_PROGRESS_MIN_BYTES, DEFAULT_NOTIFICATION_TEXTS } from './config'
5
+ import { config, DEFAULT_NOTIFICATION_TEXTS } from './config'
6
6
  import { log } from './logger'
7
7
  import { getNotificationTextsForNative } from './notifications'
8
+ import { tasksMap, uploadTasksMap } from './tasks'
8
9
  import type { Spec } from './NativeRNBackgroundDownloader'
9
10
 
10
11
  type RNBackgroundDownloaderModule = Spec & {
@@ -15,6 +16,20 @@ type RNBackgroundDownloaderModule = Spec & {
15
16
  documents: string
16
17
  }
17
18
 
19
+ // What NativeEventEmitter needs from a native module. React Native 0.88's strict
20
+ // TypeScript API no longer exports the NativeModule type
21
+ type NativeModule = {
22
+ addListener: (eventType: string) => void
23
+ removeListeners: (count: number) => void
24
+ }
25
+
26
+ // The emitter's listener types differ between React Native versions, so the
27
+ // payload types are named in each handler instead
28
+ type EventEmitterWithPayloads = {
29
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
30
+ addListener: (eventType: string, listener: (data: any) => void) => { remove: () => void }
31
+ }
32
+
18
33
  // Lazy initialization state
19
34
  let RNBackgroundDownloader: (RNBackgroundDownloaderModule & NativeModule) | null = null
20
35
  let turboModule: Spec | null = null
@@ -31,7 +46,7 @@ function ensureNativeModuleInitialized (): RNBackgroundDownloaderModule & Native
31
46
  return RNBackgroundDownloader
32
47
 
33
48
  // Try TurboModules first
34
- turboModule = TurboModuleRegistry.get<Spec>('RNBackgroundDownloader')
49
+ turboModule = TurboModuleRegistry.get<Spec>('RNBackgroundDownloader') ?? null
35
50
  // Check if iOS new architecture event emitters are available
36
51
  // On Android, we always use NativeEventEmitter because Android uses RCTDeviceEventEmitter
37
52
  isIOSNewArchitecture = Platform.OS === 'ios' && turboModule != null && typeof turboModule.onDownloadBegin === 'function'
@@ -69,8 +84,6 @@ function ensureNativeModuleInitialized (): RNBackgroundDownloaderModule & Native
69
84
  }
70
85
 
71
86
  const MIN_PROGRESS_INTERVAL = 250
72
- const tasksMap = new Map<string, DownloadTask>()
73
- const uploadTasksMap = new Map<string, UploadTask>()
74
87
 
75
88
  interface DownloadBeginEvent {
76
89
  id: string
@@ -154,7 +167,7 @@ function initializeEventListeners () {
154
167
 
155
168
  if (isIOSNewArchitecture && turboModule) {
156
169
  // iOS new architecture: use EventEmitter from TurboModule spec
157
- turboModule.onDownloadBegin((data: DownloadBeginEvent) => {
170
+ eventSubscriptions.push(turboModule.onDownloadBegin((data: DownloadBeginEvent) => {
158
171
  const { id, ...rest } = data
159
172
  log('downloadBegin', id, rest)
160
173
  const task = tasksMap.get(id)
@@ -163,9 +176,9 @@ function initializeEventListeners () {
163
176
  return
164
177
  }
165
178
  task.onBegin(rest)
166
- })
179
+ }))
167
180
 
168
- turboModule.onDownloadProgress((events: DownloadProgressEvent[]) => {
181
+ eventSubscriptions.push(turboModule.onDownloadProgress((events: DownloadProgressEvent[]) => {
169
182
  log('downloadProgress', events)
170
183
  for (const event of events) {
171
184
  const { id, ...rest } = event
@@ -173,9 +186,9 @@ function initializeEventListeners () {
173
186
  if (task)
174
187
  task.onProgress(rest)
175
188
  }
176
- })
189
+ }))
177
190
 
178
- turboModule.onDownloadComplete((data: DownloadCompleteEvent) => {
191
+ eventSubscriptions.push(turboModule.onDownloadComplete((data: DownloadCompleteEvent) => {
179
192
  const { id, ...rest } = data
180
193
  log('downloadComplete', id, rest)
181
194
  const task = tasksMap.get(id)
@@ -184,9 +197,9 @@ function initializeEventListeners () {
184
197
  else
185
198
  task.onDone(rest)
186
199
  tasksMap.delete(id)
187
- })
200
+ }))
188
201
 
189
- turboModule.onDownloadFailed((data: DownloadFailedEvent) => {
202
+ eventSubscriptions.push(turboModule.onDownloadFailed((data: DownloadFailedEvent) => {
190
203
  const { id, ...rest } = data
191
204
  log('downloadFailed', id, rest)
192
205
  const task = tasksMap.get(id)
@@ -195,11 +208,11 @@ function initializeEventListeners () {
195
208
  else
196
209
  task.onError(rest)
197
210
  tasksMap.delete(id)
198
- })
211
+ }))
199
212
 
200
213
  // Upload events for new architecture (optional - may not exist in all versions)
201
214
  if (typeof turboModule.onUploadBegin === 'function') {
202
- turboModule.onUploadBegin?.((data: UploadBeginEvent) => {
215
+ eventSubscriptions.push(turboModule.onUploadBegin!((data: UploadBeginEvent) => {
203
216
  const { id, ...rest } = data
204
217
  log('uploadBegin', id, rest)
205
218
  const task = uploadTasksMap.get(id)
@@ -208,9 +221,9 @@ function initializeEventListeners () {
208
221
  return
209
222
  }
210
223
  task.onBegin(rest)
211
- })
224
+ }))
212
225
 
213
- turboModule.onUploadProgress?.((events: UploadProgressEvent[]) => {
226
+ eventSubscriptions.push(turboModule.onUploadProgress!((events: UploadProgressEvent[]) => {
214
227
  log('uploadProgress', events)
215
228
  for (const event of events) {
216
229
  const { id, ...rest } = event
@@ -218,9 +231,9 @@ function initializeEventListeners () {
218
231
  if (task)
219
232
  task.onProgress(rest)
220
233
  }
221
- })
234
+ }))
222
235
 
223
- turboModule.onUploadComplete?.((data: UploadCompleteEvent) => {
236
+ eventSubscriptions.push(turboModule.onUploadComplete!((data: UploadCompleteEvent) => {
224
237
  const { id, ...rest } = data
225
238
  log('uploadComplete', id, rest)
226
239
  const task = uploadTasksMap.get(id)
@@ -229,9 +242,9 @@ function initializeEventListeners () {
229
242
  else
230
243
  task.onDone(rest)
231
244
  uploadTasksMap.delete(id)
232
- })
245
+ }))
233
246
 
234
- turboModule.onUploadFailed?.((data: UploadFailedEvent) => {
247
+ eventSubscriptions.push(turboModule.onUploadFailed!((data: UploadFailedEvent) => {
235
248
  const { id, ...rest } = data
236
249
  log('uploadFailed', id, rest)
237
250
  const task = uploadTasksMap.get(id)
@@ -240,14 +253,14 @@ function initializeEventListeners () {
240
253
  else
241
254
  task.onError(rest)
242
255
  uploadTasksMap.delete(id)
243
- })
256
+ }))
244
257
  }
245
258
  } else {
246
259
  // Old architecture: use NativeEventEmitter with the native module
247
260
  // RCTEventEmitter on native side requires NativeEventEmitter on JS side
248
261
  // RNBackgroundDownloader is guaranteed to be non-null here since initializeEventListeners
249
262
  // is only called after ensureNativeModuleInitialized() succeeds
250
- const eventEmitter = new NativeEventEmitter(RNBackgroundDownloader!)
263
+ const eventEmitter: EventEmitterWithPayloads = new NativeEventEmitter(RNBackgroundDownloader!)
251
264
 
252
265
  eventSubscriptions.push(
253
266
  eventEmitter.addListener('downloadBegin', (data: DownloadBeginEvent) => {
@@ -364,11 +377,12 @@ function initializeEventListeners () {
364
377
  // Event listeners are now initialized lazily when ensureNativeModuleInitialized() is called
365
378
  // This ensures the bridge is ready before any native module access
366
379
 
380
+ // Only the options passed are changed; the rest keep their current values
367
381
  export function setConfig ({
368
- headers = {},
369
- progressInterval = DEFAULT_PROGRESS_INTERVAL,
370
- progressMinBytes = DEFAULT_PROGRESS_MIN_BYTES,
371
- isLogsEnabled = false,
382
+ headers,
383
+ progressInterval,
384
+ progressMinBytes,
385
+ isLogsEnabled,
372
386
  logCallback,
373
387
  maxParallelDownloads,
374
388
  allowsCellularAccess,
@@ -378,20 +392,23 @@ export function setConfig ({
378
392
  notificationsGrouping,
379
393
  iosDataProtection,
380
394
  }: Config) {
381
- config.headers = headers
395
+ if (headers !== undefined)
396
+ config.headers = headers
382
397
 
383
398
  if (iosDataProtection !== undefined)
384
399
  config.iosDataProtection = iosDataProtection
385
400
 
386
- if (progressInterval >= MIN_PROGRESS_INTERVAL)
387
- config.progressInterval = progressInterval
388
- else
389
- console.warn(`[RNBackgroundDownloader] progressInterval must be a number >= ${MIN_PROGRESS_INTERVAL}. You passed ${progressInterval}`)
401
+ if (progressInterval !== undefined)
402
+ if (progressInterval >= MIN_PROGRESS_INTERVAL)
403
+ config.progressInterval = progressInterval
404
+ else
405
+ console.warn(`[RNBackgroundDownloader] progressInterval must be a number >= ${MIN_PROGRESS_INTERVAL}. You passed ${progressInterval}`)
390
406
 
391
- if (progressMinBytes >= 0)
392
- config.progressMinBytes = progressMinBytes
393
- else
394
- console.warn(`[RNBackgroundDownloader] progressMinBytes must be a number >= 0. You passed ${progressMinBytes}`)
407
+ if (progressMinBytes !== undefined)
408
+ if (progressMinBytes >= 0)
409
+ config.progressMinBytes = progressMinBytes
410
+ else
411
+ console.warn(`[RNBackgroundDownloader] progressMinBytes must be a number >= 0. You passed ${progressMinBytes}`)
395
412
 
396
413
  if (maxParallelDownloads !== undefined)
397
414
  if (maxParallelDownloads >= 1)
@@ -424,8 +441,10 @@ export function setConfig ({
424
441
  },
425
442
  }
426
443
 
427
- config.isLogsEnabled = isLogsEnabled
428
- config.logCallback = logCallback
444
+ if (isLogsEnabled !== undefined)
445
+ config.isLogsEnabled = isLogsEnabled
446
+ if (logCallback !== undefined)
447
+ config.logCallback = logCallback
429
448
 
430
449
  // Notify native side about configuration changes
431
450
  try {
@@ -442,7 +461,7 @@ export function setConfig ({
442
461
  texts: Record<string, string>
443
462
  }) => void
444
463
  }
445
- if (nativeModule.setLogsEnabled)
464
+ if (nativeModule.setLogsEnabled && isLogsEnabled !== undefined)
446
465
  nativeModule.setLogsEnabled(isLogsEnabled)
447
466
  // Only call native methods if config was successfully updated
448
467
  if (nativeModule.setMaxParallelDownloads && maxParallelDownloads !== undefined && maxParallelDownloads >= 1)
@@ -499,7 +518,8 @@ export const getExistingDownloadTasks = async (): Promise<DownloadTask[]> => {
499
518
  if (taskInfo.errorCode === -999) {
500
519
  task.state = 'PAUSED'
501
520
  } else {
502
- task.stop()
521
+ // Not awaited: the task is dropped either way, so a failed stop isn't actionable
522
+ task.stop().catch(() => {})
503
523
  return undefined
504
524
  }
505
525
  break
@@ -534,8 +554,12 @@ export const completeHandler = (jobId: string) => {
534
554
 
535
555
  export function createDownloadTask ({
536
556
  isAllowedOverRoaming = true,
537
- isAllowedOverMetered = true,
557
+ // Follows setConfig({ allowsCellularAccess }) unless the task sets its own
558
+ isAllowedOverMetered = config.allowsCellularAccess,
538
559
  metadata,
560
+ groupId,
561
+ groupName,
562
+ notificationTitle,
539
563
  ...rest
540
564
  }: TaskInfo & DownloadParams) {
541
565
  // Ensure native module and event listeners are initialized before creating tasks
@@ -548,9 +572,14 @@ export function createDownloadTask ({
548
572
 
549
573
  rest.destination = rest.destination.replace('file://', '')
550
574
 
575
+ // Native reads the notification fields from metadata only
576
+ const notificationFields = Object.fromEntries(
577
+ Object.entries({ groupId, groupName, notificationTitle }).filter(([, value]) => value !== undefined)
578
+ )
579
+
551
580
  const task = new DownloadTask({
552
581
  id: rest.id,
553
- metadata,
582
+ metadata: Object.keys(notificationFields).length > 0 ? { ...metadata, ...notificationFields } : metadata,
554
583
  })
555
584
 
556
585
  task.setDownloadParams({
@@ -604,7 +633,8 @@ export const getExistingUploadTasks = async (): Promise<UploadTask[]> => {
604
633
  if (taskInfo.errorCode === -999) {
605
634
  task.state = 'PAUSED'
606
635
  } else {
607
- task.stop()
636
+ // Not awaited: the task is dropped either way, so a failed stop isn't actionable
637
+ task.stop().catch(() => {})
608
638
  return undefined
609
639
  }
610
640
  break
@@ -629,7 +659,8 @@ export const getExistingUploadTasks = async (): Promise<UploadTask[]> => {
629
659
 
630
660
  export function createUploadTask ({
631
661
  isAllowedOverRoaming = true,
632
- isAllowedOverMetered = true,
662
+ // Follows setConfig({ allowsCellularAccess }) unless the task sets its own
663
+ isAllowedOverMetered = config.allowsCellularAccess,
633
664
  metadata,
634
665
  ...rest
635
666
  }: UploadTaskInfo & UploadParams) {
package/src/tasks.ts ADDED
@@ -0,0 +1,7 @@
1
+ import type { DownloadTask } from './DownloadTask'
2
+ import type { UploadTask } from './UploadTask'
3
+
4
+ // Tasks that native events are delivered to, by id. In their own module so a task can remove
5
+ // itself on stop without a circular import of index.
6
+ export const tasksMap = new Map<string, DownloadTask>()
7
+ export const uploadTasksMap = new Map<string, UploadTask>()