@hxa-rn/react-native-background-actions 4.1.0 → 4.1.1

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.
package/src/index.ts CHANGED
@@ -1,131 +1,131 @@
1
- // Copyright (c) 2026 hxa-rn
2
- import {Platform as RNPlatform, AppRegistry} from 'react-native';
3
- import EventEmitter from 'eventemitter3';
4
- import {backgroundTimers} from './BackgroundTimers';
5
- import {RNBackgroundActions, nativeEventEmitter, BackgroundEventSubscription} from './RNBackgroundActionsModule';
6
- import type {NativeOptions, TaskIcon, ProgressBar} from './specs/v1/NativeRNBackgroundActionsSpec';
7
- const Platform: {OS: string} = RNPlatform;
8
- export type ForegroundServiceType = 'dataSync' | 'mediaPlayback' | 'phoneCall' | 'location' |
9
- 'connectedDevice' | 'mediaProjection' | 'camera' | 'microphone' | 'health' |
10
- 'remoteMessaging' | 'systemExempted' | 'shortService' | 'specialUse';
11
- export type BackgroundTaskOptions = {
12
- taskName: string; taskTitle: string; taskDesc: string; taskIcon: TaskIcon;
13
- color?: string; linkingURI?: string; progressBar?: ProgressBar;
14
- foregroundServiceType?: ForegroundServiceType[];
15
- harmonyBackgroundModes?: Array<'bluetoothInteraction' | 'multiDeviceConnection' | 'audioRecording' | 'audioPlayback'>;
16
- };
17
- type RuntimeOptions = NativeOptions & {generation: number};
18
- export type NotificationPatch = Partial<Omit<BackgroundTaskOptions, 'taskName' | 'foregroundServiceType' | 'harmonyBackgroundModes'>>;
19
- export type TaskFailure = {code: string; message: string; generation: number};
20
- function invalid(message: string): Error { return new Error(`E_INVALID_OPTIONS: ${message}`); }
21
- class BackgroundServer extends EventEmitter {
22
- private generation = 0;
23
- private stopVersion = 0;
24
- private tail: Promise<void> = Promise.resolve();
25
- private options?: RuntimeOptions;
26
- private subscription?: BackgroundEventSubscription;
27
- private enqueue<T>(operation: () => Promise<T>): Promise<T> {
28
- const result = this.tail.then(operation);
29
- this.tail = result.then(() => undefined, () => undefined);
30
- return result;
31
- }
32
- private subscribe(): void {
33
- if (this.subscription && !this.subscription.removed) return;
34
- this.subscription = nativeEventEmitter.addListener('expiration', (event: {generation: number}) => {
35
- if (event?.generation !== this.options?.generation) return;
36
- this.options = undefined;
37
- backgroundTimers.deactivate();
38
- this.unsubscribe();
39
- this.emit('expiration');
40
- });
41
- }
42
- private unsubscribe(): void { this.subscription?.remove(); this.subscription = undefined; }
43
- private normalize(options: BackgroundTaskOptions, generation: number): RuntimeOptions {
44
- if (!options || typeof options.taskName !== 'string' || !options.taskName.trim()) throw invalid('taskName must be nonempty');
45
- if (typeof options.taskTitle !== 'string' || typeof options.taskDesc !== 'string') throw invalid('title/description must be strings (empty allowed)');
46
- const icon = options.taskIcon;
47
- if (!icon || typeof icon.name !== 'string' || !icon.name || typeof icon.type !== 'string') throw invalid('taskIcon is required');
48
- if (!['mipmap', 'drawable', 'media'].includes(icon.type)) throw invalid('icon.type must be mipmap/drawable/media');
49
- if (icon.package !== undefined && typeof icon.package !== 'string') throw invalid('icon.package must be string');
50
- const types = options.foregroundServiceType;
51
- if (options.harmonyBackgroundModes !== undefined && (!Array.isArray(options.harmonyBackgroundModes) || options.harmonyBackgroundModes.some(m => typeof m !== 'string'))) throw invalid('harmonyBackgroundModes must be a string array');
52
- if (types !== undefined && (!Array.isArray(types) || types.some(t => typeof t !== 'string'))) throw invalid('foregroundServiceType must be a string array');
53
- if (options.linkingURI !== undefined && (typeof options.linkingURI !== 'string' || !/^[a-zA-Z][a-zA-Z0-9+.-]*:\S+$/.test(options.linkingURI))) throw invalid('linkingURI must be an absolute URI');
54
- const progress = options.progressBar;
55
- if (progress != null && (typeof progress !== 'object' || Array.isArray(progress))) throw invalid('progressBar must be an object');
56
- if (progress && (!Number.isFinite(progress.max) || !Number.isFinite(progress.value) || Math.floor(progress.max) <= 0 || Math.floor(progress.value) < 0 || Math.floor(progress.value) > Math.floor(progress.max) || (progress.indeterminate !== undefined && typeof progress.indeterminate !== 'boolean'))) throw invalid('progress requires max > 0 and 0 <= value <= max');
57
- return {taskName: options.taskName, taskTitle: options.taskTitle, taskDesc: options.taskDesc,
58
- taskIcon: {...icon}, color: typeof options.color === 'string' ? options.color : '#ffffff',
59
- linkingURI: options.linkingURI, progressBar: progress ? {...progress} : undefined,
60
- foregroundServiceType: types ? [...types] : undefined, harmonyBackgroundModes: options.harmonyBackgroundModes ? [...options.harmonyBackgroundModes] : undefined, generation};
61
- }
62
- isRunning(): boolean { return RNBackgroundActions.isRunning(); }
63
- start<T>(task: (parameters?: T) => Promise<void>, options: BackgroundTaskOptions & {parameters?: T}): Promise<void> {
64
- if (typeof task !== 'function') return Promise.reject(invalid('task must be a function'));
65
- const generation = this.generation + 1;
66
- let normalized: RuntimeOptions;
67
- try { normalized = this.normalize(options, generation); } catch (error) { return Promise.reject(error); }
68
- this.generation = generation;
69
- const stopVersion = this.stopVersion;
70
- return this.enqueue(async () => {
71
- const previous = this.options;
72
- this.subscribe();
73
- try { await RNBackgroundActions.start(normalized); }
74
- catch (error) {
75
- if (previous && this.isRunning()) {
76
- this.options = previous;
77
- } else { this.options = undefined; backgroundTimers.deactivate(); this.unsubscribe(); }
78
- throw error;
79
- }
80
- this.options = normalized;
81
- if (stopVersion !== this.stopVersion) return;
82
- if (Platform.OS === 'harmony') backgroundTimers.activate();
83
- const execute = async () => {
84
- try {
85
- if (stopVersion !== this.stopVersion || !this.isRunning()) return;
86
- const result = task(options.parameters);
87
- if (!result || typeof result.then !== 'function') throw invalid('task must return Promise<void>');
88
- await result;
89
- } catch (error) {
90
- const failure: TaskFailure = {code: 'E_TASK', message: String(error), generation};
91
- this.emit('taskError', failure);
92
- } finally {
93
- try {
94
- await this.enqueue(async () => {
95
- if (this.options?.generation !== generation) return;
96
- await RNBackgroundActions.stop();
97
- this.options = undefined;
98
- backgroundTimers.deactivate();
99
- this.unsubscribe();
100
- });
101
- } catch (error) {
102
- this.emit('taskError', {code: 'E_CLEANUP', message: String(error), generation});
103
- }
104
- }
105
- };
106
- if (Platform.OS === 'harmony') { void execute(); }
107
- else if (Platform.OS === 'android') { AppRegistry.registerHeadlessTask(normalized.taskName, () => execute); }
108
- });
109
- }
110
- stop(): Promise<void> {
111
- ++this.stopVersion;
112
- return this.enqueue(async () => {
113
- await RNBackgroundActions.stop();
114
- this.options = undefined;
115
- backgroundTimers.deactivate();
116
- this.unsubscribe();
117
- });
118
- }
119
- updateNotification(patch: NotificationPatch): Promise<void> {
120
- return this.enqueue(async () => {
121
- if (!this.isRunning() || !this.options) throw new Error('E_NOT_RUNNING: A BackgroundAction must be running before updating the notification');
122
- const candidate = this.normalize({...this.options, ...patch} as BackgroundTaskOptions, this.options.generation);
123
- await RNBackgroundActions.updateNotification(candidate);
124
- if (this.options?.generation !== candidate.generation || !this.isRunning()) {
125
- throw new Error('E_TASK_ENDED: Task ended during notification update');
126
- }
127
- this.options = candidate;
128
- });
129
- }
130
- }
131
- export default new BackgroundServer();
1
+ // Copyright (c) 2026 hxa-rn
2
+ import {Platform as RNPlatform, AppRegistry} from 'react-native';
3
+ import EventEmitter from 'eventemitter3';
4
+ import {backgroundTimers} from './BackgroundTimers';
5
+ import {RNBackgroundActions, nativeEventEmitter, BackgroundEventSubscription} from './RNBackgroundActionsModule';
6
+ import type {NativeOptions, TaskIcon, ProgressBar} from './specs/v1/NativeRNBackgroundActionsSpec';
7
+ const Platform: {OS: string} = RNPlatform;
8
+ export type ForegroundServiceType = 'dataSync' | 'mediaPlayback' | 'phoneCall' | 'location' |
9
+ 'connectedDevice' | 'mediaProjection' | 'camera' | 'microphone' | 'health' |
10
+ 'remoteMessaging' | 'systemExempted' | 'shortService' | 'specialUse';
11
+ export type BackgroundTaskOptions = {
12
+ taskName: string; taskTitle: string; taskDesc: string; taskIcon: TaskIcon;
13
+ color?: string; linkingURI?: string; progressBar?: ProgressBar;
14
+ foregroundServiceType?: ForegroundServiceType[];
15
+ harmonyBackgroundModes?: Array<'bluetoothInteraction' | 'multiDeviceConnection' | 'audioRecording' | 'audioPlayback'>;
16
+ };
17
+ type RuntimeOptions = NativeOptions & {generation: number};
18
+ export type NotificationPatch = Partial<Omit<BackgroundTaskOptions, 'taskName' | 'foregroundServiceType' | 'harmonyBackgroundModes'>>;
19
+ export type TaskFailure = {code: string; message: string; generation: number};
20
+ function invalid(message: string): Error { return new Error(`E_INVALID_OPTIONS: ${message}`); }
21
+ class BackgroundServer extends EventEmitter {
22
+ private generation = 0;
23
+ private stopVersion = 0;
24
+ private tail: Promise<void> = Promise.resolve();
25
+ private options?: RuntimeOptions;
26
+ private subscription?: BackgroundEventSubscription;
27
+ private enqueue<T>(operation: () => Promise<T>): Promise<T> {
28
+ const result = this.tail.then(operation);
29
+ this.tail = result.then(() => undefined, () => undefined);
30
+ return result;
31
+ }
32
+ private subscribe(): void {
33
+ if (this.subscription && !this.subscription.removed) return;
34
+ this.subscription = nativeEventEmitter.addListener('expiration', (event: {generation: number}) => {
35
+ if (event?.generation !== this.options?.generation) return;
36
+ this.options = undefined;
37
+ backgroundTimers.deactivate();
38
+ this.unsubscribe();
39
+ this.emit('expiration');
40
+ });
41
+ }
42
+ private unsubscribe(): void { this.subscription?.remove(); this.subscription = undefined; }
43
+ private normalize(options: BackgroundTaskOptions, generation: number): RuntimeOptions {
44
+ if (!options || typeof options.taskName !== 'string' || !options.taskName.trim()) throw invalid('taskName must be nonempty');
45
+ if (typeof options.taskTitle !== 'string' || typeof options.taskDesc !== 'string') throw invalid('title/description must be strings (empty allowed)');
46
+ const icon = options.taskIcon;
47
+ if (!icon || typeof icon.name !== 'string' || !icon.name || typeof icon.type !== 'string') throw invalid('taskIcon is required');
48
+ if (!['mipmap', 'drawable', 'media'].includes(icon.type)) throw invalid('icon.type must be mipmap/drawable/media');
49
+ if (icon.package !== undefined && typeof icon.package !== 'string') throw invalid('icon.package must be string');
50
+ const types = options.foregroundServiceType;
51
+ if (options.harmonyBackgroundModes !== undefined && (!Array.isArray(options.harmonyBackgroundModes) || options.harmonyBackgroundModes.some(m => typeof m !== 'string'))) throw invalid('harmonyBackgroundModes must be a string array');
52
+ if (types !== undefined && (!Array.isArray(types) || types.some(t => typeof t !== 'string'))) throw invalid('foregroundServiceType must be a string array');
53
+ if (options.linkingURI !== undefined && (typeof options.linkingURI !== 'string' || !/^[a-zA-Z][a-zA-Z0-9+.-]*:\S+$/.test(options.linkingURI))) throw invalid('linkingURI must be an absolute URI');
54
+ const progress = options.progressBar;
55
+ if (progress != null && (typeof progress !== 'object' || Array.isArray(progress))) throw invalid('progressBar must be an object');
56
+ if (progress && (!Number.isFinite(progress.max) || !Number.isFinite(progress.value) || Math.floor(progress.max) <= 0 || Math.floor(progress.value) < 0 || Math.floor(progress.value) > Math.floor(progress.max) || (progress.indeterminate !== undefined && typeof progress.indeterminate !== 'boolean'))) throw invalid('progress requires max > 0 and 0 <= value <= max');
57
+ return {taskName: options.taskName, taskTitle: options.taskTitle, taskDesc: options.taskDesc,
58
+ taskIcon: {...icon}, color: typeof options.color === 'string' ? options.color : '#ffffff',
59
+ linkingURI: options.linkingURI, progressBar: progress ? {...progress} : undefined,
60
+ foregroundServiceType: types ? [...types] : undefined, harmonyBackgroundModes: options.harmonyBackgroundModes ? [...options.harmonyBackgroundModes] : undefined, generation};
61
+ }
62
+ isRunning(): boolean { return RNBackgroundActions.isRunning(); }
63
+ start<T>(task: (parameters?: T) => Promise<void>, options: BackgroundTaskOptions & {parameters?: T}): Promise<void> {
64
+ if (typeof task !== 'function') return Promise.reject(invalid('task must be a function'));
65
+ const generation = this.generation + 1;
66
+ let normalized: RuntimeOptions;
67
+ try { normalized = this.normalize(options, generation); } catch (error) { return Promise.reject(error); }
68
+ this.generation = generation;
69
+ const stopVersion = this.stopVersion;
70
+ return this.enqueue(async () => {
71
+ const previous = this.options;
72
+ this.subscribe();
73
+ try { await RNBackgroundActions.start(normalized); }
74
+ catch (error) {
75
+ if (previous && this.isRunning()) {
76
+ this.options = previous;
77
+ } else { this.options = undefined; backgroundTimers.deactivate(); this.unsubscribe(); }
78
+ throw error;
79
+ }
80
+ this.options = normalized;
81
+ if (stopVersion !== this.stopVersion) return;
82
+ if (Platform.OS === 'harmony') backgroundTimers.activate();
83
+ const execute = async () => {
84
+ try {
85
+ if (stopVersion !== this.stopVersion || !this.isRunning()) return;
86
+ const result = task(options.parameters);
87
+ if (!result || typeof result.then !== 'function') throw invalid('task must return Promise<void>');
88
+ await result;
89
+ } catch (error) {
90
+ const failure: TaskFailure = {code: 'E_TASK', message: String(error), generation};
91
+ this.emit('taskError', failure);
92
+ } finally {
93
+ try {
94
+ await this.enqueue(async () => {
95
+ if (this.options?.generation !== generation) return;
96
+ await RNBackgroundActions.stop();
97
+ this.options = undefined;
98
+ backgroundTimers.deactivate();
99
+ this.unsubscribe();
100
+ });
101
+ } catch (error) {
102
+ this.emit('taskError', {code: 'E_CLEANUP', message: String(error), generation});
103
+ }
104
+ }
105
+ };
106
+ if (Platform.OS === 'harmony') { void execute(); }
107
+ else if (Platform.OS === 'android') { AppRegistry.registerHeadlessTask(normalized.taskName, () => execute); }
108
+ });
109
+ }
110
+ stop(): Promise<void> {
111
+ ++this.stopVersion;
112
+ return this.enqueue(async () => {
113
+ await RNBackgroundActions.stop();
114
+ this.options = undefined;
115
+ backgroundTimers.deactivate();
116
+ this.unsubscribe();
117
+ });
118
+ }
119
+ updateNotification(patch: NotificationPatch): Promise<void> {
120
+ return this.enqueue(async () => {
121
+ if (!this.isRunning() || !this.options) throw new Error('E_NOT_RUNNING: A BackgroundAction must be running before updating the notification');
122
+ const candidate = this.normalize({...this.options, ...patch} as BackgroundTaskOptions, this.options.generation);
123
+ await RNBackgroundActions.updateNotification(candidate);
124
+ if (this.options?.generation !== candidate.generation || !this.isRunning()) {
125
+ throw new Error('E_TASK_ENDED: Task ended during notification update');
126
+ }
127
+ this.options = candidate;
128
+ });
129
+ }
130
+ }
131
+ export default new BackgroundServer();