@gfean/react-native-bundle-drop 0.3.8 → 0.4.1

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 (77) hide show
  1. package/BundleDrop.podspec +9 -2
  2. package/README.md +19 -0
  3. package/android/build.gradle +25 -4
  4. package/android/src/main/cpp/CMakeLists.txt +33 -0
  5. package/android/src/main/cpp/bundle_drop_xdelta_jni.c +55 -0
  6. package/android/src/main/java/com/bundledrop/BundleDropBundleVerifier.kt +73 -0
  7. package/android/src/main/java/com/bundledrop/BundleDropFileOps.kt +193 -8
  8. package/android/src/main/java/com/bundledrop/BundleDropModule.kt +60 -7
  9. package/android/src/main/java/com/bundledrop/BundleDropOtaPrefs.kt +2 -12
  10. package/android/src/main/java/com/bundledrop/BundleDropOtaResolver.kt +208 -3
  11. package/android/src/main/java/com/bundledrop/BundleDropXdeltaNative.kt +57 -0
  12. package/ios/BundleDropBridge.m +27 -0
  13. package/ios/BundleDropBundleVerifier.swift +106 -0
  14. package/ios/BundleDropFileOps.swift +149 -0
  15. package/ios/BundleDropModule.swift +100 -11
  16. package/ios/BundleDropOtaResolver.swift +149 -3
  17. package/ios/BundleDropZipExtractor.m +75 -3
  18. package/lib/CLI/cli.js +1 -8
  19. package/lib/CLI/scripts/upload-cli.d.ts +0 -1
  20. package/lib/CLI/scripts/upload-cli.js +26 -20
  21. package/lib/api/client.d.ts +11 -1
  22. package/lib/api/client.js +84 -17
  23. package/lib/api/clientApi.d.ts +2 -1
  24. package/lib/api/clientApi.js +9 -0
  25. package/lib/api/types.d.ts +65 -13
  26. package/lib/bundleInfo.d.ts +2 -0
  27. package/lib/fs/bundlePointer.d.ts +2 -1
  28. package/lib/fs/bundlePointer.js +34 -6
  29. package/lib/fs/fsUtils.js +4 -1
  30. package/lib/injectImageResolver.js +135 -45
  31. package/lib/install/bundleInstallShared.d.ts +8 -0
  32. package/lib/install/bundleInstallShared.js +97 -0
  33. package/lib/install/bundleVerification.d.ts +5 -0
  34. package/lib/install/bundleVerification.js +34 -0
  35. package/lib/install/installFromZip.d.ts +2 -5
  36. package/lib/install/installFromZip.js +33 -62
  37. package/lib/loadConfig.js +12 -1
  38. package/lib/manager/downloadAndInstall.d.ts +9 -0
  39. package/lib/manager/downloadAndInstall.js +84 -24
  40. package/lib/manager/reporting.js +26 -2
  41. package/lib/manager/rollbackState.js +21 -12
  42. package/lib/manager/updateCheck.js +89 -11
  43. package/lib/manager/updateState.js +3 -9
  44. package/lib/manifest/bundleManifest.d.ts +33 -0
  45. package/lib/manifest/bundleManifest.js +298 -0
  46. package/lib/native/bundleDropNative.js +1 -2
  47. package/lib/native/fs.d.ts +14 -0
  48. package/lib/native/fs.js +35 -0
  49. package/lib/patch-engine/installFromPatchSet.d.ts +16 -0
  50. package/lib/patch-engine/installFromPatchSet.js +143 -0
  51. package/lib/patch-engine/patchOperations.d.ts +33 -0
  52. package/lib/patch-engine/patchOperations.js +77 -0
  53. package/lib/patch-engine/patchTransport.d.ts +18 -0
  54. package/lib/patch-engine/patchTransport.js +81 -0
  55. package/lib/patchAlgorithms.d.ts +4 -0
  56. package/lib/patchAlgorithms.js +9 -0
  57. package/lib/runtime/service.js +43 -9
  58. package/lib/scripts/bundle.d.ts +3 -0
  59. package/lib/scripts/bundle.js +184 -36
  60. package/lib/scripts/download-bundle.js +18 -7
  61. package/lib/scripts/upload-bundle.js +25 -28
  62. package/package.json +44 -5
  63. package/third_party/xdelta/NOTICE +7 -0
  64. package/third_party/xdelta/PROVENANCE.md +10 -0
  65. package/third_party/xdelta/bundle_drop_xdelta.c +252 -0
  66. package/third_party/xdelta/bundle_drop_xdelta.h +26 -0
  67. package/third_party/xdelta/xdelta3/LICENSE +176 -0
  68. package/third_party/xdelta/xdelta3/config.h +34 -0
  69. package/third_party/xdelta/xdelta3/xdelta3-cfgs.h +171 -0
  70. package/third_party/xdelta/xdelta3/xdelta3-decode.h +1219 -0
  71. package/third_party/xdelta/xdelta3/xdelta3-hash.h +159 -0
  72. package/third_party/xdelta/xdelta3/xdelta3-internal.h +385 -0
  73. package/third_party/xdelta/xdelta3/xdelta3-list.h +127 -0
  74. package/third_party/xdelta/xdelta3/xdelta3.c +4819 -0
  75. package/third_party/xdelta/xdelta3/xdelta3.h +1476 -0
  76. package/lib/CLI/scripts/init-native-config.d.ts +0 -18
  77. package/lib/CLI/scripts/init-native-config.js +0 -539
