react-native-update-cli 2.20.0 → 2.20.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.
package/lib/diff.js CHANGED
@@ -37,6 +37,7 @@ var __importDefault = (this && this.__importDefault) || function (mod) {
37
37
  };
38
38
  Object.defineProperty(exports, "__esModule", { value: true });
39
39
  exports.diffCommands = exports.readEntry = exports.enumZipEntries = void 0;
40
+ const node_crypto_1 = require("node:crypto");
40
41
  const fs = __importStar(require("fs-extra"));
41
42
  const global_dirs_1 = require("global-dirs");
42
43
  const os_1 = __importDefault(require("os"));
@@ -82,98 +83,236 @@ function createOutputZip(output) {
82
83
  // baseline patch 小于该值时跳过变换尝试:节省一次 diff 的 CPU,
83
84
  // 且此时变换收益上限(~25%)也抵不过元数据开销
84
85
  const HBC_TRANSFORM_MIN_BASELINE_BYTES = 64 * 1024;
86
+ function reportDiffPhase(options, metric) {
87
+ try {
88
+ options.onDiffPhase?.(metric);
89
+ }
90
+ catch {
91
+ // Observability must never break patch generation.
92
+ }
93
+ }
94
+ const bundleSourceSize = (source) => source.kind === 'buffer' ? source.data.length : source.size;
95
+ const bundleSourceBuffer = async (source) => source.kind === 'buffer' ? source.data : fs.readFile(source.path);
96
+ async function bundleSourceFile(source, outputPath) {
97
+ if (source.kind === 'file') {
98
+ return source.path;
99
+ }
100
+ await fs.writeFile(outputPath, source.data);
101
+ return outputPath;
102
+ }
103
+ async function hashFile(filePath) {
104
+ const hash = (0, node_crypto_1.createHash)('sha256');
105
+ for await (const chunk of fs.createReadStream(filePath)) {
106
+ hash.update(chunk);
107
+ }
108
+ return hash.digest('hex');
109
+ }
110
+ async function filesEqual(leftPath, rightPath) {
111
+ const [leftStat, rightStat] = await Promise.all([
112
+ fs.stat(leftPath),
113
+ fs.stat(rightPath),
114
+ ]);
115
+ if (leftStat.size !== rightStat.size) {
116
+ return false;
117
+ }
118
+ const [leftHash, rightHash] = await Promise.all([
119
+ hashFile(leftPath),
120
+ hashFile(rightPath),
121
+ ]);
122
+ return leftHash === rightHash;
123
+ }
85
124
  /**
86
- * 大 bundle 流式路径:可选 HBC 变换(在 buffer 上做,写临时文件)后
87
- * diffStream 生成 HDIFF13,并以 patchStream + T⁻¹ 做 round-trip 自检。
88
- * 自检失败直接抛错(此路径没有 baseline 可回退——内存 diff 正是要避免的),
89
- * 由上层按任务失败重试/告警处理。
125
+ * 大 bundle 流式路径:普通 bundle 直接从 ZIP entry 落盘后传入 native,
126
+ * 避免 old/new/restored 的整块 Buffer 副本。HBC 变换仍需 Buffer,因为
127
+ * T/T⁻¹ 当前是内存算法。native 已自校验的普通产物不再重复 patch;
128
+ * 自定义/变换路径仍保留 round-trip 校验。
90
129
  */
91
- async function buildStreamBundlePatch(originSource, newSource, options) {
130
+ async function buildStreamBundlePatch(originSource, newSource, options, workRoot) {
92
131
  const diffStreamFn = options.diffStreamFn;
93
132
  const patchStreamFn = options.patchStreamFn;
94
133
  if (!diffStreamFn || !patchStreamFn) {
95
134
  throw new Error('stream diff requires diffStream/patchStream from node-hdiffpatch');
96
135
  }
97
- const pair = options.hbcTransform
98
- ? (0, hbcTransform_1.tryTransformPair)(originSource, newSource)
136
+ const tempRoot = fs.mkdtempSync(path_1.default.join(workRoot, 'stream-'));
137
+ const inputBytes = bundleSourceSize(originSource) + bundleSourceSize(newSource);
138
+ const extractionDurationMs = (originSource.kind === 'file' ? originSource.materializeDurationMs : 0) +
139
+ (newSource.kind === 'file' ? newSource.materializeDurationMs : 0);
140
+ let phaseStartedAt = performance.now();
141
+ const rawOldFile = await bundleSourceFile(originSource, path_1.default.join(tempRoot, 'old.bin'));
142
+ const rawNewFile = await bundleSourceFile(newSource, path_1.default.join(tempRoot, 'new.bin'));
143
+ const originBuffer = options.hbcTransform
144
+ ? await bundleSourceBuffer(originSource)
99
145
  : null;
100
- const tempRoot = fs.mkdtempSync(path_1.default.join(os_1.default.tmpdir(), 'rnu-stream-diff-'));
101
- try {
102
- const oldFile = path_1.default.join(tempRoot, 'old.bin');
103
- const newFile = path_1.default.join(tempRoot, 'new.bin');
104
- const patchFile = path_1.default.join(tempRoot, 'patch.bin');
146
+ const newBuffer = options.hbcTransform
147
+ ? await bundleSourceBuffer(newSource)
148
+ : null;
149
+ const pair = originBuffer && newBuffer
150
+ ? (0, hbcTransform_1.tryTransformPair)(originBuffer, newBuffer)
151
+ : null;
152
+ const oldFile = pair
153
+ ? path_1.default.join(tempRoot, 'old-transformed.bin')
154
+ : rawOldFile;
155
+ const newFile = pair
156
+ ? path_1.default.join(tempRoot, 'new-transformed.bin')
157
+ : rawNewFile;
158
+ const patchFile = path_1.default.join(tempRoot, 'patch.bin');
159
+ if (pair) {
160
+ await Promise.all([
161
+ fs.writeFile(oldFile, pair.tOld),
162
+ fs.writeFile(newFile, pair.tNew),
163
+ ]);
164
+ }
165
+ reportDiffPhase(options, {
166
+ phase: 'materialize',
167
+ durationMs: extractionDurationMs + performance.now() - phaseStartedAt,
168
+ inputBytes,
169
+ });
170
+ phaseStartedAt = performance.now();
171
+ await diffStreamFn(oldFile, newFile, patchFile);
172
+ const patchBytes = (await fs.stat(patchFile)).size;
173
+ reportDiffPhase(options, {
174
+ phase: 'diff',
175
+ durationMs: performance.now() - phaseStartedAt,
176
+ inputBytes,
177
+ outputBytes: patchBytes,
178
+ });
179
+ // 变换路径必须验证 T⁻¹ 和元数据;未声明自校验的自定义 diff 也保留
180
+ // round-trip。node-hdiffpatch native 普通路径已经在返回前完整验证。
181
+ if (pair || !options.streamOutputVerified) {
182
+ phaseStartedAt = performance.now();
105
183
  const restoredFile = path_1.default.join(tempRoot, 'restored.bin');
106
- fs.writeFileSync(oldFile, pair ? pair.tOld : originSource);
107
- fs.writeFileSync(newFile, pair ? pair.tNew : newSource);
108
- await diffStreamFn(oldFile, newFile, patchFile);
109
- // round-trip 自检:patchStream 还原(变换域则再做 T⁻¹)必须与新 bundle 一致
110
184
  await patchStreamFn(oldFile, patchFile, restoredFile);
111
- const restoredRaw = fs.readFileSync(restoredFile);
112
- const restored = pair
113
- ? (0, hbcTransform_1.transformHbcWithLayout)(restoredRaw, pair.layout, true)
114
- : restoredRaw;
115
- if (!restored || Buffer.compare(restored, newSource) !== 0) {
185
+ if (pair) {
186
+ const restoredRaw = await fs.readFile(restoredFile);
187
+ const restored = (0, hbcTransform_1.transformHbcWithLayout)(restoredRaw, pair.layout, true);
188
+ if (!restored ||
189
+ !newBuffer ||
190
+ Buffer.compare(restored, newBuffer) !== 0) {
191
+ throw new Error('stream diff round-trip verification failed');
192
+ }
193
+ }
194
+ else if (!(await filesEqual(restoredFile, rawNewFile))) {
116
195
  throw new Error('stream diff round-trip verification failed');
117
196
  }
118
- return {
119
- patchData: fs.readFileSync(patchFile),
120
- ...(pair ? { hbcTransform: pair.meta } : {}),
121
- };
197
+ reportDiffPhase(options, {
198
+ phase: 'verify',
199
+ durationMs: performance.now() - phaseStartedAt,
200
+ inputBytes,
201
+ outputBytes: patchBytes,
202
+ });
122
203
  }
123
- finally {
124
- fs.rmSync(tempRoot, { recursive: true, force: true });
204
+ else {
205
+ reportDiffPhase(options, {
206
+ phase: 'verify',
207
+ durationMs: 0,
208
+ inputBytes,
209
+ outputBytes: patchBytes,
210
+ skipped: true,
211
+ });
125
212
  }
213
+ return {
214
+ patch: { kind: 'file', path: patchFile },
215
+ ...(pair ? { hbcTransform: pair.meta } : {}),
216
+ };
126
217
  }
127
218
  /**
128
219
  * 生成 bundle patch:默认现状路径;开启 hbcTransform 时对 Hermes bundle
129
220
  * 做双候选择优(baseline vs 变换域 + 元数据开销),且变换候选必须通过
130
221
  * 本地 round-trip 还原自检才会被采用——收益永不为负,未知格式天然安全。
131
222
  */
132
- async function buildBundlePatch(diffFn, originSource, newSource, options) {
223
+ async function buildBundlePatch(diffFn, originSource, newSource, options, workRoot) {
133
224
  if (options.streamThresholdBytes &&
134
225
  originSource &&
135
- Math.max(originSource.length, newSource.length) >=
226
+ Math.max(bundleSourceSize(originSource), bundleSourceSize(newSource)) >=
136
227
  options.streamThresholdBytes) {
137
- return buildStreamBundlePatch(originSource, newSource, options);
228
+ return buildStreamBundlePatch(originSource, newSource, options, workRoot);
138
229
  }
139
- const baseline = await diffFn(originSource, newSource);
230
+ const [originBuffer, newBuffer] = await Promise.all([
231
+ originSource
232
+ ? bundleSourceBuffer(originSource)
233
+ : Promise.resolve(undefined),
234
+ bundleSourceBuffer(newSource),
235
+ ]);
236
+ const baseline = await diffFn(originBuffer, newBuffer);
140
237
  if (!options.hbcTransform ||
141
238
  !options.patchFn ||
142
- !originSource ||
239
+ !originBuffer ||
143
240
  baseline.length <
144
241
  (options.minBaselineBytes ?? HBC_TRANSFORM_MIN_BASELINE_BYTES)) {
145
- return { patchData: baseline };
242
+ return { patch: { kind: 'buffer', data: baseline } };
146
243
  }
147
- const pair = (0, hbcTransform_1.tryTransformPair)(originSource, newSource);
244
+ const pair = (0, hbcTransform_1.tryTransformPair)(originBuffer, newBuffer);
148
245
  if (!pair) {
149
- return { patchData: baseline };
246
+ return { patch: { kind: 'buffer', data: baseline } };
150
247
  }
151
248
  try {
152
249
  const candidate = await diffFn(pair.tOld, pair.tNew);
153
250
  const metaOverhead = Buffer.byteLength(JSON.stringify(pair.meta));
154
251
  if (candidate.length + metaOverhead >= baseline.length) {
155
- return { patchData: baseline };
252
+ return { patch: { kind: 'buffer', data: baseline } };
156
253
  }
157
254
  const patched = options.patchFn(pair.tOld, candidate);
158
255
  const restored = (0, hbcTransform_1.transformHbcWithLayout)(patched, pair.layout, true);
159
- if (!restored || Buffer.compare(restored, newSource) !== 0) {
256
+ if (!restored || Buffer.compare(restored, newBuffer) !== 0) {
160
257
  console.warn((0, i18n_1.t)('hbcTransformRoundTripFailed'));
161
- return { patchData: baseline };
258
+ return { patch: { kind: 'buffer', data: baseline } };
162
259
  }
163
- return { patchData: candidate, hbcTransform: pair.meta };
260
+ return {
261
+ patch: { kind: 'buffer', data: candidate },
262
+ hbcTransform: pair.meta,
263
+ };
164
264
  }
165
265
  catch {
166
- return { patchData: baseline };
266
+ return { patch: { kind: 'buffer', data: baseline } };
167
267
  }
168
268
  }
169
- async function addBundlePatch(zipfile, entry, nextZipfile, diffFn, originSource, bundleOptions, hbcTransformMetas) {
170
- const newSource = await (0, zip_entries_1.readEntry)(entry, nextZipfile);
171
- const { patchData, hbcTransform } = await buildBundlePatch(diffFn, originSource, newSource, bundleOptions);
269
+ async function addBundlePatch(zipfile, entry, nextZipfile, diffFn, originSource, bundleOptions, hbcTransformMetas, workRoot) {
270
+ const shouldStream = !!bundleOptions.streamThresholdBytes &&
271
+ !!originSource &&
272
+ Math.max(bundleSourceSize(originSource), entry.uncompressedSize) >=
273
+ bundleOptions.streamThresholdBytes;
274
+ let newSource;
275
+ if (shouldStream) {
276
+ const nextRoot = fs.mkdtempSync(path_1.default.join(workRoot, 'next-'));
277
+ const nextPath = path_1.default.join(nextRoot, 'bundle.bin');
278
+ const startedAt = performance.now();
279
+ await (0, zip_entries_1.writeEntry)(entry, nextZipfile, nextPath);
280
+ newSource = {
281
+ kind: 'file',
282
+ path: nextPath,
283
+ size: entry.uncompressedSize,
284
+ materializeDurationMs: performance.now() - startedAt,
285
+ };
286
+ }
287
+ else {
288
+ newSource = { kind: 'buffer', data: await (0, zip_entries_1.readEntry)(entry, nextZipfile) };
289
+ }
290
+ const { patch, hbcTransform } = await buildBundlePatch(diffFn, originSource, newSource, bundleOptions, workRoot);
172
291
  const patchEntryName = `${entry.fileName}.patch`;
173
292
  if (hbcTransform) {
174
293
  hbcTransformMetas[patchEntryName] = hbcTransform;
175
294
  }
176
- zipfile.addBuffer(patchData, patchEntryName, (0, zip_options_1.zipOptionsForPatchEntry)());
295
+ if (patch.kind === 'file') {
296
+ zipfile.addFile(patch.path, patchEntryName, (0, zip_options_1.zipOptionsForPatchEntry)());
297
+ }
298
+ else {
299
+ zipfile.addBuffer(patch.data, patchEntryName, (0, zip_options_1.zipOptionsForPatchEntry)());
300
+ }
301
+ }
302
+ async function readOriginBundleSource(entry, zipFile, bundleOptions, workRoot) {
303
+ if (!bundleOptions.streamThresholdBytes) {
304
+ return { kind: 'buffer', data: await (0, zip_entries_1.readEntry)(entry, zipFile) };
305
+ }
306
+ const originRoot = fs.mkdtempSync(path_1.default.join(workRoot, 'origin-'));
307
+ const originPath = path_1.default.join(originRoot, 'bundle.bin');
308
+ const startedAt = performance.now();
309
+ await (0, zip_entries_1.writeEntry)(entry, zipFile, originPath);
310
+ return {
311
+ kind: 'file',
312
+ path: originPath,
313
+ size: entry.uncompressedSize,
314
+ materializeDurationMs: performance.now() - startedAt,
315
+ };
177
316
  }
178
317
  async function addFileFromZipEntry(zipfile, entry, nextZipfile) {
179
318
  const entryPrefix = await (0, zip_entries_1.readEntryPrefix)(entry, nextZipfile, zip_options_1.ZIP_ENTRY_SNIFF_BYTES);
@@ -199,7 +338,7 @@ function finishDiffZip(zipfile, writePromise, manifest) {
199
338
  zipfile.end();
200
339
  return writePromise;
201
340
  }
202
- async function diffFromPPK(origin, next, output, diffFn, bundleOptions = {}) {
341
+ async function diffFromPPK(origin, next, output, diffFn, bundleOptions, workRoot) {
203
342
  const originEntries = {};
204
343
  const originMap = {};
205
344
  let originSource;
@@ -210,7 +349,7 @@ async function diffFromPPK(origin, next, output, diffFn, bundleOptions = {}) {
210
349
  originMap[entry.crc32] = entry.fileName;
211
350
  if ((0, constants_1.isPPKBundleFileName)(entry.fileName)) {
212
351
  // This is source.
213
- originSource = await (0, zip_entries_1.readEntry)(entry, zipFile);
352
+ originSource = await readOriginBundleSource(entry, zipFile, bundleOptions, workRoot);
214
353
  }
215
354
  }
216
355
  });
@@ -243,7 +382,7 @@ async function diffFromPPK(origin, next, output, diffFn, bundleOptions = {}) {
243
382
  }
244
383
  }
245
384
  else if ((0, constants_1.isPPKBundleFileName)(entry.fileName)) {
246
- await addBundlePatch(zipfile, entry, nextZipfile, diffFn, originSource, bundleOptions, hbcTransformMetas);
385
+ await addBundlePatch(zipfile, entry, nextZipfile, diffFn, originSource, bundleOptions, hbcTransformMetas, workRoot);
247
386
  }
248
387
  else {
249
388
  // If same file.
@@ -285,7 +424,7 @@ async function diffFromPPK(origin, next, output, diffFn, bundleOptions = {}) {
285
424
  : {}),
286
425
  });
287
426
  }
288
- async function diffFromPackage(origin, next, output, diffFn, platform, bundleOptions = {}) {
427
+ async function diffFromPackage(origin, next, output, diffFn, platform, bundleOptions, workRoot) {
289
428
  const originEntries = {};
290
429
  const originMap = {};
291
430
  let originSource;
@@ -308,7 +447,7 @@ async function diffFromPackage(origin, next, output, diffFn, platform, bundleOpt
308
447
  originMap[entry.crc32] = fn;
309
448
  if (resolvedEntry.kind === 'bundle') {
310
449
  // This is source.
311
- originSource = await (0, zip_entries_1.readEntry)(entry, zipFile);
450
+ originSource = await readOriginBundleSource(entry, zipFile, bundleOptions, workRoot);
312
451
  }
313
452
  }
314
453
  });
@@ -324,7 +463,7 @@ async function diffFromPackage(origin, next, output, diffFn, platform, bundleOpt
324
463
  zipfile.addEmptyDirectory(entry.fileName);
325
464
  }
326
465
  else if ((0, constants_1.isPPKBundleFileName)(entry.fileName)) {
327
- await addBundlePatch(zipfile, entry, nextZipfile, diffFn, originSource, bundleOptions, hbcTransformMetas);
466
+ await addBundlePatch(zipfile, entry, nextZipfile, diffFn, originSource, bundleOptions, hbcTransformMetas, workRoot);
328
467
  }
329
468
  else {
330
469
  // If same file.
@@ -374,6 +513,9 @@ function resolvePatchImplementation(options) {
374
513
  function resolveBundleDiffOptions(options) {
375
514
  const hdiffModule = options.customHdiffModule ?? hdiff;
376
515
  const streamOptions = {};
516
+ const observerOptions = typeof options.onDiffPhase === 'function'
517
+ ? { onDiffPhase: options.onDiffPhase }
518
+ : {};
377
519
  if (typeof options.bundleStreamThreshold === 'number' &&
378
520
  options.bundleStreamThreshold > 0) {
379
521
  const singleDiffStreamFn = options.customDiffSingleStream ?? hdiffModule?.diffSingleStream;
@@ -385,28 +527,35 @@ function resolveBundleDiffOptions(options) {
385
527
  streamOptions.diffStreamFn = singleDiffStreamFn;
386
528
  streamOptions.patchStreamFn = singlePatchStreamFn;
387
529
  streamOptions.streamEmitsSingleFormat = true;
530
+ streamOptions.streamOutputVerified = options.customDiffSingleStream
531
+ ? options.customDiffSingleStreamVerified === true
532
+ : hdiffModule?.capabilities?.diffSingleStreamVerifiesOutput === true;
388
533
  }
389
534
  else if (diffStreamFn && patchStreamFn) {
390
535
  streamOptions.streamThresholdBytes = options.bundleStreamThreshold;
391
536
  streamOptions.diffStreamFn = diffStreamFn;
392
537
  streamOptions.patchStreamFn = patchStreamFn;
393
538
  streamOptions.streamEmitsSingleFormat = false;
539
+ streamOptions.streamOutputVerified = options.customDiffStream
540
+ ? options.customDiffStreamVerified === true
541
+ : hdiffModule?.capabilities?.diffStreamVerifiesOutput === true;
394
542
  }
395
543
  else {
396
544
  console.warn((0, i18n_1.t)('bundleStreamNeedsHdiffpatch'));
397
545
  }
398
546
  }
399
547
  if (!options.hbcTransform) {
400
- return { ...streamOptions };
548
+ return { ...observerOptions, ...streamOptions };
401
549
  }
402
550
  const patchFn = resolvePatchImplementation(options);
403
551
  if (!patchFn) {
404
552
  console.warn((0, i18n_1.t)('hbcTransformNeedsPatch'));
405
- return { ...streamOptions };
553
+ return { ...observerOptions, ...streamOptions };
406
554
  }
407
555
  return {
408
556
  hbcTransform: true,
409
557
  patchFn,
558
+ ...observerOptions,
410
559
  ...streamOptions,
411
560
  ...(typeof options.hbcTransformMinBaseline === 'number'
412
561
  ? { minBaselineBytes: options.hbcTransformMinBaseline }
@@ -436,11 +585,17 @@ function diffArgsCheck(args, options, diffFnName) {
436
585
  const createDiffCommand = ({ diffFnName, target }) => async ({ args, options }) => {
437
586
  const { origin, next, realOutput, diffFn } = diffArgsCheck(args, options, diffFnName);
438
587
  const bundleOptions = resolveBundleDiffOptions(options);
439
- if (target.kind === 'ppk') {
440
- await diffFromPPK(origin, next, realOutput, diffFn, bundleOptions);
588
+ const workRoot = fs.mkdtempSync(path_1.default.join(os_1.default.tmpdir(), 'rnu-bundle-diff-'));
589
+ try {
590
+ if (target.kind === 'ppk') {
591
+ await diffFromPPK(origin, next, realOutput, diffFn, bundleOptions, workRoot);
592
+ }
593
+ else {
594
+ await diffFromPackage(origin, next, realOutput, diffFn, target.platform, bundleOptions, workRoot);
595
+ }
441
596
  }
442
- else {
443
- await diffFromPackage(origin, next, realOutput, diffFn, target.platform, bundleOptions);
597
+ finally {
598
+ fs.rmSync(workRoot, { recursive: true, force: true });
444
599
  }
445
600
  console.log((0, i18n_1.t)('diffPackageGenerated', { output: realOutput }));
446
601
  };
@@ -1,4 +1,5 @@
1
1
  import { type Entry, type ZipFile as YauzlZipFile } from 'yauzl';
2
2
  export declare function readEntry(entry: Entry, zipFile: YauzlZipFile): Promise<Buffer>;
3
+ export declare function writeEntry(entry: Entry, zipFile: YauzlZipFile, outputPath: string): Promise<void>;
3
4
  export declare function readEntryPrefix(entry: Entry, zipFile: YauzlZipFile, maxBytes: number): Promise<Buffer>;
4
5
  export declare function enumZipEntries(zipFn: string, callback: (entry: Entry, zipFile: YauzlZipFile, nestedPath?: string) => Promise<any> | undefined, nestedPath?: string): Promise<unknown>;
@@ -37,11 +37,13 @@ var __importDefault = (this && this.__importDefault) || function (mod) {
37
37
  };
38
38
  Object.defineProperty(exports, "__esModule", { value: true });
39
39
  exports.readEntry = readEntry;
40
+ exports.writeEntry = writeEntry;
40
41
  exports.readEntryPrefix = readEntryPrefix;
41
42
  exports.enumZipEntries = enumZipEntries;
42
43
  const fs = __importStar(require("fs-extra"));
43
44
  const os_1 = __importDefault(require("os"));
44
45
  const path_1 = __importDefault(require("path"));
46
+ const promises_1 = require("stream/promises");
45
47
  const yauzl_1 = require("yauzl");
46
48
  const i18n_1 = require("./i18n");
47
49
  function readEntry(entry, zipFile) {
@@ -66,6 +68,22 @@ function readEntry(entry, zipFile) {
66
68
  });
67
69
  });
68
70
  }
71
+ function writeEntry(entry, zipFile, outputPath) {
72
+ fs.ensureDirSync(path_1.default.dirname(outputPath));
73
+ return new Promise((resolve, reject) => {
74
+ zipFile.openReadStream(entry, (err, stream) => {
75
+ if (err) {
76
+ reject(err);
77
+ return;
78
+ }
79
+ if (!stream) {
80
+ reject(new Error(`Unable to read zip entry: ${entry.fileName}`));
81
+ return;
82
+ }
83
+ (0, promises_1.pipeline)(stream, fs.createWriteStream(outputPath)).then(resolve, reject);
84
+ });
85
+ });
86
+ }
69
87
  function readEntryPrefix(entry, zipFile, maxBytes) {
70
88
  if (maxBytes <= 0) {
71
89
  return Promise.resolve(Buffer.alloc(0));
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "react-native-update-cli",
3
- "version": "2.20.0",
3
+ "version": "2.20.1",
4
4
  "description": "command line tool for react-native-update (remote updates for react native)",
5
5
  "main": "lib/exports.js",
6
6
  "types": "lib/exports.d.ts",
@@ -39,7 +39,8 @@
39
39
  "lint": "bun run typecheck && biome check .",
40
40
  "lint:fix": "bun run typecheck && biome check --write .",
41
41
  "test": "bun test",
42
- "test:coverage": "bun test --coverage --coverage-reporter=text --coverage-reporter=lcov"
42
+ "test:coverage": "bun test --coverage --coverage-reporter=text --coverage-reporter=lcov",
43
+ "benchmark:diff-stream": "bun scripts/benchmark-diff-stream.ts"
43
44
  },
44
45
  "repository": {
45
46
  "type": "git",
package/src/diff.ts CHANGED
@@ -1,3 +1,4 @@
1
+ import { createHash } from 'node:crypto';
1
2
  import * as fs from 'fs-extra';
2
3
  import { npm, yarn } from 'global-dirs';
3
4
  import os from 'os';
@@ -18,6 +19,7 @@ import {
18
19
  enumZipEntries,
19
20
  readEntry,
20
21
  readEntryPrefix,
22
+ writeEntry,
21
23
  } from './utils/zip-entries';
22
24
  import {
23
25
  ZIP_ENTRY_SNIFF_BYTES,
@@ -48,6 +50,26 @@ type HdiffModule = {
48
50
  patchStream?: PatchStream;
49
51
  diffSingleStream?: DiffStream;
50
52
  patchSingleStream?: PatchStream;
53
+ capabilities?: {
54
+ diffStreamVerifiesOutput?: boolean;
55
+ diffSingleStreamVerifiesOutput?: boolean;
56
+ diffWindowVerifiesOutput?: boolean;
57
+ };
58
+ };
59
+ type BundleSource =
60
+ | { kind: 'buffer'; data: Buffer }
61
+ | {
62
+ kind: 'file';
63
+ path: string;
64
+ size: number;
65
+ materializeDurationMs: number;
66
+ };
67
+ type BundlePatch =
68
+ | { kind: 'buffer'; data: Buffer }
69
+ | { kind: 'file'; path: string };
70
+ type BundlePatchResult = {
71
+ patch: BundlePatch;
72
+ hbcTransform?: HbcTransformMeta;
51
73
  };
52
74
  type EntryMap = Record<string, { crc32: number; fileName: string }>;
53
75
  type CrcMap = Record<number, string>;
@@ -119,19 +141,80 @@ type BundleDiffOptions = {
119
141
  patchStreamFn?: PatchStream;
120
142
  /** 流式产物是否为 single 格式(决定 baseline 轨道是否可用) */
121
143
  streamEmitsSingleFormat?: boolean;
144
+ /** diffStreamFn 内部已经完整 apply-and-compare,可跳过重复还原 */
145
+ streamOutputVerified?: boolean;
146
+ onDiffPhase?: (metric: {
147
+ phase: 'materialize' | 'diff' | 'verify';
148
+ durationMs: number;
149
+ inputBytes: number;
150
+ outputBytes?: number;
151
+ skipped?: boolean;
152
+ }) => void;
122
153
  };
123
154
 
155
+ function reportDiffPhase(
156
+ options: BundleDiffOptions,
157
+ metric: Parameters<NonNullable<BundleDiffOptions['onDiffPhase']>>[0],
158
+ ) {
159
+ try {
160
+ options.onDiffPhase?.(metric);
161
+ } catch {
162
+ // Observability must never break patch generation.
163
+ }
164
+ }
165
+
166
+ const bundleSourceSize = (source: BundleSource) =>
167
+ source.kind === 'buffer' ? source.data.length : source.size;
168
+
169
+ const bundleSourceBuffer = async (source: BundleSource) =>
170
+ source.kind === 'buffer' ? source.data : fs.readFile(source.path);
171
+
172
+ async function bundleSourceFile(
173
+ source: BundleSource,
174
+ outputPath: string,
175
+ ): Promise<string> {
176
+ if (source.kind === 'file') {
177
+ return source.path;
178
+ }
179
+ await fs.writeFile(outputPath, source.data);
180
+ return outputPath;
181
+ }
182
+
183
+ async function hashFile(filePath: string): Promise<string> {
184
+ const hash = createHash('sha256');
185
+ for await (const chunk of fs.createReadStream(filePath)) {
186
+ hash.update(chunk as Buffer);
187
+ }
188
+ return hash.digest('hex');
189
+ }
190
+
191
+ async function filesEqual(leftPath: string, rightPath: string) {
192
+ const [leftStat, rightStat] = await Promise.all([
193
+ fs.stat(leftPath),
194
+ fs.stat(rightPath),
195
+ ]);
196
+ if (leftStat.size !== rightStat.size) {
197
+ return false;
198
+ }
199
+ const [leftHash, rightHash] = await Promise.all([
200
+ hashFile(leftPath),
201
+ hashFile(rightPath),
202
+ ]);
203
+ return leftHash === rightHash;
204
+ }
205
+
124
206
  /**
125
- * 大 bundle 流式路径:可选 HBC 变换(在 buffer 上做,写临时文件)后
126
- * diffStream 生成 HDIFF13,并以 patchStream + T⁻¹ 做 round-trip 自检。
127
- * 自检失败直接抛错(此路径没有 baseline 可回退——内存 diff 正是要避免的),
128
- * 由上层按任务失败重试/告警处理。
207
+ * 大 bundle 流式路径:普通 bundle 直接从 ZIP entry 落盘后传入 native,
208
+ * 避免 old/new/restored 的整块 Buffer 副本。HBC 变换仍需 Buffer,因为
209
+ * T/T⁻¹ 当前是内存算法。native 已自校验的普通产物不再重复 patch;
210
+ * 自定义/变换路径仍保留 round-trip 校验。
129
211
  */
130
212
  async function buildStreamBundlePatch(
131
- originSource: Buffer,
132
- newSource: Buffer,
213
+ originSource: BundleSource,
214
+ newSource: BundleSource,
133
215
  options: BundleDiffOptions,
134
- ): Promise<{ patchData: Buffer; hbcTransform?: HbcTransformMeta }> {
216
+ workRoot: string,
217
+ ): Promise<BundlePatchResult> {
135
218
  const diffStreamFn = options.diffStreamFn;
136
219
  const patchStreamFn = options.patchStreamFn;
137
220
  if (!diffStreamFn || !patchStreamFn) {
@@ -140,37 +223,100 @@ async function buildStreamBundlePatch(
140
223
  );
141
224
  }
142
225
 
143
- const pair = options.hbcTransform
144
- ? tryTransformPair(originSource, newSource)
226
+ const tempRoot = fs.mkdtempSync(path.join(workRoot, 'stream-'));
227
+ const inputBytes =
228
+ bundleSourceSize(originSource) + bundleSourceSize(newSource);
229
+ const extractionDurationMs =
230
+ (originSource.kind === 'file' ? originSource.materializeDurationMs : 0) +
231
+ (newSource.kind === 'file' ? newSource.materializeDurationMs : 0);
232
+ let phaseStartedAt = performance.now();
233
+ const rawOldFile = await bundleSourceFile(
234
+ originSource,
235
+ path.join(tempRoot, 'old.bin'),
236
+ );
237
+ const rawNewFile = await bundleSourceFile(
238
+ newSource,
239
+ path.join(tempRoot, 'new.bin'),
240
+ );
241
+ const originBuffer = options.hbcTransform
242
+ ? await bundleSourceBuffer(originSource)
145
243
  : null;
146
- const tempRoot = fs.mkdtempSync(path.join(os.tmpdir(), 'rnu-stream-diff-'));
147
- try {
148
- const oldFile = path.join(tempRoot, 'old.bin');
149
- const newFile = path.join(tempRoot, 'new.bin');
150
- const patchFile = path.join(tempRoot, 'patch.bin');
151
- const restoredFile = path.join(tempRoot, 'restored.bin');
152
- fs.writeFileSync(oldFile, pair ? pair.tOld : originSource);
153
- fs.writeFileSync(newFile, pair ? pair.tNew : newSource);
244
+ const newBuffer = options.hbcTransform
245
+ ? await bundleSourceBuffer(newSource)
246
+ : null;
247
+ const pair =
248
+ originBuffer && newBuffer
249
+ ? tryTransformPair(originBuffer, newBuffer)
250
+ : null;
251
+ const oldFile = pair
252
+ ? path.join(tempRoot, 'old-transformed.bin')
253
+ : rawOldFile;
254
+ const newFile = pair
255
+ ? path.join(tempRoot, 'new-transformed.bin')
256
+ : rawNewFile;
257
+ const patchFile = path.join(tempRoot, 'patch.bin');
258
+
259
+ if (pair) {
260
+ await Promise.all([
261
+ fs.writeFile(oldFile, pair.tOld),
262
+ fs.writeFile(newFile, pair.tNew),
263
+ ]);
264
+ }
265
+ reportDiffPhase(options, {
266
+ phase: 'materialize',
267
+ durationMs: extractionDurationMs + performance.now() - phaseStartedAt,
268
+ inputBytes,
269
+ });
154
270
 
155
- await diffStreamFn(oldFile, newFile, patchFile);
271
+ phaseStartedAt = performance.now();
272
+ await diffStreamFn(oldFile, newFile, patchFile);
273
+ const patchBytes = (await fs.stat(patchFile)).size;
274
+ reportDiffPhase(options, {
275
+ phase: 'diff',
276
+ durationMs: performance.now() - phaseStartedAt,
277
+ inputBytes,
278
+ outputBytes: patchBytes,
279
+ });
156
280
 
157
- // round-trip 自检:patchStream 还原(变换域则再做 T⁻¹)必须与新 bundle 一致
281
+ // 变换路径必须验证 T⁻¹ 和元数据;未声明自校验的自定义 diff 也保留
282
+ // round-trip。node-hdiffpatch native 普通路径已经在返回前完整验证。
283
+ if (pair || !options.streamOutputVerified) {
284
+ phaseStartedAt = performance.now();
285
+ const restoredFile = path.join(tempRoot, 'restored.bin');
158
286
  await patchStreamFn(oldFile, patchFile, restoredFile);
159
- const restoredRaw: Buffer = fs.readFileSync(restoredFile);
160
- const restored = pair
161
- ? transformHbcWithLayout(restoredRaw, pair.layout, true)
162
- : restoredRaw;
163
- if (!restored || Buffer.compare(restored, newSource) !== 0) {
287
+ if (pair) {
288
+ const restoredRaw = await fs.readFile(restoredFile);
289
+ const restored = transformHbcWithLayout(restoredRaw, pair.layout, true);
290
+ if (
291
+ !restored ||
292
+ !newBuffer ||
293
+ Buffer.compare(restored, newBuffer) !== 0
294
+ ) {
295
+ throw new Error('stream diff round-trip verification failed');
296
+ }
297
+ } else if (!(await filesEqual(restoredFile, rawNewFile))) {
164
298
  throw new Error('stream diff round-trip verification failed');
165
299
  }
166
-
167
- return {
168
- patchData: fs.readFileSync(patchFile),
169
- ...(pair ? { hbcTransform: pair.meta } : {}),
170
- };
171
- } finally {
172
- fs.rmSync(tempRoot, { recursive: true, force: true });
300
+ reportDiffPhase(options, {
301
+ phase: 'verify',
302
+ durationMs: performance.now() - phaseStartedAt,
303
+ inputBytes,
304
+ outputBytes: patchBytes,
305
+ });
306
+ } else {
307
+ reportDiffPhase(options, {
308
+ phase: 'verify',
309
+ durationMs: 0,
310
+ inputBytes,
311
+ outputBytes: patchBytes,
312
+ skipped: true,
313
+ });
173
314
  }
315
+
316
+ return {
317
+ patch: { kind: 'file', path: patchFile },
318
+ ...(pair ? { hbcTransform: pair.meta } : {}),
319
+ };
174
320
  }
175
321
 
176
322
  /**
@@ -180,51 +326,61 @@ async function buildStreamBundlePatch(
180
326
  */
181
327
  async function buildBundlePatch(
182
328
  diffFn: Diff,
183
- originSource: Buffer | undefined,
184
- newSource: Buffer,
329
+ originSource: BundleSource | undefined,
330
+ newSource: BundleSource,
185
331
  options: BundleDiffOptions,
186
- ): Promise<{ patchData: Buffer; hbcTransform?: HbcTransformMeta }> {
332
+ workRoot: string,
333
+ ): Promise<BundlePatchResult> {
187
334
  if (
188
335
  options.streamThresholdBytes &&
189
336
  originSource &&
190
- Math.max(originSource.length, newSource.length) >=
337
+ Math.max(bundleSourceSize(originSource), bundleSourceSize(newSource)) >=
191
338
  options.streamThresholdBytes
192
339
  ) {
193
- return buildStreamBundlePatch(originSource, newSource, options);
340
+ return buildStreamBundlePatch(originSource, newSource, options, workRoot);
194
341
  }
195
342
 
196
- const baseline = await diffFn(originSource, newSource);
343
+ const [originBuffer, newBuffer] = await Promise.all([
344
+ originSource
345
+ ? bundleSourceBuffer(originSource)
346
+ : Promise.resolve(undefined),
347
+ bundleSourceBuffer(newSource),
348
+ ]);
349
+ const baseline = await diffFn(originBuffer, newBuffer);
197
350
  if (
198
351
  !options.hbcTransform ||
199
352
  !options.patchFn ||
200
- !originSource ||
353
+ !originBuffer ||
201
354
  baseline.length <
202
355
  (options.minBaselineBytes ?? HBC_TRANSFORM_MIN_BASELINE_BYTES)
203
356
  ) {
204
- return { patchData: baseline };
357
+ return { patch: { kind: 'buffer', data: baseline } };
205
358
  }
206
359
 
207
- const pair = tryTransformPair(originSource, newSource);
360
+ const pair = tryTransformPair(originBuffer, newBuffer);
208
361
  if (!pair) {
209
- return { patchData: baseline };
362
+ return { patch: { kind: 'buffer', data: baseline } };
210
363
  }
211
364
 
212
365
  try {
213
366
  const candidate = await diffFn(pair.tOld, pair.tNew);
214
367
  const metaOverhead = Buffer.byteLength(JSON.stringify(pair.meta));
215
368
  if (candidate.length + metaOverhead >= baseline.length) {
216
- return { patchData: baseline };
369
+ return { patch: { kind: 'buffer', data: baseline } };
217
370
  }
218
371
 
219
372
  const patched = options.patchFn(pair.tOld, candidate);
220
373
  const restored = transformHbcWithLayout(patched, pair.layout, true);
221
- if (!restored || Buffer.compare(restored, newSource) !== 0) {
374
+ if (!restored || Buffer.compare(restored, newBuffer) !== 0) {
222
375
  console.warn(t('hbcTransformRoundTripFailed'));
223
- return { patchData: baseline };
376
+ return { patch: { kind: 'buffer', data: baseline } };
224
377
  }
225
- return { patchData: candidate, hbcTransform: pair.meta };
378
+ return {
379
+ patch: { kind: 'buffer', data: candidate },
380
+ hbcTransform: pair.meta,
381
+ };
226
382
  } catch {
227
- return { patchData: baseline };
383
+ return { patch: { kind: 'buffer', data: baseline } };
228
384
  }
229
385
  }
230
386
 
@@ -233,22 +389,69 @@ async function addBundlePatch(
233
389
  entry: Entry,
234
390
  nextZipfile: YauzlZipFile,
235
391
  diffFn: Diff,
236
- originSource: Buffer | undefined,
392
+ originSource: BundleSource | undefined,
237
393
  bundleOptions: BundleDiffOptions,
238
394
  hbcTransformMetas: Record<string, HbcTransformMeta>,
395
+ workRoot: string,
239
396
  ) {
240
- const newSource = await readEntry(entry, nextZipfile);
241
- const { patchData, hbcTransform } = await buildBundlePatch(
397
+ const shouldStream =
398
+ !!bundleOptions.streamThresholdBytes &&
399
+ !!originSource &&
400
+ Math.max(bundleSourceSize(originSource), entry.uncompressedSize) >=
401
+ bundleOptions.streamThresholdBytes;
402
+ let newSource: BundleSource;
403
+ if (shouldStream) {
404
+ const nextRoot = fs.mkdtempSync(path.join(workRoot, 'next-'));
405
+ const nextPath = path.join(nextRoot, 'bundle.bin');
406
+ const startedAt = performance.now();
407
+ await writeEntry(entry, nextZipfile, nextPath);
408
+ newSource = {
409
+ kind: 'file',
410
+ path: nextPath,
411
+ size: entry.uncompressedSize,
412
+ materializeDurationMs: performance.now() - startedAt,
413
+ };
414
+ } else {
415
+ newSource = { kind: 'buffer', data: await readEntry(entry, nextZipfile) };
416
+ }
417
+
418
+ const { patch, hbcTransform } = await buildBundlePatch(
242
419
  diffFn,
243
420
  originSource,
244
421
  newSource,
245
422
  bundleOptions,
423
+ workRoot,
246
424
  );
247
425
  const patchEntryName = `${entry.fileName}.patch`;
248
426
  if (hbcTransform) {
249
427
  hbcTransformMetas[patchEntryName] = hbcTransform;
250
428
  }
251
- zipfile.addBuffer(patchData, patchEntryName, zipOptionsForPatchEntry());
429
+ if (patch.kind === 'file') {
430
+ zipfile.addFile(patch.path, patchEntryName, zipOptionsForPatchEntry());
431
+ } else {
432
+ zipfile.addBuffer(patch.data, patchEntryName, zipOptionsForPatchEntry());
433
+ }
434
+ }
435
+
436
+ async function readOriginBundleSource(
437
+ entry: Entry,
438
+ zipFile: YauzlZipFile,
439
+ bundleOptions: BundleDiffOptions,
440
+ workRoot: string,
441
+ ): Promise<BundleSource> {
442
+ if (!bundleOptions.streamThresholdBytes) {
443
+ return { kind: 'buffer', data: await readEntry(entry, zipFile) };
444
+ }
445
+ const originRoot = fs.mkdtempSync(path.join(workRoot, 'origin-'));
446
+ const originPath = path.join(originRoot, 'bundle.bin');
447
+ const startedAt = performance.now();
448
+ await writeEntry(entry, zipFile, originPath);
449
+ return {
450
+ kind: 'file',
451
+ path: originPath,
452
+ size: entry.uncompressedSize,
453
+ materializeDurationMs: performance.now() - startedAt,
454
+ };
252
455
  }
253
456
 
254
457
  async function addFileFromZipEntry(
@@ -302,12 +505,13 @@ async function diffFromPPK(
302
505
  next: string,
303
506
  output: string,
304
507
  diffFn: Diff,
305
- bundleOptions: BundleDiffOptions = {},
508
+ bundleOptions: BundleDiffOptions,
509
+ workRoot: string,
306
510
  ) {
307
511
  const originEntries: EntryMap = {};
308
512
  const originMap: CrcMap = {};
309
513
 
310
- let originSource: Buffer | undefined;
514
+ let originSource: BundleSource | undefined;
311
515
 
312
516
  await enumZipEntries(origin, async (entry, zipFile) => {
313
517
  originEntries[entry.fileName] = entry;
@@ -317,7 +521,12 @@ async function diffFromPPK(
317
521
 
318
522
  if (isPPKBundleFileName(entry.fileName)) {
319
523
  // This is source.
320
- originSource = await readEntry(entry, zipFile);
524
+ originSource = await readOriginBundleSource(
525
+ entry,
526
+ zipFile,
527
+ bundleOptions,
528
+ workRoot,
529
+ );
321
530
  }
322
531
  }
323
532
  });
@@ -365,6 +574,7 @@ async function diffFromPPK(
365
574
  originSource,
366
575
  bundleOptions,
367
576
  hbcTransformMetas,
577
+ workRoot,
368
578
  );
369
579
  } else {
370
580
  // If same file.
@@ -419,12 +629,13 @@ async function diffFromPackage(
419
629
  output: string,
420
630
  diffFn: Diff,
421
631
  platform: Platform,
422
- bundleOptions: BundleDiffOptions = {},
632
+ bundleOptions: BundleDiffOptions,
633
+ workRoot: string,
423
634
  ) {
424
635
  const originEntries: Record<string, number> = {};
425
636
  const originMap: CrcMap = {};
426
637
 
427
- let originSource: Buffer | undefined;
638
+ let originSource: BundleSource | undefined;
428
639
 
429
640
  // Content checksum (CRC32) for entries that are copied from a *different*
430
641
  // path in the origin package ("moved" entries). On Android these are the
@@ -448,7 +659,12 @@ async function diffFromPackage(
448
659
 
449
660
  if (resolvedEntry.kind === 'bundle') {
450
661
  // This is source.
451
- originSource = await readEntry(entry, zipFile);
662
+ originSource = await readOriginBundleSource(
663
+ entry,
664
+ zipFile,
665
+ bundleOptions,
666
+ workRoot,
667
+ );
452
668
  }
453
669
  }
454
670
  });
@@ -475,6 +691,7 @@ async function diffFromPackage(
475
691
  originSource,
476
692
  bundleOptions,
477
693
  hbcTransformMetas,
694
+ workRoot,
478
695
  );
479
696
  } else {
480
697
  // If same file.
@@ -511,9 +728,12 @@ type DiffCommandOptions = {
511
728
  customPatch?: Patch;
512
729
  customDiffStream?: DiffStream;
513
730
  customPatchStream?: PatchStream;
731
+ customDiffStreamVerified?: boolean;
514
732
  customDiffSingleStream?: DiffStream;
515
733
  customPatchSingleStream?: PatchStream;
734
+ customDiffSingleStreamVerified?: boolean;
516
735
  customHdiffModule?: HdiffModule;
736
+ onDiffPhase?: BundleDiffOptions['onDiffPhase'];
517
737
  hbcTransform?: boolean;
518
738
  bundleStreamThreshold?: number;
519
739
  [key: string]: any;
@@ -552,7 +772,12 @@ function resolveBundleDiffOptions(
552
772
  | 'diffStreamFn'
553
773
  | 'patchStreamFn'
554
774
  | 'streamEmitsSingleFormat'
775
+ | 'streamOutputVerified'
555
776
  > = {};
777
+ const observerOptions =
778
+ typeof options.onDiffPhase === 'function'
779
+ ? { onDiffPhase: options.onDiffPhase }
780
+ : {};
556
781
  if (
557
782
  typeof options.bundleStreamThreshold === 'number' &&
558
783
  options.bundleStreamThreshold > 0
@@ -568,27 +793,34 @@ function resolveBundleDiffOptions(
568
793
  streamOptions.diffStreamFn = singleDiffStreamFn;
569
794
  streamOptions.patchStreamFn = singlePatchStreamFn;
570
795
  streamOptions.streamEmitsSingleFormat = true;
796
+ streamOptions.streamOutputVerified = options.customDiffSingleStream
797
+ ? options.customDiffSingleStreamVerified === true
798
+ : hdiffModule?.capabilities?.diffSingleStreamVerifiesOutput === true;
571
799
  } else if (diffStreamFn && patchStreamFn) {
572
800
  streamOptions.streamThresholdBytes = options.bundleStreamThreshold;
573
801
  streamOptions.diffStreamFn = diffStreamFn;
574
802
  streamOptions.patchStreamFn = patchStreamFn;
575
803
  streamOptions.streamEmitsSingleFormat = false;
804
+ streamOptions.streamOutputVerified = options.customDiffStream
805
+ ? options.customDiffStreamVerified === true
806
+ : hdiffModule?.capabilities?.diffStreamVerifiesOutput === true;
576
807
  } else {
577
808
  console.warn(t('bundleStreamNeedsHdiffpatch'));
578
809
  }
579
810
  }
580
811
 
581
812
  if (!options.hbcTransform) {
582
- return { ...streamOptions };
813
+ return { ...observerOptions, ...streamOptions };
583
814
  }
584
815
  const patchFn = resolvePatchImplementation(options);
585
816
  if (!patchFn) {
586
817
  console.warn(t('hbcTransformNeedsPatch'));
587
- return { ...streamOptions };
818
+ return { ...observerOptions, ...streamOptions };
588
819
  }
589
820
  return {
590
821
  hbcTransform: true,
591
822
  patchFn,
823
+ ...observerOptions,
592
824
  ...streamOptions,
593
825
  ...(typeof options.hbcTransformMinBaseline === 'number'
594
826
  ? { minBaselineBytes: options.hbcTransformMinBaseline }
@@ -636,17 +868,30 @@ const createDiffCommand =
636
868
  options as DiffCommandOptions,
637
869
  );
638
870
 
639
- if (target.kind === 'ppk') {
640
- await diffFromPPK(origin, next, realOutput, diffFn, bundleOptions);
641
- } else {
642
- await diffFromPackage(
643
- origin,
644
- next,
645
- realOutput,
646
- diffFn,
647
- target.platform,
648
- bundleOptions,
649
- );
871
+ const workRoot = fs.mkdtempSync(path.join(os.tmpdir(), 'rnu-bundle-diff-'));
872
+ try {
873
+ if (target.kind === 'ppk') {
874
+ await diffFromPPK(
875
+ origin,
876
+ next,
877
+ realOutput,
878
+ diffFn,
879
+ bundleOptions,
880
+ workRoot,
881
+ );
882
+ } else {
883
+ await diffFromPackage(
884
+ origin,
885
+ next,
886
+ realOutput,
887
+ diffFn,
888
+ target.platform,
889
+ bundleOptions,
890
+ workRoot,
891
+ );
892
+ }
893
+ } finally {
894
+ fs.rmSync(workRoot, { recursive: true, force: true });
650
895
  }
651
896
 
652
897
  console.log(t('diffPackageGenerated', { output: realOutput }));
@@ -1,6 +1,7 @@
1
1
  import * as fs from 'fs-extra';
2
2
  import os from 'os';
3
3
  import path from 'path';
4
+ import { pipeline } from 'stream/promises';
4
5
  import {
5
6
  type Entry,
6
7
  open as openZipFile,
@@ -34,6 +35,27 @@ export function readEntry(
34
35
  });
35
36
  }
36
37
 
38
+ export function writeEntry(
39
+ entry: Entry,
40
+ zipFile: YauzlZipFile,
41
+ outputPath: string,
42
+ ): Promise<void> {
43
+ fs.ensureDirSync(path.dirname(outputPath));
44
+ return new Promise((resolve, reject) => {
45
+ zipFile.openReadStream(entry, (err, stream) => {
46
+ if (err) {
47
+ reject(err);
48
+ return;
49
+ }
50
+ if (!stream) {
51
+ reject(new Error(`Unable to read zip entry: ${entry.fileName}`));
52
+ return;
53
+ }
54
+ pipeline(stream, fs.createWriteStream(outputPath)).then(resolve, reject);
55
+ });
56
+ });
57
+ }
58
+
37
59
  export function readEntryPrefix(
38
60
  entry: Entry,
39
61
  zipFile: YauzlZipFile,