native-update-capacitor 0.0.0-stage → 4.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (139) hide show
  1. package/AI-INTEGRATION-GUIDE.md +578 -0
  2. package/LICENSE +25 -0
  3. package/NativeUpdate.podspec +19 -0
  4. package/README.md +574 -2
  5. package/android/build.gradle +125 -0
  6. package/android/consumer-rules.pro +9 -0
  7. package/android/gradle/wrapper/gradle-wrapper.properties +8 -0
  8. package/android/gradle.properties +17 -0
  9. package/android/manifest-additions.xml +28 -0
  10. package/android/proguard-rules.pro +26 -0
  11. package/android/settings.gradle +2 -0
  12. package/android/src/main/AndroidManifest.xml +13 -0
  13. package/android/src/main/java/com/aoneahsan/nativeupdate/AppReviewPlugin.kt +159 -0
  14. package/android/src/main/java/com/aoneahsan/nativeupdate/AppUpdatePlugin.kt +314 -0
  15. package/android/src/main/java/com/aoneahsan/nativeupdate/BackgroundNotificationManager.kt +406 -0
  16. package/android/src/main/java/com/aoneahsan/nativeupdate/BackgroundUpdateManager.kt +48 -0
  17. package/android/src/main/java/com/aoneahsan/nativeupdate/BackgroundUpdatePlugin.kt +343 -0
  18. package/android/src/main/java/com/aoneahsan/nativeupdate/BackgroundUpdateWorker.kt +236 -0
  19. package/android/src/main/java/com/aoneahsan/nativeupdate/JsonOptional.kt +26 -0
  20. package/android/src/main/java/com/aoneahsan/nativeupdate/LiveUpdatePlugin.kt +1249 -0
  21. package/android/src/main/java/com/aoneahsan/nativeupdate/NativeUpdatePlugin.kt +404 -0
  22. package/android/src/main/java/com/aoneahsan/nativeupdate/NotificationActionReceiver.kt +107 -0
  23. package/android/src/main/java/com/aoneahsan/nativeupdate/SecurityManager.kt +240 -0
  24. package/android/variables.gradle +5 -0
  25. package/cli/commands/backend-create.js +623 -0
  26. package/cli/commands/bundle-create.js +145 -0
  27. package/cli/commands/bundle-sign.js +64 -0
  28. package/cli/commands/bundle-verify.js +58 -0
  29. package/cli/commands/init.js +146 -0
  30. package/cli/commands/keys-generate.js +58 -0
  31. package/cli/commands/monitor.js +89 -0
  32. package/cli/commands/remote-shared.js +262 -0
  33. package/cli/commands/remote.js +622 -0
  34. package/cli/commands/server-start.js +96 -0
  35. package/cli/index.js +605 -0
  36. package/cli/package.json +21 -0
  37. package/dist/esm/app-review/app-review-manager.d.ts +24 -0
  38. package/dist/esm/app-review/app-review-manager.js +194 -0
  39. package/dist/esm/app-review/index.d.ts +5 -0
  40. package/dist/esm/app-review/index.js +5 -0
  41. package/dist/esm/app-review/platform-review-handler.d.ts +20 -0
  42. package/dist/esm/app-review/platform-review-handler.js +137 -0
  43. package/dist/esm/app-review/review-conditions-checker.d.ts +22 -0
  44. package/dist/esm/app-review/review-conditions-checker.js +154 -0
  45. package/dist/esm/app-review/review-rate-limiter.d.ts +23 -0
  46. package/dist/esm/app-review/review-rate-limiter.js +163 -0
  47. package/dist/esm/app-review/types.d.ts +41 -0
  48. package/dist/esm/app-review/types.js +1 -0
  49. package/dist/esm/app-update/app-update-checker.d.ts +58 -0
  50. package/dist/esm/app-update/app-update-checker.js +227 -0
  51. package/dist/esm/app-update/app-update-installer.d.ts +20 -0
  52. package/dist/esm/app-update/app-update-installer.js +134 -0
  53. package/dist/esm/app-update/app-update-manager.d.ts +28 -0
  54. package/dist/esm/app-update/app-update-manager.js +198 -0
  55. package/dist/esm/app-update/app-update-notifier.d.ts +14 -0
  56. package/dist/esm/app-update/app-update-notifier.js +99 -0
  57. package/dist/esm/app-update/index.d.ts +6 -0
  58. package/dist/esm/app-update/index.js +6 -0
  59. package/dist/esm/app-update/platform-app-update.d.ts +19 -0
  60. package/dist/esm/app-update/platform-app-update.js +138 -0
  61. package/dist/esm/app-update/types.d.ts +58 -0
  62. package/dist/esm/app-update/types.js +11 -0
  63. package/dist/esm/background-update/background-scheduler.d.ts +63 -0
  64. package/dist/esm/background-update/background-scheduler.js +332 -0
  65. package/dist/esm/background-update/index.d.ts +3 -0
  66. package/dist/esm/background-update/index.js +2 -0
  67. package/dist/esm/background-update/notification-manager.d.ts +29 -0
  68. package/dist/esm/background-update/notification-manager.js +88 -0
  69. package/dist/esm/config/support.d.ts +9 -0
  70. package/dist/esm/config/support.js +9 -0
  71. package/dist/esm/core/analytics.d.ts +83 -0
  72. package/dist/esm/core/analytics.js +151 -0
  73. package/dist/esm/core/cache-manager.d.ts +72 -0
  74. package/dist/esm/core/cache-manager.js +274 -0
  75. package/dist/esm/core/config.d.ts +69 -0
  76. package/dist/esm/core/config.js +107 -0
  77. package/dist/esm/core/errors.d.ts +56 -0
  78. package/dist/esm/core/errors.js +85 -0
  79. package/dist/esm/core/event-emitter.d.ts +30 -0
  80. package/dist/esm/core/event-emitter.js +80 -0
  81. package/dist/esm/core/logger.d.ts +21 -0
  82. package/dist/esm/core/logger.js +108 -0
  83. package/dist/esm/core/performance.d.ts +53 -0
  84. package/dist/esm/core/performance.js +153 -0
  85. package/dist/esm/core/plugin-manager.d.ts +88 -0
  86. package/dist/esm/core/plugin-manager.js +224 -0
  87. package/dist/esm/core/security.d.ts +123 -0
  88. package/dist/esm/core/security.js +361 -0
  89. package/dist/esm/core/update-check.d.ts +121 -0
  90. package/dist/esm/core/update-check.js +127 -0
  91. package/dist/esm/definitions.d.ts +872 -0
  92. package/dist/esm/definitions.js +104 -0
  93. package/dist/esm/index.d.ts +14 -0
  94. package/dist/esm/index.js +18 -0
  95. package/dist/esm/live-update/bundle-manager.d.ts +102 -0
  96. package/dist/esm/live-update/bundle-manager.js +344 -0
  97. package/dist/esm/live-update/certificate-pinning.d.ts +38 -0
  98. package/dist/esm/live-update/certificate-pinning.js +77 -0
  99. package/dist/esm/live-update/delta-processor.d.ts +84 -0
  100. package/dist/esm/live-update/delta-processor.js +257 -0
  101. package/dist/esm/live-update/download-manager.d.ts +106 -0
  102. package/dist/esm/live-update/download-manager.js +412 -0
  103. package/dist/esm/live-update/rollout-checker.d.ts +86 -0
  104. package/dist/esm/live-update/rollout-checker.js +304 -0
  105. package/dist/esm/live-update/update-manager.d.ts +63 -0
  106. package/dist/esm/live-update/update-manager.js +321 -0
  107. package/dist/esm/live-update/version-manager.d.ts +93 -0
  108. package/dist/esm/live-update/version-manager.js +390 -0
  109. package/dist/esm/plugin.d.ts +3 -0
  110. package/dist/esm/plugin.js +848 -0
  111. package/dist/esm/security/crypto.d.ts +88 -0
  112. package/dist/esm/security/crypto.js +228 -0
  113. package/dist/esm/security/validator.d.ts +60 -0
  114. package/dist/esm/security/validator.js +142 -0
  115. package/dist/esm/types/app-identity.d.ts +36 -0
  116. package/dist/esm/types/app-identity.js +1 -0
  117. package/dist/esm/types/rollout.d.ts +91 -0
  118. package/dist/esm/types/rollout.js +25 -0
  119. package/dist/esm/web.d.ts +130 -0
  120. package/dist/esm/web.js +981 -0
  121. package/dist/plugin.cjs +1 -0
  122. package/dist/plugin.esm.js +1 -0
  123. package/dist/plugin.js +2 -0
  124. package/docs/CHANGELOG.md +993 -0
  125. package/docs/KNOWN_LIMITATIONS.md +235 -0
  126. package/docs/MIGRATION.md +391 -0
  127. package/docs/protocol/CLIENT-PROTOCOL.md +178 -0
  128. package/docs/server-requirements.md +211 -0
  129. package/ios/Plugin/AppReview/AppReviewPlugin.swift +158 -0
  130. package/ios/Plugin/AppUpdate/AppUpdatePlugin.swift +249 -0
  131. package/ios/Plugin/BackgroundUpdate/BackgroundNotificationManager.swift +333 -0
  132. package/ios/Plugin/BackgroundUpdate/BackgroundUpdatePlugin.swift +464 -0
  133. package/ios/Plugin/Info.plist +43 -0
  134. package/ios/Plugin/LiveUpdate/LiveUpdatePlugin.swift +1286 -0
  135. package/ios/Plugin/LiveUpdate/WebViewConfiguration.swift +45 -0
  136. package/ios/Plugin/NativeUpdatePlugin.m +53 -0
  137. package/ios/Plugin/NativeUpdatePlugin.swift +315 -0
  138. package/ios/Plugin/Security/SecurityManager.swift +289 -0
  139. package/package.json +135 -4