@@ -9,10 +9,11 @@ const rollbackState_1 = require("./rollbackState");
9
9
  const getUpdateState = async (cached) => {
10
10
  const info = cached?.bundleInfo !== undefined ? cached.bundleInfo : await (0, bundleInfo_1.readBundleInfo)();
11
11
  const path = cached?.bundlePath !== undefined ? cached.bundlePath : await (0, bundleDropNative_1.getDownloadedBundlePathNative)();
12
+ const pendingApply = !!path && (info?.pendingApply ?? false);
12
13
  return {
13
14
  hasBundle: !!path,
14
15
  info,
15
- pendingApply: info?.pendingApply ?? false,
16
+ pendingApply,
16
17
  };
17
18
  };
18
19
  exports.getUpdateState = getUpdateState;
@@ -34,8 +35,8 @@ const reconcileAppliedBundleOnLaunch = async (cached) => {
34
35
  exports.reconcileAppliedBundleOnLaunch = reconcileAppliedBundleOnLaunch;
35
36
  const applyUpdate = async (onStatusUpdate, onBeforeRestart) => {
36
37
  try {
37
- const path = await (0, bundleDropNative_1.getDownloadedBundlePathNative)();
38
38
  const info = await (0, bundleInfo_1.readBundleInfo)();
39
+ const path = await (0, bundleDropNative_1.getDownloadedBundlePathNative)();
39
40
  if (!path) {
40
41
  onStatusUpdate?.('⚠️ No downloaded bundle to apply');
41
42
  return { status: 'noBundle' };
@@ -54,13 +55,6 @@ const applyUpdate = async (onStatusUpdate, onBeforeRestart) => {
54
55
  }
55
56
  onStatusUpdate?.('♻️ Applying downloaded bundle...');
56
57
  await (0, bundleInfo_1.updateBundleInfo)({ pendingApply: false, installedAt: new Date().toISOString() });
57
- (0, reporting_1.reportInstalledIfReady)({
58
- hasBundle: true,
59
- info: info ? { ...info, pendingApply: false } : info,
60
- }).catch(reportError => {
61
- // Telemetry should not block applying the already-downloaded bundle.
62
- console.warn('⚠️ Failed to report bundle install during apply:', reportError);
63
- });
64
58
  onBeforeRestart?.();
65
59
  (0, bundleDropNative_1.restartReactNativeNative)();
66
60
  return { status: 'applied' };
@@ -0,0 +1,33 @@
1
+ export declare const BUNDLE_MANIFEST = "bundle-manifest.json";
2
+ export type BundleManifestFileRole = 'jsbundle' | 'metadata' | 'asset' | 'androidImageManifest';
3
+ export type BundleManifestFile = {
4
+ path: string;
5
+ size: number;
6
+ sha256: string;
7
+ role: BundleManifestFileRole;
8
+ executable?: boolean;
9
+ };
10
+ export type BundleManifest = {
11
+ manifestVersion: 1;
12
+ bundleHash: string;
13
+ jsBundleHash: string;
14
+ platform: 'ios' | 'android' | string;
15
+ runtimeVersion: string;
16
+ version: string;
17
+ manifestHash: string;
18
+ files: BundleManifestFile[];
19
+ };
20
+ export declare const byteLengthFromBase64: (value: string) => number;
21
+ export declare const base64ToBytes: (value: string) => number[];
22
+ export declare const sha256Bytes: (input: number[] | Uint8Array) => string;
23
+ export declare const sha256String: (value: string) => string;
24
+ export declare const sha256Base64: (value: string) => string;
25
+ export declare const normalizeManifestPath: (value: string) => string;
26
+ export declare const sortManifestFiles: (files: BundleManifestFile[]) => BundleManifestFile[];
27
+ export declare const canonicalManifestFileEntries: (files: BundleManifestFile[]) => Record<string, unknown>[];
28
+ export declare const calculateBundleHash: (files: BundleManifestFile[]) => string;
29
+ export declare const calculateManifestHash: (manifest: Omit<BundleManifest, "manifestHash">) => string;
30
+ export declare const createBundleManifest: (input: Omit<BundleManifest, "manifestVersion" | "manifestHash" | "files"> & {
31
+ files: BundleManifestFile[];
32
+ }) => BundleManifest;
33
+ export declare const assertValidBundleManifest: (manifest: BundleManifest, expectedBundleHash?: string, expectedPlatform?: "ios" | "android") => void;
@@ -0,0 +1,298 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.assertValidBundleManifest = exports.createBundleManifest = exports.calculateManifestHash = exports.calculateBundleHash = exports.canonicalManifestFileEntries = exports.sortManifestFiles = exports.normalizeManifestPath = exports.sha256Base64 = exports.sha256String = exports.sha256Bytes = exports.base64ToBytes = exports.byteLengthFromBase64 = exports.BUNDLE_MANIFEST = void 0;
4
+ exports.BUNDLE_MANIFEST = 'bundle-manifest.json';
5
+ const K = [
6
+ 0x428a2f98, 0x71374491, 0xb5c0fbcf, 0xe9b5dba5, 0x3956c25b, 0x59f111f1, 0x923f82a4, 0xab1c5ed5,
7
+ 0xd807aa98, 0x12835b01, 0x243185be, 0x550c7dc3, 0x72be5d74, 0x80deb1fe, 0x9bdc06a7, 0xc19bf174,
8
+ 0xe49b69c1, 0xefbe4786, 0x0fc19dc6, 0x240ca1cc, 0x2de92c6f, 0x4a7484aa, 0x5cb0a9dc, 0x76f988da,
9
+ 0x983e5152, 0xa831c66d, 0xb00327c8, 0xbf597fc7, 0xc6e00bf3, 0xd5a79147, 0x06ca6351, 0x14292967,
10
+ 0x27b70a85, 0x2e1b2138, 0x4d2c6dfc, 0x53380d13, 0x650a7354, 0x766a0abb, 0x81c2c92e, 0x92722c85,
11
+ 0xa2bfe8a1, 0xa81a664b, 0xc24b8b70, 0xc76c51a3, 0xd192e819, 0xd6990624, 0xf40e3585, 0x106aa070,
12
+ 0x19a4c116, 0x1e376c08, 0x2748774c, 0x34b0bcb5, 0x391c0cb3, 0x4ed8aa4a, 0x5b9cca4f, 0x682e6ff3,
13
+ 0x748f82ee, 0x78a5636f, 0x84c87814, 0x8cc70208, 0x90befffa, 0xa4506ceb, 0xbef9a3f7, 0xc67178f2,
14
+ ];
15
+ const utf8ToBytes = (value) => {
16
+ const encoded = encodeURIComponent(value);
17
+ const bytes = [];
18
+ for (let i = 0; i < encoded.length; i += 1) {
19
+ if (encoded[i] === '%') {
20
+ bytes.push(parseInt(encoded.slice(i + 1, i + 3), 16));
21
+ i += 2;
22
+ }
23
+ else {
24
+ bytes.push(encoded.charCodeAt(i));
25
+ }
26
+ }
27
+ return bytes;
28
+ };
29
+ const byteLengthFromBase64 = (value) => {
30
+ const clean = value.replace(/\s+/g, '');
31
+ if (!clean)
32
+ return 0;
33
+ const padding = clean.endsWith('==') ? 2 : clean.endsWith('=') ? 1 : 0;
34
+ return Math.floor((clean.length * 3) / 4) - padding;
35
+ };
36
+ exports.byteLengthFromBase64 = byteLengthFromBase64;
37
+ const base64ToBytes = (value) => {
38
+ const chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/';
39
+ const clean = value.replace(/\s+/g, '');
40
+ const bytes = [];
41
+ for (let i = 0; i < clean.length; i += 4) {
42
+ const c1 = chars.indexOf(clean[i]);
43
+ const c2 = chars.indexOf(clean[i + 1]);
44
+ const c3 = clean[i + 2] === '=' ? -1 : chars.indexOf(clean[i + 2]);
45
+ const c4 = clean[i + 3] === '=' ? -1 : chars.indexOf(clean[i + 3]);
46
+ if (c1 < 0 || c2 < 0 || (clean[i + 2] !== '=' && c3 < 0) || (clean[i + 3] !== '=' && c4 < 0)) {
47
+ throw new Error('Invalid base64 data');
48
+ }
49
+ const n = (c1 << 18) | (c2 << 12) | ((c3 < 0 ? 0 : c3) << 6) | (c4 < 0 ? 0 : c4);
50
+ bytes.push((n >> 16) & 0xff);
51
+ if (c3 >= 0)
52
+ bytes.push((n >> 8) & 0xff);
53
+ if (c4 >= 0)
54
+ bytes.push(n & 0xff);
55
+ }
56
+ return bytes;
57
+ };
58
+ exports.base64ToBytes = base64ToBytes;
59
+ const sha256Bytes = (input) => {
60
+ const bytes = Array.from(input);
61
+ const bitLength = bytes.length * 8;
62
+ bytes.push(0x80);
63
+ while ((bytes.length % 64) !== 56)
64
+ bytes.push(0);
65
+ const high = Math.floor(bitLength / 0x100000000);
66
+ const low = bitLength >>> 0;
67
+ bytes.push((high >>> 24) & 0xff, (high >>> 16) & 0xff, (high >>> 8) & 0xff, high & 0xff);
68
+ bytes.push((low >>> 24) & 0xff, (low >>> 16) & 0xff, (low >>> 8) & 0xff, low & 0xff);
69
+ let h0 = 0x6a09e667;
70
+ let h1 = 0xbb67ae85;
71
+ let h2 = 0x3c6ef372;
72
+ let h3 = 0xa54ff53a;
73
+ let h4 = 0x510e527f;
74
+ let h5 = 0x9b05688c;
75
+ let h6 = 0x1f83d9ab;
76
+ let h7 = 0x5be0cd19;
77
+ const w = new Array(64);
78
+ for (let i = 0; i < bytes.length; i += 64) {
79
+ for (let t = 0; t < 16; t += 1) {
80
+ const j = i + t * 4;
81
+ w[t] = ((bytes[j] << 24) | (bytes[j + 1] << 16) | (bytes[j + 2] << 8) | bytes[j + 3]) >>> 0;
82
+ }
83
+ for (let t = 16; t < 64; t += 1) {
84
+ const s0 = (rightRotate(w[t - 15], 7) ^ rightRotate(w[t - 15], 18) ^ (w[t - 15] >>> 3)) >>> 0;
85
+ const s1 = (rightRotate(w[t - 2], 17) ^ rightRotate(w[t - 2], 19) ^ (w[t - 2] >>> 10)) >>> 0;
86
+ w[t] = (((w[t - 16] + s0) >>> 0) + ((w[t - 7] + s1) >>> 0)) >>> 0;
87
+ }
88
+ let a = h0;
89
+ let b = h1;
90
+ let c = h2;
91
+ let d = h3;
92
+ let e = h4;
93
+ let f = h5;
94
+ let g = h6;
95
+ let h = h7;
96
+ for (let t = 0; t < 64; t += 1) {
97
+ const s1 = (rightRotate(e, 6) ^ rightRotate(e, 11) ^ rightRotate(e, 25)) >>> 0;
98
+ const ch = ((e & f) ^ (~e & g)) >>> 0;
99
+ const temp1 = (((((h + s1) >>> 0) + ch) >>> 0) + ((K[t] + w[t]) >>> 0)) >>> 0;
100
+ const s0 = (rightRotate(a, 2) ^ rightRotate(a, 13) ^ rightRotate(a, 22)) >>> 0;
101
+ const maj = ((a & b) ^ (a & c) ^ (b & c)) >>> 0;
102
+ const temp2 = (s0 + maj) >>> 0;
103
+ h = g;
104
+ g = f;
105
+ f = e;
106
+ e = (d + temp1) >>> 0;
107
+ d = c;
108
+ c = b;
109
+ b = a;
110
+ a = (temp1 + temp2) >>> 0;
111
+ }
112
+ h0 = (h0 + a) >>> 0;
113
+ h1 = (h1 + b) >>> 0;
114
+ h2 = (h2 + c) >>> 0;
115
+ h3 = (h3 + d) >>> 0;
116
+ h4 = (h4 + e) >>> 0;
117
+ h5 = (h5 + f) >>> 0;
118
+ h6 = (h6 + g) >>> 0;
119
+ h7 = (h7 + h) >>> 0;
120
+ }
121
+ return [h0, h1, h2, h3, h4, h5, h6, h7]
122
+ .map(value => value.toString(16).padStart(8, '0'))
123
+ .join('');
124
+ };
125
+ exports.sha256Bytes = sha256Bytes;
126
+ const rightRotate = (value, bits) => ((value >>> bits) | (value << (32 - bits))) >>> 0;
127
+ const sha256String = (value) => (0, exports.sha256Bytes)(utf8ToBytes(value));
128
+ exports.sha256String = sha256String;
129
+ const sha256Base64 = (value) => (0, exports.sha256Bytes)((0, exports.base64ToBytes)(value));
130
+ exports.sha256Base64 = sha256Base64;
131
+ const metadataPathForPlatform = (platform) => `metadata-${platform}.json`;
132
+ const normalizeManifestPath = (value) => {
133
+ if (typeof value !== 'string') {
134
+ throw new Error('Manifest path must be a string');
135
+ }
136
+ if (value !== value.trim()) {
137
+ throw new Error(`Invalid manifest path: ${value}`);
138
+ }
139
+ if (!value || value.includes('\0') || value.includes('\\') || value.startsWith('/') || /^[A-Za-z]:[\\/]/.test(value)) {
140
+ throw new Error(`Invalid manifest path: ${value}`);
141
+ }
142
+ const normalized = value;
143
+ if (!normalized || normalized.split('/').some(segment => !segment || segment === '..' || segment === '.')) {
144
+ throw new Error(`Invalid manifest path: ${value}`);
145
+ }
146
+ return normalized;
147
+ };
148
+ exports.normalizeManifestPath = normalizeManifestPath;
149
+ const sortManifestFiles = (files) => [...files]
150
+ .map(file => ({
151
+ ...file,
152
+ path: (0, exports.normalizeManifestPath)(file.path),
153
+ executable: file.executable || undefined,
154
+ }))
155
+ .sort((a, b) => compareUtf8(a.path, b.path));
156
+ exports.sortManifestFiles = sortManifestFiles;
157
+ const compareUtf8 = (left, right) => {
158
+ const leftBytes = utf8ToBytes(left);
159
+ const rightBytes = utf8ToBytes(right);
160
+ const length = Math.min(leftBytes.length, rightBytes.length);
161
+ for (let i = 0; i < length; i += 1) {
162
+ if (leftBytes[i] !== rightBytes[i]) {
163
+ return leftBytes[i] - rightBytes[i];
164
+ }
165
+ }
166
+ return leftBytes.length - rightBytes.length;
167
+ };
168
+ const stableStringify = (value) => {
169
+ if (Array.isArray(value)) {
170
+ return `[${value.map(item => stableStringify(item)).join(',')}]`;
171
+ }
172
+ if (value && typeof value === 'object') {
173
+ const entries = Object.entries(value)
174
+ .filter(([, entryValue]) => entryValue !== undefined)
175
+ .sort(([left], [right]) => compareUtf8(left, right));
176
+ return `{${entries
177
+ .map(([key, entryValue]) => `${JSON.stringify(key)}:${stableStringify(entryValue)}`)
178
+ .join(',')}}`;
179
+ }
180
+ return JSON.stringify(value);
181
+ };
182
+ const canonicalManifestFileEntries = (files) => (0, exports.sortManifestFiles)(files).map(file => {
183
+ const entry = {
184
+ path: file.path,
185
+ role: file.role,
186
+ size: file.size,
187
+ sha256: file.sha256,
188
+ };
189
+ if (file.executable) {
190
+ entry.executable = true;
191
+ }
192
+ return entry;
193
+ });
194
+ exports.canonicalManifestFileEntries = canonicalManifestFileEntries;
195
+ const calculateBundleHash = (files) => (0, exports.sha256String)(stableStringify({
196
+ manifestVersion: 1,
197
+ files: (0, exports.canonicalManifestFileEntries)(files),
198
+ }));
199
+ exports.calculateBundleHash = calculateBundleHash;
200
+ const calculateManifestHash = (manifest) => (0, exports.sha256String)(stableStringify({
201
+ manifestVersion: 1,
202
+ bundleHash: manifest.bundleHash,
203
+ jsBundleHash: manifest.jsBundleHash,
204
+ platform: manifest.platform,
205
+ runtimeVersion: manifest.runtimeVersion,
206
+ version: manifest.version,
207
+ files: (0, exports.sortManifestFiles)(manifest.files),
208
+ }));
209
+ exports.calculateManifestHash = calculateManifestHash;
210
+ const createBundleManifest = (input) => {
211
+ const files = (0, exports.sortManifestFiles)(input.files);
212
+ const manifestWithoutHash = {
213
+ manifestVersion: 1,
214
+ bundleHash: input.bundleHash,
215
+ jsBundleHash: input.jsBundleHash,
216
+ platform: input.platform,
217
+ runtimeVersion: input.runtimeVersion,
218
+ version: input.version,
219
+ files,
220
+ };
221
+ return {
222
+ ...manifestWithoutHash,
223
+ manifestHash: (0, exports.calculateManifestHash)(manifestWithoutHash),
224
+ };
225
+ };
226
+ exports.createBundleManifest = createBundleManifest;
227
+ const assertValidBundleManifest = (manifest, expectedBundleHash, expectedPlatform) => {
228
+ if (manifest?.manifestVersion !== 1) {
229
+ throw new Error('Invalid bundle manifest version');
230
+ }
231
+ if (!manifest.bundleHash) {
232
+ throw new Error('Bundle manifest is missing bundleHash');
233
+ }
234
+ if (!manifest.runtimeVersion) {
235
+ throw new Error('Bundle manifest is missing runtimeVersion');
236
+ }
237
+ if (!manifest.version) {
238
+ throw new Error('Bundle manifest is missing version');
239
+ }
240
+ if (!Array.isArray(manifest.files) || manifest.files.length === 0) {
241
+ throw new Error('Bundle manifest must include files');
242
+ }
243
+ const paths = new Set();
244
+ for (const file of manifest.files) {
245
+ const normalizedPath = (0, exports.normalizeManifestPath)(file.path);
246
+ if (paths.has(normalizedPath)) {
247
+ throw new Error(`Duplicate manifest file path: ${normalizedPath}`);
248
+ }
249
+ paths.add(normalizedPath);
250
+ }
251
+ const jsBundleFiles = manifest.files.filter(file => file.role === 'jsbundle');
252
+ if (jsBundleFiles.length !== 1 || (0, exports.normalizeManifestPath)(jsBundleFiles[0].path) !== 'main.jsbundle') {
253
+ throw new Error('Bundle manifest must include exactly one main.jsbundle file');
254
+ }
255
+ if (jsBundleFiles[0].sha256 !== manifest.jsBundleHash) {
256
+ throw new Error('jsBundleHash does not match manifest jsbundle file');
257
+ }
258
+ if (manifest.platform !== 'ios' && manifest.platform !== 'android') {
259
+ throw new Error('Bundle manifest platform must be ios or android');
260
+ }
261
+ if (expectedPlatform && manifest.platform !== expectedPlatform) {
262
+ throw new Error(`Bundle manifest platform mismatch: expected ${expectedPlatform}, got ${manifest.platform}`);
263
+ }
264
+ const metadataFiles = manifest.files.filter(file => file.role === 'metadata');
265
+ if (metadataFiles.length !== 1 ||
266
+ (0, exports.normalizeManifestPath)(metadataFiles[0].path) !== metadataPathForPlatform(manifest.platform)) {
267
+ throw new Error(`Bundle manifest must include exactly one ${metadataPathForPlatform(manifest.platform)} metadata file`);
268
+ }
269
+ const androidImageManifests = manifest.files.filter(file => file.role === 'androidImageManifest');
270
+ if (manifest.platform === 'android') {
271
+ if (androidImageManifests.length !== 1 ||
272
+ (0, exports.normalizeManifestPath)(androidImageManifests[0].path) !== 'image-manifest.json') {
273
+ throw new Error('Android bundle manifest must include image-manifest.json');
274
+ }
275
+ }
276
+ else if (androidImageManifests.length > 0) {
277
+ throw new Error('iOS bundle manifest must not include Android image-manifest.json');
278
+ }
279
+ if (expectedBundleHash && manifest.bundleHash !== expectedBundleHash) {
280
+ throw new Error(`Bundle manifest hash mismatch: expected ${expectedBundleHash}, got ${manifest.bundleHash}`);
281
+ }
282
+ const calculatedBundleHash = (0, exports.calculateBundleHash)(manifest.files);
283
+ if (calculatedBundleHash !== manifest.bundleHash) {
284
+ throw new Error(`Bundle hash verification failed: expected ${manifest.bundleHash}, got ${calculatedBundleHash}`);
285
+ }
286
+ if (!manifest.manifestHash) {
287
+ throw new Error('Bundle manifest is missing manifestHash');
288
+ }
289
+ if (!/^[a-f0-9]{64}$/.test(manifest.manifestHash)) {
290
+ throw new Error('Bundle manifest has invalid manifestHash');
291
+ }
292
+ const { manifestHash: _manifestHash, ...manifestWithoutHash } = manifest;
293
+ const calculatedManifestHash = (0, exports.calculateManifestHash)(manifestWithoutHash);
294
+ if (calculatedManifestHash !== manifest.manifestHash) {
295
+ throw new Error('Bundle manifest hash verification failed');
296
+ }
297
+ };
298
+ exports.assertValidBundleManifest = assertValidBundleManifest;
@@ -28,9 +28,8 @@ async function setOtaEnabledNative(enabled) {
28
28
  await BundleDrop.setOtaEnabled(enabled);
29
29
  }
30
30
  catch (e) {
31
- // Best-effort; native may not support this method on older versions.
32
31
  if (typeof __DEV__ !== 'undefined' && __DEV__) {
33
- console.debug('BundleDrop.setOtaEnabled failed (best-effort):', e);
32
+ console.debug('BundleDrop.setOtaEnabled failed:', e);
34
33
  }
35
34
  }
36
35
  }
@@ -7,6 +7,14 @@ declare function unlink(path: string): Promise<void>;
7
7
  declare function moveFile(src: string, dest: string): Promise<void>;
8
8
  declare function unzip(zipPath: string, destPath: string): Promise<string[]>;
9
9
  declare function downloadFile(url: string, destPath: string): Promise<void>;
10
+ declare function sha256File(path: string): Promise<string>;
11
+ declare function fileSize(path: string): Promise<number>;
12
+ declare function copyFile(src: string, dest: string): Promise<void>;
13
+ declare function applyXdelta(basePath: string, patchPath: string, outputPath: string): Promise<void>;
14
+ declare function verifyBundleFiles(bundleDir: string, manifestPath: string): Promise<{
15
+ verified: true;
16
+ }>;
17
+ declare function supportsXdelta(): Promise<boolean>;
10
18
  declare const BundleDropFS: {
11
19
  DocumentDirectoryPath: string;
12
20
  LibraryDirectoryPath: string;
@@ -19,5 +27,11 @@ declare const BundleDropFS: {
19
27
  moveFile: typeof moveFile;
20
28
  unzip: typeof unzip;
21
29
  downloadFile: typeof downloadFile;
30
+ sha256File: typeof sha256File;
31
+ fileSize: typeof fileSize;
32
+ copyFile: typeof copyFile;
33
+ applyXdelta: typeof applyXdelta;
34
+ verifyBundleFiles: typeof verifyBundleFiles;
35
+ supportsXdelta: typeof supportsXdelta;
22
36
  };
23
37
  export default BundleDropFS;
package/lib/native/fs.js CHANGED
@@ -44,6 +44,35 @@ async function downloadFile(url, destPath) {
44
44
  assertModule();
45
45
  return BundleDrop.fsDownloadFile(url, destPath);
46
46
  }
47
+ async function sha256File(path) {
48
+ assertModule();
49
+ return BundleDrop.fsSha256File(path);
50
+ }
51
+ async function fileSize(path) {
52
+ assertModule();
53
+ return BundleDrop.fsFileSize(path);
54
+ }
55
+ async function copyFile(src, dest) {
56
+ assertModule();
57
+ return BundleDrop.fsCopyFile(src, dest);
58
+ }
59
+ async function applyXdelta(basePath, patchPath, outputPath) {
60
+ assertModule();
61
+ return BundleDrop.fsApplyXdelta(basePath, patchPath, outputPath);
62
+ }
63
+ async function verifyBundleFiles(bundleDir, manifestPath) {
64
+ assertModule();
65
+ if (typeof BundleDrop.fsVerifyBundleFiles !== 'function') {
66
+ throw new Error('BundleDrop native module is outdated. Rebuild the app so fsVerifyBundleFiles is available.');
67
+ }
68
+ return BundleDrop.fsVerifyBundleFiles(bundleDir, manifestPath);
69
+ }
70
+ async function supportsXdelta() {
71
+ assertModule();
72
+ if (typeof BundleDrop.fsSupportsXdelta !== 'function')
73
+ return false;
74
+ return BundleDrop.fsSupportsXdelta();
75
+ }
47
76
  const BundleDropFS = {
48
77
  DocumentDirectoryPath: (BundleDrop?.DocumentDirectoryPath ?? ''),
49
78
  LibraryDirectoryPath: (BundleDrop?.LibraryDirectoryPath ?? ''),
@@ -56,5 +85,11 @@ const BundleDropFS = {
56
85
  moveFile,
57
86
  unzip,
58
87
  downloadFile,
88
+ sha256File,
89
+ fileSize,
90
+ copyFile,
91
+ applyXdelta,
92
+ verifyBundleFiles,
93
+ supportsXdelta,
59
94
  };
60
95
  exports.default = BundleDropFS;
@@ -0,0 +1,16 @@
1
+ import { InstallResult } from '../install/bundleInstallShared';
2
+ import { SupportedPatchAlgorithm } from './patchOperations';
3
+ type InstallFromPatchSetParams = {
4
+ patchesUrl: string;
5
+ patchSetHash: string;
6
+ manifestUrl?: string | null;
7
+ missingAssetsUrl?: string | null;
8
+ missingAssetsHash?: string | null;
9
+ baseHash: string;
10
+ targetHash: string;
11
+ algorithm: SupportedPatchAlgorithm;
12
+ platform?: 'ios' | 'android';
13
+ statusCb?: (status: string) => void;
14
+ };
15
+ export declare function installFromPatchSet(params: InstallFromPatchSetParams): Promise<InstallResult>;
16
+ export {};
@@ -0,0 +1,143 @@
1
+ "use strict";
2
+ var __importDefault = (this && this.__importDefault) || function (mod) {
3
+ return (mod && mod.__esModule) ? mod : { "default": mod };
4
+ };
5
+ Object.defineProperty(exports, "__esModule", { value: true });
6
+ exports.installFromPatchSet = installFromPatchSet;
7
+ const fs_1 = __importDefault(require("../native/fs"));
8
+ const context_1 = require("../context");
9
+ const fsUtils_1 = require("../fs/fsUtils");
10
+ const bundlePointer_1 = require("../fs/bundlePointer");
11
+ const errors_1 = require("../errors");
12
+ const bundleManifest_1 = require("../manifest/bundleManifest");
13
+ const bundleVerification_1 = require("../install/bundleVerification");
14
+ const bundleInstallShared_1 = require("../install/bundleInstallShared");
15
+ const patchOperations_1 = require("./patchOperations");
16
+ const reconstructPatchTarget = async (baseDir, baseHash, platform, patchDir, targetDir, targetManifest, algorithm) => {
17
+ const baseManifest = await (0, bundleVerification_1.readValidatedBundleManifestFromDir)(baseDir, baseHash, platform);
18
+ if (!baseManifest) {
19
+ throw new Error('Base bundle manifest is missing');
20
+ }
21
+ const baseFilesByPath = new Map(baseManifest.files.map(file => [(0, bundleManifest_1.normalizeManifestPath)(file.path), file]));
22
+ for (const file of targetManifest.files) {
23
+ const operation = await (0, patchOperations_1.resolvePatchOperation)({
24
+ baseDir,
25
+ patchDir,
26
+ targetDir,
27
+ targetFile: file,
28
+ baseFilesByPath,
29
+ algorithm,
30
+ });
31
+ await (0, patchOperations_1.applyPatchOperation)(operation);
32
+ }
33
+ };
34
+ async function installFromPatchSet(params) {
35
+ const { patchesUrl, patchSetHash, manifestUrl, missingAssetsUrl, missingAssetsHash, baseHash, targetHash, algorithm, statusCb, platform = context_1.platform, } = params;
36
+ (0, bundleInstallShared_1.assertCanonicalBundleHash)(baseHash, 'base hash');
37
+ (0, bundleInstallShared_1.assertCanonicalBundleHash)(targetHash, 'target hash');
38
+ const currentPointer = await (0, bundlePointer_1.readCurrentBundlePointer)();
39
+ if (currentPointer?.hash !== baseHash) {
40
+ throw new errors_1.InstallPhaseError('install', new Error('Patch base hash does not match current bundle'));
41
+ }
42
+ const baseDir = `${context_1.BUNDLE_DROP_ROOT}/bundles/${baseHash}`;
43
+ const patchDir = `${context_1.BUNDLE_DROP_ROOT}/bundles/_patch_${targetHash}`;
44
+ const targetTempDir = `${context_1.BUNDLE_DROP_ROOT}/bundles/_patch_target_${targetHash}`;
45
+ const tempZipPath = `${context_1.BUNDLE_DROP_ROOT}/bundles/_patch_${targetHash}.zip`;
46
+ let targetManifest;
47
+ try {
48
+ try {
49
+ await fs_1.default.unlink(patchDir);
50
+ }
51
+ catch { /* best-effort cleanup */ }
52
+ try {
53
+ await fs_1.default.unlink(targetTempDir);
54
+ }
55
+ catch { /* best-effort cleanup */ }
56
+ await (0, fsUtils_1.ensureDir)(patchDir);
57
+ await (0, fsUtils_1.ensureDir)(targetTempDir);
58
+ try {
59
+ await fs_1.default.downloadFile(patchesUrl, tempZipPath);
60
+ }
61
+ catch (e) {
62
+ throw new errors_1.InstallPhaseError('download', e);
63
+ }
64
+ const actualPatchSetHash = await fs_1.default.sha256File(tempZipPath);
65
+ if (actualPatchSetHash !== patchSetHash) {
66
+ throw new errors_1.InstallPhaseError('install', new Error('Patch set hash mismatch'));
67
+ }
68
+ let patchFileNames;
69
+ try {
70
+ patchFileNames = await fs_1.default.unzip(tempZipPath, patchDir);
71
+ }
72
+ catch (e) {
73
+ throw new errors_1.InstallPhaseError('install', e);
74
+ }
75
+ if (!patchFileNames.includes(bundleManifest_1.BUNDLE_MANIFEST)) {
76
+ if (!manifestUrl) {
77
+ throw new errors_1.InstallPhaseError('install', new Error('Patch set missing target manifest'));
78
+ }
79
+ try {
80
+ await fs_1.default.downloadFile(manifestUrl, `${patchDir}/${bundleManifest_1.BUNDLE_MANIFEST}`);
81
+ patchFileNames.push(bundleManifest_1.BUNDLE_MANIFEST);
82
+ }
83
+ catch (e) {
84
+ throw new errors_1.InstallPhaseError('download', e);
85
+ }
86
+ }
87
+ if (missingAssetsUrl) {
88
+ if (!missingAssetsHash) {
89
+ throw new errors_1.InstallPhaseError('install', new Error('Missing assets archive hash is required'));
90
+ }
91
+ const assetsZipPath = `${context_1.BUNDLE_DROP_ROOT}/bundles/_patch_assets_${targetHash}.zip`;
92
+ try {
93
+ await fs_1.default.downloadFile(missingAssetsUrl, assetsZipPath);
94
+ if ((await fs_1.default.sha256File(assetsZipPath)) !== missingAssetsHash) {
95
+ throw new Error('Missing assets archive hash mismatch');
96
+ }
97
+ await fs_1.default.unzip(assetsZipPath, `${patchDir}/missing-assets`);
98
+ }
99
+ catch (e) {
100
+ throw new errors_1.InstallPhaseError('install', e);
101
+ }
102
+ finally {
103
+ try {
104
+ await fs_1.default.unlink(assetsZipPath);
105
+ }
106
+ catch { /* best-effort cleanup */ }
107
+ }
108
+ }
109
+ try {
110
+ targetManifest = await (0, bundleVerification_1.readJsonFile)(`${patchDir}/${bundleManifest_1.BUNDLE_MANIFEST}`);
111
+ (0, bundleManifest_1.assertValidBundleManifest)(targetManifest, targetHash, platform);
112
+ await reconstructPatchTarget(baseDir, baseHash, platform, patchDir, targetTempDir, targetManifest, algorithm);
113
+ await fs_1.default.writeFile(`${targetTempDir}/${bundleManifest_1.BUNDLE_MANIFEST}`, JSON.stringify(targetManifest, null, 2), 'utf8');
114
+ await (0, bundleVerification_1.verifyBundleDir)(targetTempDir, targetHash, platform);
115
+ }
116
+ catch (e) {
117
+ throw new errors_1.InstallPhaseError('install', e);
118
+ }
119
+ statusCb?.('🧩 Patch reconstructed and verified');
120
+ const fileNames = targetManifest.files.map((file) => (0, bundleManifest_1.normalizeManifestPath)(file.path));
121
+ if (!fileNames.includes(bundleManifest_1.BUNDLE_MANIFEST)) {
122
+ fileNames.push(bundleManifest_1.BUNDLE_MANIFEST);
123
+ }
124
+ return await (0, bundleInstallShared_1.finalizeInstall)(targetTempDir, fileNames, targetHash, platform, statusCb);
125
+ }
126
+ catch (e) {
127
+ try {
128
+ await fs_1.default.unlink(targetTempDir);
129
+ }
130
+ catch { /* best-effort cleanup */ }
131
+ throw e;
132
+ }
133
+ finally {
134
+ try {
135
+ await fs_1.default.unlink(tempZipPath);
136
+ }
137
+ catch { /* best-effort cleanup */ }
138
+ try {
139
+ await fs_1.default.unlink(patchDir);
140
+ }
141
+ catch { /* best-effort cleanup */ }
142
+ }
143
+ }
@@ -0,0 +1,33 @@
1
+ import { BundleManifestFile } from '../manifest/bundleManifest';
2
+ export { ASSET_ONLY_PATCH_ALGORITHM, XDELTA_PATCH_ALGORITHM, } from '../patchAlgorithms';
3
+ import { type SupportedPatchAlgorithm } from '../patchAlgorithms';
4
+ export type { SupportedPatchAlgorithm } from '../patchAlgorithms';
5
+ type BaseFileIndex = Map<string, BundleManifestFile>;
6
+ type FullFileOperation = {
7
+ type: 'full-file';
8
+ sourcePath: string;
9
+ outputPath: string;
10
+ };
11
+ type XdeltaOperation = {
12
+ type: 'xdelta';
13
+ basePath: string;
14
+ patchPath: string;
15
+ outputPath: string;
16
+ };
17
+ type CopyUnchangedOperation = {
18
+ type: 'copy-unchanged';
19
+ sourcePath: string;
20
+ outputPath: string;
21
+ };
22
+ export type PatchOperation = FullFileOperation | XdeltaOperation | CopyUnchangedOperation;
23
+ export declare const isSupportedPatchAlgorithm: (algorithm: string | undefined | null) => algorithm is SupportedPatchAlgorithm;
24
+ export declare const advertisedPatchAlgorithms: (supportsXdelta: boolean) => SupportedPatchAlgorithm[];
25
+ export declare const resolvePatchOperation: ({ baseDir, patchDir, targetDir, targetFile, baseFilesByPath, algorithm, }: {
26
+ baseDir: string;
27
+ patchDir: string;
28
+ targetDir: string;
29
+ targetFile: BundleManifestFile;
30
+ baseFilesByPath: BaseFileIndex;
31
+ algorithm: SupportedPatchAlgorithm;
32
+ }) => Promise<PatchOperation>;
33
+ export declare const applyPatchOperation: (operation: PatchOperation) => Promise<void>;