@octane-xplat/background-tasks 0.0.1 → 0.18.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/LICENSE ADDED
@@ -0,0 +1,21 @@
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.
package/README.md ADDED
@@ -0,0 +1,26 @@
1
+ # `@octane-xplat/background-tasks`
2
+
3
+ ```sh
4
+ pnpm add @octane-xplat/background-tasks
5
+ ```
6
+
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`.
package/package.json CHANGED
@@ -1,11 +1,95 @@
1
1
  {
2
- "name": "@octane-xplat/background-tasks",
3
- "version": "0.0.1",
4
- "description": "Placeholder release — no supported API. The first real version publishes via octane-xplat CI.",
5
- "license": "MIT",
6
- "repository": {
7
- "type": "git",
8
- "url": "https://github.com/octane-xplat/octane-xplat",
9
- "directory": "packages/background-tasks"
10
- }
11
- }
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
+ }
@@ -0,0 +1,4 @@
1
+ <manifest xmlns:android="http://schemas.android.com/apk/res/android">
2
+ <!-- WorkManager registers its initializer via a library content provider;
3
+ no app manifest entries are required. -->
4
+ </manifest>
@@ -0,0 +1,3 @@
1
+ dependencies {
2
+ implementation "androidx.work:work-runtime:2.9.1"
3
+ }
@@ -0,0 +1,25 @@
1
+ package com.octanexplat.tasks;
2
+
3
+ import android.content.Context;
4
+ import androidx.work.*;
5
+ import com.tns.Utils;
6
+ import java.util.concurrent.TimeUnit;
7
+
8
+ public class TaskScheduler {
9
+ public static void schedule(String name, long intervalSeconds) {
10
+ long interval = Math.max(intervalSeconds, 15 * 60); // WorkManager floor
11
+ PeriodicWorkRequest request = new PeriodicWorkRequest.Builder(TaskWorker.class, interval, TimeUnit.SECONDS)
12
+ .addTag("xplat:" + name)
13
+ .build();
14
+ WorkManager.getInstance(context())
15
+ .enqueueUniquePeriodicWork("xplat:" + name, ExistingPeriodicWorkPolicy.UPDATE, request);
16
+ }
17
+
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();
24
+ }
25
+ }
@@ -0,0 +1,50 @@
1
+ package com.octanexplat.tasks;
2
+
3
+ import android.content.Context;
4
+ import androidx.work.*;
5
+ import com.tns.Runtime;
6
+
7
+ public class TaskWorker extends Worker {
8
+ public TaskWorker(Context context, WorkerParameters params) {
9
+ super(context, params);
10
+ }
11
+
12
+ @Override
13
+ public Result doWork() {
14
+ String name = getTags().stream()
15
+ .filter(t -> t.startsWith("xplat:"))
16
+ .map(t -> t.substring(6))
17
+ .findFirst()
18
+ .orElse(null);
19
+ if (name == null) {
20
+ return Result.failure();
21
+ }
22
+ Runtime runtime = Runtime.getCurrentRuntime();
23
+ if (runtime == null) {
24
+ // Cold start: the runtime isn't up — WorkManager retry re-runs us.
25
+ return Result.retry();
26
+ }
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;
41
+ }
42
+ });
43
+ long waited = 0;
44
+ while (!done[0] && waited < 25_000) {
45
+ try { Thread.sleep(50); } catch (InterruptedException e) { break; }
46
+ waited += 50;
47
+ }
48
+ return ok[0] ? Result.success() : Result.retry();
49
+ }
50
+ }
@@ -0,0 +1,14 @@
1
+ <?xml version="1.0" encoding="UTF-8"?>
2
+ <!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
3
+ <plist version="1.0">
4
+ <dict>
5
+ <key>UIBackgroundModes</key>
6
+ <array>
7
+ <string>fetch</string>
8
+ <string>processing</string>
9
+ </array>
10
+ <!-- Apps must also add their task identifiers:
11
+ <key>BGTaskSchedulerPermittedIdentifiers</key>
12
+ <array><string>com.octanexplat.tasks.TASK_NAME</string></array> -->
13
+ </dict>
14
+ </plist>
@@ -0,0 +1,14 @@
1
+ // Unsupported leaf — platform-specific schedulers (NSBackgroundActivityScheduler
2
+ // on macOS) are follow-ups; the API surface stands.
3
+ import type { BackgroundTasks, TaskStatus } from './types'
4
+
5
+ const unsupported = () => Promise.reject(new Error('unsupported: background tasks are not wired on this platform'))
6
+
7
+ 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,
14
+ }
@@ -0,0 +1,14 @@
1
+ // Unsupported leaf — platform-specific schedulers (NSBackgroundActivityScheduler
2
+ // on macOS) are follow-ups; the API surface stands.
3
+ import type { BackgroundTasks, TaskStatus } from './types'
4
+
5
+ const unsupported = () => Promise.reject(new Error('unsupported: background tasks are not wired on this platform'))
6
+
7
+ 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,
14
+ }
@@ -0,0 +1,118 @@
1
+ // Background tasks — native leaf, custom bridge (no NS plugin exists).
2
+ // iOS: BGTaskScheduler app-refresh requests; the Info.plist registers the
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.
6
+ //
7
+ // defineTask bodies must be registered at module scope — the OS can invoke a
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'
12
+
13
+ declare const BGTaskScheduler: any
14
+ declare const BGAppRefreshTaskRequest: any
15
+
16
+ const executors = new Map<string, TaskExecutor>()
17
+ const registered = new Map<string, number>()
18
+
19
+ const TASK_PREFIX = 'com.octanexplat.tasks.'
20
+
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
+ }
31
+ }
32
+
33
+ // iOS BGTaskScheduler launch handler — the OS calls the registered handler on
34
+ // a background thread; we resolve via the JS executor then mark completion.
35
+ 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
+ })
44
+ }
45
+
46
+ 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
+ },
109
+ }
110
+
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
+ )
118
+ }
@@ -0,0 +1,14 @@
1
+ // Background tasks — no reliable web equivalent (Periodic Background Sync is
2
+ // Chromium-only + requires an installed PWA). Honest unsupported leaf.
3
+ import type { BackgroundTasks, TaskStatus } from './types'
4
+
5
+ const unsupported = () => Promise.reject(new Error('unsupported: no background task API on web'))
6
+
7
+ 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,
14
+ }
@@ -0,0 +1,14 @@
1
+ // Unsupported leaf — platform-specific schedulers (NSBackgroundActivityScheduler
2
+ // on macOS) are follow-ups; the API surface stands.
3
+ import type { BackgroundTasks, TaskStatus } from './types'
4
+
5
+ const unsupported = () => Promise.reject(new Error('unsupported: background tasks are not wired on this platform'))
6
+
7
+ 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,
14
+ }
@@ -0,0 +1,2 @@
1
+ export * from './types'
2
+ export { backgroundTasks } from './background-tasks.macos'
package/src/index.ts ADDED
@@ -0,0 +1,2 @@
1
+ export * from './types'
2
+ export { backgroundTasks } from './background-tasks'
@@ -0,0 +1,2 @@
1
+ export * from './types'
2
+ export { backgroundTasks } from './background-tasks.web'
package/src/types.ts ADDED
@@ -0,0 +1,23 @@
1
+ export type TaskResult = 'success' | 'failed'
2
+
3
+ export interface TaskContext {
4
+ name: string
5
+ }
6
+
7
+ export type TaskExecutor = (context: TaskContext) => Promise<TaskResult>
8
+
9
+ export type TaskStatus = 'available' | 'restricted' | 'unavailable'
10
+
11
+ 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>
21
+ }
22
+
23
+ export declare const backgroundTasks: BackgroundTasks
@@ -0,0 +1,14 @@
1
+ {
2
+ "version": 1,
3
+ "files": [
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
+ "index.d.ts",
10
+ "index.macos.d.ts",
11
+ "index.web.d.ts",
12
+ "types.d.ts"
13
+ ]
14
+ }
@@ -0,0 +1,2 @@
1
+ import type { BackgroundTasks } from './types.js';
2
+ export declare const backgroundTasks: BackgroundTasks;
@@ -0,0 +1,2 @@
1
+ import type { BackgroundTasks } from './types.js';
2
+ export declare const backgroundTasks: BackgroundTasks;
@@ -0,0 +1,2 @@
1
+ import type { BackgroundTasks } from './types.js';
2
+ export declare const backgroundTasks: BackgroundTasks;
@@ -0,0 +1,2 @@
1
+ import type { BackgroundTasks } from './types.js';
2
+ export declare const backgroundTasks: BackgroundTasks;
@@ -0,0 +1,2 @@
1
+ import type { BackgroundTasks } from './types.js';
2
+ export declare const backgroundTasks: BackgroundTasks;
@@ -0,0 +1,2 @@
1
+ export * from './types.js';
2
+ export { backgroundTasks } from './background-tasks.js';
@@ -0,0 +1,2 @@
1
+ export * from './types.js';
2
+ export { backgroundTasks } from './background-tasks.macos.js';
@@ -0,0 +1,2 @@
1
+ export * from './types.js';
2
+ export { backgroundTasks } from './background-tasks.web.js';
@@ -0,0 +1,20 @@
1
+ export type TaskResult = 'success' | 'failed';
2
+ export interface TaskContext {
3
+ name: string;
4
+ }
5
+ export type TaskExecutor = (context: TaskContext) => Promise<TaskResult>;
6
+ export type TaskStatus = 'available' | 'restricted' | 'unavailable';
7
+ export interface BackgroundTasks {
8
+ readonly supported: boolean;
9
+ /** Define a task at module scope — the OS may invoke the name before any
10
+ * other call, so registration must be load-time (expo-task-manager's
11
+ * structural constraint, mirrored deliberately). */
12
+ defineTask(name: string, executor: TaskExecutor): void;
13
+ register(name: string, options?: {
14
+ minimumInterval?: number;
15
+ }): Promise<void>;
16
+ unregister(name: string): Promise<void>;
17
+ getStatus(): Promise<TaskStatus>;
18
+ isRegistered(name: string): Promise<boolean>;
19
+ }
20
+ export declare const backgroundTasks: BackgroundTasks;