@gfean/react-native-bundle-drop 0.6.0 → 0.8.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 (86) hide show
  1. package/BundleDrop.podspec +96 -0
  2. package/README.md +249 -9
  3. package/android/build.gradle +72 -5
  4. package/android/src/main/java/com/bundledrop/BundleDropModule.kt +137 -13
  5. package/android/src/main/java/com/bundledrop/BundleDropNativePaths.kt +43 -13
  6. package/android/src/main/java/com/bundledrop/BundleDropOtaResolver.kt +35 -0
  7. package/android/src/main/java/com/bundledrop/BundleDropStartupRecovery.kt +1117 -0
  8. package/ios/BundleDropBridge.m +27 -0
  9. package/ios/BundleDropLocator.swift +31 -15
  10. package/ios/BundleDropModule.swift +106 -3
  11. package/ios/BundleDropOtaResolver.swift +137 -29
  12. package/ios/BundleDropStartupRecovery.swift +1108 -0
  13. package/ios/BundleDropStartupRecoveryAdapter.swift +301 -0
  14. package/lib/CLI/cli.js +9 -5
  15. package/lib/CLI/scripts/doctor.js +28 -9
  16. package/lib/CLI/scripts/expo/configure-expo.js +2 -1
  17. package/lib/CLI/scripts/init-config.d.ts +2 -2
  18. package/lib/CLI/scripts/init-config.js +23 -14
  19. package/lib/CLI/scripts/login-cli.js +2 -3
  20. package/lib/CLI/scripts/native/write-runtime-identity.d.ts +19 -0
  21. package/lib/CLI/scripts/native/write-runtime-identity.js +92 -0
  22. package/lib/CLI/scripts/sight-artifacts.d.ts +9 -1
  23. package/lib/CLI/scripts/sight-artifacts.js +20 -8
  24. package/lib/CLI/scripts/sight-assets.d.ts +15 -0
  25. package/lib/CLI/scripts/sight-assets.js +71 -0
  26. package/lib/CLI/scripts/sight-cli.d.ts +3 -0
  27. package/lib/CLI/scripts/sight-cli.js +50 -4
  28. package/lib/CLI/scripts/sight-compare/assets.d.ts +6 -0
  29. package/lib/CLI/scripts/sight-compare/assets.js +73 -0
  30. package/lib/CLI/scripts/sight-compare/dependencies.d.ts +22 -0
  31. package/lib/CLI/scripts/sight-compare/dependencies.js +289 -0
  32. package/lib/CLI/scripts/sight-compare/git.d.ts +22 -0
  33. package/lib/CLI/scripts/sight-compare/git.js +116 -0
  34. package/lib/CLI/scripts/sight-compare/inspect-project.d.ts +37 -0
  35. package/lib/CLI/scripts/sight-compare/inspect-project.js +191 -0
  36. package/lib/CLI/scripts/sight-compare/metadata.d.ts +4 -0
  37. package/lib/CLI/scripts/sight-compare/metadata.js +39 -0
  38. package/lib/CLI/scripts/sight-compare/process.d.ts +22 -0
  39. package/lib/CLI/scripts/sight-compare/process.js +221 -0
  40. package/lib/CLI/scripts/sight-compare/run.d.ts +3 -0
  41. package/lib/CLI/scripts/sight-compare/run.js +290 -0
  42. package/lib/CLI/scripts/sight-compare/snapshot.d.ts +26 -0
  43. package/lib/CLI/scripts/sight-compare/snapshot.js +279 -0
  44. package/lib/CLI/scripts/sight-compare/types.d.ts +87 -0
  45. package/lib/CLI/scripts/sight-compare/types.js +2 -0
  46. package/lib/CLI/scripts/sight-ota.d.ts +18 -0
  47. package/lib/CLI/scripts/sight-ota.js +260 -0
  48. package/lib/CLI/scripts/sight-session.d.ts +9 -2
  49. package/lib/CLI/scripts/sight-session.js +58 -20
  50. package/lib/CLI/scripts/upload-cli.d.ts +12 -2
  51. package/lib/CLI/scripts/upload-cli.js +74 -11
  52. package/lib/CLI/serverUrl.d.ts +3 -0
  53. package/lib/CLI/serverUrl.js +31 -0
  54. package/lib/bundleInfo.d.ts +2 -0
  55. package/lib/bundleInfo.js +16 -1
  56. package/lib/context.js +12 -2
  57. package/lib/fs/bundlePointer.d.ts +1 -17
  58. package/lib/fs/bundlePointer.js +5 -93
  59. package/lib/install/bundleInstallShared.js +4 -4
  60. package/lib/manager/downloadAndInstall.js +25 -22
  61. package/lib/manager/reporting.d.ts +8 -1
  62. package/lib/manager/reporting.js +17 -22
  63. package/lib/manager/rollbackState.d.ts +18 -54
  64. package/lib/manager/rollbackState.js +115 -216
  65. package/lib/manager/updateCheck.js +9 -3
  66. package/lib/manager/updateState.d.ts +2 -1
  67. package/lib/manager/updateState.js +59 -6
  68. package/lib/metro.d.ts +1 -1
  69. package/lib/metro.js +4 -3
  70. package/lib/native/bundleDropNative.d.ts +62 -0
  71. package/lib/native/bundleDropNative.js +266 -1
  72. package/lib/patch-engine/installFromPatchSet.js +2 -2
  73. package/lib/runtime/service.js +29 -71
  74. package/lib/runtime-delivery/bootstrapConfig.d.ts +29 -11
  75. package/lib/runtime-delivery/bootstrapConfig.js +83 -22
  76. package/lib/runtime-delivery/manifestState.d.ts +3 -1
  77. package/lib/runtime-delivery/manifestState.js +22 -1
  78. package/lib/runtime-delivery/manifestVerifier.js +7 -1
  79. package/lib/scripts/bundle.d.ts +12 -2
  80. package/lib/scripts/bundle.js +74 -21
  81. package/lib/scripts/download-bundle.d.ts +1 -0
  82. package/lib/scripts/download-bundle.js +2 -2
  83. package/lib/scripts/resolveModule.d.ts +2 -0
  84. package/lib/scripts/resolveModule.js +5 -0
  85. package/package.json +5 -2
  86. package/plugin/xcodeBuildPhase.js +2 -1
