native-update 5.0.0 → 5.0.2

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.
@@ -10,10 +10,11 @@ yarn add native-update
10
10
 
11
11
  ## Core Concepts
12
12
 
13
- Native Update provides three main features:
13
+ Native Update provides four main feature areas:
14
14
  1. **Live Updates (OTA)** - Deploy JS/HTML/CSS updates without app store approval
15
15
  2. **App Updates** - Native app store update management (Google Play, App Store)
16
16
  3. **App Reviews** - In-app review prompts
17
+ 4. **Background Update** - Scheduled native availability checks and optional notifications
17
18
 
18
19
  ## Quick Start
19
20
 
@@ -25,7 +26,7 @@ import { NativeUpdate } from 'native-update';
25
26
  // Configure the plugin (nested UpdateConfig — one section per feature)
26
27
  await NativeUpdate.configure({
27
28
  liveUpdate: {
28
- appId: 'com.your.app',
29
+ appId: '550e8400-e29b-41d4-a716-446655440000', // UUID issued by the dashboard; not the native package ID
29
30
  // Canonical rule: serverUrl is the backend base; the plugin appends
30
31
  // /v1/updates/check. Hosted backend: https://nativeupdatebe.aoneahsan.com/api
31
32
  serverUrl: 'https://nativeupdatebe.aoneahsan.com/api',
@@ -35,8 +36,7 @@ await NativeUpdate.configure({
35
36
  publicKey: import.meta.env.VITE_NATIVE_UPDATE_PUBLIC_KEY,
36
37
  requireSignature: true,
37
38
  channel: 'production', // e.g. 'development' | 'staging' | 'production'
38
- autoUpdate: true,
39
- updateStrategy: 'background', // 'immediate' | 'background' | 'manual'
39
+ autoUpdate: false, // native sync() checks only; download and apply explicitly
40
40
  },
41
41
  });
42
42
  ```
@@ -46,43 +46,41 @@ await NativeUpdate.configure({
46
46
  ```typescript
47
47
  import { NativeUpdate } from 'native-update';
48
48
 
49
- // Check and apply updates — sync() reports a status enum
50
- const result = await NativeUpdate.sync();
51
- if (result.status === 'UPDATE_INSTALLED') {
52
- // sync() already downloaded + staged the bundle
53
- await NativeUpdate.reload();
54
- }
49
+ // Confirm the current bundle after a successful render.
50
+ await NativeUpdate.notifyAppReady();
55
51
 
56
- // Manual update flow
52
+ // Native sync() only checks. Use the explicit cross-platform flow.
57
53
  const latest = await NativeUpdate.checkForUpdate();
58
54
  if (latest.available) {
59
55
  // Fetches the complete signed manifest and uses a compatible NUDELTA/1
60
56
  // patch when available, with verified full-bundle fallback.
61
- await NativeUpdate.downloadUpdate();
62
- await NativeUpdate.applyUpdate();
57
+ const bundle = await NativeUpdate.downloadUpdate();
58
+ await NativeUpdate.set({ ...bundle, applyOn: 'next-start' });
63
59
  }
64
-
65
- // Notify app is stable after update (prevents auto-rollback)
66
- await NativeUpdate.notifyAppReady();
67
60
  ```
68
61
 
69
62
  ### App Store Updates
70
63
 
71
64
  ```typescript
72
65
  import { NativeUpdate } from 'native-update';
66
+ import { Capacitor } from '@capacitor/core';
73
67
 
74
68
  // Check for app store updates
75
69
  const updateInfo = await NativeUpdate.getAppUpdateInfo();
76
- if (updateInfo.updateAvailable) {
77
- if ((updateInfo.updatePriority ?? 0) >= 4) {
78
- // Critical update - force immediate
70
+ if (updateInfo.updateAvailable && Capacitor.getPlatform() === 'android') {
71
+ if (updateInfo.immediateUpdateAllowed && (updateInfo.updatePriority ?? 0) >= 4) {
79
72
  await NativeUpdate.performImmediateUpdate();
80
- } else {
81
- // Flexible update - download in background
73
+ } else if (updateInfo.flexibleUpdateAllowed) {
74
+ const ready = await NativeUpdate.addListener('appUpdateReady', () => {
75
+ showRestartPrompt(async () => {
76
+ await ready.remove();
77
+ await NativeUpdate.completeFlexibleUpdate();
78
+ });
79
+ });
82
80
  await NativeUpdate.startFlexibleUpdate();
83
- // Later, when ready to install
84
- await NativeUpdate.completeFlexibleUpdate();
85
81
  }
82
+ } else if (updateInfo.updateAvailable) {
83
+ await NativeUpdate.openAppStore();
86
84
  }
87
85
  ```
88
86
 
@@ -105,7 +103,7 @@ if (eligibility.canRequest) {
105
103
 
106
104
  | Method | Description | Returns |
107
105
  |--------|-------------|---------|
108
- | `sync(options?)` | Check and apply updates | `Promise<SyncResult>` |
106
+ | `sync(options?)` | Check for updates on Android and iOS; use explicit download and apply methods | `Promise<SyncResult>` |
109
107
  | `download(options)` | Download specific version | `Promise<BundleInfo>` |
110
108
  | `set({ ...bundle, applyOn? })` | Make a bundle the app's bundle: `'now'` (default) switches at once, `'next-start'` (4.4.5+) stages it for the next cold start | `Promise<void>` |
111
109
  | `reload()` | Reload app with current bundle | `Promise<void>` |
@@ -153,7 +151,7 @@ interface LiveUpdateConfig {
153
151
  serverUrl?: string; // Backend base URL; checks hit {serverUrl}/v1/updates/check (HTTPS required in production)
154
152
  apiKey?: string; // Sent as X-API-Key on every check (dashboard: Apps → your app → API Keys). Since v3.1.3
155
153
  channel?: string; // Update channel (default: 'production')
156
- autoUpdate?: boolean; // Auto-check + apply updates
154
+ autoUpdate?: boolean; // Compatibility field; native sync() checks only
157
155
  updateStrategy?: 'immediate' | 'background' | 'manual';
158
156
  publicKey?: string; // RSA public key for RSA-SHA256 verification
159
157
  requireSignature?: boolean; // Reject unsigned bundles (default: true)
@@ -162,7 +160,7 @@ interface LiveUpdateConfig {
162
160
  maxBundleSize?: number; // Maximum compressed download (default: 100 MiB)
163
161
  maxUncompressedBundleSize?: number; // Native extraction cap (default: 500 MiB)
164
162
  checksumAlgorithm?: 'SHA-256' | 'SHA-512'; // (default: 'SHA-256')
165
- checkInterval?: number; // Auto-check interval
163
+ checkInterval?: number; // Compatibility field in ms; does not schedule native checks
166
164
  }
167
165
  ```
168
166
 
@@ -199,11 +197,13 @@ const stateListener = await NativeUpdate.addListener('updateStateChanged', (even
199
197
 
200
198
  ## Update Channels
201
199
 
202
- | Channel | Purpose | Auto-Update | Check Interval |
203
- |---------|---------|-------------|----------------|
204
- | `development` | Internal testing | Yes | 1 minute |
205
- | `staging` | QA/Beta testing | Configurable | 1 hour |
206
- | `production` | Live users | No (consent) | Daily |
200
+ | Channel | Typical use |
201
+ |---------|-------------|
202
+ | `development` | Internal builds and test bundles |
203
+ | `staging` | Release validation |
204
+ | `production` | Live users |
205
+
206
+ Channel names do not set an automatic check interval or install policy. The native app chooses when to call `checkForUpdate()`, `downloadUpdate()`, and `applyUpdate()`.
207
207
 
208
208
  ## Backend Requirements
209
209
 
@@ -254,10 +254,11 @@ your own backend just to hide it. In the dashboard (**Apps → API Keys →
254
254
  Restrictions**) you can lock each key to the clients that may use it:
255
255
 
256
256
  - **Web** — allowed origins (exact `https://app.example.com` or a
257
- `https://*.example.com` wildcard). Enforced against the browser's `Origin`
258
- header, so the update API is safe to call directly from your web app. (The
259
- `/v1/*` API sends permissive CORS precisely so browsers can call it; the real
260
- gate is this per-key check, not CORS.)
257
+ `https://*.example.com` wildcard). Browsers attach an `Origin` header, so
258
+ your web app can call the update API directly. A non-browser client can forge
259
+ that header; an origin restriction limits ordinary browser use but is not
260
+ proof of a caller's identity. The `/v1/*` API permits CORS; the per-key
261
+ restriction performs the server-side check.
261
262
  - **Android** — allowed apps by package name + signing-cert SHA-256/SHA-1
262
263
  (`keytool -list -printcert`; add both your upload key and the Play App
263
264
  Signing cert).
@@ -290,7 +291,8 @@ blocked by an Android/iOS restriction — web restrictions work with any version
290
291
  The native identity headers are **client-attested** (parity with Google Maps
291
292
  API-key app restrictions): they stop cross-site/casual key reuse and quota
292
293
  abuse, not a determined attacker replaying headers by hand. Only the web
293
- `Origin` check is browser-enforced.
294
+ `Origin` header is browser-controlled in browsers, but can be forged outside
295
+ them.
294
296
 
295
297
  ## CLI Tools
296
298
 
@@ -358,13 +360,13 @@ curl -H "Authorization: Bearer $NATIVE_UPDATE_TOKEN" \
358
360
  { "data": {
359
361
  "name": "GitHub Actions",
360
362
  "permissions": ["manage"],
361
- "apps": [{ "id": 12, "app_id": "com.example.app", "name": "Example" }]
363
+ "apps": [{ "id": 12, "app_id": "550e8400-e29b-41d4-a716-446655440000", "name": "Example" }]
362
364
  } }
363
365
  ```
364
366
 
365
367
  ### Endpoints
366
368
 
367
- `{app}` accepts the numeric id **or** the string `app_id` (`com.example.app`).
369
+ `{app}` accepts the numeric id **or** the string `app_id` (a server-generated UUID, for example `550e8400-e29b-41d4-a716-446655440000`).
368
370
 
369
371
  | Method | Path | Does |
370
372
  |---|---|---|
@@ -410,7 +412,7 @@ curl -X POST \
410
412
  -F "version=1.2.0" \
411
413
  -F "channel=production" \
412
414
  -F "release_notes=Bug fixes" \
413
- https://nativeupdatebe.aoneahsan.com/api/public/v1/apps/com.example.app/builds
415
+ https://nativeupdatebe.aoneahsan.com/api/public/v1/apps/550e8400-e29b-41d4-a716-446655440000/builds
414
416
  ```
415
417
 
416
418
  ```json
@@ -449,38 +451,38 @@ npx native-update token info # who am I, which apps?
449
451
  # Apps
450
452
  npx native-update apps list
451
453
  npx native-update apps create --name "Example" --bundle-id com.example.app --platform both
452
- npx native-update apps show com.example.app
453
- npx native-update apps update com.example.app --name "Example (renamed)"
454
- npx native-update apps delete com.example.app
454
+ npx native-update apps show 550e8400-e29b-41d4-a716-446655440000
455
+ npx native-update apps update 550e8400-e29b-41d4-a716-446655440000 --name "Example (renamed)"
456
+ npx native-update apps delete 550e8400-e29b-41d4-a716-446655440000
455
457
 
456
458
  # API keys
457
- npx native-update apps keys list com.example.app
458
- npx native-update apps keys create com.example.app --name production # prints the secret once
459
- npx native-update apps keys show com.example.app 6
460
- npx native-update apps keys rotate com.example.app 6
461
- npx native-update apps keys reveal com.example.app 6
462
- npx native-update apps keys restrict com.example.app 6 --origins https://app.example.com
463
- npx native-update apps keys revoke com.example.app 6
464
- npx native-update apps keys deprecate com.example.app 6
465
- npx native-update apps keys delete com.example.app 6
459
+ npx native-update apps keys list 550e8400-e29b-41d4-a716-446655440000
460
+ npx native-update apps keys create 550e8400-e29b-41d4-a716-446655440000 --name production # prints the secret once
461
+ npx native-update apps keys show 550e8400-e29b-41d4-a716-446655440000 6
462
+ npx native-update apps keys rotate 550e8400-e29b-41d4-a716-446655440000 6
463
+ npx native-update apps keys reveal 550e8400-e29b-41d4-a716-446655440000 6
464
+ npx native-update apps keys restrict 550e8400-e29b-41d4-a716-446655440000 6 --origins https://app.example.com
465
+ npx native-update apps keys revoke 550e8400-e29b-41d4-a716-446655440000 6
466
+ npx native-update apps keys deprecate 550e8400-e29b-41d4-a716-446655440000 6
467
+ npx native-update apps keys delete 550e8400-e29b-41d4-a716-446655440000 6
466
468
 
467
469
  # Signing key (public key + fingerprint only) and keystore backup
468
- npx native-update apps signing show com.example.app
469
- npx native-update apps signing create com.example.app --name release
470
- npx native-update apps signing rotate com.example.app
471
- npx native-update apps keystore upload com.example.app ./example-release.zip
472
- npx native-update apps keystore info com.example.app
473
- npx native-update apps keystore download com.example.app ./keystore.zip
474
- npx native-update apps keystore delete com.example.app
470
+ npx native-update apps signing show 550e8400-e29b-41d4-a716-446655440000
471
+ npx native-update apps signing create 550e8400-e29b-41d4-a716-446655440000 --name release
472
+ npx native-update apps signing rotate 550e8400-e29b-41d4-a716-446655440000
473
+ npx native-update apps keystore upload 550e8400-e29b-41d4-a716-446655440000 ./example-release.zip
474
+ npx native-update apps keystore info 550e8400-e29b-41d4-a716-446655440000
475
+ npx native-update apps keystore download 550e8400-e29b-41d4-a716-446655440000 ./keystore.zip
476
+ npx native-update apps keystore delete 550e8400-e29b-41d4-a716-446655440000
475
477
 
476
478
  # Builds — deploy: zips the directory, uploads, and (with --wait) blocks until
477
479
  # live. Exits non-zero if the release fails, so CI fails too.
478
- npx native-update deploy ./dist --app com.example.app --version 1.2.0 --wait
480
+ npx native-update deploy ./dist --app 550e8400-e29b-41d4-a716-446655440000 --version 1.2.0 --wait
479
481
 
480
- npx native-update builds list com.example.app
481
- npx native-update builds promote com.example.app 42 --to production
482
- npx native-update builds rollout com.example.app 42 --percent 10
483
- npx native-update builds status com.example.app 42 --set paused
482
+ npx native-update builds list 550e8400-e29b-41d4-a716-446655440000
483
+ npx native-update builds promote 550e8400-e29b-41d4-a716-446655440000 42 --to production
484
+ npx native-update builds rollout 550e8400-e29b-41d4-a716-446655440000 42 --percent 10
485
+ npx native-update builds status 550e8400-e29b-41d4-a716-446655440000 42 --set paused
484
486
  npx native-update jobs status 01hq2xk8... --wait
485
487
  ```
486
488
 
@@ -510,17 +512,24 @@ app is missing.
510
512
 
511
513
  ### Android
512
514
 
513
- No additional setup required. The plugin's own Gradle config already includes
514
- the Google Play App Update and Play Review libraries (do NOT add the legacy
515
- `com.google.android.play:core` artifact — it conflicts with them).
515
+ The plugin's Gradle config includes the Google Play App Update and Play Review
516
+ libraries (do not add the legacy `com.google.android.play:core` artifact). For
517
+ background checks, review the merged permissions and worker setup in the
518
+ [Android guide](https://nativeupdate-docs.aoneahsan.com/platforms/android).
516
519
 
517
520
  ### iOS
518
521
 
519
- No additional setup required. Uses native APIs.
522
+ Store redirects and review prompts use native APIs. Background checks require
523
+ the host app's `BGTaskSchedulerPermittedIdentifiers` entry and Background fetch
524
+ capability; see the [iOS guide](https://nativeupdate-docs.aoneahsan.com/platforms/ios).
520
525
 
521
- ### Web (Limited Support)
526
+ ### Web
522
527
 
523
- Web platform supports checking for updates only. Actual OTA updates require native platforms.
528
+ The web implementation can check service-worker registrations for updates and
529
+ offers bundle download APIs. Its `applyUpdate()` records a verified bundle and
530
+ reloads the current page; it does not install assets into a native WebView or
531
+ replace the site's deployed files. Keep Android Play and iOS App Store flows on
532
+ the corresponding native platform.
524
533
 
525
534
  ## Security Best Practices
526
535
 
@@ -540,19 +549,19 @@ import { NativeUpdate } from 'native-update';
540
549
 
541
550
  App.addListener('appStateChange', async ({ isActive }) => {
542
551
  if (isActive) {
543
- const result = await NativeUpdate.sync();
544
- if (result.status === 'UPDATE_INSTALLED') {
545
- // Show user prompt to reload (NativeUpdate.reload())
546
- }
552
+ const update = await NativeUpdate.checkForUpdate();
553
+ if (!update.available) return;
554
+ const bundle = await NativeUpdate.downloadUpdate();
555
+ await NativeUpdate.set({ ...bundle, applyOn: 'next-start' });
547
556
  }
548
557
  });
549
558
  ```
550
559
 
551
- ### Review After Positive Action
560
+ ### Review After a Completed Task
552
561
 
553
562
  ```typescript
554
- async function handlePurchaseComplete() {
555
- // After successful purchase
563
+ async function handleTaskComplete() {
564
+ // Call only after the user finishes an ordinary task in your app.
556
565
  const eligibility = await NativeUpdate.canRequestReview();
557
566
  if (eligibility.canRequest) {
558
567
  await NativeUpdate.requestReview();
package/README.md CHANGED
@@ -38,8 +38,8 @@ are available as an HTTP API for CI and coding agents.
38
38
 
39
39
  | | |
40
40
  |---|---|
41
- | **Version** | `5.0.0` |
42
- | **License** | Proprietary — free to use in your apps ([LICENSE](./LICENSE)) |
41
+ | **Version** | `5.0.2` |
42
+ | **License** | Proprietary — free to use in your apps ([Native Update License](https://unpkg.com/native-update@latest/LICENSE)) |
43
43
  | **Node** | `>=24.16.0` (install + CLI toolchain) |
44
44
  | **Platforms** | iOS 16+ (implementation pending device proof) · Android 8.0+ (API 26) · Web |
45
45
  | **Package size** | See the published npm tarball |
@@ -170,7 +170,7 @@ import { Preferences } from '@capacitor/preferences';
170
170
  await NativeUpdate.initialize({
171
171
  filesystem: Filesystem,
172
172
  preferences: Preferences,
173
- appId: 'com.example.app',
173
+ appId: '550e8400-e29b-41d4-a716-446655440000',
174
174
  serverUrl: 'https://nativeupdatebe.aoneahsan.com/api',
175
175
  apiKey: import.meta.env.VITE_NATIVE_UPDATE_API_KEY,
176
176
  publicKey: import.meta.env.VITE_NATIVE_UPDATE_PUBLIC_KEY,
@@ -182,9 +182,10 @@ await NativeUpdate.initialize({
182
182
  // bundle after two cold starts.
183
183
  await NativeUpdate.notifyAppReady();
184
184
 
185
- const result = await NativeUpdate.sync();
186
- if (result.status === 'UPDATE_INSTALLED') {
187
- await NativeUpdate.reload();
185
+ const update = await NativeUpdate.checkForUpdate();
186
+ if (update.available) {
187
+ const bundle = await NativeUpdate.downloadUpdate();
188
+ await NativeUpdate.applyUpdate(bundle.bundleId);
188
189
  }
189
190
  ```
190
191
 
@@ -193,15 +194,16 @@ if (result.status === 'UPDATE_INSTALLED') {
193
194
 
194
195
  ### Prompt before applying an update
195
196
 
196
- `sync()` reports what it found; you decide whether to interrupt the user.
197
+ Check first, then ask before downloading and applying. On Android, `sync()` only checks and does not install an update.
197
198
 
198
199
  ```ts
199
- const result = await NativeUpdate.sync();
200
+ const update = await NativeUpdate.checkForUpdate();
200
201
 
201
- if (result.status === 'UPDATE_INSTALLED') {
202
- const proceed = result.mandatory || (await askTheUser(result.version));
202
+ if (update.available && update.latestVersion) {
203
+ const proceed = update.mandatory || (await askTheUser(update.latestVersion));
203
204
  if (proceed) {
204
- await NativeUpdate.reload();
205
+ const bundle = await NativeUpdate.downloadUpdate();
206
+ await NativeUpdate.applyUpdate(bundle.bundleId);
205
207
  }
206
208
  }
207
209
  ```
@@ -240,6 +242,12 @@ if (info.updateAvailable) {
240
242
  if (info.immediateUpdateAllowed) {
241
243
  await NativeUpdate.performImmediateUpdate();
242
244
  } else if (info.flexibleUpdateAllowed) {
245
+ const ready = await NativeUpdate.addListener('appUpdateReady', () => {
246
+ showRestartPrompt(async () => {
247
+ await ready.remove();
248
+ await NativeUpdate.completeFlexibleUpdate();
249
+ });
250
+ });
243
251
  await NativeUpdate.startFlexibleUpdate();
244
252
  } else {
245
253
  await NativeUpdate.openAppStore();
@@ -277,7 +285,7 @@ if (result.held) {
277
285
  <a id="configuration"></a>
278
286
  ## ⚙️ Configuration&nbsp;[#](#configuration)
279
287
 
280
- Passed to `initialize()`. The complete set is in the
288
+ On Android, `plugins.NativeUpdate` in `capacitor.config.ts` supplies packaged defaults. A complete block can run update checks before JavaScript calls `initialize()`; values passed to `initialize()` override matching keys. Web builds still pass their own configuration. The app API key is a client credential, so restrict it to your app in the dashboard. The complete set is in the
281
289
  [configuration reference](https://nativeupdate-docs.aoneahsan.com/reference/sdk/core/config).
282
290
 
283
291
  | Option | Type | Default | What it does |
@@ -286,7 +294,7 @@ Passed to `initialize()`. The complete set is in the
286
294
  | `preferences` | `Preferences` | — | the `@capacitor/preferences` instance used to record bundle state |
287
295
  | `appId` | `string` | — | identifies your app to the update server |
288
296
  | `serverUrl` | `string` | — | base URL of the backend; the plugin appends `/v1/updates/check` |
289
- | `apiKey` | `string` | — | sent as `X-API-Key`. Not persisted — pass it on every `initialize()` |
297
+ | `apiKey` | `string` | — | sent as `X-API-Key`. Not persisted; pass it on every web boot or package it in the Android Capacitor config block |
290
298
  | `channel` | `string` | `'production'` | which release channel this install follows |
291
299
  | `autoCheck` | `boolean` | `false` | check for updates without an explicit `sync()` |
292
300
  | `autoUpdate` | `boolean` | `false` | apply what it finds without asking |
@@ -387,7 +395,7 @@ export NATIVE_UPDATE_TOKEN=nu_pat_…
387
395
 
388
396
  # Zips ./dist, uploads it, and blocks until the release is live.
389
397
  # Exits non-zero on failure, so a broken release fails the build.
390
- npx native-update deploy ./dist --app com.example.app --version 1.2.0 --wait
398
+ npx native-update deploy ./dist --app 550e8400-e29b-41d4-a716-446655440000 --version 1.2.0 --wait
391
399
  ```
392
400
 
393
401
  | Flag | Default | What it does |
@@ -535,7 +543,7 @@ indexed at [`/raw/manifest.json`](https://nativeupdate-docs.aoneahsan.com/raw/ma
535
543
  <a id="changelog"></a>
536
544
  ## 🔄 Changelog&nbsp;[#](#changelog)
537
545
 
538
- Current release: **`5.0.0`** (Capacitor 9 migration; see [migration guide](docs/MIGRATION.md)). In 4.4.5, `set()` gained `applyOn: 'next-start'`, which stages a bundle for the next cold start instead of reloading the running app. Before that, 4.4.4: `--ota-tag` reads `versionName` only from a real statement in `build.gradle`
546
+ Current release: **`5.0.2`**. CLI ZIP creation no longer depends on the vulnerable archive chain. Android now reads packaged Capacitor configuration, and flexible Play updates wait for a user-confirmed restart. The Capacitor 9 migration landed in v5; see the [migration guide](https://unpkg.com/native-update@latest/docs/MIGRATION.md). In 4.4.5, `set()` gained `applyOn: 'next-start'`, which stages a bundle for the next cold start instead of reloading the running app. Before that, 4.4.4: `--ota-tag` reads `versionName` only from a real statement in `build.gradle`
539
547
  (comments and message strings are skipped, `versionName appVersionName` is followed to its value). **`4.4.3`**: Android logs `Built <id> from a N-byte patch` when an update arrives as a `NUDELTA/1`
540
548
  patch, so you can see deltas working on a device. No API change.
541
549
 
@@ -30,7 +30,7 @@ android {
30
30
  defaultConfig {
31
31
  minSdkVersion project.minSdkVersion
32
32
  versionCode 1
33
- versionName "1.0"
33
+ versionName "5.0.2"
34
34
  testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
35
35
  // Shipped to every consuming app's R8 run (ISSUE-09).
36
36
  consumerProguardFiles 'consumer-rules.pro'
@@ -119,8 +119,17 @@ class AppUpdatePlugin(
119
119
  }
120
120
 
121
121
  fun completeFlexibleUpdate(call: PluginCall) {
122
- appUpdateManager.completeUpdate()
123
- call.resolve()
122
+ appUpdateManager.appUpdateInfo.addOnSuccessListener { info ->
123
+ if (info.installStatus() != InstallStatus.DOWNLOADED) {
124
+ call.reject("UPDATE_NOT_AVAILABLE", "No downloaded flexible update is ready to install")
125
+ return@addOnSuccessListener
126
+ }
127
+ appUpdateManager.completeUpdate()
128
+ .addOnSuccessListener { call.resolve() }
129
+ .addOnFailureListener { error -> call.reject("UPDATE_FAILED", error.message) }
130
+ }.addOnFailureListener { error ->
131
+ call.reject("UPDATE_CHECK_FAILED", error.message)
132
+ }
124
133
  }
125
134
 
126
135
  fun openAppStore(call: PluginCall) {
@@ -205,10 +214,7 @@ class AppUpdatePlugin(
205
214
 
206
215
  when (state.installStatus()) {
207
216
  InstallStatus.DOWNLOADED -> {
208
- // Update has been downloaded, prompt user to restart
209
- popupSnackbarForCompleteUpdate()
210
-
211
- // Emit ready event
217
+ // The host app asks when to restart and calls completeFlexibleUpdate().
212
218
  val readyData = JSObject()
213
219
  readyData.put("message", "Update downloaded and ready to install")
214
220
  eventListener?.invoke("appUpdateReady", readyData)
@@ -230,12 +236,6 @@ class AppUpdatePlugin(
230
236
  }
231
237
  }
232
238
 
233
- private fun popupSnackbarForCompleteUpdate() {
234
- // In a real implementation, show a snackbar or notification
235
- // For now, we'll just complete the update
236
- appUpdateManager.completeUpdate()
237
- }
238
-
239
239
  private fun getCurrentAppVersion(): String {
240
240
  return try {
241
241
  val packageInfo = context.packageManager.getPackageInfo(context.packageName, 0)
@@ -311,4 +311,4 @@ class AppUpdatePlugin(
311
311
  null
312
312
  }
313
313
  }
314
- }
314
+ }
@@ -13,6 +13,7 @@ import java.io.File
13
13
  import java.io.FileOutputStream
14
14
  import java.io.IOException
15
15
  import java.security.MessageDigest
16
+ import java.util.Locale
16
17
  import java.util.concurrent.TimeUnit
17
18
  import java.util.zip.ZipFile
18
19
 
@@ -61,7 +62,7 @@ class LiveUpdatePlugin(
61
62
 
62
63
  companion object {
63
64
  /** This plugin's version, sent as X-Sdk-Version. Kept equal to package.json by tests/sdk-version.test.ts. */
64
- const val SDK_VERSION = "5.0.0"
65
+ const val SDK_VERSION = "5.0.2"
65
66
 
66
67
  // SharedPreferences keys. Kept as constants so A2 (boot-time
67
68
  // re-verification) and A3 (crash-loop auto-rollback) stay in sync
@@ -595,6 +596,7 @@ class LiveUpdatePlugin(
595
596
  // SDK identity: the server offers this WebView only web bundles (docs/protocol/CLIENT-PROTOCOL.md).
596
597
  .header("X-Client-Sdk", "capacitor")
597
598
  .header("X-Sdk-Version", SDK_VERSION)
599
+ .header("Accept-Language", Locale.getDefault().toLanguageTag())
598
600
  .header("X-Android-Package", context.packageName)
599
601
  getBinaryVersion()?.let { requestBuilder.header("X-App-Version", it) }
600
602
  // App-identity headers for API-key client restrictions. Best-effort:
@@ -18,6 +18,8 @@ class NativeUpdatePlugin : Plugin() {
18
18
  private lateinit var backgroundUpdatePlugin: BackgroundUpdatePlugin
19
19
  private lateinit var securityManager: SecurityManager
20
20
  private var isInitialized = false
21
+ private var capacitorConfiguration: JSObject? = null
22
+ private var initializedFromCapacitorConfig = false
21
23
 
22
24
  /** The configuration that took the lock, so an identical repeat can be told apart from a change (ISSUE-16). */
23
25
  private var appliedConfiguration: String? = null
@@ -31,6 +33,21 @@ class NativeUpdatePlugin : Plugin() {
31
33
  appReviewPlugin = AppReviewPlugin(activity, context)
32
34
  backgroundUpdatePlugin = BackgroundUpdatePlugin(context)
33
35
  securityManager = SecurityManager(context)
36
+
37
+ val packagedConfig = getConfig().configJSON
38
+ if (packagedConfig.length() > 0) {
39
+ capacitorConfiguration = JSObject(packagedConfig.toString())
40
+ if (canInitializeFromCapacitorConfiguration(capacitorConfiguration!!)) {
41
+ try {
42
+ applyConfiguration(capacitorConfiguration!!)
43
+ appliedConfiguration = configurationFingerprint(capacitorConfiguration!!)
44
+ isInitialized = true
45
+ initializedFromCapacitorConfig = true
46
+ } catch (_: Exception) {
47
+ // An invalid native block can still be replaced by initialize().
48
+ }
49
+ }
50
+ }
34
51
 
35
52
  // Set up app update event listener
36
53
  appUpdatePlugin.setEventListener { eventName, data ->
@@ -83,14 +100,15 @@ class NativeUpdatePlugin : Plugin() {
83
100
  @PluginMethod
84
101
  fun initialize(call: PluginCall) {
85
102
  try {
86
- val config = call.getObject("config") ?: call.data
87
- if (isInitialized) {
103
+ val config = mergeWithCapacitorConfiguration(call.getObject("config") ?: call.data)
104
+ if (isInitialized && !initializedFromCapacitorConfig) {
88
105
  rejectUnlessSameConfiguration(call, config)
89
106
  return
90
107
  }
91
108
  applyConfiguration(config)
92
109
  appliedConfiguration = configurationFingerprint(config)
93
110
  isInitialized = true
111
+ initializedFromCapacitorConfig = false
94
112
  call.resolve()
95
113
  } catch (e: Exception) {
96
114
  call.reject("Initialization failed", e)
@@ -122,8 +140,8 @@ class NativeUpdatePlugin : Plugin() {
122
140
  // configure(UpdateConfig) — nested sections
123
141
  // Before this fix, only the wrapped shape reached native, so the
124
142
  // flat initialize() every consumer uses configured NOTHING here.
125
- val config = call.getObject("config") ?: call.data
126
- if (isInitialized) {
143
+ val config = mergeWithCapacitorConfiguration(call.getObject("config") ?: call.data)
144
+ if (isInitialized && !initializedFromCapacitorConfig) {
127
145
  rejectUnlessSameConfiguration(call, config)
128
146
  return
129
147
  }
@@ -132,6 +150,7 @@ class NativeUpdatePlugin : Plugin() {
132
150
  applyConfiguration(config)
133
151
  appliedConfiguration = configurationFingerprint(config)
134
152
  isInitialized = true
153
+ initializedFromCapacitorConfig = false
135
154
  call.resolve()
136
155
  } catch (e: Exception) {
137
156
  call.reject("Configuration failed", e)
@@ -154,6 +173,46 @@ class NativeUpdatePlugin : Plugin() {
154
173
  /** A stable comparison form; injected JS objects (filesystem, preferences) arrive as {} and compare equal. */
155
174
  private fun configurationFingerprint(config: JSObject): String = config.toString()
156
175
 
176
+ internal fun canInitializeFromCapacitorConfiguration(config: JSObject): Boolean {
177
+ val live = effectiveLiveUpdateConfig(config) ?: return true
178
+ val requiresSignature = live.getBool("requireSignature") ?: config.getBool("requireSignature") ?: true
179
+ return !live.getString("appId").isNullOrBlank() &&
180
+ live.getString("serverUrl")?.startsWith("https://") == true &&
181
+ !live.getString("apiKey").isNullOrBlank() &&
182
+ (!requiresSignature || !live.getString("publicKey").isNullOrBlank())
183
+ }
184
+
185
+ /** The packaged Capacitor block supplies defaults; JS initialization wins per key. */
186
+ private fun mergeWithCapacitorConfiguration(overrides: JSObject): JSObject =
187
+ mergeWithCapacitorConfiguration(capacitorConfiguration, overrides)
188
+
189
+ internal fun mergeWithCapacitorConfiguration(defaults: JSObject?, overrides: JSObject): JSObject {
190
+ if (defaults == null) return overrides
191
+ val merged = mergeObjects(defaults, overrides)
192
+ val defaultLive = effectiveLiveUpdateConfig(defaults)
193
+ val overrideLive = effectiveLiveUpdateConfig(overrides)
194
+ if (defaultLive != null || overrideLive != null) {
195
+ merged.put("liveUpdate", mergeObjects(defaultLive ?: JSObject(), overrideLive ?: JSObject()))
196
+ }
197
+ return merged
198
+ }
199
+
200
+ private fun mergeObjects(defaults: JSObject, overrides: JSObject): JSObject {
201
+ val merged = JSObject(defaults.toString())
202
+ val keys = overrides.keys()
203
+ while (keys.hasNext()) {
204
+ val key = keys.next()
205
+ val existing = merged.getJSObject(key)
206
+ val replacement = overrides.getJSObject(key)
207
+ merged.put(key, if (existing != null && replacement != null) {
208
+ mergeObjects(existing, replacement)
209
+ } else {
210
+ overrides.get(key)
211
+ })
212
+ }
213
+ return merged
214
+ }
215
+
157
216
  private fun applyConfiguration(config: JSObject) {
158
217
  securityManager.configure(config)
159
218
  normalizeLiveUpdateConfig(config)?.let(liveUpdatePlugin::configure)
@@ -170,7 +229,10 @@ class NativeUpdatePlugin : Plugin() {
170
229
  private fun buildFlatLiveUpdateConfig(config: JSObject): JSObject? {
171
230
  val serverUrl = config.getString("serverUrl") ?: config.getString("baseUrl")
172
231
  val apiKey = config.getString("apiKey")
173
- if (serverUrl == null && apiKey == null) {
232
+ val liveKeys = listOf("serverUrl", "baseUrl", "apiKey", "appId", "channel", "publicKey",
233
+ "requireSignature", "allowUnsignedDevelopmentUpdates", "checksumAlgorithm", "maxBundleSize",
234
+ "maxUncompressedBundleSize", "enableDeltaUpdates", "allowedHosts")
235
+ if (liveKeys.none(config::has)) {
174
236
  return null
175
237
  }
176
238
 
@@ -195,9 +257,19 @@ class NativeUpdatePlugin : Plugin() {
195
257
  return liveUpdate
196
258
  }
197
259
 
260
+ private fun effectiveLiveUpdateConfig(config: JSObject): JSObject? {
261
+ val flat = buildFlatLiveUpdateConfig(config)
262
+ val nested = config.getJSObject("liveUpdate")
263
+ return when {
264
+ flat != null && nested != null -> mergeObjects(flat, nested)
265
+ nested != null -> nested
266
+ else -> flat
267
+ }
268
+ }
269
+
198
270
  /** Merge root security controls into both documented configuration shapes. */
199
271
  private fun normalizeLiveUpdateConfig(config: JSObject): JSObject? {
200
- val liveUpdate = config.getJSObject("liveUpdate") ?: buildFlatLiveUpdateConfig(config) ?: return null
272
+ val liveUpdate = effectiveLiveUpdateConfig(config) ?: return null
201
273
  if (!liveUpdate.has("security")) {
202
274
  config.getJSObject("security")?.let { liveUpdate.put("security", it) }
203
275
  }
@@ -258,6 +330,7 @@ class NativeUpdatePlugin : Plugin() {
258
330
  liveUpdatePlugin.reset(call)
259
331
  isInitialized = false
260
332
  appliedConfiguration = null
333
+ initializedFromCapacitorConfig = false
261
334
  } catch (e: Exception) {
262
335
  call.reject("Reset failed", e)
263
336
  }