@gfean/react-native-bundle-drop 0.5.1 → 0.7.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 (127) hide show
  1. package/BundleDrop.podspec +96 -0
  2. package/README.md +194 -5
  3. package/android/build.gradle +66 -0
  4. package/android/src/main/java/com/bundledrop/BundleDropBoundedDownloader.kt +86 -0
  5. package/android/src/main/java/com/bundledrop/BundleDropModule.kt +206 -13
  6. package/android/src/main/java/com/bundledrop/BundleDropNativePaths.kt +43 -13
  7. package/android/src/main/java/com/bundledrop/BundleDropOtaResolver.kt +35 -0
  8. package/android/src/main/java/com/bundledrop/BundleDropRuntimeCrypto.kt +81 -0
  9. package/android/src/main/java/com/bundledrop/BundleDropStartupRecovery.kt +1117 -0
  10. package/ios/BundleDropBridge.m +45 -0
  11. package/ios/BundleDropLocator.swift +66 -4
  12. package/ios/BundleDropModule.swift +181 -3
  13. package/ios/BundleDropOtaResolver.swift +137 -29
  14. package/ios/BundleDropRuntimeCrypto.swift +45 -0
  15. package/ios/BundleDropStartupRecovery.swift +1108 -0
  16. package/ios/BundleDropStartupRecoveryAdapter.swift +301 -0
  17. package/lib/CLI/cli.d.ts +1 -0
  18. package/lib/CLI/cli.js +57 -6
  19. package/lib/CLI/scripts/aipowered/apply-setup-plan.js +7 -17
  20. package/lib/CLI/scripts/aipowered/backend-client.js +29 -4
  21. package/lib/CLI/scripts/aipowered/code-push-residue.d.ts +5 -0
  22. package/lib/CLI/scripts/aipowered/code-push-residue.js +126 -0
  23. package/lib/CLI/scripts/aipowered/credential-safety.d.ts +1 -0
  24. package/lib/CLI/scripts/aipowered/credential-safety.js +14 -0
  25. package/lib/CLI/scripts/aipowered/diff-preview.js +12 -4
  26. package/lib/CLI/scripts/aipowered/init-project-config.d.ts +4 -0
  27. package/lib/CLI/scripts/aipowered/init-project-config.js +221 -45
  28. package/lib/CLI/scripts/aipowered/scanner.d.ts +1 -0
  29. package/lib/CLI/scripts/aipowered/scanner.js +164 -32
  30. package/lib/CLI/scripts/aipowered/terminal-safety.d.ts +4 -0
  31. package/lib/CLI/scripts/aipowered/terminal-safety.js +124 -0
  32. package/lib/CLI/scripts/aipowered/validate-plan.d.ts +3 -0
  33. package/lib/CLI/scripts/aipowered/validate-plan.js +1080 -19
  34. package/lib/CLI/scripts/bare-metro-config.d.ts +1 -1
  35. package/lib/CLI/scripts/bare-metro-config.js +24 -32
  36. package/lib/CLI/scripts/doctor.js +162 -22
  37. package/lib/CLI/scripts/expo/configure-expo.js +52 -60
  38. package/lib/CLI/scripts/expo/package-manager.d.ts +2 -0
  39. package/lib/CLI/scripts/expo/package-manager.js +63 -25
  40. package/lib/CLI/scripts/init-config.d.ts +7 -7
  41. package/lib/CLI/scripts/init-config.js +198 -14
  42. package/lib/CLI/scripts/login-cli.js +31 -7
  43. package/lib/CLI/scripts/metro-config-authority.d.ts +8 -0
  44. package/lib/CLI/scripts/metro-config-authority.js +303 -0
  45. package/lib/CLI/scripts/native/write-runtime-identity.d.ts +19 -0
  46. package/lib/CLI/scripts/native/write-runtime-identity.js +92 -0
  47. package/lib/CLI/scripts/native-entrypoint-authority.d.ts +2 -0
  48. package/lib/CLI/scripts/native-entrypoint-authority.js +378 -0
  49. package/lib/CLI/scripts/native-setup-contract.d.ts +2 -2
  50. package/lib/CLI/scripts/native-setup-contract.js +63 -33
  51. package/lib/CLI/scripts/native-startup-validator.d.ts +3 -0
  52. package/lib/CLI/scripts/native-startup-validator.js +964 -0
  53. package/lib/CLI/scripts/safe-file-transaction.d.ts +12 -0
  54. package/lib/CLI/scripts/safe-file-transaction.js +159 -0
  55. package/lib/CLI/scripts/upload-cli.d.ts +12 -2
  56. package/lib/CLI/scripts/upload-cli.js +74 -11
  57. package/lib/CLI/serverUrl.d.ts +3 -0
  58. package/lib/CLI/serverUrl.js +31 -0
  59. package/lib/api/clientApi.d.ts +3 -1
  60. package/lib/api/clientApi.js +14 -0
  61. package/lib/api/types.d.ts +39 -0
  62. package/lib/bundleInfo.d.ts +2 -0
  63. package/lib/bundleInfo.js +16 -1
  64. package/lib/context.d.ts +1 -1
  65. package/lib/context.js +12 -2
  66. package/lib/fs/bundlePointer.d.ts +1 -17
  67. package/lib/fs/bundlePointer.js +5 -93
  68. package/lib/index.d.ts +2 -0
  69. package/lib/index.js +3 -1
  70. package/lib/install/bundleInstallShared.js +4 -4
  71. package/lib/install/installFromZip.d.ts +3 -0
  72. package/lib/install/installFromZip.js +10 -1
  73. package/lib/loadConfig.d.ts +17 -1
  74. package/lib/loadConfig.js +16 -0
  75. package/lib/manager/downloadAndInstall.d.ts +3 -2
  76. package/lib/manager/downloadAndInstall.js +134 -66
  77. package/lib/manager/reporting.d.ts +8 -1
  78. package/lib/manager/reporting.js +17 -22
  79. package/lib/manager/rollbackState.d.ts +18 -52
  80. package/lib/manager/rollbackState.js +115 -216
  81. package/lib/manager/updateCheck.d.ts +1 -0
  82. package/lib/manager/updateCheck.js +224 -78
  83. package/lib/manager/updateState.d.ts +2 -1
  84. package/lib/manager/updateState.js +59 -6
  85. package/lib/metro.d.ts +8 -1
  86. package/lib/metro.js +69 -19
  87. package/lib/native/bundleDropNative.d.ts +62 -0
  88. package/lib/native/bundleDropNative.js +268 -2
  89. package/lib/native/fs.d.ts +6 -0
  90. package/lib/native/fs.js +24 -0
  91. package/lib/patch-engine/installFromPatchSet.d.ts +2 -0
  92. package/lib/patch-engine/installFromPatchSet.js +16 -5
  93. package/lib/patch-engine/patchTransport.d.ts +2 -0
  94. package/lib/patch-engine/patchTransport.js +9 -0
  95. package/lib/runtime/initState.d.ts +5 -0
  96. package/lib/runtime/initState.js +4 -0
  97. package/lib/runtime/service.js +82 -67
  98. package/lib/runtime-delivery/artifactCapability.d.ts +1 -0
  99. package/lib/runtime-delivery/artifactCapability.js +32 -0
  100. package/lib/runtime-delivery/authorityLeaseVerifier.d.ts +3 -0
  101. package/lib/runtime-delivery/authorityLeaseVerifier.js +106 -0
  102. package/lib/runtime-delivery/bootstrapConfig.d.ts +68 -0
  103. package/lib/runtime-delivery/bootstrapConfig.js +278 -0
  104. package/lib/runtime-delivery/diagnostics.d.ts +17 -0
  105. package/lib/runtime-delivery/diagnostics.js +58 -0
  106. package/lib/runtime-delivery/encoding.d.ts +5 -0
  107. package/lib/runtime-delivery/encoding.js +132 -0
  108. package/lib/runtime-delivery/heartbeat.d.ts +3 -0
  109. package/lib/runtime-delivery/heartbeat.js +88 -0
  110. package/lib/runtime-delivery/localResolver.d.ts +23 -0
  111. package/lib/runtime-delivery/localResolver.js +81 -0
  112. package/lib/runtime-delivery/manifestState.d.ts +11 -0
  113. package/lib/runtime-delivery/manifestState.js +123 -0
  114. package/lib/runtime-delivery/manifestVerifier.d.ts +13 -0
  115. package/lib/runtime-delivery/manifestVerifier.js +335 -0
  116. package/lib/runtime-delivery/runtimeDelivery.d.ts +19 -0
  117. package/lib/runtime-delivery/runtimeDelivery.js +375 -0
  118. package/lib/runtime-delivery/types.d.ts +87 -0
  119. package/lib/runtime-delivery/types.js +6 -0
  120. package/lib/scripts/bundle.d.ts +9 -2
  121. package/lib/scripts/bundle.js +68 -18
  122. package/lib/scripts/download-bundle.d.ts +1 -0
  123. package/lib/scripts/download-bundle.js +2 -2
  124. package/lib/scripts/resolveModule.d.ts +2 -0
  125. package/lib/scripts/resolveModule.js +5 -0
  126. package/package.json +5 -2
  127. package/plugin/xcodeBuildPhase.js +2 -1
