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.
- package/AI-INTEGRATION-GUIDE.md +578 -0
- package/LICENSE +25 -0
- package/NativeUpdate.podspec +19 -0
- package/README.md +574 -2
- package/android/build.gradle +125 -0
- package/android/consumer-rules.pro +9 -0
- package/android/gradle/wrapper/gradle-wrapper.properties +8 -0
- package/android/gradle.properties +17 -0
- package/android/manifest-additions.xml +28 -0
- package/android/proguard-rules.pro +26 -0
- package/android/settings.gradle +2 -0
- package/android/src/main/AndroidManifest.xml +13 -0
- package/android/src/main/java/com/aoneahsan/nativeupdate/AppReviewPlugin.kt +159 -0
- package/android/src/main/java/com/aoneahsan/nativeupdate/AppUpdatePlugin.kt +314 -0
- package/android/src/main/java/com/aoneahsan/nativeupdate/BackgroundNotificationManager.kt +406 -0
- package/android/src/main/java/com/aoneahsan/nativeupdate/BackgroundUpdateManager.kt +48 -0
- package/android/src/main/java/com/aoneahsan/nativeupdate/BackgroundUpdatePlugin.kt +343 -0
- package/android/src/main/java/com/aoneahsan/nativeupdate/BackgroundUpdateWorker.kt +236 -0
- package/android/src/main/java/com/aoneahsan/nativeupdate/JsonOptional.kt +26 -0
- package/android/src/main/java/com/aoneahsan/nativeupdate/LiveUpdatePlugin.kt +1249 -0
- package/android/src/main/java/com/aoneahsan/nativeupdate/NativeUpdatePlugin.kt +404 -0
- package/android/src/main/java/com/aoneahsan/nativeupdate/NotificationActionReceiver.kt +107 -0
- package/android/src/main/java/com/aoneahsan/nativeupdate/SecurityManager.kt +240 -0
- package/android/variables.gradle +5 -0
- package/cli/commands/backend-create.js +623 -0
- package/cli/commands/bundle-create.js +145 -0
- package/cli/commands/bundle-sign.js +64 -0
- package/cli/commands/bundle-verify.js +58 -0
- package/cli/commands/init.js +146 -0
- package/cli/commands/keys-generate.js +58 -0
- package/cli/commands/monitor.js +89 -0
- package/cli/commands/remote-shared.js +262 -0
- package/cli/commands/remote.js +622 -0
- package/cli/commands/server-start.js +96 -0
- package/cli/index.js +605 -0
- package/cli/package.json +21 -0
- package/dist/esm/app-review/app-review-manager.d.ts +24 -0
- package/dist/esm/app-review/app-review-manager.js +194 -0
- package/dist/esm/app-review/index.d.ts +5 -0
- package/dist/esm/app-review/index.js +5 -0
- package/dist/esm/app-review/platform-review-handler.d.ts +20 -0
- package/dist/esm/app-review/platform-review-handler.js +137 -0
- package/dist/esm/app-review/review-conditions-checker.d.ts +22 -0
- package/dist/esm/app-review/review-conditions-checker.js +154 -0
- package/dist/esm/app-review/review-rate-limiter.d.ts +23 -0
- package/dist/esm/app-review/review-rate-limiter.js +163 -0
- package/dist/esm/app-review/types.d.ts +41 -0
- package/dist/esm/app-review/types.js +1 -0
- package/dist/esm/app-update/app-update-checker.d.ts +58 -0
- package/dist/esm/app-update/app-update-checker.js +227 -0
- package/dist/esm/app-update/app-update-installer.d.ts +20 -0
- package/dist/esm/app-update/app-update-installer.js +134 -0
- package/dist/esm/app-update/app-update-manager.d.ts +28 -0
- package/dist/esm/app-update/app-update-manager.js +198 -0
- package/dist/esm/app-update/app-update-notifier.d.ts +14 -0
- package/dist/esm/app-update/app-update-notifier.js +99 -0
- package/dist/esm/app-update/index.d.ts +6 -0
- package/dist/esm/app-update/index.js +6 -0
- package/dist/esm/app-update/platform-app-update.d.ts +19 -0
- package/dist/esm/app-update/platform-app-update.js +138 -0
- package/dist/esm/app-update/types.d.ts +58 -0
- package/dist/esm/app-update/types.js +11 -0
- package/dist/esm/background-update/background-scheduler.d.ts +63 -0
- package/dist/esm/background-update/background-scheduler.js +332 -0
- package/dist/esm/background-update/index.d.ts +3 -0
- package/dist/esm/background-update/index.js +2 -0
- package/dist/esm/background-update/notification-manager.d.ts +29 -0
- package/dist/esm/background-update/notification-manager.js +88 -0
- package/dist/esm/config/support.d.ts +9 -0
- package/dist/esm/config/support.js +9 -0
- package/dist/esm/core/analytics.d.ts +83 -0
- package/dist/esm/core/analytics.js +151 -0
- package/dist/esm/core/cache-manager.d.ts +72 -0
- package/dist/esm/core/cache-manager.js +274 -0
- package/dist/esm/core/config.d.ts +69 -0
- package/dist/esm/core/config.js +107 -0
- package/dist/esm/core/errors.d.ts +56 -0
- package/dist/esm/core/errors.js +85 -0
- package/dist/esm/core/event-emitter.d.ts +30 -0
- package/dist/esm/core/event-emitter.js +80 -0
- package/dist/esm/core/logger.d.ts +21 -0
- package/dist/esm/core/logger.js +108 -0
- package/dist/esm/core/performance.d.ts +53 -0
- package/dist/esm/core/performance.js +153 -0
- package/dist/esm/core/plugin-manager.d.ts +88 -0
- package/dist/esm/core/plugin-manager.js +224 -0
- package/dist/esm/core/security.d.ts +123 -0
- package/dist/esm/core/security.js +361 -0
- package/dist/esm/core/update-check.d.ts +121 -0
- package/dist/esm/core/update-check.js +127 -0
- package/dist/esm/definitions.d.ts +872 -0
- package/dist/esm/definitions.js +104 -0
- package/dist/esm/index.d.ts +14 -0
- package/dist/esm/index.js +18 -0
- package/dist/esm/live-update/bundle-manager.d.ts +102 -0
- package/dist/esm/live-update/bundle-manager.js +344 -0
- package/dist/esm/live-update/certificate-pinning.d.ts +38 -0
- package/dist/esm/live-update/certificate-pinning.js +77 -0
- package/dist/esm/live-update/delta-processor.d.ts +84 -0
- package/dist/esm/live-update/delta-processor.js +257 -0
- package/dist/esm/live-update/download-manager.d.ts +106 -0
- package/dist/esm/live-update/download-manager.js +412 -0
- package/dist/esm/live-update/rollout-checker.d.ts +86 -0
- package/dist/esm/live-update/rollout-checker.js +304 -0
- package/dist/esm/live-update/update-manager.d.ts +63 -0
- package/dist/esm/live-update/update-manager.js +321 -0
- package/dist/esm/live-update/version-manager.d.ts +93 -0
- package/dist/esm/live-update/version-manager.js +390 -0
- package/dist/esm/plugin.d.ts +3 -0
- package/dist/esm/plugin.js +848 -0
- package/dist/esm/security/crypto.d.ts +88 -0
- package/dist/esm/security/crypto.js +228 -0
- package/dist/esm/security/validator.d.ts +60 -0
- package/dist/esm/security/validator.js +142 -0
- package/dist/esm/types/app-identity.d.ts +36 -0
- package/dist/esm/types/app-identity.js +1 -0
- package/dist/esm/types/rollout.d.ts +91 -0
- package/dist/esm/types/rollout.js +25 -0
- package/dist/esm/web.d.ts +130 -0
- package/dist/esm/web.js +981 -0
- package/dist/plugin.cjs +1 -0
- package/dist/plugin.esm.js +1 -0
- package/dist/plugin.js +2 -0
- package/docs/CHANGELOG.md +993 -0
- package/docs/KNOWN_LIMITATIONS.md +235 -0
- package/docs/MIGRATION.md +391 -0
- package/docs/protocol/CLIENT-PROTOCOL.md +178 -0
- package/docs/server-requirements.md +211 -0
- package/ios/Plugin/AppReview/AppReviewPlugin.swift +158 -0
- package/ios/Plugin/AppUpdate/AppUpdatePlugin.swift +249 -0
- package/ios/Plugin/BackgroundUpdate/BackgroundNotificationManager.swift +333 -0
- package/ios/Plugin/BackgroundUpdate/BackgroundUpdatePlugin.swift +464 -0
- package/ios/Plugin/Info.plist +43 -0
- package/ios/Plugin/LiveUpdate/LiveUpdatePlugin.swift +1286 -0
- package/ios/Plugin/LiveUpdate/WebViewConfiguration.swift +45 -0
- package/ios/Plugin/NativeUpdatePlugin.m +53 -0
- package/ios/Plugin/NativeUpdatePlugin.swift +315 -0
- package/ios/Plugin/Security/SecurityManager.swift +289 -0
- package/package.json +135 -4
|
@@ -0,0 +1,412 @@
|
|
|
1
|
+
import { ConfigManager } from '../core/config';
|
|
2
|
+
import { Logger } from '../core/logger';
|
|
3
|
+
import { DownloadError, ErrorCode, ValidationError } from '../core/errors';
|
|
4
|
+
import { Directory } from '@capacitor/filesystem';
|
|
5
|
+
/**
|
|
6
|
+
* Manages file downloads with progress tracking and resume capability
|
|
7
|
+
*/
|
|
8
|
+
export class DownloadManager {
|
|
9
|
+
constructor() {
|
|
10
|
+
this.activeDownloads = new Map();
|
|
11
|
+
/**
|
|
12
|
+
* Persisted-past-request metadata for the most recent `download()`
|
|
13
|
+
* call per bundleId. Today we only stash whether the server honoured
|
|
14
|
+
* a Range request (HTTP 206 vs 200). resumeDownload() consults this
|
|
15
|
+
* to decide whether to concatenate or discard its partial prefix.
|
|
16
|
+
*/
|
|
17
|
+
this.lastResponseMeta = new Map();
|
|
18
|
+
this.filesystem = null;
|
|
19
|
+
this.logger = Logger.getInstance();
|
|
20
|
+
this.configManager = ConfigManager.getInstance();
|
|
21
|
+
}
|
|
22
|
+
/**
|
|
23
|
+
* Initialize the download manager
|
|
24
|
+
*/
|
|
25
|
+
async initialize() {
|
|
26
|
+
this.filesystem = this.configManager.get('filesystem');
|
|
27
|
+
if (!this.filesystem) {
|
|
28
|
+
throw new DownloadError(ErrorCode.MISSING_DEPENDENCY, 'Filesystem not configured. Please configure the plugin first.');
|
|
29
|
+
}
|
|
30
|
+
}
|
|
31
|
+
/**
|
|
32
|
+
* Validate URL against allowed hosts
|
|
33
|
+
*/
|
|
34
|
+
validateUrl(url) {
|
|
35
|
+
try {
|
|
36
|
+
const parsedUrl = new URL(url);
|
|
37
|
+
// Ensure HTTPS
|
|
38
|
+
if (parsedUrl.protocol !== 'https:') {
|
|
39
|
+
throw new ValidationError(ErrorCode.INVALID_URL, 'Only HTTPS URLs are allowed for security reasons');
|
|
40
|
+
}
|
|
41
|
+
// Check against allowed hosts if configured
|
|
42
|
+
const allowedHosts = this.configManager.get('allowedHosts');
|
|
43
|
+
if (allowedHosts.length > 0 &&
|
|
44
|
+
!allowedHosts.includes(parsedUrl.hostname)) {
|
|
45
|
+
throw new ValidationError(ErrorCode.UNAUTHORIZED_HOST, `Host ${parsedUrl.hostname} is not in the allowed hosts list`);
|
|
46
|
+
}
|
|
47
|
+
}
|
|
48
|
+
catch (error) {
|
|
49
|
+
if (error instanceof ValidationError)
|
|
50
|
+
throw error;
|
|
51
|
+
throw new ValidationError(ErrorCode.INVALID_URL, 'Invalid URL format');
|
|
52
|
+
}
|
|
53
|
+
}
|
|
54
|
+
/**
|
|
55
|
+
* Download a file with progress tracking.
|
|
56
|
+
*
|
|
57
|
+
* Accepts either a bare `onProgress` callback (back-compat) or a full
|
|
58
|
+
* DownloadOptions object. When `resumePosition` is set, the request
|
|
59
|
+
* carries a Range header; the resulting download state records
|
|
60
|
+
* whether the server actually honoured it (`serverReturnedPartial`).
|
|
61
|
+
*/
|
|
62
|
+
async download(url, bundleId, onProgressOrOptions) {
|
|
63
|
+
var _a;
|
|
64
|
+
const options = typeof onProgressOrOptions === 'function'
|
|
65
|
+
? { onProgress: onProgressOrOptions }
|
|
66
|
+
: onProgressOrOptions !== null && onProgressOrOptions !== void 0 ? onProgressOrOptions : {};
|
|
67
|
+
const onProgress = options.onProgress;
|
|
68
|
+
const resumePosition = (_a = options.resumePosition) !== null && _a !== void 0 ? _a : 0;
|
|
69
|
+
// Validate inputs
|
|
70
|
+
this.validateUrl(url);
|
|
71
|
+
if (!bundleId) {
|
|
72
|
+
throw new ValidationError(ErrorCode.INVALID_BUNDLE_FORMAT, 'Bundle ID is required');
|
|
73
|
+
}
|
|
74
|
+
// Check if already downloading
|
|
75
|
+
if (this.activeDownloads.has(bundleId)) {
|
|
76
|
+
throw new DownloadError(ErrorCode.DOWNLOAD_FAILED, `Download already in progress for bundle ${bundleId}`);
|
|
77
|
+
}
|
|
78
|
+
// Create abort controller for this download
|
|
79
|
+
const abortController = new AbortController();
|
|
80
|
+
const downloadState = {
|
|
81
|
+
controller: abortController,
|
|
82
|
+
startTime: Date.now(),
|
|
83
|
+
resumePosition: resumePosition > 0 ? resumePosition : undefined,
|
|
84
|
+
};
|
|
85
|
+
this.activeDownloads.set(bundleId, downloadState);
|
|
86
|
+
try {
|
|
87
|
+
const timeout = this.configManager.get('downloadTimeout');
|
|
88
|
+
const timeoutId = setTimeout(() => abortController.abort(), timeout);
|
|
89
|
+
// Build headers including Range header for resume support
|
|
90
|
+
const headers = {
|
|
91
|
+
'Cache-Control': 'no-cache',
|
|
92
|
+
Accept: 'application/octet-stream, application/zip',
|
|
93
|
+
};
|
|
94
|
+
// Add Range header if resuming from a previous position
|
|
95
|
+
if (resumePosition > 0) {
|
|
96
|
+
headers['Range'] = `bytes=${resumePosition}-`;
|
|
97
|
+
}
|
|
98
|
+
const response = await fetch(url, {
|
|
99
|
+
signal: abortController.signal,
|
|
100
|
+
headers,
|
|
101
|
+
});
|
|
102
|
+
clearTimeout(timeoutId);
|
|
103
|
+
if (!response.ok) {
|
|
104
|
+
throw new DownloadError(ErrorCode.DOWNLOAD_FAILED, `Download failed: ${response.status} ${response.statusText}`, { status: response.status, statusText: response.statusText });
|
|
105
|
+
}
|
|
106
|
+
// Record whether the server actually honoured the Range request.
|
|
107
|
+
// Stored on both the live state (for introspection during the
|
|
108
|
+
// download) and the lastResponseMeta map (so resumeDownload can
|
|
109
|
+
// read it after download() cleans up the live state).
|
|
110
|
+
const serverReturnedPartial = resumePosition > 0 && response.status === 206;
|
|
111
|
+
downloadState.serverReturnedPartial = serverReturnedPartial;
|
|
112
|
+
this.lastResponseMeta.set(bundleId, { partial: serverReturnedPartial });
|
|
113
|
+
// Validate content type
|
|
114
|
+
const contentType = response.headers.get('content-type');
|
|
115
|
+
if (contentType && !this.isValidContentType(contentType)) {
|
|
116
|
+
throw new ValidationError(ErrorCode.INVALID_BUNDLE_FORMAT, `Invalid content type: ${contentType}`);
|
|
117
|
+
}
|
|
118
|
+
// Get total size from headers
|
|
119
|
+
const contentLength = response.headers.get('content-length');
|
|
120
|
+
const totalBytes = contentLength ? parseInt(contentLength, 10) : 0;
|
|
121
|
+
// Check size limit
|
|
122
|
+
if (totalBytes > this.configManager.get('maxBundleSize')) {
|
|
123
|
+
throw new ValidationError(ErrorCode.BUNDLE_TOO_LARGE, `Bundle size ${totalBytes} exceeds maximum allowed size`);
|
|
124
|
+
}
|
|
125
|
+
// If no content length, fall back to simple download
|
|
126
|
+
if (!totalBytes || !response.body) {
|
|
127
|
+
const blob = await response.blob();
|
|
128
|
+
this.validateBlobSize(blob);
|
|
129
|
+
return blob;
|
|
130
|
+
}
|
|
131
|
+
// Stream the response with progress tracking
|
|
132
|
+
const reader = response.body.getReader();
|
|
133
|
+
const chunks = [];
|
|
134
|
+
let receivedBytes = 0;
|
|
135
|
+
while (true) {
|
|
136
|
+
const { done, value } = await reader.read();
|
|
137
|
+
if (done)
|
|
138
|
+
break;
|
|
139
|
+
chunks.push(value);
|
|
140
|
+
receivedBytes += value.length;
|
|
141
|
+
// Check if size exceeds limit during download
|
|
142
|
+
if (receivedBytes > this.configManager.get('maxBundleSize')) {
|
|
143
|
+
throw new ValidationError(ErrorCode.BUNDLE_TOO_LARGE, `Download size exceeds maximum allowed size`);
|
|
144
|
+
}
|
|
145
|
+
// Report progress
|
|
146
|
+
if (onProgress) {
|
|
147
|
+
// Calculate progress accounting for resumed position
|
|
148
|
+
const resumeOffset = downloadState.resumePosition || 0;
|
|
149
|
+
const adjustedLoaded = resumeOffset + receivedBytes;
|
|
150
|
+
const adjustedTotal = resumeOffset + totalBytes;
|
|
151
|
+
const percent = Math.round((adjustedLoaded / adjustedTotal) * 100);
|
|
152
|
+
onProgress({
|
|
153
|
+
percent,
|
|
154
|
+
bytesDownloaded: adjustedLoaded,
|
|
155
|
+
totalBytes: adjustedTotal,
|
|
156
|
+
bundleId,
|
|
157
|
+
});
|
|
158
|
+
}
|
|
159
|
+
}
|
|
160
|
+
// Combine chunks into a single blob
|
|
161
|
+
const blob = new Blob(chunks);
|
|
162
|
+
this.validateBlobSize(blob);
|
|
163
|
+
this.logger.info('Download completed', {
|
|
164
|
+
bundleId,
|
|
165
|
+
size: blob.size,
|
|
166
|
+
duration: Date.now() - downloadState.startTime,
|
|
167
|
+
});
|
|
168
|
+
return blob;
|
|
169
|
+
}
|
|
170
|
+
catch (error) {
|
|
171
|
+
if (error instanceof Error && error.name === 'AbortError') {
|
|
172
|
+
const isTimeout = Date.now() - downloadState.startTime >=
|
|
173
|
+
this.configManager.get('downloadTimeout');
|
|
174
|
+
throw new DownloadError(isTimeout ? ErrorCode.DOWNLOAD_TIMEOUT : ErrorCode.DOWNLOAD_FAILED, isTimeout ? 'Download timed out' : 'Download cancelled', undefined, error);
|
|
175
|
+
}
|
|
176
|
+
throw error;
|
|
177
|
+
}
|
|
178
|
+
finally {
|
|
179
|
+
// Clean up
|
|
180
|
+
this.activeDownloads.delete(bundleId);
|
|
181
|
+
}
|
|
182
|
+
}
|
|
183
|
+
/**
|
|
184
|
+
* Resume a previously interrupted download.
|
|
185
|
+
*
|
|
186
|
+
* Emits a Range-request download starting at the partial-data offset.
|
|
187
|
+
* If the server honours the range (HTTP 206), the partial + remaining
|
|
188
|
+
* bytes are concatenated. If the server returns a full response
|
|
189
|
+
* (HTTP 200 — common when the upstream URL's ETag changed, or when a
|
|
190
|
+
* CDN doesn't honour ranges) the partial data is discarded and the
|
|
191
|
+
* full response is used. Previously this path silently double-wrote
|
|
192
|
+
* bytes when the server fell back to 200; this was a latent
|
|
193
|
+
* bundle-corruption bug.
|
|
194
|
+
*/
|
|
195
|
+
async resumeDownload(url, bundleId, partialData, onProgress) {
|
|
196
|
+
const responseBlob = await this.download(url, bundleId, {
|
|
197
|
+
onProgress,
|
|
198
|
+
resumePosition: partialData.size,
|
|
199
|
+
});
|
|
200
|
+
// Read the flag download() set in lastResponseMeta. If the server
|
|
201
|
+
// returned 206 we concatenate; if 200 we discard the partial.
|
|
202
|
+
const meta = this.lastResponseMeta.get(bundleId);
|
|
203
|
+
this.lastResponseMeta.delete(bundleId);
|
|
204
|
+
if (meta === null || meta === void 0 ? void 0 : meta.partial) {
|
|
205
|
+
return new Blob([partialData, responseBlob]);
|
|
206
|
+
}
|
|
207
|
+
this.logger.info('Resume: server returned full response; discarding partial data', { bundleId, partialSize: partialData.size, responseSize: responseBlob.size });
|
|
208
|
+
return responseBlob;
|
|
209
|
+
}
|
|
210
|
+
/**
|
|
211
|
+
* Check if a download can be resumed
|
|
212
|
+
*/
|
|
213
|
+
async canResume(url) {
|
|
214
|
+
try {
|
|
215
|
+
const response = await fetch(url, {
|
|
216
|
+
method: 'HEAD',
|
|
217
|
+
});
|
|
218
|
+
// Check if server supports Range requests
|
|
219
|
+
const acceptRanges = response.headers.get('Accept-Ranges');
|
|
220
|
+
return acceptRanges === 'bytes';
|
|
221
|
+
}
|
|
222
|
+
catch (_a) {
|
|
223
|
+
return false;
|
|
224
|
+
}
|
|
225
|
+
}
|
|
226
|
+
/**
|
|
227
|
+
* Validate content type
|
|
228
|
+
*/
|
|
229
|
+
isValidContentType(contentType) {
|
|
230
|
+
const validTypes = [
|
|
231
|
+
'application/octet-stream',
|
|
232
|
+
'application/zip',
|
|
233
|
+
'application/x-zip-compressed',
|
|
234
|
+
'application/x-zip',
|
|
235
|
+
];
|
|
236
|
+
return validTypes.some((type) => contentType.includes(type));
|
|
237
|
+
}
|
|
238
|
+
/**
|
|
239
|
+
* Validate blob size
|
|
240
|
+
*/
|
|
241
|
+
validateBlobSize(blob) {
|
|
242
|
+
if (blob.size === 0) {
|
|
243
|
+
throw new ValidationError(ErrorCode.INVALID_BUNDLE_FORMAT, 'Downloaded file is empty');
|
|
244
|
+
}
|
|
245
|
+
if (blob.size > this.configManager.get('maxBundleSize')) {
|
|
246
|
+
throw new ValidationError(ErrorCode.BUNDLE_TOO_LARGE, `File size ${blob.size} exceeds maximum allowed size`);
|
|
247
|
+
}
|
|
248
|
+
}
|
|
249
|
+
/**
|
|
250
|
+
* Cancel a download
|
|
251
|
+
*/
|
|
252
|
+
cancelDownload(bundleId) {
|
|
253
|
+
const state = this.activeDownloads.get(bundleId);
|
|
254
|
+
if (state) {
|
|
255
|
+
state.controller.abort();
|
|
256
|
+
this.activeDownloads.delete(bundleId);
|
|
257
|
+
this.logger.info('Download cancelled', { bundleId });
|
|
258
|
+
}
|
|
259
|
+
}
|
|
260
|
+
/**
|
|
261
|
+
* Cancel all active downloads
|
|
262
|
+
*/
|
|
263
|
+
cancelAllDownloads() {
|
|
264
|
+
for (const state of this.activeDownloads.values()) {
|
|
265
|
+
state.controller.abort();
|
|
266
|
+
}
|
|
267
|
+
const count = this.activeDownloads.size;
|
|
268
|
+
this.activeDownloads.clear();
|
|
269
|
+
if (count > 0) {
|
|
270
|
+
this.logger.info('All downloads cancelled', { count });
|
|
271
|
+
}
|
|
272
|
+
}
|
|
273
|
+
/**
|
|
274
|
+
* Check if a download is active
|
|
275
|
+
*/
|
|
276
|
+
isDownloading(bundleId) {
|
|
277
|
+
return this.activeDownloads.has(bundleId);
|
|
278
|
+
}
|
|
279
|
+
/**
|
|
280
|
+
* Get active download count
|
|
281
|
+
*/
|
|
282
|
+
getActiveDownloadCount() {
|
|
283
|
+
return this.activeDownloads.size;
|
|
284
|
+
}
|
|
285
|
+
/**
|
|
286
|
+
* Download with retry logic
|
|
287
|
+
*/
|
|
288
|
+
async downloadWithRetry(url, bundleId, onProgress) {
|
|
289
|
+
const maxRetries = this.configManager.get('retryAttempts');
|
|
290
|
+
const retryDelay = this.configManager.get('retryDelay');
|
|
291
|
+
let lastError = null;
|
|
292
|
+
for (let attempt = 0; attempt < maxRetries; attempt++) {
|
|
293
|
+
try {
|
|
294
|
+
// Exponential backoff with ±25% jitter, capped at 30s. Jitter
|
|
295
|
+
// avoids a thundering-herd when many clients retry in lockstep
|
|
296
|
+
// after a common failure (CDN blip, server restart) — without
|
|
297
|
+
// it every client would wake up at exactly the same moment and
|
|
298
|
+
// DDoS the recovering server. 25% is enough desync without
|
|
299
|
+
// making the retry interval feel unpredictable.
|
|
300
|
+
if (attempt > 0) {
|
|
301
|
+
const base = retryDelay * Math.pow(2, attempt - 1);
|
|
302
|
+
const jitter = (Math.random() - 0.5) * 0.5 * base;
|
|
303
|
+
const delay = Math.min(Math.max(base + jitter, 100), 30000);
|
|
304
|
+
await new Promise((resolve) => setTimeout(resolve, delay));
|
|
305
|
+
this.logger.debug('Retrying download', { bundleId, attempt, delay });
|
|
306
|
+
}
|
|
307
|
+
return await this.download(url, bundleId, onProgress);
|
|
308
|
+
}
|
|
309
|
+
catch (error) {
|
|
310
|
+
lastError = error;
|
|
311
|
+
// Don't retry if cancelled or validation error
|
|
312
|
+
if (error instanceof ValidationError ||
|
|
313
|
+
(error instanceof Error && error.name === 'AbortError')) {
|
|
314
|
+
throw error;
|
|
315
|
+
}
|
|
316
|
+
this.logger.warn(`Download attempt ${attempt + 1} failed`, {
|
|
317
|
+
bundleId,
|
|
318
|
+
error,
|
|
319
|
+
});
|
|
320
|
+
}
|
|
321
|
+
}
|
|
322
|
+
throw new DownloadError(ErrorCode.DOWNLOAD_FAILED, 'Download failed after all retries', { attempts: maxRetries }, lastError || undefined);
|
|
323
|
+
}
|
|
324
|
+
/**
|
|
325
|
+
* Convert blob to ArrayBuffer
|
|
326
|
+
*/
|
|
327
|
+
async blobToArrayBuffer(blob) {
|
|
328
|
+
return blob.arrayBuffer();
|
|
329
|
+
}
|
|
330
|
+
/**
|
|
331
|
+
* Save blob to filesystem
|
|
332
|
+
*/
|
|
333
|
+
async saveBlob(bundleId, blob) {
|
|
334
|
+
if (!this.filesystem) {
|
|
335
|
+
throw new DownloadError(ErrorCode.MISSING_DEPENDENCY, 'Filesystem not initialized');
|
|
336
|
+
}
|
|
337
|
+
const arrayBuffer = await this.blobToArrayBuffer(blob);
|
|
338
|
+
// Spreading a 100MB Uint8Array into String.fromCharCode is a stack
|
|
339
|
+
// overflow on most engines. Chunk the conversion in 32KB blocks.
|
|
340
|
+
const bytes = new Uint8Array(arrayBuffer);
|
|
341
|
+
const chunkSize = 0x8000;
|
|
342
|
+
let binary = '';
|
|
343
|
+
for (let i = 0; i < bytes.length; i += chunkSize) {
|
|
344
|
+
binary += String.fromCharCode.apply(null, Array.from(bytes.subarray(i, i + chunkSize)));
|
|
345
|
+
}
|
|
346
|
+
const base64 = btoa(binary);
|
|
347
|
+
const path = `bundles/${bundleId}/bundle.zip`;
|
|
348
|
+
await this.filesystem.writeFile({
|
|
349
|
+
path,
|
|
350
|
+
data: base64,
|
|
351
|
+
directory: Directory.Data,
|
|
352
|
+
recursive: true,
|
|
353
|
+
});
|
|
354
|
+
this.logger.debug('Bundle saved to filesystem', {
|
|
355
|
+
bundleId,
|
|
356
|
+
path,
|
|
357
|
+
size: blob.size,
|
|
358
|
+
});
|
|
359
|
+
return path;
|
|
360
|
+
}
|
|
361
|
+
/**
|
|
362
|
+
* Load blob from filesystem
|
|
363
|
+
*/
|
|
364
|
+
async loadBlob(bundleId) {
|
|
365
|
+
if (!this.filesystem) {
|
|
366
|
+
throw new DownloadError(ErrorCode.MISSING_DEPENDENCY, 'Filesystem not initialized');
|
|
367
|
+
}
|
|
368
|
+
try {
|
|
369
|
+
const path = `bundles/${bundleId}/bundle.zip`;
|
|
370
|
+
const result = await this.filesystem.readFile({
|
|
371
|
+
path,
|
|
372
|
+
directory: Directory.Data,
|
|
373
|
+
});
|
|
374
|
+
const binaryString = atob(result.data);
|
|
375
|
+
const bytes = new Uint8Array(binaryString.length);
|
|
376
|
+
for (let i = 0; i < binaryString.length; i++) {
|
|
377
|
+
bytes[i] = binaryString.charCodeAt(i);
|
|
378
|
+
}
|
|
379
|
+
return new Blob([bytes], { type: 'application/zip' });
|
|
380
|
+
}
|
|
381
|
+
catch (error) {
|
|
382
|
+
this.logger.debug('Failed to load bundle from filesystem', {
|
|
383
|
+
bundleId,
|
|
384
|
+
error,
|
|
385
|
+
});
|
|
386
|
+
return null;
|
|
387
|
+
}
|
|
388
|
+
}
|
|
389
|
+
/**
|
|
390
|
+
* Delete blob from filesystem
|
|
391
|
+
*/
|
|
392
|
+
async deleteBlob(bundleId) {
|
|
393
|
+
if (!this.filesystem) {
|
|
394
|
+
throw new DownloadError(ErrorCode.MISSING_DEPENDENCY, 'Filesystem not initialized');
|
|
395
|
+
}
|
|
396
|
+
try {
|
|
397
|
+
const path = `bundles/${bundleId}`;
|
|
398
|
+
await this.filesystem.rmdir({
|
|
399
|
+
path,
|
|
400
|
+
directory: Directory.Data,
|
|
401
|
+
recursive: true,
|
|
402
|
+
});
|
|
403
|
+
this.logger.debug('Bundle deleted from filesystem', { bundleId });
|
|
404
|
+
}
|
|
405
|
+
catch (error) {
|
|
406
|
+
this.logger.warn('Failed to delete bundle from filesystem', {
|
|
407
|
+
bundleId,
|
|
408
|
+
error,
|
|
409
|
+
});
|
|
410
|
+
}
|
|
411
|
+
}
|
|
412
|
+
}
|
|
@@ -0,0 +1,86 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Rollout Checker
|
|
3
|
+
*
|
|
4
|
+
* Client-side rollout eligibility checking for staged deployments.
|
|
5
|
+
* Uses deterministic hashing for consistent rollout decisions.
|
|
6
|
+
*/
|
|
7
|
+
import type { RolloutConfig, DeviceInfo } from '../types/rollout';
|
|
8
|
+
/**
|
|
9
|
+
* Rollout eligibility result
|
|
10
|
+
*/
|
|
11
|
+
export interface RolloutEligibilityResult {
|
|
12
|
+
/** Whether device is eligible for the update */
|
|
13
|
+
eligible: boolean;
|
|
14
|
+
/** Reason for the eligibility decision */
|
|
15
|
+
reason: string;
|
|
16
|
+
/** Device's calculated percentile (0-100) */
|
|
17
|
+
devicePercentile?: number;
|
|
18
|
+
/** Current rollout percentage */
|
|
19
|
+
currentPercentage?: number;
|
|
20
|
+
}
|
|
21
|
+
/**
|
|
22
|
+
* Rollout checker for determining update eligibility
|
|
23
|
+
*/
|
|
24
|
+
export declare class RolloutChecker {
|
|
25
|
+
private readonly logger;
|
|
26
|
+
private readonly configManager;
|
|
27
|
+
private deviceInfoCache;
|
|
28
|
+
constructor();
|
|
29
|
+
/**
|
|
30
|
+
* Check if device is eligible for update based on rollout config
|
|
31
|
+
*/
|
|
32
|
+
checkEligibility(rollout: RolloutConfig, deviceInfo: DeviceInfo): Promise<RolloutEligibilityResult>;
|
|
33
|
+
/**
|
|
34
|
+
* Check time window for rollout
|
|
35
|
+
*/
|
|
36
|
+
private checkTimeWindow;
|
|
37
|
+
/**
|
|
38
|
+
* Check scheduled start time
|
|
39
|
+
*/
|
|
40
|
+
private checkScheduled;
|
|
41
|
+
/**
|
|
42
|
+
* Check target segments
|
|
43
|
+
*/
|
|
44
|
+
private checkSegments;
|
|
45
|
+
/**
|
|
46
|
+
* Calculate current rollout percentage based on schedule
|
|
47
|
+
*/
|
|
48
|
+
private calculateCurrentPercentage;
|
|
49
|
+
/**
|
|
50
|
+
* Get deterministic percentile for device ID
|
|
51
|
+
* Uses SHA-256 hash for uniform distribution
|
|
52
|
+
*/
|
|
53
|
+
getDevicePercentile(deviceId: string): Promise<number>;
|
|
54
|
+
/**
|
|
55
|
+
* Hash a string using SHA-256
|
|
56
|
+
*/
|
|
57
|
+
private hashString;
|
|
58
|
+
/**
|
|
59
|
+
* Convert hash to percentile (0-100)
|
|
60
|
+
*/
|
|
61
|
+
private hashToPercentile;
|
|
62
|
+
/**
|
|
63
|
+
* Compare semantic versions
|
|
64
|
+
*/
|
|
65
|
+
private compareVersions;
|
|
66
|
+
/**
|
|
67
|
+
* Set cached device info
|
|
68
|
+
*/
|
|
69
|
+
setDeviceInfo(deviceInfo: DeviceInfo): void;
|
|
70
|
+
/**
|
|
71
|
+
* Get cached device info
|
|
72
|
+
*/
|
|
73
|
+
getDeviceInfo(): DeviceInfo | null;
|
|
74
|
+
/**
|
|
75
|
+
* Check if staged rollouts are enabled
|
|
76
|
+
*/
|
|
77
|
+
isEnabled(): boolean;
|
|
78
|
+
}
|
|
79
|
+
/**
|
|
80
|
+
* Create rollout checker instance
|
|
81
|
+
*/
|
|
82
|
+
export declare function createRolloutChecker(): RolloutChecker;
|
|
83
|
+
/**
|
|
84
|
+
* Collect device information for rollout eligibility
|
|
85
|
+
*/
|
|
86
|
+
export declare function collectDeviceInfo(): Promise<DeviceInfo>;
|