@@ -3,21 +3,12 @@ Object.defineProperty(exports, "__esModule", { value: true });
3
3
  exports.installBundle = exports.downloadUpdate = void 0;
4
4
  const context_1 = require("../context");
5
5
  const bundleInfo_1 = require("../bundleInfo");
6
- const bundlePointer_1 = require("../fs/bundlePointer");
7
6
  const installFromZip_1 = require("../install/installFromZip");
8
7
  const patchTransport_1 = require("../patch-engine/patchTransport");
9
- const bundleDropNative_1 = require("../native/bundleDropNative");
10
8
  const updateCheck_1 = require("./updateCheck");
11
9
  const errors_1 = require("../errors");
12
10
  const rollbackState_1 = require("./rollbackState");
13
11
  const artifactCapability_1 = require("../runtime-delivery/artifactCapability");
14
- async function restoreCurrentPointer(pointer) {
15
- if (pointer) {
16
- await (0, bundlePointer_1.writeCurrentBundlePointer)({ ...pointer, updatedAt: new Date().toISOString() });
17
- return;
18
- }
19
- await (0, bundlePointer_1.deleteCurrentBundlePointer)();
20
- }
21
12
  function isSameRuntimeDeliverySelection(selected, refreshed) {
22
13
  if (!refreshed ||
23
14
  refreshed.action !== 'INSTALL' ||
@@ -211,11 +202,7 @@ async function downloadAndStageUpdate(options, onStatusUpdate) {
211
202
  const installedHash = hash;
212
203
  statusCb?.('✅ Update downloaded. Will apply on next launch or when you call applyUpdate().');
213
204
  // Persist installed metadata for future skip logic.
214
- const [previousInfo, previousCurrentPointer, previousRollbackPointer] = await Promise.all([
215
- (0, bundleInfo_1.readBundleInfo)(),
216
- (0, bundlePointer_1.readCurrentBundlePointer)(),
217
- (0, bundlePointer_1.readPreviousBundlePointer)(),
218
- ]);
205
+ const previousInfo = await (0, bundleInfo_1.readBundleInfo)();
219
206
  const installedInfo = {
220
207
  bundleVersion: serverBundleVersion ?? metadataFromZip.bundleVersion,
221
208
  version: serverVersion ?? metadataFromZip.version,
@@ -228,21 +215,39 @@ async function downloadAndStageUpdate(options, onStatusUpdate) {
228
215
  lastInstalledReportedHash: previousInfo?.lastInstalledReportedHash,
229
216
  installedReportedHashes: previousInfo?.installedReportedHashes,
230
217
  };
231
- await (0, bundlePointer_1.setCurrentBundlePointer)(bundlePath, installedHash);
218
+ let candidateActivated = false;
232
219
  try {
233
- const resolvedBundlePath = await (0, bundleDropNative_1.getDownloadedBundlePathNative)();
234
- if (resolvedBundlePath !== bundlePath) {
220
+ const activation = await (0, rollbackState_1.activateStartupCandidate)(installedHash);
221
+ candidateActivated = activation !== null;
222
+ if (!activation) {
223
+ throw new errors_1.BundleDropError({
224
+ message: 'Installed bundle requires native startup recovery support',
225
+ code: 'INSTALL_FAILED',
226
+ step: 'install',
227
+ context: { channelName, platform, hash },
228
+ });
229
+ }
230
+ if (activation.hash !== installedHash || activation.bundlePath !== bundlePath) {
235
231
  throw new errors_1.BundleDropError({
236
232
  message: 'Installed bundle was not accepted by the native resolver',
237
233
  code: 'INSTALL_FAILED',
238
234
  step: 'install',
239
- context: { channelName, platform, hash, expectedBundlePath: bundlePath, resolvedBundlePath },
235
+ context: {
236
+ channelName,
237
+ platform,
238
+ hash,
239
+ expectedBundlePath: bundlePath,
240
+ resolvedBundlePath: activation.bundlePath,
241
+ resolvedHash: activation.hash,
242
+ },
240
243
  });
241
244
  }
245
+ await (0, bundleInfo_1.writeBundleInfoDurably)(installedInfo);
242
246
  }
243
247
  catch (nativeError) {
244
- await restoreCurrentPointer(previousCurrentPointer);
245
- await (0, bundlePointer_1.restorePreviousBundlePointer)(previousRollbackPointer);
248
+ if (candidateActivated) {
249
+ await (0, rollbackState_1.rollbackStartupBundle)(false).catch(() => false);
250
+ }
246
251
  if (nativeError instanceof errors_1.BundleDropError) {
247
252
  throw nativeError;
248
253
  }
@@ -254,8 +259,6 @@ async function downloadAndStageUpdate(options, onStatusUpdate) {
254
259
  cause: nativeError,
255
260
  });
256
261
  }
257
- await (0, bundleInfo_1.writeBundleInfo)(installedInfo);
258
- await (0, rollbackState_1.markCandidateActivated)(installedHash);
259
262
  return { status: 'staged', bundlePath, hash: installedHash };
260
263
  }
261
264
  catch (err) {
@@ -1,5 +1,12 @@
1
1
  import { BundleInfo } from '../bundleInfo';
2
- import type { FailedBundleRecord } from './rollbackState';
2
+ export type FailedBundleRecord = {
3
+ reason: 'crash_loop';
4
+ failedAt: number;
5
+ crashCount?: number;
6
+ channelName?: string;
7
+ runtimeVersion?: string;
8
+ previousHash?: string;
9
+ };
3
10
  export declare function reportInstalledIfReady(state?: {
4
11
  hasBundle?: boolean;
5
12
  info?: BundleInfo | null;
@@ -74,26 +74,21 @@ async function reportInstalledIfReady(state) {
74
74
  }
75
75
  }
76
76
  async function reportLocalRollback(hash, record) {
77
- try {
78
- const [installId, userProperties] = await Promise.all([
79
- (0, installId_1.getOrCreateInstallId)(),
80
- (0, userProperties_1.getCurrentUserProperties)(),
81
- ]);
82
- const appEnvironment = (0, initState_1.getBundleDropRuntimeConfig)()?.environment ?? null;
83
- await (0, clientApi_1.reportLocalRollback)(context_1.config.project.slug, hash, {
84
- reason: record.reason,
85
- previousHash: record.previousHash ?? null,
86
- channelName: record.channelName ?? null,
87
- platform: context_1.platform,
88
- installId,
89
- runtimeVersion: record.runtimeVersion ?? context_1.runtimeVersion ?? null,
90
- environment: appEnvironment,
91
- userProperties: Object.keys(userProperties).length > 0 ? userProperties : undefined,
92
- crashCount: record.crashCount ?? null,
93
- failedAt: record.failedAt ? new Date(record.failedAt * 1000).toISOString() : null,
94
- });
95
- }
96
- catch (e) {
97
- console.warn('⚠️ Failed to report local rollback:', e?.toString?.() || e);
98
- }
77
+ const [installId, userProperties] = await Promise.all([
78
+ (0, installId_1.getOrCreateInstallId)(),
79
+ (0, userProperties_1.getCurrentUserProperties)(),
80
+ ]);
81
+ const appEnvironment = (0, initState_1.getBundleDropRuntimeConfig)()?.environment ?? null;
82
+ await (0, clientApi_1.reportLocalRollback)(context_1.config.project.slug, hash, {
83
+ reason: record.reason,
84
+ previousHash: record.previousHash ?? null,
85
+ channelName: record.channelName ?? null,
86
+ platform: context_1.platform,
87
+ installId,
88
+ runtimeVersion: record.runtimeVersion ?? context_1.runtimeVersion ?? null,
89
+ environment: appEnvironment,
90
+ userProperties: Object.keys(userProperties).length > 0 ? userProperties : undefined,
91
+ crashCount: record.crashCount ?? null,
92
+ failedAt: record.failedAt ? new Date(record.failedAt * 1000).toISOString() : null,
93
+ });
99
94
  }
@@ -1,60 +1,24 @@
1
- import { type BundlePointer } from '../fs/bundlePointer';
1
+ import type { BundleInfo } from '../bundleInfo';
2
+ import { type StartupRecoveryState, type StartupCandidateActivation, type StartupRollbackResult } from '../native/bundleDropNative';
2
3
  export type RollbackPolicy = {
3
4
  maxCrashCount?: number;
4
5
  healthCheckMode?: 'auto' | 'manual';
5
6
  healthyAfterSec?: number;
6
7
  };
7
- export type FailedBundleReason = 'crash_loop';
8
- export type FailedBundleRecord = {
9
- reason: FailedBundleReason;
10
- failedAt: number;
11
- crashCount?: number;
12
- channelName?: string;
13
- runtimeVersion?: string;
14
- previousHash?: string;
15
- };
16
- export type RollbackState = {
17
- activeHash?: string;
18
- lastGoodHash?: string;
19
- candidateHash?: string;
20
- candidateActivatedAt?: number;
21
- candidateCommitted?: boolean;
22
- crashCount?: number;
23
- lastLaunchAt?: number;
24
- failedBundles?: Record<string, FailedBundleRecord>;
25
- };
26
- type RollbackDecision = {
27
- shouldRollback: false;
28
- } | {
29
- shouldRollback: true;
30
- reason: FailedBundleReason;
31
- };
32
- declare function readState(): Promise<RollbackState | null>;
33
- export { readState as readRollbackState };
34
- export declare function markCandidateActivated(hash: string): Promise<void>;
35
- export declare function reportActiveBundleHealthy(cached?: {
36
- currentPointer?: BundlePointer | null;
37
- }, expectedHash?: string): Promise<boolean>;
38
- export declare function commitActiveBundle(cached?: {
39
- currentPointer?: BundlePointer | null;
40
- }): Promise<void>;
41
- export declare function isBundleHashFailed(hash?: string | null): Promise<boolean>;
42
- export declare function getFailedBundleHashes(): Promise<string[]>;
43
- export declare function evaluateRollbackOnLaunch(policy: Required<RollbackPolicy>, cached?: {
44
- currentPointer?: BundlePointer | null;
45
- rollbackState?: RollbackState | null;
46
- }): Promise<RollbackDecision>;
47
- export declare function rollbackToPreviousIfNeeded(policy: Required<RollbackPolicy>, cached?: {
48
- currentPointer?: BundlePointer | null;
49
- rollbackState?: RollbackState | null;
50
- }): Promise<{
51
- rolledBack: boolean;
52
- reason?: FailedBundleReason;
53
- }>;
8
+ export type { FailedBundleRecord } from './reporting';
9
+ export type { StartupRecoveryState } from '../native/bundleDropNative';
10
+ export declare const STARTUP_RECOVERY_TELEMETRY_CONTEXT_PATH: string;
54
11
  export declare function getRollbackPolicy(): Required<RollbackPolicy>;
55
- export declare function rollbackToPreviousOrNative(options?: {
56
- forceNative?: boolean;
57
- }): Promise<{
58
- rolledBack: boolean;
59
- toNative?: boolean;
60
- }>;
12
+ export declare function activateStartupCandidate(hash: string): Promise<StartupCandidateActivation | null>;
13
+ export declare function reportActiveBundleHealthy(): Promise<boolean>;
14
+ export declare function readStartupRecoveryState(): Promise<StartupRecoveryState | null>;
15
+ export declare function getFailedBundleHashes(cachedState?: StartupRecoveryState | null): Promise<string[]>;
16
+ export declare function isBundleHashFailed(hash?: string | null): Promise<boolean>;
17
+ export declare function syncVerifiedRevokedHashes(hashes: string[]): Promise<boolean>;
18
+ export declare function rollbackStartupBundle(forceEmbedded: boolean): Promise<StartupRollbackResult | null>;
19
+ /**
20
+ * Flush native recovery events without making JS part of the recovery decision.
21
+ * Native keeps each event durable until its backend report succeeds and JS
22
+ * acknowledges that exact event id.
23
+ */
24
+ export declare function reconcileStartupRecovery(cachedState?: StartupRecoveryState | null, failedBundleInfo?: BundleInfo | null): Promise<StartupRecoveryState | null>;
@@ -3,246 +3,145 @@ var __importDefault = (this && this.__importDefault) || function (mod) {
3
3
  return (mod && mod.__esModule) ? mod : { "default": mod };
4
4
  };
5
5
  Object.defineProperty(exports, "__esModule", { value: true });
6
- exports.readRollbackState = readState;
7
- exports.markCandidateActivated = markCandidateActivated;
6
+ exports.STARTUP_RECOVERY_TELEMETRY_CONTEXT_PATH = void 0;
7
+ exports.getRollbackPolicy = getRollbackPolicy;
8
+ exports.activateStartupCandidate = activateStartupCandidate;
8
9
  exports.reportActiveBundleHealthy = reportActiveBundleHealthy;
9
- exports.commitActiveBundle = commitActiveBundle;
10
- exports.isBundleHashFailed = isBundleHashFailed;
10
+ exports.readStartupRecoveryState = readStartupRecoveryState;
11
11
  exports.getFailedBundleHashes = getFailedBundleHashes;
12
- exports.evaluateRollbackOnLaunch = evaluateRollbackOnLaunch;
13
- exports.rollbackToPreviousIfNeeded = rollbackToPreviousIfNeeded;
14
- exports.getRollbackPolicy = getRollbackPolicy;
15
- exports.rollbackToPreviousOrNative = rollbackToPreviousOrNative;
16
- const fs_1 = __importDefault(require("../native/fs"));
12
+ exports.isBundleHashFailed = isBundleHashFailed;
13
+ exports.syncVerifiedRevokedHashes = syncVerifiedRevokedHashes;
14
+ exports.rollbackStartupBundle = rollbackStartupBundle;
15
+ exports.reconcileStartupRecovery = reconcileStartupRecovery;
17
16
  const context_1 = require("../context");
18
17
  const fsUtils_1 = require("../fs/fsUtils");
19
- const bundlePointer_1 = require("../fs/bundlePointer");
20
- const bundleInfo_1 = require("../bundleInfo");
18
+ const fs_1 = __importDefault(require("../native/fs"));
19
+ const bundleDropNative_1 = require("../native/bundleDropNative");
21
20
  const reporting_1 = require("./reporting");
22
- const bundleManifest_1 = require("../manifest/bundleManifest");
23
- const STATE_PATH = `${context_1.BUNDLE_DROP_ROOT}/state.json`;
24
- const MAX_FAILED_BUNDLES = 20;
25
- function nowSec() {
26
- return Math.floor(Date.now() / 1000);
27
- }
28
- async function readState() {
21
+ exports.STARTUP_RECOVERY_TELEMETRY_CONTEXT_PATH = `${context_1.BUNDLE_DROP_ROOT}/recovery-telemetry-context.json`;
22
+ let telemetryContextMutation = Promise.resolve();
23
+ async function readRecoveryTelemetryContexts() {
29
24
  try {
30
- if (!(await fs_1.default.exists(STATE_PATH)))
31
- return null;
32
- const raw = await fs_1.default.readFile(STATE_PATH, 'utf8');
33
- return JSON.parse(raw);
25
+ if (!await fs_1.default.exists(exports.STARTUP_RECOVERY_TELEMETRY_CONTEXT_PATH)) {
26
+ return { schemaVersion: 1, events: {} };
27
+ }
28
+ const parsed = JSON.parse(await fs_1.default.readFile(exports.STARTUP_RECOVERY_TELEMETRY_CONTEXT_PATH, 'utf8'));
29
+ if (parsed?.schemaVersion !== 1 || !parsed.events || typeof parsed.events !== 'object') {
30
+ throw new Error('unsupported recovery telemetry context');
31
+ }
32
+ return parsed;
34
33
  }
35
- catch {
36
- return null;
34
+ catch (error) {
35
+ console.warn('⚠️ Ignoring malformed BundleDrop recovery telemetry context:', error);
36
+ return { schemaVersion: 1, events: {} };
37
37
  }
38
38
  }
39
- async function writeState(state) {
40
- await (0, fsUtils_1.ensureDir)(context_1.BUNDLE_DROP_ROOT);
41
- await (0, fsUtils_1.atomicWriteJson)(STATE_PATH, state);
39
+ async function mutateRecoveryTelemetryContexts(mutate) {
40
+ let result = { schemaVersion: 1, events: {} };
41
+ const mutation = telemetryContextMutation.then(async () => {
42
+ result = await readRecoveryTelemetryContexts();
43
+ if (!mutate(result))
44
+ return;
45
+ await (0, fsUtils_1.ensureDir)(context_1.BUNDLE_DROP_ROOT);
46
+ await (0, fsUtils_1.atomicWriteJson)(exports.STARTUP_RECOVERY_TELEMETRY_CONTEXT_PATH, result);
47
+ });
48
+ telemetryContextMutation = mutation.then(() => undefined, () => undefined);
49
+ await mutation;
50
+ return result;
51
+ }
52
+ async function prepareRecoveryTelemetryContexts(events, failedBundleInfo) {
53
+ const pendingEventIds = new Set(events.map(event => event.id));
54
+ return mutateRecoveryTelemetryContexts(state => {
55
+ let changed = false;
56
+ for (const eventId of Object.keys(state.events)) {
57
+ if (!pendingEventIds.has(eventId)) {
58
+ delete state.events[eventId];
59
+ changed = true;
60
+ }
61
+ }
62
+ for (const event of events) {
63
+ if (!state.events[event.id] &&
64
+ failedBundleInfo?.hash === event.failedHash) {
65
+ state.events[event.id] = {
66
+ failedHash: event.failedHash,
67
+ channelName: failedBundleInfo.channelName,
68
+ runtimeVersion: failedBundleInfo.runtimeVersion,
69
+ };
70
+ changed = true;
71
+ }
72
+ }
73
+ return changed;
74
+ });
42
75
  }
43
- async function updateState(partial) {
44
- const existing = (await readState()) || {};
45
- const next = { ...existing, ...partial };
46
- await writeState(next);
47
- return next;
76
+ async function removeRecoveryTelemetryContext(eventId) {
77
+ await mutateRecoveryTelemetryContexts(state => {
78
+ if (!state.events[eventId])
79
+ return false;
80
+ delete state.events[eventId];
81
+ return true;
82
+ });
48
83
  }
49
- function pruneFailedBundles(failedBundles) {
50
- return Object.fromEntries(Object.entries(failedBundles)
51
- .sort(([, left], [, right]) => right.failedAt - left.failedAt)
52
- .slice(0, MAX_FAILED_BUNDLES));
84
+ function getRollbackPolicy() {
85
+ return context_1.bundleDropConfig.rollback;
53
86
  }
54
- async function markCandidateActivated(hash) {
55
- const previous = await (0, bundlePointer_1.readPreviousBundlePointer)();
56
- const previousHash = previous?.hash;
57
- const now = nowSec();
58
- await updateState({
59
- activeHash: hash,
60
- candidateHash: hash,
61
- candidateActivatedAt: now,
62
- candidateCommitted: false,
63
- crashCount: 0,
64
- lastLaunchAt: now,
65
- lastGoodHash: previousHash ?? undefined,
66
- });
87
+ async function activateStartupCandidate(hash) {
88
+ return (0, bundleDropNative_1.activateStartupCandidateNative)(hash, getRollbackPolicy());
67
89
  }
68
- async function reportActiveBundleHealthy(cached, expectedHash) {
69
- const current = cached?.currentPointer !== undefined ? cached.currentPointer : await (0, bundlePointer_1.readCurrentBundlePointer)();
70
- const hash = current?.hash;
71
- if (!hash)
72
- return false;
73
- if (expectedHash && hash !== expectedHash)
74
- return false;
75
- const state = (await readState()) || {};
76
- const isCandidate = state.candidateHash === hash && state.candidateCommitted !== true;
77
- if (!isCandidate)
90
+ async function reportActiveBundleHealthy() {
91
+ const attempt = (0, bundleDropNative_1.getStartupRecoveryAttemptNative)();
92
+ if (!attempt)
78
93
  return false;
79
- await updateState({
80
- activeHash: hash,
81
- candidateHash: hash,
82
- candidateCommitted: true,
83
- crashCount: 0,
84
- lastGoodHash: hash,
85
- });
86
- return true;
94
+ return (0, bundleDropNative_1.markStartupHealthyNative)(attempt);
95
+ }
96
+ async function readStartupRecoveryState() {
97
+ return (0, bundleDropNative_1.getStartupRecoveryStateNative)();
87
98
  }
88
- async function commitActiveBundle(cached) {
89
- await reportActiveBundleHealthy(cached);
99
+ async function getFailedBundleHashes(cachedState) {
100
+ const state = cachedState === undefined ? await readStartupRecoveryState() : cachedState;
101
+ return [...(state?.quarantinedHashes || [])];
90
102
  }
91
103
  async function isBundleHashFailed(hash) {
92
104
  if (!hash)
93
105
  return false;
94
- const state = await readState();
95
- return !!state?.failedBundles?.[hash];
106
+ return (await getFailedBundleHashes()).includes(hash);
96
107
  }
97
- async function getFailedBundleHashes() {
98
- const state = await readState();
99
- return Object.entries(state?.failedBundles || {})
100
- .sort(([, left], [, right]) => right.failedAt - left.failedAt)
101
- .slice(0, MAX_FAILED_BUNDLES)
102
- .map(([hash]) => hash);
108
+ async function syncVerifiedRevokedHashes(hashes) {
109
+ return (0, bundleDropNative_1.setStartupRecoveryRevokedHashesNative)(hashes);
103
110
  }
104
- async function buildFailedBundleRecord(hash, reason, state) {
105
- const [bundleInfo, previous] = await Promise.all([
106
- (0, bundleInfo_1.readBundleInfo)(),
107
- (0, bundlePointer_1.readPreviousBundlePointer)(),
108
- ]);
109
- const record = {
110
- reason,
111
- failedAt: nowSec(),
112
- crashCount: state.crashCount,
113
- channelName: bundleInfo?.channelName,
114
- runtimeVersion: bundleInfo?.runtimeVersion,
115
- previousHash: previous?.hash,
116
- };
117
- return record;
111
+ async function rollbackStartupBundle(forceEmbedded) {
112
+ return (0, bundleDropNative_1.rollbackStartupBundleNative)(forceEmbedded);
118
113
  }
119
- async function recordFailedBundle(hash, record) {
120
- const state = (await readState()) || {};
121
- const failedBundles = pruneFailedBundles({
122
- ...(state.failedBundles || {}),
123
- [hash]: record,
124
- });
125
- await updateState({ failedBundles });
126
- }
127
- async function evaluateRollbackOnLaunch(policy, cached) {
128
- const current = cached?.currentPointer !== undefined ? cached.currentPointer : await (0, bundlePointer_1.readCurrentBundlePointer)();
129
- const activeHash = current?.hash;
130
- if (!activeHash)
131
- return { shouldRollback: false };
132
- const now = nowSec();
133
- const persistedState = (await readState()) || {};
134
- const state = cached?.rollbackState !== undefined
135
- ? {
136
- ...persistedState,
137
- ...cached.rollbackState,
138
- failedBundles: persistedState.failedBundles ?? cached.rollbackState?.failedBundles,
139
- }
140
- : persistedState;
141
- const next = {
142
- ...state,
143
- activeHash,
144
- lastLaunchAt: now,
114
+ function recoveryRecord(event, context) {
115
+ return {
116
+ reason: event.reason,
117
+ failedAt: event.failedAt,
118
+ crashCount: event.crashCount,
119
+ channelName: context?.channelName,
120
+ runtimeVersion: context?.runtimeVersion,
121
+ previousHash: event.recoveredHash,
145
122
  };
146
- const isCandidate = state.candidateHash === activeHash && state.candidateCommitted !== true;
147
- if (isCandidate) {
148
- const crashCount = (state.crashCount ?? 0) + 1;
149
- next.crashCount = crashCount;
150
- if (policy.maxCrashCount > 0 &&
151
- crashCount >= policy.maxCrashCount) {
152
- await writeState(next);
153
- return { shouldRollback: true, reason: 'crash_loop' };
154
- }
155
- }
156
- await writeState(next);
157
- return { shouldRollback: false };
158
123
  }
159
- async function rollbackToPreviousIfNeeded(policy, cached) {
160
- const decision = await evaluateRollbackOnLaunch(policy, cached);
161
- if (!decision.shouldRollback)
162
- return { rolledBack: false };
163
- const current = cached?.currentPointer !== undefined ? cached.currentPointer : await (0, bundlePointer_1.readCurrentBundlePointer)();
164
- const failedHash = current?.hash;
165
- const state = (await readState()) || {};
166
- if (!failedHash)
167
- return { rolledBack: false };
168
- const failedRecord = await buildFailedBundleRecord(failedHash, decision.reason, state);
169
- await rollbackToPreviousOrNative();
170
- await recordFailedBundle(failedHash, failedRecord);
171
- await (0, reporting_1.reportLocalRollback)(failedHash, failedRecord).catch(() => undefined);
172
- return { rolledBack: true, reason: decision.reason };
173
- }
174
- function getRollbackPolicy() {
175
- return context_1.bundleDropConfig.rollback;
176
- }
177
- async function rollbackToPreviousOrNative(options = {}) {
178
- const [current, previous, state] = await Promise.all([
179
- (0, bundlePointer_1.readCurrentBundlePointer)(),
180
- (0, bundlePointer_1.readPreviousBundlePointer)(),
181
- readState(),
182
- ]);
183
- const previousIsFailed = previous ? !!state?.failedBundles?.[previous.hash] : false;
184
- if (!options.forceNative && previous && previous.hash !== current?.hash && !previousIsFailed) {
185
- await (0, bundlePointer_1.writeCurrentBundlePointer)({ ...previous, updatedAt: new Date().toISOString() });
186
- const metadata = await readBundleMetadata(previous.bundlePath);
187
- await (0, bundleInfo_1.updateBundleInfo)({
188
- hash: previous.hash,
189
- bundleVersion: metadata?.bundleVersion,
190
- version: metadata?.version,
191
- runtimeVersion: metadata?.runtimeVersion,
192
- pendingApply: false,
193
- installedAt: new Date().toISOString(),
194
- lastInstalledReportedHash: previous.hash,
195
- });
196
- await updateState({
197
- activeHash: previous.hash,
198
- candidateHash: previous.hash,
199
- candidateCommitted: true,
200
- crashCount: 0,
201
- lastGoodHash: previous.hash,
202
- });
203
- return { rolledBack: true };
204
- }
205
- // No previous OTA bundle exists; fall back to native bundle by clearing the active pointer.
206
- await (0, bundlePointer_1.deleteCurrentBundlePointer)();
207
- await (0, bundlePointer_1.deletePreviousBundlePointer)();
208
- await (0, bundleInfo_1.updateBundleInfo)({
209
- hash: undefined,
210
- bundleVersion: undefined,
211
- version: undefined,
212
- runtimeVersion: undefined,
213
- pendingApply: false,
214
- installedAt: new Date().toISOString(),
215
- });
216
- await updateState({
217
- activeHash: undefined,
218
- candidateHash: undefined,
219
- candidateCommitted: true,
220
- crashCount: 0,
221
- });
222
- return { rolledBack: true, toNative: true };
223
- }
224
- async function readJsonIfExists(path) {
225
- try {
226
- if (!(await fs_1.default.exists(path)))
227
- return null;
228
- const raw = await fs_1.default.readFile(path, 'utf8');
229
- return JSON.parse(raw);
230
- }
231
- catch {
232
- return null;
233
- }
234
- }
235
- async function readBundleMetadata(bundlePath) {
236
- const dir = bundlePath.substring(0, bundlePath.lastIndexOf('/'));
237
- const manifest = await readJsonIfExists(`${dir}/${bundleManifest_1.BUNDLE_MANIFEST}`);
238
- const metadataFile = context_1.platform === 'android' ? 'metadata-android.json' : 'metadata-ios.json';
239
- const parsed = await readJsonIfExists(`${dir}/${metadataFile}`);
240
- if (!manifest && !parsed) {
124
+ /**
125
+ * Flush native recovery events without making JS part of the recovery decision.
126
+ * Native keeps each event durable until its backend report succeeds and JS
127
+ * acknowledges that exact event id.
128
+ */
129
+ async function reconcileStartupRecovery(cachedState, failedBundleInfo) {
130
+ const state = cachedState === undefined ? await readStartupRecoveryState() : cachedState;
131
+ if (!state)
241
132
  return null;
133
+ const telemetryContexts = await prepareRecoveryTelemetryContexts(state.pendingRecoveryEvents, failedBundleInfo);
134
+ for (const event of state.pendingRecoveryEvents) {
135
+ try {
136
+ const telemetryContext = telemetryContexts.events[event.id];
137
+ await (0, reporting_1.reportLocalRollback)(event.failedHash, recoveryRecord(event, telemetryContext?.failedHash === event.failedHash ? telemetryContext : undefined));
138
+ if (await (0, bundleDropNative_1.acknowledgeStartupRecoveryNative)(event.id)) {
139
+ await removeRecoveryTelemetryContext(event.id);
140
+ }
141
+ }
142
+ catch (error) {
143
+ console.warn(`⚠️ Failed to report BundleDrop startup recovery event ${event.id}:`, error?.toString?.() || error);
144
+ }
242
145
  }
243
- return {
244
- bundleVersion: parsed?.bundleVersion,
245
- version: manifest?.version ?? parsed?.version,
246
- runtimeVersion: manifest?.runtimeVersion ?? parsed?.runtimeVersion,
247
- };
146
+ return state;
248
147
  }
@@ -106,8 +106,9 @@ async function getAvailableChannels() {
106
106
  }
107
107
  }
108
108
  async function readResolveContext(channelName) {
109
- const [currentPtr, nativeBundlePath, userProperties, installId, rejectedHashes] = await Promise.all([
110
- (0, bundlePointer_1.readCurrentBundlePointer)(),
109
+ const selectedHash = (0, bundleDropNative_1.getStartupRecoverySelectedHashNative)();
110
+ const [pointerHash, nativeBundlePath, userProperties, installId, rejectedHashes] = await Promise.all([
111
+ (0, bundlePointer_1.readCurrentBundleHash)(),
111
112
  (0, bundleDropNative_1.getDownloadedBundlePathNative)(),
112
113
  (0, userProperties_1.getCurrentUserProperties)(),
113
114
  (0, installId_1.getOrCreateInstallId)(),
@@ -117,7 +118,12 @@ async function readResolveContext(channelName) {
117
118
  .catch(() => false);
118
119
  return {
119
120
  channelName,
120
- currentHash: nativeBundlePath && currentPtr?.hash ? currentPtr.hash : null,
121
+ // Only adapters that predate startupRecoverySelectedHash infer the running
122
+ // identity from passive eligibility. New adapters distinguish embedded
123
+ // selection from an OTA that became ineligible after this runtime started.
124
+ currentHash: selectedHash === undefined
125
+ ? nativeBundlePath && pointerHash ? pointerHash : null
126
+ : selectedHash,
121
127
  rejectedHashes,
122
128
  installId,
123
129
  patchAlgorithms: (0, patchOperations_1.advertisedPatchAlgorithms)(supportsXdelta),
@@ -23,5 +23,6 @@ export declare const getUpdateState: (cached?: {
23
23
  export declare const reconcileAppliedBundleOnLaunch: (cached?: {
24
24
  bundleInfo?: BundleInfo | null;
25
25
  bundlePath?: string | null;
26
- }) => Promise<void>;
26
+ currentHash?: string | null;
27
+ }) => Promise<BundleInfo | null>;
27
28
  export declare const applyUpdate: (onStatusUpdate?: (status: string) => void, onBeforeRestart?: () => void) => Promise<ApplyUpdateResult>;