@@ -0,0 +1,848 @@
1
+ import { registerPlugin } from '@capacitor/core';
2
+ import { SyncStatus, BundleStatus, UpdateErrorCode } from './definitions';
3
+ import { PluginManager } from './core/plugin-manager';
4
+ import { NativeUpdateError, ErrorCode } from './core/errors';
5
+ import { checkForUpdate } from './core/update-check';
6
+ import { DeltaProcessor } from './live-update/delta-processor';
7
+ import { VersionManager } from './live-update/version-manager';
8
+ /**
9
+ * Web implementation of the Native Update Plugin
10
+ */
11
+ class NativeUpdatePluginWeb {
12
+ constructor() {
13
+ this.initialized = false;
14
+ this.windowEventListeners = new Map();
15
+ this.pluginManager = PluginManager.getInstance();
16
+ }
17
+ // Main plugin methods
18
+ async initialize(config) {
19
+ await this.pluginManager.initialize(config);
20
+ this.initialized = true;
21
+ // Setup window event bridge for AppUpdateNotifier events
22
+ this.setupWindowEventBridge();
23
+ }
24
+ async isInitialized() {
25
+ return this.initialized && this.pluginManager.isInitialized();
26
+ }
27
+ async reset() {
28
+ await this.pluginManager.reset();
29
+ this.initialized = false;
30
+ }
31
+ async cleanup() {
32
+ await this.pluginManager.cleanup();
33
+ }
34
+ // NativeUpdatePlugin methods
35
+ async configure(config) {
36
+ // Handle both UpdateConfig and wrapped PluginInitConfig formats
37
+ let initConfig;
38
+ if ('config' in config && typeof config.config === 'object') {
39
+ // Format: { config: PluginInitConfig }
40
+ initConfig = config.config;
41
+ }
42
+ else {
43
+ const liveUpdate = config.liveUpdate;
44
+ const appUpdate = config.appUpdate;
45
+ const appReview = config.appReview;
46
+ // Format: UpdateConfig - convert to PluginInitConfig
47
+ initConfig = {
48
+ appId: liveUpdate === null || liveUpdate === void 0 ? void 0 : liveUpdate.appId,
49
+ baseUrl: liveUpdate === null || liveUpdate === void 0 ? void 0 : liveUpdate.serverUrl,
50
+ serverUrl: liveUpdate === null || liveUpdate === void 0 ? void 0 : liveUpdate.serverUrl,
51
+ apiKey: liveUpdate === null || liveUpdate === void 0 ? void 0 : liveUpdate.apiKey,
52
+ channel: liveUpdate === null || liveUpdate === void 0 ? void 0 : liveUpdate.channel,
53
+ autoCheck: liveUpdate === null || liveUpdate === void 0 ? void 0 : liveUpdate.autoUpdate,
54
+ autoUpdate: liveUpdate === null || liveUpdate === void 0 ? void 0 : liveUpdate.autoUpdate,
55
+ updateStrategy: liveUpdate === null || liveUpdate === void 0 ? void 0 : liveUpdate.updateStrategy,
56
+ publicKey: liveUpdate === null || liveUpdate === void 0 ? void 0 : liveUpdate.publicKey,
57
+ requireSignature: liveUpdate === null || liveUpdate === void 0 ? void 0 : liveUpdate.requireSignature,
58
+ allowUnsignedDevelopmentUpdates: liveUpdate === null || liveUpdate === void 0 ? void 0 : liveUpdate.allowUnsignedDevelopmentUpdates,
59
+ maxBundleSize: liveUpdate === null || liveUpdate === void 0 ? void 0 : liveUpdate.maxBundleSize,
60
+ maxUncompressedBundleSize: liveUpdate === null || liveUpdate === void 0 ? void 0 : liveUpdate.maxUncompressedBundleSize,
61
+ allowedHosts: liveUpdate === null || liveUpdate === void 0 ? void 0 : liveUpdate.allowedHosts,
62
+ enableDeltaUpdates: liveUpdate === null || liveUpdate === void 0 ? void 0 : liveUpdate.enableDeltaUpdates,
63
+ checksumAlgorithm: liveUpdate === null || liveUpdate === void 0 ? void 0 : liveUpdate.checksumAlgorithm,
64
+ checkInterval: liveUpdate === null || liveUpdate === void 0 ? void 0 : liveUpdate.checkInterval,
65
+ security: config.security,
66
+ appStoreId: appUpdate === null || appUpdate === void 0 ? void 0 : appUpdate.appStoreId,
67
+ packageName: appUpdate === null || appUpdate === void 0 ? void 0 : appUpdate.packageName,
68
+ webReviewUrl: appReview === null || appReview === void 0 ? void 0 : appReview.webReviewUrl,
69
+ };
70
+ }
71
+ if (!this.initialized) {
72
+ // Auto-initialize with the provided config
73
+ await this.initialize(initConfig);
74
+ }
75
+ else {
76
+ throw new NativeUpdateError(ErrorCode.INVALID_CONFIG, 'Configuration is locked after initialization. Call reset() before configuring again.');
77
+ }
78
+ }
79
+ async getSecurityInfo() {
80
+ return {
81
+ enforceHttps: true,
82
+ certificatePinning: {
83
+ enabled: false,
84
+ pins: [],
85
+ },
86
+ validateInputs: true,
87
+ secureStorage: true,
88
+ };
89
+ }
90
+ // LiveUpdatePlugin methods
91
+ async sync(options) {
92
+ try {
93
+ const updateInfo = await this.checkForUpdate();
94
+ if (!updateInfo.available || !updateInfo.latestVersion || !updateInfo.url) {
95
+ return {
96
+ status: SyncStatus.UP_TO_DATE,
97
+ version: updateInfo.currentVersion,
98
+ };
99
+ }
100
+ if ((options === null || options === void 0 ? void 0 : options.updateMode) === 'immediate' || (options === null || options === void 0 ? void 0 : options.updateMode) === undefined) {
101
+ const bundle = await this.downloadUpdate({
102
+ url: updateInfo.url,
103
+ version: updateInfo.latestVersion,
104
+ checksum: updateInfo.checksum,
105
+ signature: updateInfo.signature,
106
+ signatureAlgorithm: updateInfo.signatureAlgorithm,
107
+ delta: updateInfo.delta,
108
+ });
109
+ await this.applyUpdate(bundle.bundleId);
110
+ return {
111
+ status: SyncStatus.UPDATE_INSTALLED,
112
+ version: updateInfo.latestVersion,
113
+ description: updateInfo.notes,
114
+ mandatory: updateInfo.mandatory,
115
+ };
116
+ }
117
+ return {
118
+ status: SyncStatus.UPDATE_AVAILABLE,
119
+ version: updateInfo.latestVersion,
120
+ description: updateInfo.notes,
121
+ mandatory: updateInfo.mandatory,
122
+ };
123
+ }
124
+ catch (error) {
125
+ return {
126
+ status: SyncStatus.ERROR,
127
+ error: {
128
+ code: UpdateErrorCode.UNKNOWN_ERROR,
129
+ message: error instanceof Error ? error.message : 'Sync failed',
130
+ },
131
+ };
132
+ }
133
+ }
134
+ async download(options) {
135
+ const downloadManager = this.pluginManager.getDownloadManager();
136
+ const bundleManager = this.pluginManager.getBundleManager();
137
+ let blob;
138
+ const activeBundle = await bundleManager.getActiveBundle();
139
+ if (options.delta && (activeBundle === null || activeBundle === void 0 ? void 0 : activeBundle.version) === options.delta.fromVersion) {
140
+ const activeBlob = await downloadManager.loadBlob(activeBundle.bundleId);
141
+ const result = await new DeltaProcessor().downloadWithDelta({
142
+ updateAvailable: true,
143
+ version: options.version,
144
+ bundleUrl: options.url,
145
+ checksum: options.checksum,
146
+ size: undefined,
147
+ delta: {
148
+ available: true,
149
+ patchUrl: options.delta.patchUrl,
150
+ patchSize: options.delta.patchSize,
151
+ patchChecksum: options.delta.patchChecksum,
152
+ targetChecksum: options.delta.targetChecksum,
153
+ },
154
+ }, activeBlob ? await activeBlob.arrayBuffer() : null);
155
+ blob = new Blob([result.bundleData], { type: 'application/zip' });
156
+ }
157
+ else {
158
+ blob = await downloadManager.downloadWithRetry(options.url, options.version);
159
+ }
160
+ // Verify checksum/signature against ACTUAL downloaded bytes before
161
+ // persisting. Without this, an attacker who swaps the URL or proxies
162
+ // a tampered bundle can plant arbitrary code and the next set() will
163
+ // activate it. validateBundleData throws on mismatch.
164
+ const bundleData = await blob.arrayBuffer();
165
+ await this.validateBundleData(bundleData, options.checksum, options.signature);
166
+ const validatedBlob = new Blob([bundleData], { type: blob.type });
167
+ const path = await downloadManager.saveBlob(options.version, validatedBlob);
168
+ const bundleInfo = {
169
+ bundleId: options.version,
170
+ version: options.version,
171
+ path,
172
+ downloadTime: Date.now(),
173
+ size: validatedBlob.size,
174
+ status: BundleStatus.READY,
175
+ checksum: options.checksum,
176
+ signature: options.signature,
177
+ signatureAlgorithm: options.signatureAlgorithm,
178
+ verified: true,
179
+ };
180
+ await bundleManager.saveBundleInfo(bundleInfo);
181
+ return bundleInfo;
182
+ }
183
+ async set(bundle) {
184
+ const bundleManager = this.pluginManager.getBundleManager();
185
+ if (!bundle.verified) {
186
+ throw new NativeUpdateError(ErrorCode.SIGNATURE_INVALID, `Refusing to activate unverified bundle ${bundle.bundleId}`);
187
+ }
188
+ await bundleManager.setActiveBundle(bundle.bundleId);
189
+ }
190
+ async reload() {
191
+ // In web implementation, we can reload the page
192
+ if (typeof window !== 'undefined') {
193
+ window.location.reload();
194
+ }
195
+ }
196
+ async current() {
197
+ const bundleManager = this.pluginManager.getBundleManager();
198
+ const bundle = await bundleManager.getActiveBundle();
199
+ if (!bundle) {
200
+ throw new NativeUpdateError(ErrorCode.FILE_NOT_FOUND, 'No active bundle found');
201
+ }
202
+ return bundle;
203
+ }
204
+ async list() {
205
+ const bundleManager = this.pluginManager.getBundleManager();
206
+ return bundleManager.getAllBundles();
207
+ }
208
+ async delete(options) {
209
+ const bundleManager = this.pluginManager.getBundleManager();
210
+ if (options.bundleId) {
211
+ await bundleManager.deleteBundle(options.bundleId);
212
+ }
213
+ else if (options.keepVersions !== undefined) {
214
+ // Delete old versions keeping the specified number
215
+ const bundles = await bundleManager.getAllBundles();
216
+ const sortedBundles = bundles.sort((a, b) => b.downloadTime - a.downloadTime);
217
+ for (let i = options.keepVersions; i < sortedBundles.length; i++) {
218
+ await bundleManager.deleteBundle(sortedBundles[i].bundleId);
219
+ }
220
+ }
221
+ }
222
+ async notifyAppReady() {
223
+ // Mark the current bundle as stable
224
+ const bundleManager = this.pluginManager.getBundleManager();
225
+ const activeBundle = await bundleManager.getActiveBundle();
226
+ if (activeBundle) {
227
+ activeBundle.status = BundleStatus.ACTIVE;
228
+ await bundleManager.saveBundleInfo(activeBundle);
229
+ }
230
+ }
231
+ async getLatest() {
232
+ // Real implementation since v3.1.3 (was a hardcoded {available:false}
233
+ // stub): delegates to checkForUpdate(), which speaks the
234
+ // /v1/updates/check wire contract. Unconfigured (no baseUrl) stays a
235
+ // tolerant no-update result, matching the old stub's behavior.
236
+ const result = await this.checkForUpdate();
237
+ if (!result.available) {
238
+ return result.held ? { available: false, held: true, version: result.latestVersion, heldMessage: result.heldMessage } : { available: false };
239
+ }
240
+ return {
241
+ available: true,
242
+ version: result.latestVersion,
243
+ url: result.url,
244
+ mandatory: result.mandatory,
245
+ notes: result.notes,
246
+ size: result.size,
247
+ checksum: result.checksum,
248
+ signature: result.signature,
249
+ signatureAlgorithm: result.signatureAlgorithm,
250
+ delta: result.delta,
251
+ };
252
+ }
253
+ async setChannel(channel) {
254
+ const channelName = typeof channel === 'string' ? channel : channel.channel;
255
+ // Store the channel preference
256
+ const preferences = this.pluginManager
257
+ .getConfigManager()
258
+ .get('preferences');
259
+ if (preferences) {
260
+ await preferences.set({
261
+ key: 'update_channel',
262
+ value: channelName,
263
+ });
264
+ }
265
+ }
266
+ /**
267
+ * @deprecated since v2. The update server URL is fixed at `initialize()`
268
+ * time and cannot be mutated at runtime. Runtime mutation is an XSS
269
+ * attack vector — a compromised WebView could repoint updates to a
270
+ * malicious host. Call `initialize()` again with the new config if you
271
+ * legitimately need to switch servers, call reset() and initialize()
272
+ * again.
273
+ */
274
+ async setUpdateUrl(url) {
275
+ void url;
276
+ const logger = this.pluginManager.getLogger();
277
+ logger.warn('setUpdateUrl() is deprecated and ignored. Update URL is locked after initialize(). ' +
278
+ 'Call reset(), then initialize() with an updated serverUrl to switch servers.');
279
+ }
280
+ async validateUpdate(options) {
281
+ const securityValidator = this.pluginManager.getSecurityValidator();
282
+ const downloadManager = this.pluginManager.getDownloadManager();
283
+ try {
284
+ // bundlePath may be either a stored path (`bundles/<id>/bundle.zip`)
285
+ // or a bare bundleId. Normalize to bundleId so we can read the
286
+ // persisted blob.
287
+ const pathMatch = options.bundlePath.match(/bundles\/([^/]+)\/bundle\.zip$/);
288
+ const bundleId = pathMatch ? pathMatch[1] : options.bundlePath;
289
+ const blob = await downloadManager.loadBlob(bundleId);
290
+ if (!blob) {
291
+ return {
292
+ isValid: false,
293
+ error: `Bundle not found at ${options.bundlePath}`,
294
+ };
295
+ }
296
+ const bundleData = await blob.arrayBuffer();
297
+ const checksumValid = await securityValidator.verifyChecksum(bundleData, options.checksum);
298
+ let signatureValid = true;
299
+ if (options.signature) {
300
+ signatureValid = await securityValidator.verifySignature(bundleData, options.signature);
301
+ }
302
+ const sizeValid = options.maxSize
303
+ ? bundleData.byteLength <= options.maxSize
304
+ : true;
305
+ return {
306
+ isValid: checksumValid && signatureValid && sizeValid,
307
+ details: {
308
+ checksumValid,
309
+ signatureValid,
310
+ sizeValid,
311
+ versionValid: true,
312
+ },
313
+ };
314
+ }
315
+ catch (error) {
316
+ return {
317
+ isValid: false,
318
+ error: error instanceof Error ? error.message : 'Validation failed',
319
+ };
320
+ }
321
+ }
322
+ // ============================================
323
+ // Convenience Methods (Aliases)
324
+ // ============================================
325
+ /**
326
+ * The app's client identity for API-key client restrictions. On web this is
327
+ * `{ platform: 'web' }` — browsers identify via the Origin header. On native
328
+ * platforms this method is served by the native layer (Android: applicationId
329
+ * + signing-cert SHA-256/SHA-1; iOS: bundle identifier).
330
+ */
331
+ async getAppIdentity() {
332
+ return { platform: 'web' };
333
+ }
334
+ /** Session-cached identity; never throws (falls back to `{ platform: 'web' }`). */
335
+ async resolveAppIdentity() {
336
+ if (this.appIdentity) {
337
+ return this.appIdentity;
338
+ }
339
+ try {
340
+ this.appIdentity = await this.getAppIdentity();
341
+ }
342
+ catch (_a) {
343
+ this.appIdentity = { platform: 'web' };
344
+ }
345
+ return this.appIdentity;
346
+ }
347
+ /**
348
+ * Check for available updates (convenience wrapper around getLatest + current version)
349
+ */
350
+ async checkForUpdate() {
351
+ var _a, _b, _c;
352
+ const bundleManager = this.pluginManager.getBundleManager();
353
+ const configManager = this.pluginManager.getConfigManager();
354
+ try {
355
+ const currentBundle = await bundleManager.getActiveBundle();
356
+ const currentVersion = (currentBundle === null || currentBundle === void 0 ? void 0 : currentBundle.version) || '1.0.0';
357
+ const baseUrl = configManager.get('baseUrl');
358
+ if (!baseUrl) {
359
+ return {
360
+ available: false,
361
+ currentVersion,
362
+ };
363
+ }
364
+ // Laravel backend contract: GET /v1/updates/check with X-API-Key,
365
+ // X-Device-ID, X-Current-Version, X-Platform headers. The
366
+ // backend returns either {available: false} or {available: true,
367
+ // version, downloadUrl, checksum, signature, size, ...}.
368
+ const apiKey = configManager.get('apiKey');
369
+ if (!apiKey) {
370
+ throw new NativeUpdateError(ErrorCode.INVALID_CONFIG, 'apiKey is required when using Laravel backend');
371
+ }
372
+ const channel = configManager.get('channel') || 'production';
373
+ const deviceInfo = this.getDeviceInfo(currentVersion);
374
+ // Delegate the wire contract to the shared helper so plugin.ts,
375
+ // version-manager, and background-scheduler all hit the same
376
+ // /v1/updates/check endpoint with identical headers.
377
+ const data = await checkForUpdate(baseUrl, {
378
+ apiKey,
379
+ channel,
380
+ currentVersion,
381
+ deviceId: deviceInfo.deviceId,
382
+ platform: deviceInfo.platform,
383
+ appVersion: deviceInfo.appVersion,
384
+ identity: await this.resolveAppIdentity(),
385
+ });
386
+ if (!data.available) {
387
+ return data.held
388
+ ? { available: false, currentVersion, latestVersion: data.version, held: true, heldMessage: data.message }
389
+ : { available: false, currentVersion };
390
+ }
391
+ return {
392
+ available: true,
393
+ currentVersion,
394
+ latestVersion: data.version,
395
+ url: data.downloadUrl,
396
+ mandatory: data.mandatory,
397
+ notes: (_a = data.releaseNotes) !== null && _a !== void 0 ? _a : undefined,
398
+ size: data.size,
399
+ checksum: data.checksum,
400
+ signature: (_b = data.signature) !== null && _b !== void 0 ? _b : undefined,
401
+ signatureAlgorithm: data.signature ? 'RSA-SHA256' : undefined,
402
+ delta: (_c = data.delta) !== null && _c !== void 0 ? _c : undefined,
403
+ };
404
+ }
405
+ catch (error) {
406
+ throw new NativeUpdateError(ErrorCode.NETWORK_ERROR, error instanceof Error ? error.message : 'Failed to check for updates');
407
+ }
408
+ }
409
+ /**
410
+ * Download the latest available update
411
+ */
412
+ async downloadUpdate(options) {
413
+ const downloadManager = this.pluginManager.getDownloadManager();
414
+ const bundleManager = this.pluginManager.getBundleManager();
415
+ const eventEmitter = this.pluginManager.getEventEmitter();
416
+ // If no options provided, check for update first
417
+ let updateInfo;
418
+ if (!(options === null || options === void 0 ? void 0 : options.url) || !(options === null || options === void 0 ? void 0 : options.version)) {
419
+ updateInfo = await this.checkForUpdate();
420
+ if (!updateInfo.available || !updateInfo.url) {
421
+ throw new NativeUpdateError(ErrorCode.UPDATE_NOT_AVAILABLE, 'No update available to download');
422
+ }
423
+ }
424
+ const url = (options === null || options === void 0 ? void 0 : options.url) || (updateInfo === null || updateInfo === void 0 ? void 0 : updateInfo.url) || '';
425
+ const version = (options === null || options === void 0 ? void 0 : options.version) || (updateInfo === null || updateInfo === void 0 ? void 0 : updateInfo.latestVersion) || '';
426
+ const checksum = (options === null || options === void 0 ? void 0 : options.checksum) || (updateInfo === null || updateInfo === void 0 ? void 0 : updateInfo.checksum) || '';
427
+ const signature = (options === null || options === void 0 ? void 0 : options.signature) || (updateInfo === null || updateInfo === void 0 ? void 0 : updateInfo.signature) || '';
428
+ const signatureAlgorithm = (options === null || options === void 0 ? void 0 : options.signatureAlgorithm) || (updateInfo === null || updateInfo === void 0 ? void 0 : updateInfo.signatureAlgorithm);
429
+ const delta = (options === null || options === void 0 ? void 0 : options.delta) || (updateInfo === null || updateInfo === void 0 ? void 0 : updateInfo.delta);
430
+ if (!url || !version) {
431
+ throw new NativeUpdateError(ErrorCode.INVALID_CONFIG, 'URL and version are required for download');
432
+ }
433
+ // Create progress callback that emits events
434
+ const onProgress = (event) => {
435
+ eventEmitter.emit('downloadProgress', event);
436
+ if (options === null || options === void 0 ? void 0 : options.onProgress) {
437
+ options.onProgress(event);
438
+ }
439
+ };
440
+ // Download the bundle
441
+ const blob = await downloadManager.downloadWithRetry(url, version, onProgress);
442
+ // Get ArrayBuffer for validation
443
+ const bundleData = await blob.arrayBuffer();
444
+ // Validate checksum and signature before saving
445
+ await this.validateBundleData(bundleData, checksum, signature || undefined);
446
+ // Convert back to Blob for storage
447
+ const validatedBlob = new Blob([bundleData], { type: blob.type });
448
+ const path = await downloadManager.saveBlob(version, validatedBlob);
449
+ // Create bundle info
450
+ const bundleInfo = {
451
+ bundleId: version,
452
+ version,
453
+ path,
454
+ downloadTime: Date.now(),
455
+ size: validatedBlob.size,
456
+ status: BundleStatus.READY,
457
+ checksum,
458
+ signature: signature || undefined,
459
+ signatureAlgorithm,
460
+ metadata: delta ? { delta } : undefined,
461
+ verified: true, // Validated before saving
462
+ };
463
+ // Save bundle info
464
+ await bundleManager.saveBundleInfo(bundleInfo);
465
+ return bundleInfo;
466
+ }
467
+ /**
468
+ * Apply a downloaded update and reload the app
469
+ */
470
+ async applyUpdate(bundleId) {
471
+ const bundleManager = this.pluginManager.getBundleManager();
472
+ // If bundleId not provided, find the most recent ready bundle
473
+ let targetBundleId = bundleId;
474
+ if (!targetBundleId) {
475
+ const bundles = await bundleManager.getAllBundles();
476
+ const readyBundles = bundles
477
+ .filter(b => b.status === BundleStatus.READY)
478
+ .sort((a, b) => b.downloadTime - a.downloadTime);
479
+ if (readyBundles.length === 0) {
480
+ throw new NativeUpdateError(ErrorCode.FILE_NOT_FOUND, 'No ready bundle found to apply');
481
+ }
482
+ targetBundleId = readyBundles[0].bundleId;
483
+ }
484
+ // Get the bundle
485
+ const bundle = await bundleManager.getBundle(targetBundleId);
486
+ if (!bundle) {
487
+ throw new NativeUpdateError(ErrorCode.FILE_NOT_FOUND, `Bundle ${targetBundleId} not found`);
488
+ }
489
+ // Set as active and reload
490
+ await this.set(bundle);
491
+ await this.reload();
492
+ }
493
+ /**
494
+ * Cancel an active download
495
+ */
496
+ async cancelDownload(bundleId) {
497
+ const downloadManager = this.pluginManager.getDownloadManager();
498
+ downloadManager.cancelDownload(typeof bundleId === 'string' ? bundleId : bundleId.bundleId);
499
+ }
500
+ /**
501
+ * Cancel all active downloads
502
+ */
503
+ async cancelAllDownloads() {
504
+ const downloadManager = this.pluginManager.getDownloadManager();
505
+ downloadManager.cancelAllDownloads();
506
+ }
507
+ /**
508
+ * Check if a download is currently active
509
+ */
510
+ async isDownloading(bundleId) {
511
+ const downloadManager = this.pluginManager.getDownloadManager();
512
+ return downloadManager.isDownloading(typeof bundleId === 'string' ? bundleId : bundleId.bundleId);
513
+ }
514
+ /**
515
+ * Get the count of active downloads
516
+ */
517
+ async getActiveDownloadCount() {
518
+ const downloadManager = this.pluginManager.getDownloadManager();
519
+ return downloadManager.getActiveDownloadCount();
520
+ }
521
+ /**
522
+ * Compare two semantic versions. Currently unused — the Laravel
523
+ * backend decides update availability server-side. Retained as a
524
+ * helper for advanced consumers that need client-side comparison.
525
+ * Returns: -1 if v1 < v2, 0 if equal, 1 if v1 > v2
526
+ */
527
+ // @ts-expect-error retained as a helper for advanced consumers
528
+ compareVersions(v1, v2) {
529
+ const parts1 = v1.split('.').map(Number);
530
+ const parts2 = v2.split('.').map(Number);
531
+ for (let i = 0; i < Math.max(parts1.length, parts2.length); i++) {
532
+ const p1 = parts1[i] || 0;
533
+ const p2 = parts2[i] || 0;
534
+ if (p1 < p2)
535
+ return -1;
536
+ if (p1 > p2)
537
+ return 1;
538
+ }
539
+ return 0;
540
+ }
541
+ getDeviceInfo(currentVersion) {
542
+ return {
543
+ deviceId: 'web-client',
544
+ platform: 'web',
545
+ appVersion: currentVersion,
546
+ bundleVersion: currentVersion,
547
+ osVersion: typeof navigator !== 'undefined' ? navigator.userAgent : 'unknown',
548
+ locale: typeof navigator !== 'undefined' ? navigator.language : 'en-US',
549
+ };
550
+ }
551
+ /**
552
+ * Validate bundle data using SecurityValidator
553
+ * Returns true if valid, throws error if invalid
554
+ */
555
+ async validateBundleData(bundleData, expectedChecksum, signature) {
556
+ const securityValidator = this.pluginManager.getSecurityValidator();
557
+ const configManager = this.pluginManager.getConfigManager();
558
+ // Verify checksum if provided
559
+ if (expectedChecksum) {
560
+ const isValidChecksum = await securityValidator.verifyChecksum(bundleData, expectedChecksum);
561
+ if (!isValidChecksum) {
562
+ throw new NativeUpdateError(ErrorCode.CHECKSUM_MISMATCH, 'Bundle checksum verification failed');
563
+ }
564
+ }
565
+ // Verify signature if requireSignature is enabled
566
+ const requireSignature = configManager.get('requireSignature');
567
+ const publicKey = configManager.get('publicKey');
568
+ if (requireSignature) {
569
+ if (!publicKey) {
570
+ throw new NativeUpdateError(ErrorCode.INVALID_CONFIG, 'Signature verification required but publicKey is not configured');
571
+ }
572
+ if (!signature) {
573
+ throw new NativeUpdateError(ErrorCode.SIGNATURE_INVALID, 'Signature verification required but no signature provided');
574
+ }
575
+ const isValidSignature = await securityValidator.verifySignature(bundleData, signature);
576
+ if (!isValidSignature) {
577
+ throw new NativeUpdateError(ErrorCode.SIGNATURE_INVALID, 'Bundle signature verification failed');
578
+ }
579
+ }
580
+ return true;
581
+ }
582
+ // AppUpdatePlugin methods
583
+ async getAppUpdateInfo() {
584
+ const appUpdateManager = this.pluginManager.getAppUpdateManager();
585
+ return appUpdateManager.getAppUpdateInfo();
586
+ }
587
+ async performImmediateUpdate() {
588
+ const appUpdateManager = this.pluginManager.getAppUpdateManager();
589
+ return appUpdateManager.performImmediateUpdate();
590
+ }
591
+ async startFlexibleUpdate() {
592
+ const appUpdateManager = this.pluginManager.getAppUpdateManager();
593
+ return appUpdateManager.startFlexibleUpdate();
594
+ }
595
+ async completeFlexibleUpdate() {
596
+ const appUpdateManager = this.pluginManager.getAppUpdateManager();
597
+ return appUpdateManager.completeFlexibleUpdate();
598
+ }
599
+ async openAppStore(options) {
600
+ const appUpdateManager = this.pluginManager.getAppUpdateManager();
601
+ return appUpdateManager.openAppStore(options);
602
+ }
603
+ // AppReviewPlugin methods
604
+ async requestReview() {
605
+ return {
606
+ displayed: false,
607
+ error: 'Reviews are not supported on web',
608
+ };
609
+ }
610
+ async canRequestReview() {
611
+ return {
612
+ canRequest: false,
613
+ reason: 'Reviews are not supported on web',
614
+ };
615
+ }
616
+ // BackgroundUpdatePlugin methods
617
+ async enableBackgroundUpdates(config) {
618
+ // Configure the background scheduler
619
+ const scheduler = this.pluginManager.getBackgroundScheduler();
620
+ scheduler.configure(config);
621
+ // Store the configuration in preferences for persistence
622
+ const preferences = this.pluginManager
623
+ .getConfigManager()
624
+ .get('preferences');
625
+ if (preferences) {
626
+ await preferences.set({
627
+ key: 'background_update_config',
628
+ value: JSON.stringify(config),
629
+ });
630
+ }
631
+ }
632
+ async disableBackgroundUpdates() {
633
+ // Disable the scheduler
634
+ const scheduler = this.pluginManager.getBackgroundScheduler();
635
+ scheduler.configure({
636
+ enabled: false,
637
+ checkInterval: 0,
638
+ updateTypes: [],
639
+ });
640
+ // Remove the configuration from preferences
641
+ const preferences = this.pluginManager
642
+ .getConfigManager()
643
+ .get('preferences');
644
+ if (preferences) {
645
+ await preferences.remove({ key: 'background_update_config' });
646
+ }
647
+ }
648
+ async getBackgroundUpdateStatus() {
649
+ const scheduler = this.pluginManager.getBackgroundScheduler();
650
+ return scheduler.getStatus();
651
+ }
652
+ async scheduleBackgroundCheck(_interval) {
653
+ // Not supported on web
654
+ throw new NativeUpdateError(ErrorCode.PLATFORM_NOT_SUPPORTED, 'Background updates are not supported on web');
655
+ }
656
+ async triggerBackgroundCheck() {
657
+ const scheduler = this.pluginManager.getBackgroundScheduler();
658
+ return scheduler.performCheck();
659
+ }
660
+ async setNotificationPreferences(preferences) {
661
+ // Store preferences but notifications aren't supported on web
662
+ const prefs = this.pluginManager.getConfigManager().get('preferences');
663
+ if (prefs) {
664
+ await prefs.set({
665
+ key: 'notification_preferences',
666
+ value: JSON.stringify(preferences),
667
+ });
668
+ }
669
+ }
670
+ async getNotificationPermissions() {
671
+ return {
672
+ granted: false,
673
+ canRequest: false,
674
+ };
675
+ }
676
+ async requestNotificationPermissions() {
677
+ return false;
678
+ }
679
+ // Event listener methods
680
+ async addListener(eventName,
681
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
682
+ listenerFunc) {
683
+ const eventEmitter = this.pluginManager.getEventEmitter();
684
+ // Add listener to central event emitter
685
+ const removeListener = eventEmitter.addListener(eventName, listenerFunc);
686
+ return {
687
+ remove: async () => {
688
+ removeListener();
689
+ },
690
+ };
691
+ }
692
+ async removeAllListeners() {
693
+ const eventEmitter = this.pluginManager.getEventEmitter();
694
+ eventEmitter.removeAllListeners();
695
+ }
696
+ /**
697
+ * Setup bridge between window custom events and central event emitter
698
+ */
699
+ setupWindowEventBridge() {
700
+ const eventEmitter = this.pluginManager.getEventEmitter();
701
+ // List of events emitted by AppUpdateNotifier via window
702
+ const windowEvents = [
703
+ 'appUpdateAvailable',
704
+ 'appUpdateProgress',
705
+ 'appUpdateReady',
706
+ 'appUpdateFailed',
707
+ 'appUpdateNotificationClicked',
708
+ 'appUpdateInstallClicked'
709
+ ];
710
+ windowEvents.forEach(eventName => {
711
+ const listener = (event) => {
712
+ eventEmitter.emit(eventName, event.detail);
713
+ };
714
+ window.addEventListener(eventName, listener);
715
+ this.windowEventListeners.set(eventName, listener);
716
+ });
717
+ }
718
+ }
719
+ /**
720
+ * Register the plugin
721
+ */
722
+ const NativeUpdateBridge = registerPlugin('NativeUpdate', {
723
+ web: () => new NativeUpdatePluginWeb(),
724
+ });
725
+ const NativeUpdate = new Proxy(NativeUpdateBridge, {
726
+ get(target, property, receiver) {
727
+ if (property === 'isInitialized') {
728
+ return async () => {
729
+ const result = await target.isInitialized();
730
+ return typeof result === 'boolean'
731
+ ? result
732
+ : !!(result && typeof result === 'object' && 'initialized' in result && result.initialized);
733
+ };
734
+ }
735
+ if (property === 'list') {
736
+ return async () => {
737
+ const result = await target.list();
738
+ if (Array.isArray(result))
739
+ return result;
740
+ if (result && typeof result === 'object' && 'bundles' in result && Array.isArray(result.bundles)) {
741
+ return result.bundles;
742
+ }
743
+ return [];
744
+ };
745
+ }
746
+ if (property === 'setChannel') {
747
+ return (channel) => target.setChannel({ channel });
748
+ }
749
+ if (property === 'setUpdateUrl') {
750
+ return (url) => target.setUpdateUrl({ url });
751
+ }
752
+ if (property === 'scheduleBackgroundCheck') {
753
+ return (interval) => target.scheduleBackgroundCheck({ interval });
754
+ }
755
+ if (property === 'requestNotificationPermissions') {
756
+ return async () => {
757
+ const result = await target.requestNotificationPermissions();
758
+ return typeof result === 'boolean'
759
+ ? result
760
+ : !!(result && typeof result === 'object' && 'granted' in result && result.granted);
761
+ };
762
+ }
763
+ if (property === 'checkForUpdate') {
764
+ return async () => {
765
+ const [latest, current] = await Promise.all([target.getLatest(), target.current()]);
766
+ const available = latest.available === true
767
+ && typeof latest.version === 'string'
768
+ && VersionManager.compareVersions(latest.version, current.version) > 0;
769
+ return {
770
+ available,
771
+ latestVersion: latest.version,
772
+ currentVersion: current.version,
773
+ url: latest.url,
774
+ mandatory: latest.mandatory,
775
+ notes: latest.notes,
776
+ size: latest.size,
777
+ checksum: latest.checksum,
778
+ signature: latest.signature,
779
+ signatureAlgorithm: latest.signatureAlgorithm,
780
+ delta: latest.delta,
781
+ held: latest.held === true ? true : undefined,
782
+ heldMessage: latest.heldMessage,
783
+ };
784
+ };
785
+ }
786
+ if (property === 'downloadUpdate') {
787
+ return async (options = {}) => {
788
+ var _a, _b, _c, _d, _e, _f;
789
+ const latest = options.url && options.version && options.checksum
790
+ ? undefined
791
+ : await target.getLatest();
792
+ const url = (_a = options.url) !== null && _a !== void 0 ? _a : latest === null || latest === void 0 ? void 0 : latest.url;
793
+ const version = (_b = options.version) !== null && _b !== void 0 ? _b : latest === null || latest === void 0 ? void 0 : latest.version;
794
+ const checksum = (_c = options.checksum) !== null && _c !== void 0 ? _c : latest === null || latest === void 0 ? void 0 : latest.checksum;
795
+ if (!url || !version || !checksum) {
796
+ throw new NativeUpdateError(ErrorCode.UPDATE_NOT_AVAILABLE, 'No downloadable update is available');
797
+ }
798
+ return target.download({
799
+ url,
800
+ version,
801
+ checksum,
802
+ signature: (_d = options.signature) !== null && _d !== void 0 ? _d : latest === null || latest === void 0 ? void 0 : latest.signature,
803
+ signatureAlgorithm: (_e = options.signatureAlgorithm) !== null && _e !== void 0 ? _e : latest === null || latest === void 0 ? void 0 : latest.signatureAlgorithm,
804
+ delta: (_f = options.delta) !== null && _f !== void 0 ? _f : latest === null || latest === void 0 ? void 0 : latest.delta,
805
+ });
806
+ };
807
+ }
808
+ if (property === 'applyUpdate') {
809
+ return async (bundleId) => {
810
+ const bundles = await NativeUpdate.list();
811
+ const bundle = bundleId
812
+ ? bundles.find(candidate => candidate.bundleId === bundleId)
813
+ : bundles
814
+ .filter(candidate => candidate.status === BundleStatus.READY)
815
+ .sort((left, right) => right.downloadTime - left.downloadTime)[0];
816
+ if (!bundle) {
817
+ throw new NativeUpdateError(ErrorCode.FILE_NOT_FOUND, 'No ready bundle found to apply');
818
+ }
819
+ await target.set(bundle);
820
+ await target.reload();
821
+ };
822
+ }
823
+ if (property === 'cancelDownload') {
824
+ return (bundleId) => target.cancelDownload({ bundleId });
825
+ }
826
+ if (property === 'isDownloading') {
827
+ return async (bundleId) => {
828
+ const result = await target.isDownloading({ bundleId });
829
+ return typeof result === 'boolean'
830
+ ? result
831
+ : !!(result && typeof result === 'object' && 'isDownloading' in result && result.isDownloading);
832
+ };
833
+ }
834
+ if (property === 'getActiveDownloadCount') {
835
+ return async () => {
836
+ const result = await target.getActiveDownloadCount();
837
+ return typeof result === 'number'
838
+ ? result
839
+ : result && typeof result === 'object' && 'count' in result && typeof result.count === 'number'
840
+ ? result.count
841
+ : 0;
842
+ };
843
+ }
844
+ const value = Reflect.get(target, property, receiver);
845
+ return typeof value === 'function' ? value.bind(target) : value;
846
+ },
847
+ });
848
+ export { NativeUpdate };