@@ -35,6 +35,7 @@ var __importStar = (this && this.__importStar) || (function () {
35
35
  Object.defineProperty(exports, "__esModule", { value: true });
36
36
  exports.getAvailableChannels = getAvailableChannels;
37
37
  exports.checkForUpdate = checkForUpdate;
38
+ exports.authorizeRuntimeDeliveryUpdate = authorizeRuntimeDeliveryUpdate;
38
39
  exports.getInstalledBundleInfo = getInstalledBundleInfo;
39
40
  exports.getAvailableBundles = getAvailableBundles;
40
41
  const context_1 = require("../context");
@@ -48,6 +49,11 @@ const initState_1 = require("../runtime/initState");
48
49
  const rollbackState_1 = require("./rollbackState");
49
50
  const bundleDropNative_1 = require("../native/bundleDropNative");
50
51
  const patchOperations_1 = require("../patch-engine/patchOperations");
52
+ const runtimeDelivery_1 = require("../runtime-delivery/runtimeDelivery");
53
+ const diagnostics_1 = require("../runtime-delivery/diagnostics");
54
+ const manifestVerifier_1 = require("../runtime-delivery/manifestVerifier");
55
+ const loadConfig_1 = require("../loadConfig");
56
+ const ACTIVE_INSTALL_HEARTBEAT_VERSION = 1;
51
57
  function assertInstallDecisionShape(decision) {
52
58
  const { target } = decision;
53
59
  if (!target?.bundleHash) {
@@ -99,97 +105,237 @@ async function getAvailableChannels() {
99
105
  throw e;
100
106
  }
101
107
  }
108
+ async function readResolveContext(channelName) {
109
+ const selectedHash = (0, bundleDropNative_1.getStartupRecoverySelectedHashNative)();
110
+ const [pointerHash, nativeBundlePath, userProperties, installId, rejectedHashes] = await Promise.all([
111
+ (0, bundlePointer_1.readCurrentBundleHash)(),
112
+ (0, bundleDropNative_1.getDownloadedBundlePathNative)(),
113
+ (0, userProperties_1.getCurrentUserProperties)(),
114
+ (0, installId_1.getOrCreateInstallId)(),
115
+ (0, rollbackState_1.getFailedBundleHashes)(),
116
+ ]);
117
+ const supportsXdelta = await Promise.resolve().then(() => __importStar(require('../native/fs'))).then(module => module.default.supportsXdelta())
118
+ .catch(() => false);
119
+ return {
120
+ channelName,
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,
127
+ rejectedHashes,
128
+ installId,
129
+ patchAlgorithms: (0, patchOperations_1.advertisedPatchAlgorithms)(supportsXdelta),
130
+ supportsContentAddressedAssets: true,
131
+ environment: (0, initState_1.getBundleDropRuntimeConfig)()?.environment ?? null,
132
+ userProperties,
133
+ };
134
+ }
135
+ async function mapServerDecision(decision, channelName, onStatusUpdate) {
136
+ if (decision.action === 'NOOP') {
137
+ const incompatible = decision.reason === 'NO_COMPATIBLE_BUNDLE';
138
+ onStatusUpdate?.(incompatible
139
+ ? '⛔️ No compatible update for this binary'
140
+ : '✅ You have the latest version');
141
+ return {
142
+ action: 'NOOP',
143
+ upToDate: !incompatible,
144
+ channelName,
145
+ reason: decision.reason,
146
+ incompatible: incompatible || undefined,
147
+ requestedRuntimeVersion: decision.requestedRuntimeVersion,
148
+ latestRuntimeVersionOnChannel: decision.latestRuntimeVersionOnChannel,
149
+ };
150
+ }
151
+ if (decision.action === 'ROLLBACK') {
152
+ onStatusUpdate?.('↩️ Rollback requested');
153
+ return { action: 'ROLLBACK', channelName, reason: decision.reason };
154
+ }
155
+ assertInstallDecisionShape(decision);
156
+ const targetHash = decision.target.bundleHash;
157
+ if (await (0, rollbackState_1.isBundleHashFailed)(targetHash)) {
158
+ onStatusUpdate?.('✅ Current bundle retained; latest update previously failed on this device');
159
+ return {
160
+ action: 'NOOP',
161
+ upToDate: false,
162
+ channelName,
163
+ reason: 'BUNDLE_PREVIOUSLY_FAILED',
164
+ skippedFailedBundle: true,
165
+ skippedHash: targetHash,
166
+ };
167
+ }
168
+ onStatusUpdate?.('⬇️ Update available');
169
+ return {
170
+ action: 'INSTALL',
171
+ upToDate: false,
172
+ channelName,
173
+ hash: targetHash,
174
+ bundleHash: targetHash,
175
+ mode: decision.mode,
176
+ baseHash: decision.mode === 'patch' ? decision.baseHash : undefined,
177
+ patchSet: decision.mode === 'patch' ? decision.patchSet : undefined,
178
+ fallback: decision.mode === 'patch' ? decision.fallback : undefined,
179
+ downloadUrl: decision.target.downloadUrl,
180
+ manifestUrl: decision.target.manifestUrl,
181
+ bundleVersion: decision.target.bundleVersion,
182
+ version: decision.target.version,
183
+ runtimeVersion: decision.target.runtimeVersion,
184
+ };
185
+ }
186
+ async function resolveWithServer(context, onStatusUpdate, options = {}) {
187
+ const response = await (0, clientApi_1.postOtaResolve)(context_1.config.project.slug, {
188
+ channelName: context.channelName,
189
+ platform: context_1.platform,
190
+ runtimeVersion: context_1.runtimeVersion ?? null,
191
+ environment: context.environment,
192
+ currentHash: context.currentHash,
193
+ currentUserProperties: context.userProperties,
194
+ rejectedHashes: context.rejectedHashes,
195
+ installId: context.installId,
196
+ transport: {
197
+ manifestVersion: 1,
198
+ patchAlgorithms: context.patchAlgorithms,
199
+ supportsContentAddressedAssets: context.supportsContentAddressedAssets,
200
+ ...(options.activeInstallHeartbeatVersion
201
+ ? { activeInstallHeartbeatVersion: options.activeInstallHeartbeatVersion }
202
+ : {}),
203
+ },
204
+ });
205
+ return mapServerDecision(response.data, context.channelName, onStatusUpdate);
206
+ }
207
+ function emitLocalDecisionStatus(decision, onStatusUpdate) {
208
+ if (decision.action === 'INSTALL')
209
+ onStatusUpdate?.('⬇️ Update available');
210
+ else if (decision.action === 'ROLLBACK')
211
+ onStatusUpdate?.('↩️ Rollback requested');
212
+ else
213
+ onStatusUpdate?.('✅ You have the latest version');
214
+ }
102
215
  async function checkForUpdate(channelName = context_2.defaultChannel, onStatusUpdate) {
103
- const { project } = context_1.config;
216
+ if (!context_1.config.project?.slug) {
217
+ const error = new Error('Missing project slug in bundle.drop.config.js');
218
+ console.warn('⚠️ checkForUpdate failed:', error.toString());
219
+ return null;
220
+ }
221
+ onStatusUpdate?.('🔍 Checking for updates...');
222
+ let context = null;
104
223
  try {
105
- if (!project?.slug) {
106
- throw new Error('Missing project slug in bundle.drop.config.js');
224
+ context = await readResolveContext(channelName);
225
+ if (!(0, loadConfig_1.isRuntimeDeliveryConfigured)(context_1.config.runtimeDelivery) || !context_1.runtimeVersion) {
226
+ return await resolveWithServer(context, onStatusUpdate);
107
227
  }
108
- onStatusUpdate?.('🔍 Checking for updates...');
109
- const [currentPtr, nativeBundlePath, currentUserProperties, installId, rejectedHashes] = await Promise.all([
110
- (0, bundlePointer_1.readCurrentBundlePointer)(),
111
- (0, bundleDropNative_1.getDownloadedBundlePathNative)(),
112
- (0, userProperties_1.getCurrentUserProperties)(),
113
- (0, installId_1.getOrCreateInstallId)(),
114
- (0, rollbackState_1.getFailedBundleHashes)(),
115
- ]);
116
- const currentHash = nativeBundlePath && currentPtr?.hash ? currentPtr.hash : null;
117
- const appEnvironment = (0, initState_1.getBundleDropRuntimeConfig)()?.environment ?? null;
118
- const supportsXdelta = await Promise.resolve().then(() => __importStar(require('../native/fs'))).then(module => module.default.supportsXdelta())
119
- .catch(() => false);
120
- const res = await (0, clientApi_1.postOtaResolve)(project.slug, {
121
- channelName,
228
+ (0, runtimeDelivery_1.reportActiveInstall)(context);
229
+ try {
230
+ const manifest = await (0, runtimeDelivery_1.fetchRuntimeDeliveryManifest)(channelName);
231
+ if (manifest.resolutionMode === 'dynamic') {
232
+ (0, diagnostics_1.recordRuntimeDeliveryDiagnostic)('origin_fallback', {
233
+ channelName,
234
+ reason: `dynamic:${manifest.dynamicReason ?? 'unspecified'}`,
235
+ });
236
+ return await resolveWithServer(context, onStatusUpdate, {
237
+ activeInstallHeartbeatVersion: ACTIVE_INSTALL_HEARTBEAT_VERSION,
238
+ });
239
+ }
240
+ const local = await (0, runtimeDelivery_1.resolveFromRuntimeDeliveryManifest)(manifest, context);
241
+ emitLocalDecisionStatus(local, onStatusUpdate);
242
+ return local;
243
+ }
244
+ catch (manifestError) {
245
+ (0, diagnostics_1.recordRuntimeDeliveryDiagnostic)('origin_fallback', {
246
+ channelName,
247
+ reason: manifestError instanceof manifestVerifier_1.RuntimeDeliveryManifestError
248
+ ? manifestError.code
249
+ : 'manifest_error',
250
+ });
251
+ console.warn('[BundleDrop] manifest delivery unavailable; falling back to /resolve:', manifestError);
252
+ return await resolveWithServer(context, onStatusUpdate, {
253
+ activeInstallHeartbeatVersion: ACTIVE_INSTALL_HEARTBEAT_VERSION,
254
+ });
255
+ }
256
+ }
257
+ catch (error) {
258
+ if ((0, loadConfig_1.isRuntimeDeliveryConfigured)(context_1.config.runtimeDelivery) &&
259
+ context &&
260
+ await (0, runtimeDelivery_1.shouldRollbackFromLastKnownRevocations)(channelName, context.currentHash).catch(() => false)) {
261
+ onStatusUpdate?.('↩️ Rollback requested');
262
+ return {
263
+ action: 'ROLLBACK',
264
+ channelName,
265
+ reason: 'CURRENT_REVOKED_ORIGIN_UNAVAILABLE',
266
+ };
267
+ }
268
+ console.warn('⚠️ checkForUpdate failed:', error?.toString?.() || error);
269
+ return null;
270
+ }
271
+ }
272
+ async function authorizeRuntimeDeliveryUpdate(decision) {
273
+ if (decision.action !== 'INSTALL' || !decision.runtimeDelivery || !decision.channelName) {
274
+ return decision;
275
+ }
276
+ const context = await readResolveContext(decision.channelName);
277
+ try {
278
+ if (!context_1.runtimeVersion)
279
+ throw new Error('Runtime version is required for artifact authorization');
280
+ const response = await (0, clientApi_1.postOtaArtifactAuthorization)(context_1.config.project.slug, {
281
+ channelName: decision.channelName,
122
282
  platform: context_1.platform,
123
- runtimeVersion: context_1.runtimeVersion ?? null,
124
- environment: appEnvironment,
125
- currentHash,
126
- currentUserProperties,
127
- rejectedHashes,
128
- installId,
283
+ runtimeVersion: context_1.runtimeVersion,
284
+ generation: decision.runtimeDelivery.generation,
285
+ targetReleaseRef: decision.runtimeDelivery.targetReleaseRef,
286
+ targetHash: decision.hash,
287
+ mode: decision.runtimeDelivery.selectedMode,
288
+ patchArtifactRef: decision.runtimeDelivery.patchArtifactRef ?? null,
289
+ currentHash: context.currentHash,
290
+ rejectedHashes: context.rejectedHashes,
291
+ installId: context.installId,
129
292
  transport: {
130
293
  manifestVersion: 1,
131
- patchAlgorithms: (0, patchOperations_1.advertisedPatchAlgorithms)(supportsXdelta),
132
- supportsContentAddressedAssets: true,
294
+ patchAlgorithms: context.patchAlgorithms,
295
+ supportsContentAddressedAssets: context.supportsContentAddressedAssets,
133
296
  },
134
297
  });
135
- const decision = res.data;
136
- if (decision.action === 'NOOP') {
137
- const incompatible = decision.reason === 'NO_COMPATIBLE_BUNDLE';
138
- if (incompatible) {
139
- onStatusUpdate?.('⛔️ No compatible update for this binary');
298
+ const authorized = await mapServerDecision(response.data, decision.channelName);
299
+ if (authorized.action === 'INSTALL') {
300
+ if (authorized.hash !== decision.hash || authorized.runtimeVersion !== context_1.runtimeVersion) {
301
+ throw new Error('Artifact authorization returned a different target identity');
140
302
  }
141
- else {
142
- onStatusUpdate?.('✅ You have the latest version');
303
+ const selection = decision.runtimeDelivery;
304
+ if (authorized.mode === 'patch') {
305
+ if (selection.selectedMode !== 'patch' ||
306
+ authorized.baseHash !== selection.baseHash ||
307
+ authorized.patchSet?.algorithm !== selection.patchAlgorithm ||
308
+ authorized.patchSet.patchSetHash !== selection.patchSetHash ||
309
+ (authorized.patchSet.assets?.missingAssetsHash ?? null) !==
310
+ (selection.missingAssetsHash ?? null)) {
311
+ throw new Error('Artifact authorization returned an unsafe patch selection');
312
+ }
143
313
  }
144
- return {
145
- action: 'NOOP',
146
- upToDate: !incompatible,
147
- channelName,
148
- reason: decision.reason,
149
- incompatible: incompatible || undefined,
150
- requestedRuntimeVersion: decision.requestedRuntimeVersion,
151
- latestRuntimeVersionOnChannel: decision.latestRuntimeVersionOnChannel,
152
- };
314
+ return { ...authorized, runtimeDelivery: selection };
153
315
  }
154
- if (decision.action === 'ROLLBACK') {
155
- onStatusUpdate?.('↩️ Rollback requested');
156
- return { action: 'ROLLBACK', channelName, reason: decision.reason };
316
+ return authorized;
317
+ }
318
+ catch (error) {
319
+ (0, diagnostics_1.recordRuntimeDeliveryDiagnostic)('origin_fallback', {
320
+ channelName: decision.channelName,
321
+ reason: 'artifact_authorization_failed',
322
+ });
323
+ console.warn('[BundleDrop] artifact authorization failed; falling back to /resolve:', error);
324
+ try {
325
+ return await resolveWithServer(context, undefined, {
326
+ activeInstallHeartbeatVersion: ACTIVE_INSTALL_HEARTBEAT_VERSION,
327
+ });
157
328
  }
158
- assertInstallDecisionShape(decision);
159
- // INSTALL
160
- const targetHash = decision.target.bundleHash;
161
- if (await (0, rollbackState_1.isBundleHashFailed)(targetHash)) {
162
- onStatusUpdate?.('✅ Current bundle retained; latest update previously failed on this device');
163
- return {
164
- action: 'NOOP',
165
- upToDate: false,
166
- channelName,
167
- reason: 'BUNDLE_PREVIOUSLY_FAILED',
168
- skippedFailedBundle: true,
169
- skippedHash: targetHash,
170
- };
329
+ catch {
330
+ if (await (0, runtimeDelivery_1.shouldRollbackFromLastKnownRevocations)(decision.channelName, context.currentHash).catch(() => false)) {
331
+ return {
332
+ action: 'ROLLBACK',
333
+ channelName: decision.channelName,
334
+ reason: 'CURRENT_REVOKED_ORIGIN_UNAVAILABLE',
335
+ };
336
+ }
337
+ return null;
171
338
  }
172
- onStatusUpdate?.('⬇️ Update available');
173
- return {
174
- action: 'INSTALL',
175
- upToDate: false,
176
- channelName,
177
- hash: targetHash,
178
- bundleHash: targetHash,
179
- mode: decision.mode,
180
- baseHash: decision.mode === 'patch' ? decision.baseHash : undefined,
181
- patchSet: decision.mode === 'patch' ? decision.patchSet : undefined,
182
- fallback: decision.mode === 'patch' ? decision.fallback : undefined,
183
- downloadUrl: decision.target.downloadUrl,
184
- manifestUrl: decision.target.manifestUrl,
185
- bundleVersion: decision.target.bundleVersion,
186
- version: decision.target.version,
187
- runtimeVersion: decision.target.runtimeVersion,
188
- };
189
- }
190
- catch (e) {
191
- console.warn('⚠️ checkForUpdate failed:', e?.toString?.() || e);
192
- return null;
193
339
  }
194
340
  }
195
341
  async function getInstalledBundleInfo() {
@@ -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>;
@@ -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
@@ -6,9 +6,16 @@ export type BundleDropMetroConfig = {
6
6
  };
7
7
  [key: string]: unknown;
8
8
  };
9
- export type WithBundleDropExpoOptions = {
9
+ export type WithBundleDropOptions = {
10
10
  projectRoot?: string;
11
11
  };
12
+ export type WithBundleDropExpoOptions = WithBundleDropOptions;
13
+ /**
14
+ * Preserves a bare React Native Metro config and resolves Bundle Drop through
15
+ * the project-owned, package-validated runtime-delivery lockfile.
16
+ */
17
+ export declare function withBundleDrop<T extends BundleDropMetroConfig>(config: T, options?: WithBundleDropOptions): T;
18
+ export declare const withBundleDropBare: typeof withBundleDrop;
12
19
  /**
13
20
  * Preserves the caller's Expo Metro config and only adds Bundle Drop's config
14
21
  * alias after resolving the same concrete identity used by build and upload.
package/lib/metro.js CHANGED
@@ -3,34 +3,88 @@ 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.withBundleDropBare = void 0;
7
+ exports.withBundleDrop = withBundleDrop;
6
8
  exports.withBundleDropExpo = withBundleDropExpo;
7
9
  const fs_extra_1 = __importDefault(require("fs-extra"));
8
10
  const path_1 = __importDefault(require("path"));
9
11
  const expo_1 = require("./expo");
12
+ const bootstrapConfig_1 = require("./runtime-delivery/bootstrapConfig");
13
+ const loadBaseConfig = (projectRoot) => {
14
+ const configPath = path_1.default.join(projectRoot, 'bundle.drop.config.js');
15
+ if (!fs_extra_1.default.existsSync(configPath)) {
16
+ throw new Error('Bundle Drop Metro setup requires bundle.drop.config.js in the project root.');
17
+ }
18
+ delete require.cache[require.resolve(configPath)];
19
+ // eslint-disable-next-line @typescript-eslint/no-var-requires
20
+ const config = require(configPath);
21
+ if (!config?.serverUrl || !config.org?.slug || !config.project?.slug) {
22
+ throw new Error('bundle.drop.config.js must define serverUrl, org.slug, and project.slug before Metro setup.');
23
+ }
24
+ return config;
25
+ };
26
+ const resolveRuntimeDelivery = (projectRoot, baseConfig) => {
27
+ const bootstrap = (0, bootstrapConfig_1.readRuntimeDeliveryBootstrap)({
28
+ projectRoot,
29
+ expectedIdentity: {
30
+ serverUrl: baseConfig.serverUrl,
31
+ orgSlug: baseConfig.org.slug,
32
+ projectSlug: baseConfig.project.slug,
33
+ },
34
+ });
35
+ return bootstrap?.runtimeDelivery;
36
+ };
10
37
  const writeGeneratedRuntimeConfig = (params) => {
11
38
  const generatedDirectory = path_1.default.join(params.projectRoot, '.bundle-drop', 'generated');
12
39
  const generatedConfigPath = path_1.default.join(generatedDirectory, 'bundle.drop.config.js');
13
40
  fs_extra_1.default.ensureDirSync(generatedDirectory);
14
- const baseConfigPath = path_1.default.join(params.projectRoot, 'bundle.drop.config.js');
15
- if (!fs_extra_1.default.existsSync(baseConfigPath)) {
16
- throw new Error('Bundle Drop Expo Metro setup requires bundle.drop.config.js in the project root.');
41
+ const generatedFields = [];
42
+ if (params.runtimeVersion) {
43
+ generatedFields.push(` runtimeVersion: ${JSON.stringify(params.runtimeVersion)},`);
44
+ }
45
+ if (params.runtimeDelivery) {
46
+ generatedFields.push(` runtimeDelivery: ${JSON.stringify(params.runtimeDelivery)},`);
17
47
  }
18
48
  const content = [
49
+ '/* eslint-disable */',
19
50
  "'use strict';",
20
51
  '',
21
52
  "const baseConfig = require('../../bundle.drop.config.js');",
53
+ 'const resolvedConfig = { ...baseConfig };',
54
+ 'delete resolvedConfig.runtimeDelivery;',
22
55
  'module.exports = {',
23
- ' ...baseConfig,',
24
- ` runtimeVersion: ${JSON.stringify({
25
- ios: params.ios,
26
- android: params.android,
27
- })},`,
56
+ ' ...resolvedConfig,',
57
+ ...generatedFields,
28
58
  '};',
29
59
  '',
30
60
  ].join('\n');
31
61
  fs_extra_1.default.writeFileSync(generatedConfigPath, content, 'utf8');
32
62
  return generatedConfigPath;
33
63
  };
64
+ const mergeMetroAlias = (config, generatedConfigPath) => ({
65
+ ...config,
66
+ resolver: {
67
+ ...(config.resolver || {}),
68
+ extraNodeModules: {
69
+ ...(config.resolver?.extraNodeModules || {}),
70
+ 'bundle-drop-config': generatedConfigPath,
71
+ },
72
+ },
73
+ });
74
+ /**
75
+ * Preserves a bare React Native Metro config and resolves Bundle Drop through
76
+ * the project-owned, package-validated runtime-delivery lockfile.
77
+ */
78
+ function withBundleDrop(config, options = {}) {
79
+ const projectRoot = path_1.default.resolve(options.projectRoot || process.cwd());
80
+ const baseConfig = loadBaseConfig(projectRoot);
81
+ const generatedConfigPath = writeGeneratedRuntimeConfig({
82
+ projectRoot,
83
+ runtimeDelivery: resolveRuntimeDelivery(projectRoot, baseConfig),
84
+ });
85
+ return mergeMetroAlias(config, generatedConfigPath);
86
+ }
87
+ exports.withBundleDropBare = withBundleDrop;
34
88
  /**
35
89
  * Preserves the caller's Expo Metro config and only adds Bundle Drop's config
36
90
  * alias after resolving the same concrete identity used by build and upload.
@@ -42,16 +96,12 @@ async function withBundleDropExpo(configOrPromise, options = {}) {
42
96
  (0, expo_1.resolveExpoMetroRuntimeVersion)(projectRoot, 'ios'),
43
97
  (0, expo_1.resolveExpoMetroRuntimeVersion)(projectRoot, 'android'),
44
98
  ]);
45
- const generatedConfigPath = writeGeneratedRuntimeConfig({ projectRoot, ios, android });
46
- return {
47
- ...config,
48
- resolver: {
49
- ...(config.resolver || {}),
50
- extraNodeModules: {
51
- ...(config.resolver?.extraNodeModules || {}),
52
- 'bundle-drop-config': generatedConfigPath,
53
- },
54
- },
55
- };
99
+ const baseConfig = loadBaseConfig(projectRoot);
100
+ const generatedConfigPath = writeGeneratedRuntimeConfig({
101
+ projectRoot,
102
+ runtimeDelivery: resolveRuntimeDelivery(projectRoot, baseConfig),
103
+ runtimeVersion: { ios, android },
104
+ });
105
+ return mergeMetroAlias(config, generatedConfigPath);
56
106
  }
57
107
  exports.default = withBundleDropExpo;
@@ -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 {};