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,77 @@
1
+ /**
2
+ * Certificate pinning utilities
3
+ */
4
+ export class CertificatePinning {
5
+ /**
6
+ * Generate SHA-256 fingerprint from certificate
7
+ * Note: This is a utility for generating pins, not for runtime validation
8
+ */
9
+ static async generateFingerprint(certificatePem) {
10
+ // Remove PEM headers and convert to binary
11
+ const base64 = certificatePem
12
+ .replace(/-----BEGIN CERTIFICATE-----/g, '')
13
+ .replace(/-----END CERTIFICATE-----/g, '')
14
+ .replace(/\s/g, '');
15
+ const binaryString = atob(base64);
16
+ const bytes = new Uint8Array(binaryString.length);
17
+ for (let i = 0; i < binaryString.length; i++) {
18
+ bytes[i] = binaryString.charCodeAt(i);
19
+ }
20
+ // Calculate SHA-256
21
+ const hashBuffer = await crypto.subtle.digest('SHA-256', bytes);
22
+ const hashArray = Array.from(new Uint8Array(hashBuffer));
23
+ const hashBase64 = btoa(String.fromCharCode(...hashArray));
24
+ return `sha256/${hashBase64}`;
25
+ }
26
+ /**
27
+ * Validate certificate pinning configuration
28
+ */
29
+ static validateConfig(config) {
30
+ if (!config || typeof config !== 'object') {
31
+ throw new Error('Certificate pinning config must be an object');
32
+ }
33
+ if (typeof config.enabled !== 'boolean') {
34
+ throw new Error('Certificate pinning enabled must be a boolean');
35
+ }
36
+ if (!config.enabled) {
37
+ return; // No need to validate pins if disabled
38
+ }
39
+ if (!Array.isArray(config.pins)) {
40
+ throw new Error('Certificate pins must be an array');
41
+ }
42
+ for (const pin of config.pins) {
43
+ if (!pin.hostname || typeof pin.hostname !== 'string') {
44
+ throw new Error('Certificate pin hostname must be a non-empty string');
45
+ }
46
+ if (!Array.isArray(pin.sha256) || pin.sha256.length === 0) {
47
+ throw new Error('Certificate pin sha256 must be a non-empty array');
48
+ }
49
+ for (const hash of pin.sha256) {
50
+ if (!hash || typeof hash !== 'string' || !hash.startsWith('sha256/')) {
51
+ throw new Error('Certificate pin hash must be in format "sha256/base64hash"');
52
+ }
53
+ }
54
+ }
55
+ }
56
+ /**
57
+ * Example configuration
58
+ */
59
+ static example() {
60
+ return {
61
+ enabled: true,
62
+ pins: [
63
+ {
64
+ hostname: 'api.example.com',
65
+ sha256: [
66
+ 'sha256/AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA=',
67
+ 'sha256/BBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBB=', // Backup pin
68
+ ],
69
+ },
70
+ {
71
+ hostname: 'cdn.example.com',
72
+ sha256: ['sha256/CCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCC='],
73
+ },
74
+ ],
75
+ };
76
+ }
77
+ }
@@ -0,0 +1,84 @@
1
+ /**
2
+ * Delta Processor
3
+ *
4
+ * Handles delta/patch-based updates for reduced download sizes.
5
+ * Applies the bounded, deterministic NUDELTA/1 copy/literal format emitted by
6
+ * the canonical backend. Unknown legacy patch formats fail closed and trigger
7
+ * the normal full-bundle fallback.
8
+ */
9
+ import type { UpdateCheckResponse } from '../types/rollout';
10
+ /**
11
+ * Delta patch information
12
+ */
13
+ export interface DeltaPatchInfo {
14
+ /** Whether delta is available for current version */
15
+ available: boolean;
16
+ /** Patch download URL */
17
+ patchUrl?: string;
18
+ /** Patch size in bytes */
19
+ patchSize?: number;
20
+ /** Checksum of the patch file */
21
+ patchChecksum?: string;
22
+ /** Expected checksum after applying patch */
23
+ targetChecksum?: string;
24
+ }
25
+ /**
26
+ * Delta download result
27
+ */
28
+ export interface DeltaDownloadResult {
29
+ /** Whether delta was used */
30
+ usedDelta: boolean;
31
+ /** The final bundle data */
32
+ bundleData: ArrayBuffer;
33
+ /** Checksum of the bundle */
34
+ checksum: string;
35
+ /** Download size (delta or full) */
36
+ downloadSize: number;
37
+ /** Time taken in milliseconds */
38
+ duration: number;
39
+ }
40
+ /**
41
+ * Delta processor for applying patch updates
42
+ */
43
+ export declare class DeltaProcessor {
44
+ private readonly logger;
45
+ private readonly configManager;
46
+ constructor();
47
+ /**
48
+ * Download update with delta support
49
+ * Falls back to full download if delta fails
50
+ */
51
+ downloadWithDelta(updateInfo: UpdateCheckResponse, currentBundleData: ArrayBuffer | null, onProgress?: (percent: number) => void): Promise<DeltaDownloadResult>;
52
+ /**
53
+ * Download a delta patch file
54
+ */
55
+ private downloadPatch;
56
+ /**
57
+ * Download full bundle
58
+ */
59
+ private downloadFull;
60
+ /**
61
+ * Apply a delta patch to create new bundle
62
+ *
63
+ * Only NUDELTA/1 is accepted. Target checksum verification still runs after
64
+ * reconstruction, providing an independent integrity boundary.
65
+ */
66
+ private applyPatch;
67
+ private applyNuDelta;
68
+ /**
69
+ * Calculate SHA-256 checksum
70
+ */
71
+ calculateChecksum(data: ArrayBuffer): Promise<string>;
72
+ /**
73
+ * Verify checksum matches
74
+ */
75
+ verifyChecksum(data: ArrayBuffer, expectedChecksum: string): Promise<boolean>;
76
+ /**
77
+ * Check if delta updates are enabled
78
+ */
79
+ isDeltaEnabled(): boolean;
80
+ }
81
+ /**
82
+ * Create delta processor instance
83
+ */
84
+ export declare function createDeltaProcessor(): DeltaProcessor;
@@ -0,0 +1,257 @@
1
+ /**
2
+ * Delta Processor
3
+ *
4
+ * Handles delta/patch-based updates for reduced download sizes.
5
+ * Applies the bounded, deterministic NUDELTA/1 copy/literal format emitted by
6
+ * the canonical backend. Unknown legacy patch formats fail closed and trigger
7
+ * the normal full-bundle fallback.
8
+ */
9
+ import { Logger } from '../core/logger';
10
+ import { ConfigManager } from '../core/config';
11
+ import { DownloadError, ErrorCode, ValidationError } from '../core/errors';
12
+ import { SecurityValidator } from '../core/security';
13
+ /**
14
+ * Delta processor for applying patch updates
15
+ */
16
+ export class DeltaProcessor {
17
+ constructor() {
18
+ this.logger = Logger.getInstance();
19
+ this.configManager = ConfigManager.getInstance();
20
+ }
21
+ /**
22
+ * Download update with delta support
23
+ * Falls back to full download if delta fails
24
+ */
25
+ async downloadWithDelta(updateInfo, currentBundleData, onProgress) {
26
+ var _a;
27
+ const startTime = Date.now();
28
+ // Check if delta is available and we have current bundle
29
+ if (this.configManager.get('enableDeltaUpdates') &&
30
+ ((_a = updateInfo.delta) === null || _a === void 0 ? void 0 : _a.available) &&
31
+ updateInfo.delta.patchUrl &&
32
+ currentBundleData) {
33
+ try {
34
+ this.logger.info('Attempting delta update', {
35
+ patchSize: updateInfo.delta.patchSize,
36
+ fullSize: updateInfo.size,
37
+ });
38
+ onProgress === null || onProgress === void 0 ? void 0 : onProgress(10);
39
+ // Download delta patch
40
+ const patchData = await this.downloadPatch(updateInfo.delta.patchUrl);
41
+ if (updateInfo.delta.patchChecksum &&
42
+ !await this.verifyChecksum(patchData, updateInfo.delta.patchChecksum)) {
43
+ throw new ValidationError(ErrorCode.CHECKSUM_MISMATCH, 'Delta patch checksum mismatch');
44
+ }
45
+ onProgress === null || onProgress === void 0 ? void 0 : onProgress(50);
46
+ // Apply delta patch
47
+ const patchedBundle = await this.applyPatch(currentBundleData, patchData, updateInfo.delta.targetChecksum || updateInfo.checksum);
48
+ onProgress === null || onProgress === void 0 ? void 0 : onProgress(90);
49
+ // Verify result
50
+ const resultChecksum = await this.calculateChecksum(patchedBundle);
51
+ if (resultChecksum !== (updateInfo.delta.targetChecksum || updateInfo.checksum)) {
52
+ throw new ValidationError(ErrorCode.CHECKSUM_MISMATCH, 'Delta patch result checksum mismatch');
53
+ }
54
+ onProgress === null || onProgress === void 0 ? void 0 : onProgress(100);
55
+ const duration = Date.now() - startTime;
56
+ this.logger.info('Delta update successful', {
57
+ downloadSize: patchData.byteLength,
58
+ resultSize: patchedBundle.byteLength,
59
+ savings: `${Math.round((1 - patchData.byteLength / (updateInfo.size || patchedBundle.byteLength)) * 100)}%`,
60
+ duration,
61
+ });
62
+ return {
63
+ usedDelta: true,
64
+ bundleData: patchedBundle,
65
+ checksum: resultChecksum,
66
+ downloadSize: patchData.byteLength,
67
+ duration,
68
+ };
69
+ }
70
+ catch (error) {
71
+ this.logger.warn('Delta update failed, falling back to full download', { error });
72
+ // Fall through to full download
73
+ }
74
+ }
75
+ // Full download
76
+ onProgress === null || onProgress === void 0 ? void 0 : onProgress(10);
77
+ if (!updateInfo.bundleUrl) {
78
+ throw new DownloadError(ErrorCode.DOWNLOAD_FAILED, 'No bundle URL provided');
79
+ }
80
+ const fullBundle = await this.downloadFull(updateInfo.bundleUrl, onProgress);
81
+ const duration = Date.now() - startTime;
82
+ const checksum = await this.calculateChecksum(fullBundle);
83
+ // Verify checksum
84
+ if (updateInfo.checksum && checksum !== updateInfo.checksum) {
85
+ throw new ValidationError(ErrorCode.CHECKSUM_MISMATCH, 'Full bundle checksum mismatch');
86
+ }
87
+ return {
88
+ usedDelta: false,
89
+ bundleData: fullBundle,
90
+ checksum,
91
+ downloadSize: fullBundle.byteLength,
92
+ duration,
93
+ };
94
+ }
95
+ /**
96
+ * Download a delta patch file
97
+ */
98
+ async downloadPatch(url) {
99
+ SecurityValidator.validateDownloadUrl(url);
100
+ const response = await fetch(url);
101
+ if (!response.ok) {
102
+ throw new DownloadError(ErrorCode.DOWNLOAD_FAILED, `Failed to download delta patch: ${response.status}`);
103
+ }
104
+ const maxSize = this.configManager.get('maxBundleSize');
105
+ const declaredSize = Number(response.headers.get('content-length') || 0);
106
+ if (declaredSize > maxSize) {
107
+ throw new DownloadError(ErrorCode.BUNDLE_TOO_LARGE, 'Delta patch exceeds the bundle size limit');
108
+ }
109
+ const data = await response.arrayBuffer();
110
+ if (data.byteLength > maxSize) {
111
+ throw new DownloadError(ErrorCode.BUNDLE_TOO_LARGE, 'Delta patch exceeds the bundle size limit');
112
+ }
113
+ return data;
114
+ }
115
+ /**
116
+ * Download full bundle
117
+ */
118
+ async downloadFull(url, onProgress) {
119
+ SecurityValidator.validateDownloadUrl(url);
120
+ const response = await fetch(url);
121
+ if (!response.ok) {
122
+ throw new DownloadError(ErrorCode.DOWNLOAD_FAILED, `Failed to download bundle: ${response.status}`);
123
+ }
124
+ // If we can track progress
125
+ const contentLength = response.headers.get('content-length');
126
+ const totalBytes = contentLength ? parseInt(contentLength, 10) : 0;
127
+ const maxSize = this.configManager.get('maxBundleSize');
128
+ if (totalBytes > maxSize) {
129
+ throw new DownloadError(ErrorCode.BUNDLE_TOO_LARGE, 'Bundle exceeds the configured size limit');
130
+ }
131
+ if (totalBytes && response.body) {
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
+ if (receivedBytes > maxSize) {
142
+ await reader.cancel();
143
+ throw new DownloadError(ErrorCode.BUNDLE_TOO_LARGE, 'Bundle exceeds the configured size limit');
144
+ }
145
+ if (onProgress) {
146
+ const percent = Math.round((receivedBytes / totalBytes) * 90) + 10;
147
+ onProgress(Math.min(percent, 99));
148
+ }
149
+ }
150
+ onProgress === null || onProgress === void 0 ? void 0 : onProgress(100);
151
+ // Combine chunks
152
+ const result = new Uint8Array(receivedBytes);
153
+ let offset = 0;
154
+ for (const chunk of chunks) {
155
+ result.set(chunk, offset);
156
+ offset += chunk.length;
157
+ }
158
+ return result.buffer;
159
+ }
160
+ // Simple download without progress
161
+ const data = await response.arrayBuffer();
162
+ if (data.byteLength > maxSize) {
163
+ throw new DownloadError(ErrorCode.BUNDLE_TOO_LARGE, 'Bundle exceeds the configured size limit');
164
+ }
165
+ onProgress === null || onProgress === void 0 ? void 0 : onProgress(100);
166
+ return data;
167
+ }
168
+ /**
169
+ * Apply a delta patch to create new bundle
170
+ *
171
+ * Only NUDELTA/1 is accepted. Target checksum verification still runs after
172
+ * reconstruction, providing an independent integrity boundary.
173
+ */
174
+ async applyPatch(currentBundle, patchData, expectedChecksum) {
175
+ const patchText = new TextDecoder().decode(patchData);
176
+ const patch = JSON.parse(patchText);
177
+ if (patch.format !== 'NUDELTA/1' || patch.targetChecksum !== expectedChecksum) {
178
+ throw new Error('Unsupported or inconsistent delta patch');
179
+ }
180
+ const baseChecksum = await this.calculateChecksum(currentBundle);
181
+ if (patch.baseChecksum !== baseChecksum)
182
+ throw new Error('NUDELTA base checksum mismatch');
183
+ return this.applyNuDelta(currentBundle, patch);
184
+ }
185
+ applyNuDelta(currentBundle, patch) {
186
+ const maxSize = this.configManager.get('maxBundleSize');
187
+ if (!Number.isSafeInteger(patch.targetSize) || patch.targetSize <= 0 || patch.targetSize > maxSize) {
188
+ throw new Error('NUDELTA target size is invalid');
189
+ }
190
+ if (!Array.isArray(patch.operations) || patch.operations.length === 0 || patch.operations.length > 100000) {
191
+ throw new Error('NUDELTA operation count is invalid');
192
+ }
193
+ const base = new Uint8Array(currentBundle);
194
+ const chunks = [];
195
+ let resultSize = 0;
196
+ for (const operation of patch.operations) {
197
+ let chunk;
198
+ if (operation.op === 'copy') {
199
+ if (!Number.isSafeInteger(operation.offset) || !Number.isSafeInteger(operation.length) ||
200
+ operation.offset < 0 || operation.length <= 0 || operation.offset + operation.length > base.length) {
201
+ throw new Error('NUDELTA copy operation is out of bounds');
202
+ }
203
+ chunk = base.slice(operation.offset, operation.offset + operation.length);
204
+ }
205
+ else if (operation.op === 'literal' && typeof operation.data === 'string') {
206
+ if (!/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/.test(operation.data)) {
207
+ throw new Error('NUDELTA literal is not valid base64');
208
+ }
209
+ const binary = atob(operation.data);
210
+ chunk = Uint8Array.from(binary, character => character.charCodeAt(0));
211
+ }
212
+ else {
213
+ throw new Error('NUDELTA operation is invalid');
214
+ }
215
+ resultSize += chunk.length;
216
+ if (resultSize > patch.targetSize)
217
+ throw new Error('NUDELTA output exceeds declared size');
218
+ chunks.push(chunk);
219
+ }
220
+ if (resultSize !== patch.targetSize)
221
+ throw new Error('NUDELTA output size mismatch');
222
+ const result = new Uint8Array(resultSize);
223
+ let offset = 0;
224
+ for (const chunk of chunks) {
225
+ result.set(chunk, offset);
226
+ offset += chunk.length;
227
+ }
228
+ return result.buffer;
229
+ }
230
+ /**
231
+ * Calculate SHA-256 checksum
232
+ */
233
+ async calculateChecksum(data) {
234
+ const hashBuffer = await crypto.subtle.digest('SHA-256', data);
235
+ const hashArray = Array.from(new Uint8Array(hashBuffer));
236
+ return hashArray.map((b) => b.toString(16).padStart(2, '0')).join('');
237
+ }
238
+ /**
239
+ * Verify checksum matches
240
+ */
241
+ async verifyChecksum(data, expectedChecksum) {
242
+ const actualChecksum = await this.calculateChecksum(data);
243
+ return actualChecksum.toLowerCase() === expectedChecksum.toLowerCase();
244
+ }
245
+ /**
246
+ * Check if delta updates are enabled
247
+ */
248
+ isDeltaEnabled() {
249
+ return this.configManager.get('enableDeltaUpdates');
250
+ }
251
+ }
252
+ /**
253
+ * Create delta processor instance
254
+ */
255
+ export function createDeltaProcessor() {
256
+ return new DeltaProcessor();
257
+ }
@@ -0,0 +1,106 @@
1
+ import type { DownloadProgressEvent } from '../definitions';
2
+ export interface DownloadOptions {
3
+ onProgress?: (event: DownloadProgressEvent) => void;
4
+ /**
5
+ * Byte offset to resume from. When set, the request carries a
6
+ * `Range: bytes=<N>-` header. If the server responds with 200 instead
7
+ * of 206, the plugin discards any partial data the caller held and
8
+ * treats the response as a full download (see resumeDownload).
9
+ */
10
+ resumePosition?: number;
11
+ }
12
+ /**
13
+ * Manages file downloads with progress tracking and resume capability
14
+ */
15
+ export declare class DownloadManager {
16
+ private activeDownloads;
17
+ /**
18
+ * Persisted-past-request metadata for the most recent `download()`
19
+ * call per bundleId. Today we only stash whether the server honoured
20
+ * a Range request (HTTP 206 vs 200). resumeDownload() consults this
21
+ * to decide whether to concatenate or discard its partial prefix.
22
+ */
23
+ private lastResponseMeta;
24
+ private readonly logger;
25
+ private readonly configManager;
26
+ private filesystem;
27
+ constructor();
28
+ /**
29
+ * Initialize the download manager
30
+ */
31
+ initialize(): Promise<void>;
32
+ /**
33
+ * Validate URL against allowed hosts
34
+ */
35
+ private validateUrl;
36
+ /**
37
+ * Download a file with progress tracking.
38
+ *
39
+ * Accepts either a bare `onProgress` callback (back-compat) or a full
40
+ * DownloadOptions object. When `resumePosition` is set, the request
41
+ * carries a Range header; the resulting download state records
42
+ * whether the server actually honoured it (`serverReturnedPartial`).
43
+ */
44
+ download(url: string, bundleId: string, onProgressOrOptions?: ((event: DownloadProgressEvent) => void) | DownloadOptions): Promise<Blob>;
45
+ /**
46
+ * Resume a previously interrupted download.
47
+ *
48
+ * Emits a Range-request download starting at the partial-data offset.
49
+ * If the server honours the range (HTTP 206), the partial + remaining
50
+ * bytes are concatenated. If the server returns a full response
51
+ * (HTTP 200 — common when the upstream URL's ETag changed, or when a
52
+ * CDN doesn't honour ranges) the partial data is discarded and the
53
+ * full response is used. Previously this path silently double-wrote
54
+ * bytes when the server fell back to 200; this was a latent
55
+ * bundle-corruption bug.
56
+ */
57
+ resumeDownload(url: string, bundleId: string, partialData: Blob, onProgress?: (event: DownloadProgressEvent) => void): Promise<Blob>;
58
+ /**
59
+ * Check if a download can be resumed
60
+ */
61
+ canResume(url: string): Promise<boolean>;
62
+ /**
63
+ * Validate content type
64
+ */
65
+ private isValidContentType;
66
+ /**
67
+ * Validate blob size
68
+ */
69
+ private validateBlobSize;
70
+ /**
71
+ * Cancel a download
72
+ */
73
+ cancelDownload(bundleId: string): void;
74
+ /**
75
+ * Cancel all active downloads
76
+ */
77
+ cancelAllDownloads(): void;
78
+ /**
79
+ * Check if a download is active
80
+ */
81
+ isDownloading(bundleId: string): boolean;
82
+ /**
83
+ * Get active download count
84
+ */
85
+ getActiveDownloadCount(): number;
86
+ /**
87
+ * Download with retry logic
88
+ */
89
+ downloadWithRetry(url: string, bundleId: string, onProgress?: (event: DownloadProgressEvent) => void): Promise<Blob>;
90
+ /**
91
+ * Convert blob to ArrayBuffer
92
+ */
93
+ blobToArrayBuffer(blob: Blob): Promise<ArrayBuffer>;
94
+ /**
95
+ * Save blob to filesystem
96
+ */
97
+ saveBlob(bundleId: string, blob: Blob): Promise<string>;
98
+ /**
99
+ * Load blob from filesystem
100
+ */
101
+ loadBlob(bundleId: string): Promise<Blob | null>;
102
+ /**
103
+ * Delete blob from filesystem
104
+ */
105
+ deleteBlob(bundleId: string): Promise<void>;
106
+ }