@octane-xplat/background-tasks 0.18.0 → 0.20.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.
package/README.md CHANGED
@@ -1,26 +1,5 @@
1
- # `@octane-xplat/background-tasks`
1
+ # @octane-xplat/background-tasks
2
2
 
3
- ```sh
4
- pnpm add @octane-xplat/background-tasks
5
- ```
3
+ [Documentation](https://octane-xplat.goddardai.org/package-background-tasks).
6
4
 
7
- OS-scheduled periodic work — `BGTaskScheduler` app-refresh on iOS,
8
- WorkManager periodic requests on Android (custom bridge; no NS plugin
9
- exists). Mirrors `expo-task-manager`'s structural contract: `defineTask`
10
- bodies must be declared at module scope because the OS can invoke a task on
11
- a cold start before app code runs again.
12
-
13
- ```ts
14
- import { backgroundTasks } from '@octane-xplat/background-tasks'
15
-
16
- backgroundTasks.defineTask('sync-cache', async () => {
17
- await refreshCache()
18
- return 'success'
19
- })
20
-
21
- await backgroundTasks.register('sync-cache', { minimumInterval: 3600 })
22
- ```
23
-
24
- The OS decides actual cadence — `minimumInterval` is an earliest hint, not a
25
- timer (Android WorkManager floors at 15 minutes). Web/desktop report
26
- `supported: false`.
5
+ [API reference](https://octane-xplat.goddardai.org/api-background-tasks).
package/package.json CHANGED
@@ -1,95 +1,89 @@
1
1
  {
2
- "name": "@octane-xplat/background-tasks",
3
- "version": "0.18.0",
4
- "description": "OS-scheduled periodic background work for Octane xplat — BGTaskScheduler and WorkManager",
5
- "keywords": [
6
- "android",
7
- "cross-platform",
8
- "nativescript",
9
- "octane",
10
- "xplat",
11
- "background-tasks",
12
- "background-fetch",
13
- "workmanager"
14
- ],
15
- "homepage": "https://github.com/octane-xplat/octane-xplat/tree/main/packages/background-tasks",
16
- "license": "MIT",
17
- "repository": {
18
- "type": "git",
19
- "url": "https://github.com/octane-xplat/octane-xplat",
20
- "directory": "packages/background-tasks"
21
- },
22
- "files": [
23
- "src",
24
- "platforms",
25
- "types",
26
- "!src/**/*.test.*",
27
- "!src/**/*.spec.*"
28
- ],
29
- "type": "module",
30
- "exports": {
31
- ".": {
32
- "macos": {
33
- "types": "./types/generated/index.macos.d.ts",
34
- "default": "./src/index.macos.ts"
35
- },
36
- "web": {
37
- "types": "./types/generated/index.web.d.ts",
38
- "default": "./src/index.web.ts"
39
- },
40
- "native": {
41
- "types": "./types/generated/index.d.ts",
42
- "default": "./src/index.ts"
43
- },
44
- "types": "./types/generated/index.d.ts",
45
- "default": "./src/index.ts"
46
- },
47
- "./*": {
48
- "types": "./types/generated/*.d.ts",
49
- "default": "./src/*"
50
- },
51
- "./*.ts": {
52
- "types": "./types/generated/*.d.ts",
53
- "default": "./src/*.ts"
54
- }
55
- },
56
- "publishConfig": {
57
- "access": "public"
58
- },
59
- "devDependencies": {
60
- "@nativescript-community/octane": "0.2.5",
61
- "@nativescript/core": "9.1.3",
62
- "@nativescript/types": "9.1.4",
63
- "@tsrx/typescript-plugin": "0.4.11",
64
- "octane": "0.14.0",
65
- "tsrx-typegen": "0.4.0",
66
- "typescript": "5.9.3"
67
- },
68
- "peerDependencies": {
69
- "@nativescript-community/octane": ">=0.2.1 <1",
70
- "@nativescript/core": ">=9.1.0 <10",
71
- "octane": ">=0.6.3 <1"
72
- },
73
- "peerDependenciesMeta": {
74
- "@nativescript-community/octane": {
75
- "optional": true
76
- },
77
- "@nativescript/core": {
78
- "optional": true
79
- }
80
- },
81
- "nativescript": {
82
- "platforms": {
83
- "android": "9.1.0",
84
- "ios": "9.1.0"
85
- }
86
- },
87
- "dependencies": {
88
- "@octane-xplat/platform": "0.18.0"
89
- },
90
- "scripts": {
91
- "typegen": "tsrx-typegen --target octane",
92
- "pack:check": "tsrx-typegen --pack-check",
93
- "typecheck": "node ../../scripts/typecheck.ts"
94
- }
95
- }
2
+ "name": "@octane-xplat/background-tasks",
3
+ "version": "0.20.0",
4
+ "description": "OS-scheduled periodic background work for Octane xplat — BGTaskScheduler and WorkManager",
5
+ "keywords": [
6
+ "android",
7
+ "cross-platform",
8
+ "nativescript",
9
+ "octane",
10
+ "xplat",
11
+ "background-tasks",
12
+ "background-fetch",
13
+ "workmanager"
14
+ ],
15
+ "homepage": "https://github.com/octane-xplat/octane-xplat/tree/main/packages/background-tasks",
16
+ "license": "MIT",
17
+ "repository": {
18
+ "type": "git",
19
+ "url": "https://github.com/octane-xplat/octane-xplat",
20
+ "directory": "packages/background-tasks"
21
+ },
22
+ "files": [
23
+ "src",
24
+ "platforms",
25
+ "types",
26
+ "!src/**/*.test.*",
27
+ "!src/**/*.spec.*"
28
+ ],
29
+ "type": "module",
30
+ "exports": {
31
+ ".": {
32
+ "types": "./types/generated/index.d.ts",
33
+ "macos": "./src/index.macos.ts",
34
+ "web": "./src/index.web.ts",
35
+ "native": "./src/index.ts",
36
+ "default": "./src/index.ts"
37
+ },
38
+ "./*": {
39
+ "types": "./types/generated/*.d.ts",
40
+ "default": "./src/*"
41
+ },
42
+ "./*.ts": {
43
+ "types": "./types/generated/*.d.ts",
44
+ "default": "./src/*.ts"
45
+ }
46
+ },
47
+ "publishConfig": {
48
+ "access": "public"
49
+ },
50
+ "scripts": {
51
+ "test": "node --test tests/*.test.ts tests/*.test.mjs",
52
+ "typegen": "tsrx-typegen --target octane",
53
+ "prepack": "bun run typegen && tsrx-typegen --pack-check",
54
+ "pack:check": "tsrx-typegen --pack-check",
55
+ "typecheck": "node ../../scripts/typecheck.ts"
56
+ },
57
+ "devDependencies": {
58
+ "@nativescript-community/octane": "0.2.5",
59
+ "@nativescript/core": "9.1.3",
60
+ "@nativescript/types": "9.1.4",
61
+ "octane": "0.16.3",
62
+ "tsrx-typegen": "0.6.1",
63
+ "typescript": "7.1.0-beta",
64
+ "@tsrx/content-mapper": "0.1.2",
65
+ "typescript-classic": "npm:typescript@5.9.3"
66
+ },
67
+ "peerDependencies": {
68
+ "@nativescript-community/octane": ">=0.2.1 <1",
69
+ "@nativescript/core": ">=9.1.0 <10",
70
+ "octane": ">=0.6.3 <1"
71
+ },
72
+ "peerDependenciesMeta": {
73
+ "@nativescript-community/octane": {
74
+ "optional": true
75
+ },
76
+ "@nativescript/core": {
77
+ "optional": true
78
+ }
79
+ },
80
+ "nativescript": {
81
+ "platforms": {
82
+ "android": "9.1.0",
83
+ "ios": "9.1.0"
84
+ }
85
+ },
86
+ "dependencies": {
87
+ "@octane-xplat/platform": "0.20.0"
88
+ }
89
+ }
@@ -2,24 +2,19 @@ package com.octanexplat.tasks;
2
2
 
3
3
  import android.content.Context;
4
4
  import androidx.work.*;
5
- import com.tns.Utils;
6
5
  import java.util.concurrent.TimeUnit;
7
6
 
8
7
  public class TaskScheduler {
9
- public static void schedule(String name, long intervalSeconds) {
8
+ public static void schedule(Context context, String name, long intervalSeconds) {
10
9
  long interval = Math.max(intervalSeconds, 15 * 60); // WorkManager floor
11
10
  PeriodicWorkRequest request = new PeriodicWorkRequest.Builder(TaskWorker.class, interval, TimeUnit.SECONDS)
12
11
  .addTag("xplat:" + name)
13
12
  .build();
14
- WorkManager.getInstance(context())
13
+ WorkManager.getInstance(context.getApplicationContext())
15
14
  .enqueueUniquePeriodicWork("xplat:" + name, ExistingPeriodicWorkPolicy.UPDATE, request);
16
15
  }
17
16
 
18
- public static void cancel(String name) {
19
- WorkManager.getInstance(context()).cancelUniqueWork("xplat:" + name);
20
- }
21
-
22
- private static Context context() {
23
- return Utils.getApplicationContext();
17
+ public static void cancel(Context context, String name) {
18
+ WorkManager.getInstance(context.getApplicationContext()).cancelUniqueWork("xplat:" + name);
24
19
  }
25
20
  }
@@ -3,8 +3,49 @@ package com.octanexplat.tasks;
3
3
  import android.content.Context;
4
4
  import androidx.work.*;
5
5
  import com.tns.Runtime;
6
+ import java.util.concurrent.CountDownLatch;
7
+ import java.util.concurrent.TimeUnit;
6
8
 
7
9
  public class TaskWorker extends Worker {
10
+ private static final long RESULT_TIMEOUT_MS = 25_000;
11
+
12
+ // Implemented by the JS module. Calls dispatched from Java run on the JS
13
+ // thread through the NativeScript proxy and block until it returns.
14
+ public interface TaskRunner {
15
+ void run(String name, TaskOutcome outcome);
16
+ }
17
+
18
+ // The JS side reports the executor's settled result through onResult;
19
+ // the first report wins and releases the waiting worker thread.
20
+ public static class TaskOutcome {
21
+ private final CountDownLatch done = new CountDownLatch(1);
22
+ private volatile String result = "failed";
23
+
24
+ public void onResult(String value) {
25
+ if (done.getCount() == 0) {
26
+ return;
27
+ }
28
+ result = value == null ? "failed" : value;
29
+ done.countDown();
30
+ }
31
+
32
+ String result() {
33
+ return result;
34
+ }
35
+
36
+ boolean await() throws InterruptedException {
37
+ return done.await(RESULT_TIMEOUT_MS, TimeUnit.MILLISECONDS);
38
+ }
39
+ }
40
+
41
+ private static volatile TaskRunner runner;
42
+
43
+ // The JS module registers its runner at evaluation time — the supported
44
+ // Java→JS bridge needs a JS-implemented object, not a global function.
45
+ public static void setTaskRunner(TaskRunner taskRunner) {
46
+ runner = taskRunner;
47
+ }
48
+
8
49
  public TaskWorker(Context context, WorkerParameters params) {
9
50
  super(context, params);
10
51
  }
@@ -19,32 +60,29 @@ public class TaskWorker extends Worker {
19
60
  if (name == null) {
20
61
  return Result.failure();
21
62
  }
22
- Runtime runtime = Runtime.getCurrentRuntime();
23
- if (runtime == null) {
63
+ if (Runtime.getCurrentRuntime() == null) {
24
64
  // Cold start: the runtime isn't up — WorkManager retry re-runs us.
25
65
  return Result.retry();
26
66
  }
27
- final boolean[] done = { false };
28
- final boolean[] ok = { false };
29
- runtime.runOnJSThread(() -> {
30
- try {
31
- Object fn = ((com.tns.Runtime) runtime).callJSMethod(
32
- com.tns.Runtime.getCurrentRuntime(),
33
- "global.__xplatBackgroundTaskRun",
34
- Object.class,
35
- name,
36
- (com.tns.CompletionListener) null);
37
- ok[0] = !"failed".equals(String.valueOf(fn));
38
- } catch (Throwable ignored) {
39
- } finally {
40
- done[0] = true;
67
+ TaskRunner taskRunner = runner;
68
+ if (taskRunner == null) {
69
+ // Warm runtime whose module evaluation never registered a runner.
70
+ return Result.retry();
71
+ }
72
+ TaskOutcome outcome = new TaskOutcome();
73
+ try {
74
+ taskRunner.run(name, outcome);
75
+ } catch (Throwable t) {
76
+ return Result.retry();
77
+ }
78
+ try {
79
+ if (!outcome.await()) {
80
+ return Result.retry();
41
81
  }
42
- });
43
- long waited = 0;
44
- while (!done[0] && waited < 25_000) {
45
- try { Thread.sleep(50); } catch (InterruptedException e) { break; }
46
- waited += 50;
82
+ } catch (InterruptedException e) {
83
+ Thread.currentThread().interrupt();
84
+ return Result.retry();
47
85
  }
48
- return ok[0] ? Result.success() : Result.retry();
86
+ return "success".equals(outcome.result()) ? Result.success() : Result.retry();
49
87
  }
50
88
  }
@@ -2,13 +2,15 @@
2
2
  // on macOS) are follow-ups; the API surface stands.
3
3
  import type { BackgroundTasks, TaskStatus } from './types'
4
4
 
5
- const unsupported = () => Promise.reject(new Error('unsupported: background tasks are not wired on this platform'))
5
+ const unsupported = () =>
6
+ Promise.reject(new Error('unsupported: background tasks are not wired on this platform'))
6
7
 
8
+ /** Background-task scheduler service — see BackgroundTasks for the contract. */
7
9
  export const backgroundTasks: BackgroundTasks = {
8
- supported: false,
9
- defineTask: () => {},
10
- register: unsupported,
11
- unregister: unsupported,
12
- getStatus: async (): Promise<TaskStatus> => 'unavailable',
13
- isRegistered: async () => false,
10
+ supported: false,
11
+ defineTask: () => {},
12
+ register: unsupported,
13
+ unregister: unsupported,
14
+ getStatus: async (): Promise<TaskStatus> => 'unavailable',
15
+ isRegistered: async () => false,
14
16
  }
@@ -1,14 +1,89 @@
1
- // Unsupported leaf — platform-specific schedulers (NSBackgroundActivityScheduler
2
- // on macOS) are follow-ups; the API surface stands.
3
- import type { BackgroundTasks, TaskStatus } from './types'
1
+ // Background tasks — AppKit leaf over NSBackgroundActivityScheduler. The
2
+ // scheduler is deferrable maintenance work: `interval` is a request the OS
3
+ // may stretch, the app must be running (no launch-on-event), and a deferred
4
+ // fire surfaces TaskResult through the executor's completion.
5
+ import { NSBackgroundActivityScheduler } from '@octane-xplat/platform/macos'
6
+ import type { BackgroundTasks, TaskExecutor, TaskResult, TaskStatus } from './types'
4
7
 
5
- const unsupported = () => Promise.reject(new Error('unsupported: background tasks are not wired on this platform'))
8
+ // NSBackgroundActivityResult: 1 deferred, 2 finished.
9
+ const RESULT_FINISHED = 2
10
+ const RESULT_DEFERRED = 1
6
11
 
12
+ const executors = new Map<string, TaskExecutor>()
13
+ const schedulers = new Map<string, any>()
14
+
15
+ const schedulerClass = (): any => {
16
+ try {
17
+ return typeof NSBackgroundActivityScheduler?.alloc === 'function'
18
+ ? NSBackgroundActivityScheduler
19
+ : null
20
+ } catch {
21
+ return null
22
+ }
23
+ }
24
+
25
+ /** Background-task scheduler service — see BackgroundTasks for the contract. */
7
26
  export const backgroundTasks: BackgroundTasks = {
8
- supported: false,
9
- defineTask: () => {},
10
- register: unsupported,
11
- unregister: unsupported,
12
- getStatus: async (): Promise<TaskStatus> => 'unavailable',
13
- isRegistered: async () => false,
27
+ get supported() {
28
+ return schedulerClass() !== null
29
+ },
30
+
31
+ defineTask(name: string, executor: TaskExecutor): void {
32
+ executors.set(name, executor)
33
+ },
34
+
35
+ register: async (name: string, options?: { minimumInterval?: number }): Promise<void> => {
36
+ if (!executors.has(name)) {
37
+ throw new Error(`backgroundTasks.register: no task defined as '${name}'`)
38
+ }
39
+
40
+ const klass = schedulerClass()
41
+
42
+ if (!klass) {
43
+ throw new Error('backgroundTasks.register: NSBackgroundActivityScheduler is unavailable')
44
+ }
45
+
46
+ backgroundTasks.unregister(name).catch(() => {})
47
+
48
+ const scheduler = klass.alloc().initWithIdentifier(`xplat.background.${name}`)
49
+
50
+ scheduler.repeats = true
51
+ scheduler.interval = Math.max(options?.minimumInterval ?? 3600, 60)
52
+ scheduler.tolerance = scheduler.interval / 2
53
+ scheduler.qualityOfService = 0x09 // NSQualityOfServiceBackground
54
+ scheduler.scheduleWithBlock((completion: (result: number) => void) => {
55
+ const executor = executors.get(name)
56
+
57
+ if (scheduler.shouldDefer || !executor) {
58
+ completion(RESULT_DEFERRED)
59
+ return
60
+ }
61
+
62
+ Promise.resolve()
63
+ .then(() => executor({ name, expired: false }))
64
+ .then((result: TaskResult) =>
65
+ completion(result === 'success' ? RESULT_FINISHED : RESULT_DEFERRED),
66
+ )
67
+ .catch(() => completion(RESULT_DEFERRED))
68
+ })
69
+
70
+ schedulers.set(name, scheduler)
71
+ },
72
+
73
+ unregister: async (name: string): Promise<void> => {
74
+ const scheduler = schedulers.get(name)
75
+
76
+ if (scheduler) {
77
+ schedulers.delete(name)
78
+ try {
79
+ scheduler.invalidate()
80
+ } catch {
81
+ // Invalidating a released scheduler must not poison unregister.
82
+ }
83
+ }
84
+ },
85
+
86
+ getStatus: async (): Promise<TaskStatus> => (schedulerClass() ? 'available' : 'unavailable'),
87
+
88
+ isRegistered: async (name: string): Promise<boolean> => schedulers.has(name),
14
89
  }
@@ -1,118 +1,260 @@
1
1
  // Background tasks — native leaf, custom bridge (no NS plugin exists).
2
2
  // iOS: BGTaskScheduler app-refresh requests; the Info.plist registers the
3
3
  // task identifier and UIBackgroundModes fetch. Android: WorkManager periodic
4
- // requests through platforms/android Gradle deps; the Worker spins up the
5
- // runtime and calls back into __xplatBackgroundTaskRun.
4
+ // requests through platforms/android Gradle deps; the Worker dispatches to
5
+ // the TaskRunner registered below while a runtime is warm.
6
6
  //
7
7
  // defineTask bodies must be registered at module scope — the OS can invoke a
8
8
  // task before app code runs again, and a relaunch only re-evaluates module
9
- // top-level. expo-task-manager's constraint, mirrored deliberately.
10
- import { Application, Utils, isIOS } from '@nativescript/core'
11
- import type { BackgroundTasks, TaskExecutor, TaskResult, TaskStatus } from './types'
9
+ // top-level. That placement is also Apple's registration window: launch
10
+ // handlers must be registered before app launch finishes, and a second
11
+ // registration of the same identifier kills the app. defineTask therefore
12
+ // owns iOS handler registration (once per identifier); register/unregister
13
+ // only submit or cancel refresh requests and are safe to repeat.
14
+ import { isIOS, Utils } from '@nativescript/core'
15
+ import type { BackgroundTasks, TaskContext, TaskExecutor, TaskResult, TaskStatus } from './types'
12
16
 
13
17
  declare const BGTaskScheduler: any
14
18
  declare const BGAppRefreshTaskRequest: any
19
+ declare const interop: any
15
20
 
16
21
  const executors = new Map<string, TaskExecutor>()
17
22
  const registered = new Map<string, number>()
23
+ const handledIdentifiers = new Set<string>()
24
+ const handlerReady = new Set<string>()
18
25
 
19
26
  const TASK_PREFIX = 'com.octanexplat.tasks.'
20
27
 
21
- async function runTask(name: string): Promise<TaskResult> {
22
- const executor = executors.get(name)
23
- if (!executor) {
24
- return 'failed'
25
- }
26
- try {
27
- return (await executor({ name })) ?? 'success'
28
- } catch {
29
- return 'failed'
30
- }
28
+ async function runTask(name: string, context: TaskContext): Promise<TaskResult> {
29
+ const executor = executors.get(name)
30
+
31
+ if (!executor) {
32
+ return 'failed'
33
+ }
34
+
35
+ try {
36
+ return (await executor(context)) ?? 'success'
37
+ } catch {
38
+ return 'failed'
39
+ }
40
+ }
41
+
42
+ // iOS: submit (or replace) the pending refresh request for a task. Each
43
+ // request is consumed by one run, so enable/reschedule and the post-run
44
+ // resubmission share this path. Cancelling first keeps repeated calls
45
+ // idempotent — submitting over a pending request can fail with
46
+ // BGTaskSchedulerErrorCodeTooManyPendingTaskRequests. Submitting without a
47
+ // registered launch handler is not a soft failure: BGTaskScheduler raises an
48
+ // uncatchable NSInternalInconsistencyException that kills the process, so the
49
+ // ready check is a hard gate.
50
+ function iosSubmit(name: string): void {
51
+ const identifier = TASK_PREFIX + name
52
+
53
+ if (!handlerReady.has(name)) {
54
+ throw new Error(
55
+ `backgroundTasks.register: '${name}' has no registered iOS launch handler — ` +
56
+ `its defineTask must run at module scope so registration finishes before app launch completes`,
57
+ )
58
+ }
59
+
60
+ BGTaskScheduler.sharedScheduler.cancelTaskRequestWithIdentifier(identifier)
61
+
62
+ const request = BGAppRefreshTaskRequest.alloc().initWithIdentifier(identifier)
63
+ const interval = registered.get(name)
64
+
65
+ if (interval) {
66
+ request.earliestBeginDate = (globalThis as any).NSDate.dateWithTimeIntervalSinceNow(interval)
67
+ }
68
+
69
+ const errorRef = typeof interop !== 'undefined' ? new interop.Reference() : null
70
+ const submitted = BGTaskScheduler.sharedScheduler.submitTaskRequestError(request, errorRef)
71
+
72
+ if (!submitted) {
73
+ const detail = errorRef?.value?.localizedDescription ?? 'unknown scheduler error'
74
+
75
+ throw new Error(
76
+ `backgroundTasks.register: refresh request for '${name}' was rejected — ${detail}. ` +
77
+ `Confirm ${identifier} is in BGTaskSchedulerPermittedIdentifiers and UIBackgroundModes includes fetch`,
78
+ )
79
+ }
31
80
  }
32
81
 
33
82
  // iOS BGTaskScheduler launch handler — the OS calls the registered handler on
34
- // a background thread; we resolve via the JS executor then mark completion.
83
+ // a background thread; we resolve via the JS executor, report its real outcome
84
+ // then resubmit the request while the task stays registered. Completion and
85
+ // expiration funnel through one flag: whichever reaches the OS first marks the
86
+ // task exactly once, and a late executor result is discarded.
35
87
  function iosHandle(task: any): void {
36
- const identifier: string = task?.identifier ?? ''
37
- const name = identifier.startsWith(TASK_PREFIX) ? identifier.slice(TASK_PREFIX.length) : identifier
38
- task.expirationHandler = () => {}
39
- runTask(name).finally(() => {
40
- try {
41
- task.setTaskCompletedWithSuccess(true)
42
- } catch {}
43
- })
88
+ const identifier: string = task?.identifier ?? ''
89
+ const name = identifier.startsWith(TASK_PREFIX)
90
+ ? identifier.slice(TASK_PREFIX.length)
91
+ : identifier
92
+
93
+ let expired = false
94
+ let completed = false
95
+ const complete = (success: boolean) => {
96
+ if (completed) {
97
+ return
98
+ }
99
+
100
+ completed = true
101
+ try {
102
+ task.setTaskCompletedWithSuccess(success)
103
+ } catch {}
104
+
105
+ // Requests are single-shot — this run consumed it. Resubmit while the
106
+ // task stays registered so refresh recurs; a run that ended by
107
+ // expiration still leaves the schedule alive.
108
+ if (registered.has(name)) {
109
+ try {
110
+ iosSubmit(name)
111
+ } catch {}
112
+ }
113
+ }
114
+
115
+ task.expirationHandler = () => {
116
+ expired = true
117
+ // The OS is reclaiming the run. The executor may still be mid-flight —
118
+ // signal it cooperatively and complete now; waiting for it risks the
119
+ // process being terminated with the task never marked finished.
120
+ complete(false)
121
+ }
122
+
123
+ const context: TaskContext = {
124
+ name,
125
+ get expired() {
126
+ return expired
127
+ },
128
+ }
129
+
130
+ runTask(name, context).then(
131
+ (result) => complete(result === 'success'),
132
+ () => complete(false),
133
+ )
44
134
  }
45
135
 
136
+ /** Background-task scheduler service — see BackgroundTasks for the contract. */
46
137
  export const backgroundTasks: BackgroundTasks = {
47
- supported: isIOS ? typeof BGTaskScheduler !== 'undefined' : true,
48
-
49
- defineTask(name: string, executor: TaskExecutor): void {
50
- executors.set(name, executor)
51
- },
52
-
53
- async register(name: string, options?: { minimumInterval?: number }): Promise<void> {
54
- if (!executors.has(name)) {
55
- throw new Error(`backgroundTasks.register: '${name}' has no defineTask — declare it at module scope`)
56
- }
57
- registered.set(name, options?.minimumInterval ?? 0)
58
- if (isIOS) {
59
- if (typeof BGTaskScheduler === 'undefined') {
60
- throw new Error('unsupported: BGTaskScheduler is not available')
61
- }
62
- const identifier = TASK_PREFIX + name
63
- BGTaskScheduler.sharedScheduler.registerForTaskWithIdentifierLaunchHandler(
64
- identifier,
65
- null,
66
- iosHandle,
67
- )
68
- const request = BGAppRefreshTaskRequest.alloc().initWithIdentifier(identifier)
69
- const interval = options?.minimumInterval
70
- if (interval) {
71
- request.earliestBeginDate = (globalThis as any).NSDate.dateWithTimeIntervalSinceNow(interval)
72
- }
73
- BGTaskScheduler.sharedScheduler.submitTaskRequestError(request, null)
74
- return
75
- }
76
- // Android: WorkManager — the Java side reads the registered map off the
77
- // global so a cold start rebuilds scheduled work from defineTask calls.
78
- const worker = (globalThis as any).com?.octanexplat?.tasks?.TaskScheduler
79
- if (worker?.schedule) {
80
- worker.schedule(name, options?.minimumInterval ?? 0)
81
- }
82
- },
83
-
84
- async unregister(name: string): Promise<void> {
85
- registered.delete(name)
86
- if (isIOS) {
87
- BGTaskScheduler.sharedScheduler?.cancelTaskRequestWithIdentifier?.(TASK_PREFIX + name)
88
- return
89
- }
90
- const worker = (globalThis as any).com?.octanexplat?.tasks?.TaskScheduler
91
- worker?.cancel?.(name)
92
- },
93
-
94
- async getStatus(): Promise<TaskStatus> {
95
- if (isIOS) {
96
- if (typeof BGTaskScheduler === 'undefined') {
97
- return 'unavailable'
98
- }
99
- const status = (globalThis as any).UIApplication?.sharedApplication?.backgroundRefreshStatus
100
- // UIBackgroundRefreshStatus: 0 restricted, 1 denied, 2 available
101
- return status === 0 || status === 1 ? 'restricted' : 'available'
102
- }
103
- return 'available'
104
- },
105
-
106
- async isRegistered(name: string): Promise<boolean> {
107
- return registered.has(name)
108
- },
138
+ supported: isIOS ? typeof BGTaskScheduler !== 'undefined' : true,
139
+
140
+ defineTask(name: string, executor: TaskExecutor): void {
141
+ executors.set(name, executor)
142
+ // iOS: Apple's launch-handler registration. Module scope is already the
143
+ // contract, which is exactly Apple's "before app launch finishes" window.
144
+ // Registration is once per identifier — a second registration of the
145
+ // same identifier kills the app, so a failure is never retried. An
146
+ // "already registered" failure still marks the identifier ready: a module
147
+ // re-eval (hot reload) finds the handler the first evaluation registered.
148
+ if (isIOS && typeof BGTaskScheduler !== 'undefined' && !handledIdentifiers.has(name)) {
149
+ handledIdentifiers.add(name)
150
+ try {
151
+ const registeredHandler =
152
+ BGTaskScheduler.sharedScheduler.registerForTaskWithIdentifierUsingQueueLaunchHandler(
153
+ TASK_PREFIX + name,
154
+ null,
155
+ iosHandle,
156
+ )
157
+
158
+ if (registeredHandler) {
159
+ handlerReady.add(name)
160
+ }
161
+ } catch (error) {
162
+ if (/already been registered/i.test(String(error))) {
163
+ handlerReady.add(name)
164
+ }
165
+ }
166
+ }
167
+ },
168
+
169
+ async register(name: string, options?: { minimumInterval?: number }): Promise<void> {
170
+ if (!executors.has(name)) {
171
+ throw new Error(
172
+ `backgroundTasks.register: '${name}' has no defineTask — declare it at module scope`,
173
+ )
174
+ }
175
+
176
+ if (isIOS) {
177
+ if (typeof BGTaskScheduler === 'undefined') {
178
+ throw new Error('unsupported: BGTaskScheduler is not available')
179
+ }
180
+
181
+ registered.set(name, options?.minimumInterval ?? 0)
182
+ try {
183
+ iosSubmit(name)
184
+ } catch (error) {
185
+ registered.delete(name)
186
+ throw error
187
+ }
188
+
189
+ return
190
+ }
191
+
192
+ // Android: WorkManager — the Java side reads the registered map off the
193
+ // global so a cold start rebuilds scheduled work from defineTask calls.
194
+ // `Utils.android` is a {} stub off Android, so the context stays absent
195
+ // and scheduling is skipped there.
196
+ const worker = (globalThis as any).com?.octanexplat?.tasks?.TaskScheduler
197
+ const context = (Utils.android as any)?.getApplicationContext?.()
198
+
199
+ if (worker?.schedule && context) {
200
+ worker.schedule(context, name, options?.minimumInterval ?? 0)
201
+ }
202
+
203
+ registered.set(name, options?.minimumInterval ?? 0)
204
+ },
205
+
206
+ async unregister(name: string): Promise<void> {
207
+ registered.delete(name)
208
+ if (isIOS) {
209
+ BGTaskScheduler.sharedScheduler?.cancelTaskRequestWithIdentifier?.(TASK_PREFIX + name)
210
+ return
211
+ }
212
+
213
+ const worker = (globalThis as any).com?.octanexplat?.tasks?.TaskScheduler
214
+ const context = (Utils.android as any)?.getApplicationContext?.()
215
+
216
+ if (context) {
217
+ worker?.cancel?.(context, name)
218
+ }
219
+ },
220
+
221
+ async getStatus(): Promise<TaskStatus> {
222
+ if (isIOS) {
223
+ if (typeof BGTaskScheduler === 'undefined') {
224
+ return 'unavailable'
225
+ }
226
+
227
+ const status = (globalThis as any).UIApplication?.sharedApplication?.backgroundRefreshStatus
228
+
229
+ // UIBackgroundRefreshStatus: 0 restricted, 1 denied, 2 available
230
+ return status === 0 || status === 1 ? 'restricted' : 'available'
231
+ }
232
+
233
+ return 'available'
234
+ },
235
+
236
+ async isRegistered(name: string): Promise<boolean> {
237
+ return registered.has(name)
238
+ },
109
239
  }
110
240
 
111
- // Worker → JS entry. platforms/android's TaskWorker calls this after bringing
112
- // the runtime up; buffered invocations replay once an executor exists.
113
- ;(globalThis as any).__xplatBackgroundTaskRun = (name: string, done: (r: string) => void) => {
114
- runTask(name).then(
115
- (r) => done(r),
116
- () => done('failed'),
117
- )
241
+ // Worker → JS entry. Android's TaskWorker invokes the TaskRunner registered
242
+ // at module evaluation — calls from the worker thread dispatch onto the JS
243
+ // thread, then the worker blocks on TaskOutcome until the executor settles.
244
+ const taskWorker = (globalThis as any).com?.octanexplat?.tasks?.TaskWorker
245
+
246
+ if (!isIOS && typeof taskWorker?.setTaskRunner === 'function') {
247
+ taskWorker.setTaskRunner(
248
+ new taskWorker.TaskRunner({
249
+ run(name: string, outcome: { onResult(r: string): void }) {
250
+ const report = (r: string) => {
251
+ try {
252
+ outcome.onResult(r)
253
+ } catch {}
254
+ }
255
+
256
+ runTask(name, { name, expired: false }).then(report, () => report('failed'))
257
+ },
258
+ }),
259
+ )
118
260
  }
@@ -4,11 +4,12 @@ import type { BackgroundTasks, TaskStatus } from './types'
4
4
 
5
5
  const unsupported = () => Promise.reject(new Error('unsupported: no background task API on web'))
6
6
 
7
+ /** Background-task scheduler service — see BackgroundTasks for the contract. */
7
8
  export const backgroundTasks: BackgroundTasks = {
8
- supported: false,
9
- defineTask: () => {},
10
- register: unsupported,
11
- unregister: unsupported,
12
- getStatus: async (): Promise<TaskStatus> => 'unavailable',
13
- isRegistered: async () => false,
9
+ supported: false,
10
+ defineTask: () => {},
11
+ register: unsupported,
12
+ unregister: unsupported,
13
+ getStatus: async (): Promise<TaskStatus> => 'unavailable',
14
+ isRegistered: async () => false,
14
15
  }
@@ -2,13 +2,15 @@
2
2
  // on macOS) are follow-ups; the API surface stands.
3
3
  import type { BackgroundTasks, TaskStatus } from './types'
4
4
 
5
- const unsupported = () => Promise.reject(new Error('unsupported: background tasks are not wired on this platform'))
5
+ const unsupported = () =>
6
+ Promise.reject(new Error('unsupported: background tasks are not wired on this platform'))
6
7
 
8
+ /** Background-task scheduler service — see BackgroundTasks for the contract. */
7
9
  export const backgroundTasks: BackgroundTasks = {
8
- supported: false,
9
- defineTask: () => {},
10
- register: unsupported,
11
- unregister: unsupported,
12
- getStatus: async (): Promise<TaskStatus> => 'unavailable',
13
- isRegistered: async () => false,
10
+ supported: false,
11
+ defineTask: () => {},
12
+ register: unsupported,
13
+ unregister: unsupported,
14
+ getStatus: async (): Promise<TaskStatus> => 'unavailable',
15
+ isRegistered: async () => false,
14
16
  }
package/src/types.ts CHANGED
@@ -1,23 +1,57 @@
1
+ /** Reported outcome of a task run — the OS uses it for scheduling heuristics
2
+ * (repeated 'failed' runs get deferred on both stores). */
1
3
  export type TaskResult = 'success' | 'failed'
2
4
 
5
+ /** Invocation payload handed to a TaskExecutor. */
3
6
  export interface TaskContext {
4
- name: string
7
+ /** The registered task name — one executor may serve several names. */
8
+ name: string
9
+ /** true once the OS has reclaimed the run's time budget (the iOS
10
+ * expiration handler). Cancellation is cooperative: the executor cannot
11
+ * be preempted, so check this between awaits and resolve promptly. The
12
+ * task is already being completed as failed — a late result is
13
+ * discarded. Always false on platforms without an expiration concept. */
14
+ readonly expired: boolean
5
15
  }
6
16
 
17
+ /** The task body; resolves 'success' | 'failed' for OS scheduling feedback. */
7
18
  export type TaskExecutor = (context: TaskContext) => Promise<TaskResult>
8
19
 
20
+ /** OS willingness to run background tasks — 'restricted' means the user or
21
+ * a battery/data saver mode has throttled them; 'unavailable' means the
22
+ * platform has no background-task path at all. */
9
23
  export type TaskStatus = 'available' | 'restricted' | 'unavailable'
10
24
 
25
+ /** Background-task façade. Tasks are defined at module scope, then
26
+ * enabled/disabled against the OS scheduler (iOS BGTaskScheduler /
27
+ * Android WorkManager-style periodic work). Intervals are minimums — the OS
28
+ * decides actual timing. */
11
29
  export interface BackgroundTasks {
12
- readonly supported: boolean
13
- /** Define a task at module scope — the OS may invoke the name before any
14
- * other call, so registration must be load-time (expo-task-manager's
15
- * structural constraint, mirrored deliberately). */
16
- defineTask(name: string, executor: TaskExecutor): void
17
- register(name: string, options?: { minimumInterval?: number }): Promise<void>
18
- unregister(name: string): Promise<void>
19
- getStatus(): Promise<TaskStatus>
20
- isRegistered(name: string): Promise<boolean>
30
+ /** Synchronous fast check — a background-task scheduler exists. */
31
+ readonly supported: boolean
32
+ /** Define a task at module scope — the OS may invoke the name before any
33
+ * other call, so registration must be load-time (expo-task-manager's
34
+ * structural constraint, mirrored deliberately). On iOS this is also
35
+ * Apple's launch-handler registration, which must finish before app
36
+ * launch completes and is registered once per task for the process'
37
+ * lifetime — module scope is what makes both requirements safe. */
38
+ defineTask(name: string, executor: TaskExecutor): void
39
+ /** Enable or reschedule a defined task by submitting the next refresh
40
+ * request. Idempotent — a repeated call replaces the pending request, so
41
+ * it is safe to call at every launch or from an enable action. iOS
42
+ * requests are single-shot: the scheduler resubmits after each run while
43
+ * the task stays enabled. `minimumInterval` is a hint in scheduler units
44
+ * (seconds on iOS via earliestBeginDate) — the OS decides actual timing
45
+ * and may defer well past it. */
46
+ register(name: string, options?: { minimumInterval?: number }): Promise<void>
47
+ /** Cancel a previously enabled task's pending request; no-op when not
48
+ * enabled. Does not interrupt an executor already running. */
49
+ unregister(name: string): Promise<void>
50
+ /** Current OS scheduling posture for this app. */
51
+ getStatus(): Promise<TaskStatus>
52
+ /** Whether `name` is enabled in this process — an in-memory record, not a
53
+ * query of the OS's durable request queue. */
54
+ isRegistered(name: string): Promise<boolean>
21
55
  }
22
56
 
23
57
  export declare const backgroundTasks: BackgroundTasks
@@ -2,13 +2,7 @@
2
2
  "version": 1,
3
3
  "files": [
4
4
  "background-tasks.d.ts",
5
- "background-tasks.linux.d.ts",
6
- "background-tasks.macos.d.ts",
7
- "background-tasks.web.d.ts",
8
- "background-tasks.windows.d.ts",
9
5
  "index.d.ts",
10
- "index.macos.d.ts",
11
- "index.web.d.ts",
12
6
  "types.d.ts"
13
7
  ]
14
8
  }
@@ -1,2 +1,3 @@
1
1
  import type { BackgroundTasks } from './types.js';
2
+ /** Background-task scheduler service — see BackgroundTasks for the contract. */
2
3
  export declare const backgroundTasks: BackgroundTasks;
@@ -1,20 +1,54 @@
1
+ /** Reported outcome of a task run — the OS uses it for scheduling heuristics
2
+ * (repeated 'failed' runs get deferred on both stores). */
1
3
  export type TaskResult = 'success' | 'failed';
4
+ /** Invocation payload handed to a TaskExecutor. */
2
5
  export interface TaskContext {
6
+ /** The registered task name — one executor may serve several names. */
3
7
  name: string;
8
+ /** true once the OS has reclaimed the run's time budget (the iOS
9
+ * expiration handler). Cancellation is cooperative: the executor cannot
10
+ * be preempted, so check this between awaits and resolve promptly. The
11
+ * task is already being completed as failed — a late result is
12
+ * discarded. Always false on platforms without an expiration concept. */
13
+ readonly expired: boolean;
4
14
  }
15
+ /** The task body; resolves 'success' | 'failed' for OS scheduling feedback. */
5
16
  export type TaskExecutor = (context: TaskContext) => Promise<TaskResult>;
17
+ /** OS willingness to run background tasks — 'restricted' means the user or
18
+ * a battery/data saver mode has throttled them; 'unavailable' means the
19
+ * platform has no background-task path at all. */
6
20
  export type TaskStatus = 'available' | 'restricted' | 'unavailable';
21
+ /** Background-task façade. Tasks are defined at module scope, then
22
+ * enabled/disabled against the OS scheduler (iOS BGTaskScheduler /
23
+ * Android WorkManager-style periodic work). Intervals are minimums — the OS
24
+ * decides actual timing. */
7
25
  export interface BackgroundTasks {
26
+ /** Synchronous fast check — a background-task scheduler exists. */
8
27
  readonly supported: boolean;
9
28
  /** Define a task at module scope — the OS may invoke the name before any
10
29
  * other call, so registration must be load-time (expo-task-manager's
11
- * structural constraint, mirrored deliberately). */
30
+ * structural constraint, mirrored deliberately). On iOS this is also
31
+ * Apple's launch-handler registration, which must finish before app
32
+ * launch completes and is registered once per task for the process'
33
+ * lifetime — module scope is what makes both requirements safe. */
12
34
  defineTask(name: string, executor: TaskExecutor): void;
35
+ /** Enable or reschedule a defined task by submitting the next refresh
36
+ * request. Idempotent — a repeated call replaces the pending request, so
37
+ * it is safe to call at every launch or from an enable action. iOS
38
+ * requests are single-shot: the scheduler resubmits after each run while
39
+ * the task stays enabled. `minimumInterval` is a hint in scheduler units
40
+ * (seconds on iOS via earliestBeginDate) — the OS decides actual timing
41
+ * and may defer well past it. */
13
42
  register(name: string, options?: {
14
43
  minimumInterval?: number;
15
44
  }): Promise<void>;
45
+ /** Cancel a previously enabled task's pending request; no-op when not
46
+ * enabled. Does not interrupt an executor already running. */
16
47
  unregister(name: string): Promise<void>;
48
+ /** Current OS scheduling posture for this app. */
17
49
  getStatus(): Promise<TaskStatus>;
50
+ /** Whether `name` is enabled in this process — an in-memory record, not a
51
+ * query of the OS's durable request queue. */
18
52
  isRegistered(name: string): Promise<boolean>;
19
53
  }
20
54
  export declare const backgroundTasks: BackgroundTasks;
package/LICENSE DELETED
@@ -1,21 +0,0 @@
1
- The MIT License (MIT)
2
-
3
- Copyright (c) 2026 Alec Larson
4
-
5
- Permission is hereby granted, free of charge, to any person obtaining a copy
6
- of this software and associated documentation files (the "Software"), to deal
7
- in the Software without restriction, including without limitation the rights
8
- to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
- copies of the Software, and to permit persons to whom the Software is
10
- furnished to do so, subject to the following conditions:
11
-
12
- The above copyright notice and this permission notice shall be included in
13
- all copies or substantial portions of the Software.
14
-
15
- THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
- IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
- FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
- AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
- LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
- OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
21
- THE SOFTWARE.
@@ -1,2 +0,0 @@
1
- import type { BackgroundTasks } from './types.js';
2
- export declare const backgroundTasks: BackgroundTasks;
@@ -1,2 +0,0 @@
1
- import type { BackgroundTasks } from './types.js';
2
- export declare const backgroundTasks: BackgroundTasks;
@@ -1,2 +0,0 @@
1
- import type { BackgroundTasks } from './types.js';
2
- export declare const backgroundTasks: BackgroundTasks;
@@ -1,2 +0,0 @@
1
- import type { BackgroundTasks } from './types.js';
2
- export declare const backgroundTasks: BackgroundTasks;
@@ -1,2 +0,0 @@
1
- export * from './types.js';
2
- export { backgroundTasks } from './background-tasks.macos.js';
@@ -1,2 +0,0 @@
1
- export * from './types.js';
2
- export { backgroundTasks } from './background-tasks.web.js';