@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
@@ -1,8 +1,14 @@
1
1
  "use strict";
2
+ var __importDefault = (this && this.__importDefault) || function (mod) {
3
+ return (mod && mod.__esModule) ? mod : { "default": mod };
4
+ };
2
5
  Object.defineProperty(exports, "__esModule", { value: true });
3
6
  exports.applyUpdate = exports.reconcileAppliedBundleOnLaunch = exports.getUpdateState = void 0;
4
7
  const bundleDropNative_1 = require("../native/bundleDropNative");
5
8
  const bundleInfo_1 = require("../bundleInfo");
9
+ const fs_1 = __importDefault(require("../native/fs"));
10
+ const context_1 = require("../context");
11
+ const bundleVerification_1 = require("../install/bundleVerification");
6
12
  const reporting_1 = require("./reporting");
7
13
  const errors_1 = require("../errors");
8
14
  const rollbackState_1 = require("./rollbackState");
@@ -17,20 +23,67 @@ const getUpdateState = async (cached) => {
17
23
  };
18
24
  };
19
25
  exports.getUpdateState = getUpdateState;
26
+ async function readRecoveredBundleInfo(bundlePath, hash, previousInfo) {
27
+ const bundleDir = bundlePath.slice(0, bundlePath.lastIndexOf('/'));
28
+ const manifest = await (0, bundleVerification_1.verifyBundleDir)(bundleDir, hash, context_1.platform);
29
+ const metadataPath = `${bundleDir}/${context_1.platform === 'android' ? 'metadata-android.json' : 'metadata-ios.json'}`;
30
+ const metadata = await fs_1.default.exists(metadataPath)
31
+ ? await (0, bundleVerification_1.readJsonFile)(metadataPath)
32
+ : null;
33
+ const bundleVersion = typeof metadata?.bundleVersion === 'number'
34
+ ? metadata.bundleVersion
35
+ : undefined;
36
+ const metadataVersion = typeof metadata?.version === 'string' ? metadata.version : undefined;
37
+ const metadataRuntimeVersion = typeof metadata?.runtimeVersion === 'string'
38
+ ? metadata.runtimeVersion
39
+ : undefined;
40
+ const alreadyReported = previousInfo?.installedReportedHashes?.includes(hash) === true;
41
+ return {
42
+ hash,
43
+ bundleVersion,
44
+ version: manifest?.version ?? metadataVersion,
45
+ runtimeVersion: manifest?.runtimeVersion ?? metadataRuntimeVersion,
46
+ platform: context_1.platform,
47
+ installedAt: new Date().toISOString(),
48
+ pendingApply: false,
49
+ lastInstalledReportedHash: alreadyReported ? hash : undefined,
50
+ installedReportedHashes: previousInfo?.installedReportedHashes,
51
+ };
52
+ }
20
53
  const reconcileAppliedBundleOnLaunch = async (cached) => {
21
- const state = await (0, exports.getUpdateState)(cached);
22
- if (!state.hasBundle)
23
- return;
54
+ const bundlePath = cached?.bundlePath !== undefined
55
+ ? cached.bundlePath
56
+ : await (0, bundleDropNative_1.getDownloadedBundlePathNative)();
57
+ const state = await (0, exports.getUpdateState)({ ...cached, bundlePath });
58
+ if (!state.hasBundle) {
59
+ if (state.info) {
60
+ await (0, bundleInfo_1.deleteBundleInfo)();
61
+ }
62
+ return null;
63
+ }
64
+ const currentHash = cached?.currentHash;
65
+ if (currentHash && state.info?.hash !== currentHash) {
66
+ const recoveredInfo = await readRecoveredBundleInfo(bundlePath, currentHash, state.info);
67
+ await (0, bundleInfo_1.writeBundleInfoDurably)(recoveredInfo);
68
+ (0, reporting_1.reportInstalledIfReady)({ hasBundle: true, info: recoveredInfo }).catch(() => { });
69
+ return recoveredInfo;
70
+ }
24
71
  if (!state.info?.pendingApply) {
25
72
  (0, reporting_1.reportInstalledIfReady)(state).catch(() => { });
26
- return;
73
+ return state.info || null;
27
74
  }
28
- await (0, bundleInfo_1.updateBundleInfo)({ pendingApply: false, installedAt: new Date().toISOString() });
75
+ const appliedInfo = {
76
+ ...state.info,
77
+ pendingApply: false,
78
+ installedAt: new Date().toISOString(),
79
+ };
80
+ await (0, bundleInfo_1.updateBundleInfo)(appliedInfo);
29
81
  // Fire-and-forget: don't block the startup path for server reporting
30
82
  (0, reporting_1.reportInstalledIfReady)({
31
83
  hasBundle: true,
32
- info: state.info ? { ...state.info, pendingApply: false } : state.info,
84
+ info: appliedInfo,
33
85
  }).catch(() => { });
86
+ return appliedInfo;
34
87
  };
35
88
  exports.reconcileAppliedBundleOnLaunch = reconcileAppliedBundleOnLaunch;
36
89
  const applyUpdate = async (onStatusUpdate, onBeforeRestart) => {
package/lib/metro.d.ts CHANGED
@@ -12,7 +12,7 @@ export type WithBundleDropOptions = {
12
12
  export type WithBundleDropExpoOptions = WithBundleDropOptions;
13
13
  /**
14
14
  * Preserves a bare React Native Metro config and resolves Bundle Drop through
15
- * the project-owned, package-validated generated bootstrap.
15
+ * the project-owned, package-validated runtime-delivery lockfile.
16
16
  */
17
17
  export declare function withBundleDrop<T extends BundleDropMetroConfig>(config: T, options?: WithBundleDropOptions): T;
18
18
  export declare const withBundleDropBare: typeof withBundleDrop;
package/lib/metro.js CHANGED
@@ -24,7 +24,7 @@ const loadBaseConfig = (projectRoot) => {
24
24
  return config;
25
25
  };
26
26
  const resolveRuntimeDelivery = (projectRoot, baseConfig) => {
27
- const generated = (0, bootstrapConfig_1.readGeneratedRuntimeDeliveryBootstrap)({
27
+ const bootstrap = (0, bootstrapConfig_1.readRuntimeDeliveryBootstrap)({
28
28
  projectRoot,
29
29
  expectedIdentity: {
30
30
  serverUrl: baseConfig.serverUrl,
@@ -32,7 +32,7 @@ const resolveRuntimeDelivery = (projectRoot, baseConfig) => {
32
32
  projectSlug: baseConfig.project.slug,
33
33
  },
34
34
  });
35
- return generated?.runtimeDelivery;
35
+ return bootstrap?.runtimeDelivery;
36
36
  };
37
37
  const writeGeneratedRuntimeConfig = (params) => {
38
38
  const generatedDirectory = path_1.default.join(params.projectRoot, '.bundle-drop', 'generated');
@@ -46,6 +46,7 @@ const writeGeneratedRuntimeConfig = (params) => {
46
46
  generatedFields.push(` runtimeDelivery: ${JSON.stringify(params.runtimeDelivery)},`);
47
47
  }
48
48
  const content = [
49
+ '/* eslint-disable */',
49
50
  "'use strict';",
50
51
  '',
51
52
  "const baseConfig = require('../../bundle.drop.config.js');",
@@ -72,7 +73,7 @@ const mergeMetroAlias = (config, generatedConfigPath) => ({
72
73
  });
73
74
  /**
74
75
  * Preserves a bare React Native Metro config and resolves Bundle Drop through
75
- * the project-owned, package-validated generated bootstrap.
76
+ * the project-owned, package-validated runtime-delivery lockfile.
76
77
  */
77
78
  function withBundleDrop(config, options = {}) {
78
79
  const projectRoot = path_1.default.resolve(options.projectRoot || process.cwd());
@@ -1,5 +1,67 @@
1
+ declare const STARTUP_RECOVERY_PROTOCOL_VERSION = 1;
2
+ export type StartupRecoveryHealthCheckMode = 'auto' | 'manual';
3
+ export type StartupRecoveryAttempt = {
4
+ hash: string;
5
+ attemptId: string;
6
+ };
7
+ export type StartupRecoverySnapshotAttempt = StartupRecoveryAttempt & {
8
+ status: 'launching';
9
+ unacknowledgedLaunchCount: number;
10
+ };
11
+ export type StartupRecoveryEvent = {
12
+ id: string;
13
+ failedHash: string;
14
+ recoveryTarget: 'previous' | 'embedded';
15
+ recoveredHash?: string;
16
+ crashCount: number;
17
+ reason: 'crash_loop';
18
+ failedAt: number;
19
+ };
20
+ export type StartupRecoveryState = {
21
+ protocolVersion: typeof STARTUP_RECOVERY_PROTOCOL_VERSION;
22
+ revision: number;
23
+ phase: 'idle' | 'armed' | 'launching' | 'stable' | 'recovered';
24
+ candidateHash?: string;
25
+ stableHash?: string;
26
+ activeAttempt?: StartupRecoverySnapshotAttempt;
27
+ policy?: {
28
+ maxCrashCount: number;
29
+ healthCheckMode: StartupRecoveryHealthCheckMode;
30
+ healthyAfterSec: number;
31
+ };
32
+ quarantinedHashes: string[];
33
+ pendingRecoveryEvents: StartupRecoveryEvent[];
34
+ };
35
+ export type StartupCandidateActivation = {
36
+ hash: string;
37
+ bundlePath: string;
38
+ };
39
+ export type StartupRollbackResult = {
40
+ rolledBack: boolean;
41
+ toEmbedded: boolean;
42
+ hash?: string;
43
+ };
1
44
  export declare function isBundleDropNativeAvailable(): boolean;
2
45
  export declare function isExpoOtaStartupEnabledNative(): boolean;
46
+ export declare function isStartupRecoveryAvailableNative(): boolean;
47
+ export declare function warnIfStartupRecoveryUnavailableNative(): void;
48
+ export declare function getStartupRecoveryAttemptNative(): StartupRecoveryAttempt | null;
49
+ /**
50
+ * Hash selected for this exact React runtime. `undefined` means the installed
51
+ * native adapter predates this constant; `null` means native selected embedded.
52
+ */
53
+ export declare function getStartupRecoverySelectedHashNative(): string | null | undefined;
54
+ export declare function activateStartupCandidateNative(hash: string, policy: {
55
+ maxCrashCount: number;
56
+ healthCheckMode: StartupRecoveryHealthCheckMode;
57
+ healthyAfterSec: number;
58
+ }): Promise<StartupCandidateActivation | null>;
59
+ export declare function markStartupHealthyNative(attempt: StartupRecoveryAttempt): Promise<boolean>;
60
+ export declare function getStartupRecoveryStateNative(): Promise<StartupRecoveryState | null>;
61
+ export declare function setStartupRecoveryRevokedHashesNative(hashes: string[]): Promise<boolean>;
62
+ export declare function acknowledgeStartupRecoveryNative(eventId: string): Promise<boolean>;
63
+ export declare function rollbackStartupBundleNative(forceEmbedded: boolean): Promise<StartupRollbackResult | null>;
3
64
  export declare function getDownloadedBundlePathNative(): Promise<string | null>;
4
65
  export declare function restartReactNativeNative(): void;
5
66
  export declare function setOtaEnabledNative(enabled: boolean): Promise<void>;
67
+ export {};
@@ -2,11 +2,209 @@
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
3
  exports.isBundleDropNativeAvailable = isBundleDropNativeAvailable;
4
4
  exports.isExpoOtaStartupEnabledNative = isExpoOtaStartupEnabledNative;
5
+ exports.isStartupRecoveryAvailableNative = isStartupRecoveryAvailableNative;
6
+ exports.warnIfStartupRecoveryUnavailableNative = warnIfStartupRecoveryUnavailableNative;
7
+ exports.getStartupRecoveryAttemptNative = getStartupRecoveryAttemptNative;
8
+ exports.getStartupRecoverySelectedHashNative = getStartupRecoverySelectedHashNative;
9
+ exports.activateStartupCandidateNative = activateStartupCandidateNative;
10
+ exports.markStartupHealthyNative = markStartupHealthyNative;
11
+ exports.getStartupRecoveryStateNative = getStartupRecoveryStateNative;
12
+ exports.setStartupRecoveryRevokedHashesNative = setStartupRecoveryRevokedHashesNative;
13
+ exports.acknowledgeStartupRecoveryNative = acknowledgeStartupRecoveryNative;
14
+ exports.rollbackStartupBundleNative = rollbackStartupBundleNative;
5
15
  exports.getDownloadedBundlePathNative = getDownloadedBundlePathNative;
6
16
  exports.restartReactNativeNative = restartReactNativeNative;
7
17
  exports.setOtaEnabledNative = setOtaEnabledNative;
8
18
  const react_native_1 = require("react-native");
9
- const { BundleDrop, BundleDropExpoIdentity } = react_native_1.NativeModules;
19
+ const STARTUP_RECOVERY_PROTOCOL_VERSION = 1;
20
+ const SHA256_HASH_PATTERN = /^[a-f0-9]{64}$/;
21
+ const STARTUP_RECOVERY_CAPABILITY_WARNING = '[BundleDrop] Automatic startup recovery requires a newer BundleDrop native build. ' +
22
+ 'Recovery is disabled for this binary; rebuild the app before shipping another OTA update.';
23
+ const BundleDrop = react_native_1.NativeModules.BundleDrop;
24
+ const BundleDropExpoIdentity = react_native_1.NativeModules.BundleDropExpoIdentity;
25
+ // These constants describe the bundle selected by native code for this specific
26
+ // React runtime. Capture them once so later native state changes cannot rewrite
27
+ // the running identity or the attempt acknowledged by reportHealthy().
28
+ const startupRecoverySelectedHash = readStartupRecoverySelectedHash(BundleDrop);
29
+ const startupRecoveryAttempt = readStartupRecoveryAttempt(BundleDrop);
30
+ let hasWarnedAboutStartupRecoveryCapability = false;
31
+ function isRecord(value) {
32
+ return !!value && typeof value === 'object' && !Array.isArray(value);
33
+ }
34
+ function nonEmptyString(value) {
35
+ return typeof value === 'string' && value.trim() ? value : null;
36
+ }
37
+ function canonicalHash(value) {
38
+ return typeof value === 'string' && SHA256_HASH_PATTERN.test(value) ? value : null;
39
+ }
40
+ function readStartupRecoverySelectedHash(nativeModule) {
41
+ if (!nativeModule || !Object.prototype.hasOwnProperty.call(nativeModule, 'startupRecoverySelectedHash')) {
42
+ return undefined;
43
+ }
44
+ if (nativeModule.startupRecoverySelectedHash == null)
45
+ return null;
46
+ return canonicalHash(nativeModule.startupRecoverySelectedHash);
47
+ }
48
+ function nonNegativeInteger(value) {
49
+ return Number.isSafeInteger(value) && value >= 0 ? value : null;
50
+ }
51
+ function readStartupRecoveryAttempt(nativeModule) {
52
+ const hash = canonicalHash(nativeModule?.startupRecoveryAttemptHash);
53
+ const attemptId = nonEmptyString(nativeModule?.startupRecoveryAttemptId);
54
+ return hash && attemptId ? { hash, attemptId } : null;
55
+ }
56
+ function hasStartupRecoveryMethods(nativeModule) {
57
+ return nativeModule?.startupRecoveryProtocolVersion === STARTUP_RECOVERY_PROTOCOL_VERSION &&
58
+ typeof nativeModule.activateStartupCandidate === 'function' &&
59
+ typeof nativeModule.markStartupHealthy === 'function' &&
60
+ typeof nativeModule.getStartupRecoveryState === 'function' &&
61
+ typeof nativeModule.setStartupRecoveryRevokedHashes === 'function' &&
62
+ typeof nativeModule.acknowledgeStartupRecovery === 'function' &&
63
+ typeof nativeModule.rollbackStartupBundle === 'function';
64
+ }
65
+ function warnAboutMissingStartupRecovery() {
66
+ if (hasWarnedAboutStartupRecoveryCapability)
67
+ return;
68
+ hasWarnedAboutStartupRecoveryCapability = true;
69
+ console.warn(STARTUP_RECOVERY_CAPABILITY_WARNING);
70
+ }
71
+ function requireStartupRecoveryCapability() {
72
+ if (!hasStartupRecoveryMethods(BundleDrop)) {
73
+ warnAboutMissingStartupRecovery();
74
+ return null;
75
+ }
76
+ return BundleDrop;
77
+ }
78
+ function normalizeRecoveryEvent(value) {
79
+ if (!isRecord(value))
80
+ return null;
81
+ const id = nonEmptyString(value.id);
82
+ const failedHash = canonicalHash(value.failedHash);
83
+ const hasRecoveredHash = value.recoveredHash != null;
84
+ const recoveredHash = hasRecoveredHash ? canonicalHash(value.recoveredHash) : undefined;
85
+ const crashCount = nonNegativeInteger(value.crashCount);
86
+ const failedAt = nonNegativeInteger(value.failedAt);
87
+ const recoveryTarget = value.recoveryTarget;
88
+ if (!id ||
89
+ !failedHash ||
90
+ (hasRecoveredHash && !recoveredHash) ||
91
+ crashCount === null ||
92
+ failedAt === null ||
93
+ value.reason !== 'crash_loop' ||
94
+ (recoveryTarget !== 'previous' && recoveryTarget !== 'embedded')) {
95
+ return null;
96
+ }
97
+ if (recoveryTarget === 'previous' && !recoveredHash)
98
+ return null;
99
+ return {
100
+ id,
101
+ failedHash,
102
+ recoveryTarget,
103
+ ...(recoveredHash ? { recoveredHash } : {}),
104
+ crashCount,
105
+ reason: 'crash_loop',
106
+ failedAt,
107
+ };
108
+ }
109
+ function normalizeStartupRecoveryState(value) {
110
+ if (!isRecord(value) || value.protocolVersion !== STARTUP_RECOVERY_PROTOCOL_VERSION) {
111
+ return null;
112
+ }
113
+ const revision = nonNegativeInteger(value.revision);
114
+ if (revision === null)
115
+ return null;
116
+ const phase = value.phase;
117
+ if (!['idle', 'armed', 'launching', 'stable', 'recovered'].includes(String(phase))) {
118
+ return null;
119
+ }
120
+ const hasCandidateHash = value.candidateHash != null;
121
+ const candidateHash = hasCandidateHash ? canonicalHash(value.candidateHash) : undefined;
122
+ const hasStableHash = value.stableHash != null;
123
+ const stableHash = hasStableHash ? canonicalHash(value.stableHash) : undefined;
124
+ if ((hasCandidateHash && !candidateHash) || (hasStableHash && !stableHash))
125
+ return null;
126
+ const baseAttempt = value.activeAttempt == null
127
+ ? null
128
+ : readStartupRecoveryAttempt({
129
+ startupRecoveryAttemptHash: isRecord(value.activeAttempt)
130
+ ? value.activeAttempt.hash
131
+ : undefined,
132
+ startupRecoveryAttemptId: isRecord(value.activeAttempt)
133
+ ? value.activeAttempt.attemptId
134
+ : undefined,
135
+ });
136
+ const activeAttemptCount = isRecord(value.activeAttempt)
137
+ ? nonNegativeInteger(value.activeAttempt.unacknowledgedLaunchCount)
138
+ : null;
139
+ const activeAttempt = baseAttempt && isRecord(value.activeAttempt) &&
140
+ value.activeAttempt.status === 'launching' && activeAttemptCount !== null
141
+ ? {
142
+ ...baseAttempt,
143
+ status: 'launching',
144
+ unacknowledgedLaunchCount: activeAttemptCount,
145
+ }
146
+ : undefined;
147
+ if (value.activeAttempt != null && !activeAttempt)
148
+ return null;
149
+ let policy;
150
+ if (value.policy != null) {
151
+ if (!isRecord(value.policy))
152
+ return null;
153
+ const maxCrashCount = nonNegativeInteger(value.policy.maxCrashCount);
154
+ const healthyAfterSec = typeof value.policy.healthyAfterSec === 'number' &&
155
+ Number.isFinite(value.policy.healthyAfterSec) && value.policy.healthyAfterSec >= 0
156
+ ? value.policy.healthyAfterSec
157
+ : null;
158
+ const healthCheckMode = value.policy.healthCheckMode;
159
+ if (maxCrashCount === null ||
160
+ healthyAfterSec === null ||
161
+ (healthCheckMode !== 'auto' && healthCheckMode !== 'manual')) {
162
+ return null;
163
+ }
164
+ policy = { maxCrashCount, healthCheckMode, healthyAfterSec };
165
+ }
166
+ const quarantinedHashes = Array.isArray(value.quarantinedHashes)
167
+ ? Array.from(new Set(value.quarantinedHashes.map(canonicalHash).filter(Boolean)))
168
+ : null;
169
+ const pendingRecoveryEvents = Array.isArray(value.pendingRecoveryEvents)
170
+ ? value.pendingRecoveryEvents.map(normalizeRecoveryEvent).filter(Boolean)
171
+ : null;
172
+ if (!quarantinedHashes || !pendingRecoveryEvents)
173
+ return null;
174
+ const uniqueEvents = Array.from(new Map(pendingRecoveryEvents.map(event => [event.id, event])).values());
175
+ return {
176
+ protocolVersion: STARTUP_RECOVERY_PROTOCOL_VERSION,
177
+ revision,
178
+ phase: phase,
179
+ ...(candidateHash ? { candidateHash } : {}),
180
+ ...(stableHash ? { stableHash } : {}),
181
+ ...(activeAttempt ? { activeAttempt } : {}),
182
+ ...(policy ? { policy } : {}),
183
+ quarantinedHashes,
184
+ pendingRecoveryEvents: uniqueEvents,
185
+ };
186
+ }
187
+ function normalizeCandidateActivation(value) {
188
+ if (!isRecord(value))
189
+ return null;
190
+ const hash = canonicalHash(value.hash);
191
+ const bundlePath = nonEmptyString(value.bundlePath);
192
+ return hash && bundlePath ? { hash, bundlePath } : null;
193
+ }
194
+ function normalizeRollbackResult(value) {
195
+ if (!isRecord(value) || typeof value.rolledBack !== 'boolean' || typeof value.toEmbedded !== 'boolean') {
196
+ return null;
197
+ }
198
+ const hasHash = value.hash != null;
199
+ const hash = hasHash ? canonicalHash(value.hash) : undefined;
200
+ if (hasHash && !hash)
201
+ return null;
202
+ return {
203
+ rolledBack: value.rolledBack,
204
+ toEmbedded: value.toEmbedded,
205
+ ...(hash ? { hash } : {}),
206
+ };
207
+ }
10
208
  function isBundleDropNativeAvailable() {
11
209
  return Boolean(BundleDrop);
12
210
  }
@@ -14,6 +212,73 @@ function isExpoOtaStartupEnabledNative() {
14
212
  const nativeValue = BundleDropExpoIdentity?.otaStartupEnabled;
15
213
  return nativeValue === true || nativeValue === 1;
16
214
  }
215
+ function isStartupRecoveryAvailableNative() {
216
+ return hasStartupRecoveryMethods(BundleDrop);
217
+ }
218
+ function warnIfStartupRecoveryUnavailableNative() {
219
+ if (!isStartupRecoveryAvailableNative()) {
220
+ warnAboutMissingStartupRecovery();
221
+ }
222
+ }
223
+ function getStartupRecoveryAttemptNative() {
224
+ return startupRecoveryAttempt ? { ...startupRecoveryAttempt } : null;
225
+ }
226
+ /**
227
+ * Hash selected for this exact React runtime. `undefined` means the installed
228
+ * native adapter predates this constant; `null` means native selected embedded.
229
+ */
230
+ function getStartupRecoverySelectedHashNative() {
231
+ return startupRecoverySelectedHash;
232
+ }
233
+ async function activateStartupCandidateNative(hash, policy) {
234
+ if (!Number.isSafeInteger(policy.maxCrashCount) ||
235
+ policy.maxCrashCount < 0 ||
236
+ policy.maxCrashCount > 2147483647) {
237
+ throw new Error('maxCrashCount must be a non-negative 32-bit integer');
238
+ }
239
+ if (!Number.isFinite(policy.healthyAfterSec) || policy.healthyAfterSec < 0) {
240
+ throw new Error('healthyAfterSec must be a finite non-negative number');
241
+ }
242
+ const nativeModule = requireStartupRecoveryCapability();
243
+ if (!nativeModule)
244
+ return null;
245
+ const result = await nativeModule.activateStartupCandidate(hash, policy.maxCrashCount, policy.healthCheckMode, policy.healthyAfterSec);
246
+ return normalizeCandidateActivation(result);
247
+ }
248
+ async function markStartupHealthyNative(attempt) {
249
+ const nativeModule = requireStartupRecoveryCapability();
250
+ if (!nativeModule)
251
+ return false;
252
+ return nativeModule.markStartupHealthy(attempt.hash, attempt.attemptId);
253
+ }
254
+ async function getStartupRecoveryStateNative() {
255
+ const nativeModule = requireStartupRecoveryCapability();
256
+ if (!nativeModule)
257
+ return null;
258
+ const state = normalizeStartupRecoveryState(await nativeModule.getStartupRecoveryState());
259
+ if (!state) {
260
+ console.warn('[BundleDrop] Ignoring malformed native startup recovery state.');
261
+ }
262
+ return state;
263
+ }
264
+ async function setStartupRecoveryRevokedHashesNative(hashes) {
265
+ const nativeModule = requireStartupRecoveryCapability();
266
+ if (!nativeModule)
267
+ return false;
268
+ return nativeModule.setStartupRecoveryRevokedHashes(Array.from(new Set(hashes)));
269
+ }
270
+ async function acknowledgeStartupRecoveryNative(eventId) {
271
+ const nativeModule = requireStartupRecoveryCapability();
272
+ if (!nativeModule)
273
+ return false;
274
+ return nativeModule.acknowledgeStartupRecovery(eventId);
275
+ }
276
+ async function rollbackStartupBundleNative(forceEmbedded) {
277
+ const nativeModule = requireStartupRecoveryCapability();
278
+ if (!nativeModule)
279
+ return null;
280
+ return normalizeRollbackResult(await nativeModule.rollbackStartupBundle(forceEmbedded));
281
+ }
17
282
  async function getDownloadedBundlePathNative() {
18
283
  if (!BundleDrop?.getDownloadedBundlePath) {
19
284
  console.warn('BundleDrop.getDownloadedBundlePath is not defined');
@@ -35,8 +35,8 @@ async function installFromPatchSet(params) {
35
35
  const { patchesUrl, patchSetHash, manifestUrl, missingAssetsUrl, missingAssetsHash, baseHash, targetHash, algorithm, statusCb, platform = context_1.platform, expectedManifestHash, expectedJsBundleHash, } = params;
36
36
  (0, bundleInstallShared_1.assertCanonicalBundleHash)(baseHash, 'base hash');
37
37
  (0, bundleInstallShared_1.assertCanonicalBundleHash)(targetHash, 'target hash');
38
- const currentPointer = await (0, bundlePointer_1.readCurrentBundlePointer)();
39
- if (currentPointer?.hash !== baseHash) {
38
+ const currentHash = await (0, bundlePointer_1.readCurrentBundleHash)();
39
+ if (currentHash !== baseHash) {
40
40
  throw new errors_1.InstallPhaseError('install', new Error('Patch base hash does not match current bundle'));
41
41
  }
42
42
  const baseDir = `${context_1.BUNDLE_DROP_ROOT}/bundles/${baseHash}`;
@@ -50,7 +50,6 @@ const MANAGED_DIRECT_INSTALL_NOT_AUTHORIZED_STATUS = '⚠️ Direct URL installs
50
50
  let updateFlowActive = false;
51
51
  let startupPromise = null;
52
52
  let localStartupPromise = null;
53
- let healthTimer = null;
54
53
  let runtimeRestartRequested = false;
55
54
  let activeBundleInfoForObservability = null;
56
55
  let nativeOtaEnabledPromise = Promise.resolve();
@@ -168,58 +167,23 @@ function getApplyStatus(result) {
168
167
  ? '⚠️ Update previously failed on this device'
169
168
  : 'ℹ️ Bundle already applied';
170
169
  }
171
- function clearHealthTimer() {
172
- if (!healthTimer)
173
- return;
174
- clearTimeout(healthTimer);
175
- healthTimer = null;
176
- }
177
170
  function requestRuntimeRestart() {
178
171
  runtimeRestartRequested = true;
179
172
  (0, bundleDropNative_1.restartReactNativeNative)();
180
173
  }
181
174
  async function applyAuthoritativeRollback(reason) {
182
- if (isCurrentRevokedRollback(reason)) {
183
- await (0, rollbackState_1.rollbackToPreviousOrNative)({ forceNative: true });
184
- }
185
- else {
186
- await (0, rollbackState_1.rollbackToPreviousOrNative)();
175
+ const result = await (0, rollbackState_1.rollbackStartupBundle)(isCurrentRevokedRollback(reason));
176
+ if (result?.rolledBack) {
177
+ requestRuntimeRestart();
187
178
  }
188
- requestRuntimeRestart();
189
179
  }
190
- async function markActiveCandidateHealthy(expectedHash) {
191
- if (runtimeRestartRequested) {
192
- return false;
193
- }
194
- const state = await (0, updateState_1.getUpdateState)();
195
- if (runtimeRestartRequested) {
196
- return false;
197
- }
198
- if (state.pendingApply) {
199
- return false;
200
- }
201
- const markedHealthy = await (0, rollbackState_1.reportActiveBundleHealthy)(undefined, expectedHash);
180
+ async function markActiveCandidateHealthy() {
181
+ const markedHealthy = await (0, rollbackState_1.reportActiveBundleHealthy)();
202
182
  if (markedHealthy) {
203
183
  await refreshState();
204
184
  }
205
185
  return markedHealthy;
206
186
  }
207
- function scheduleCandidateHealthMark(currentPointer, rollbackState) {
208
- clearHealthTimer();
209
- const hash = currentPointer?.hash;
210
- const rollbackPolicy = (0, rollbackState_1.getRollbackPolicy)();
211
- if (!hash || rollbackPolicy.healthCheckMode === 'manual')
212
- return;
213
- if (rollbackState?.candidateHash !== hash || rollbackState.candidateCommitted === true)
214
- return;
215
- const delayMs = Math.max(0, rollbackPolicy.healthyAfterSec || 0) * 1000;
216
- healthTimer = setTimeout(() => {
217
- healthTimer = null;
218
- markActiveCandidateHealthy(hash).catch(error => {
219
- console.warn('⚠️ Failed to mark BundleDrop candidate healthy:', error);
220
- });
221
- }, delayMs);
222
- }
223
187
  async function refreshState(cached) {
224
188
  const state = await (0, updateState_1.getUpdateState)(cached);
225
189
  patchSnapshot({
@@ -257,21 +221,27 @@ async function waitForLocalStartupIfNeeded() {
257
221
  }
258
222
  }
259
223
  async function runLocalStartupFlow() {
260
- const [bundleInfo, bundlePath, currentPointer, rollbackState] = await Promise.all([
224
+ const [bundleInfo, bundlePath, currentHash, recoveryState] = await Promise.all([
261
225
  (0, bundleInfo_1.readBundleInfo)(),
262
226
  (0, bundleDropNative_1.getDownloadedBundlePathNative)(),
263
- (0, bundlePointer_1.readCurrentBundlePointer)(),
264
- (0, rollbackState_1.readRollbackState)(),
227
+ (0, bundlePointer_1.readCurrentBundleHash)(),
228
+ (0, rollbackState_1.readStartupRecoveryState)(),
265
229
  ]);
266
- await (0, updateState_1.reconcileAppliedBundleOnLaunch)({ bundleInfo, bundlePath });
267
- await refreshState({ bundleInfo, bundlePath });
268
- const state = await (0, updateState_1.getUpdateState)({ bundlePath });
269
- activeBundleInfoForObservability = state.hasBundle ? state.info || null : null;
270
- return {
230
+ void (0, rollbackState_1.reconcileStartupRecovery)(recoveryState, bundleInfo).catch(error => {
231
+ console.warn('⚠️ Failed to reconcile BundleDrop startup recovery telemetry:', error);
232
+ });
233
+ const reconciledBundleInfo = await (0, updateState_1.reconcileAppliedBundleOnLaunch)({
234
+ bundleInfo,
271
235
  bundlePath,
272
- currentPointer,
273
- rollbackState,
274
- };
236
+ currentHash,
237
+ });
238
+ await refreshState({ bundleInfo: reconciledBundleInfo, bundlePath });
239
+ const state = await (0, updateState_1.getUpdateState)({
240
+ bundleInfo: reconciledBundleInfo,
241
+ bundlePath,
242
+ });
243
+ activeBundleInfoForObservability = state.hasBundle ? state.info || null : null;
244
+ return { bundlePath };
275
245
  }
276
246
  async function runStartupFlow() {
277
247
  const runtime = (0, initState_1.assertBundleDropInitialized)();
@@ -281,19 +251,7 @@ async function runStartupFlow() {
281
251
  await nativeOtaEnabledPromise;
282
252
  return runLocalStartupFlow();
283
253
  })();
284
- const { bundlePath, currentPointer, rollbackState } = await localStartupPromise;
285
- const rollbackPolicy = (0, rollbackState_1.getRollbackPolicy)();
286
- const rollbackResult = await (0, rollbackState_1.rollbackToPreviousIfNeeded)(rollbackPolicy, {
287
- currentPointer,
288
- rollbackState,
289
- });
290
- if (rollbackResult.rolledBack) {
291
- clearHealthTimer();
292
- emitStatus('↩️ Rolled back to previous bundle');
293
- requestRuntimeRestart();
294
- return;
295
- }
296
- scheduleCandidateHealthMark(currentPointer, await (0, rollbackState_1.readRollbackState)());
254
+ const { bundlePath } = await localStartupPromise;
297
255
  const pendingState = await refreshState({ bundlePath });
298
256
  if (pendingState.pendingApply) {
299
257
  if (runtime.policy === 'immediate') {
@@ -408,6 +366,9 @@ function initBundleDrop(options) {
408
366
  if (!alreadyInitialized) {
409
367
  runtimeRestartRequested = false;
410
368
  activeBundleInfoForObservability = null;
369
+ if (config.enabled) {
370
+ (0, bundleDropNative_1.warnIfStartupRecoveryUnavailableNative)();
371
+ }
411
372
  }
412
373
  // Persist for the next cold start and for native path reads in this process.
413
374
  nativeOtaEnabledPromise = (0, bundleDropNative_1.setOtaEnabledNative)(config.enabled);
@@ -528,11 +489,9 @@ async function reportHealthy() {
528
489
  if (!runtime) {
529
490
  return;
530
491
  }
531
- await waitForStartupIfNeeded();
532
- if (runtimeRestartRequested || updateFlowActive) {
492
+ if (runtimeRestartRequested) {
533
493
  return;
534
494
  }
535
- clearHealthTimer();
536
495
  await markActiveCandidateHealthy();
537
496
  }
538
497
  /**
@@ -695,9 +654,9 @@ async function getObservabilityContext() {
695
654
  }
696
655
  return {
697
656
  source: 'ota',
698
- dist: info.hash ?? 'embedded',
657
+ dist: info.hash,
699
658
  tags: {
700
- bundle_drop_hash: info.hash ?? null,
659
+ bundle_drop_hash: info.hash,
701
660
  bundle_drop_channel: info.channelName ?? null,
702
661
  bundle_drop_version: info.bundleVersion != null ? `${info.bundleVersion}` : null,
703
662
  bundle_drop_runtime_version: info.runtimeVersion ?? null,
@@ -778,7 +737,6 @@ async function installBundle(hash, downloadUrl, bundleVersion, version, runtimeV
778
737
  });
779
738
  }
780
739
  function resetBundleDropRuntimeServiceForTests() {
781
- clearHealthTimer();
782
740
  updateFlowActive = false;
783
741
  startupPromise = null;
784
742
  localStartupPromise = null;