@gfean/react-native-bundle-drop 0.10.0 → 0.12.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 (107) hide show
  1. package/BundleDrop.podspec +17 -20
  2. package/README.md +60 -1
  3. package/android/build.gradle +4 -0
  4. package/android/src/main/java/com/bundledrop/BundleDropFileOps.kt +20 -0
  5. package/android/src/main/java/com/bundledrop/BundleDropModule.kt +4 -1
  6. package/android/src/main/java/com/bundledrop/BundleDropNativePaths.kt +5 -1
  7. package/docs/native-fingerprint.md +211 -0
  8. package/expo/android/build.gradle +61 -56
  9. package/ios/BundleDropLocator.swift +12 -0
  10. package/ios/BundleDropModule.swift +31 -13
  11. package/ios/BundleDropReactContent.swift +54 -0
  12. package/ios/BundleDropStartupRecovery.swift +48 -2
  13. package/ios/BundleDropStartupRecoveryAdapter.swift +87 -30
  14. package/lib/CLI/cli.js +9 -0
  15. package/lib/CLI/scripts/doctor.js +18 -7
  16. package/lib/CLI/scripts/expo/configure-expo.js +8 -3
  17. package/lib/CLI/scripts/fingerprint-cli.d.ts +12 -0
  18. package/lib/CLI/scripts/fingerprint-cli.js +36 -0
  19. package/lib/CLI/scripts/native/write-runtime-identity.js +3 -1
  20. package/lib/CLI/scripts/sight-ota.js +12 -3
  21. package/lib/CLI/scripts/upload-cli.d.ts +1 -0
  22. package/lib/CLI/scripts/upload-cli.js +43 -0
  23. package/lib/context.js +9 -1
  24. package/lib/errors.d.ts +2 -1
  25. package/lib/errors.js +2 -1
  26. package/lib/expo/buildIdentity.d.ts +1 -1
  27. package/lib/expo/buildIdentity.js +3 -0
  28. package/lib/expo/runtimeVersion.d.ts +10 -0
  29. package/lib/expo/runtimeVersion.js +11 -9
  30. package/lib/fingerprint/client.d.ts +5 -0
  31. package/lib/fingerprint/client.js +21 -0
  32. package/lib/fingerprint/collect.d.ts +3 -0
  33. package/lib/fingerprint/collect.js +116 -0
  34. package/lib/fingerprint/config.d.ts +14 -0
  35. package/lib/fingerprint/config.js +60 -0
  36. package/lib/fingerprint/normalizeBuildNumber.d.ts +4 -0
  37. package/lib/fingerprint/normalizeBuildNumber.js +55 -0
  38. package/lib/fingerprint/normalizeIosBuildNumber.d.ts +4 -0
  39. package/lib/fingerprint/normalizeIosBuildNumber.js +62 -0
  40. package/lib/fingerprint/types.d.ts +29 -0
  41. package/lib/fingerprint/types.js +2 -0
  42. package/lib/fingerprint/worker.d.ts +1 -0
  43. package/lib/fingerprint/worker.js +24 -0
  44. package/lib/fs/installedReportHistory.d.ts +2 -0
  45. package/lib/fs/installedReportHistory.js +55 -0
  46. package/lib/loadConfig.d.ts +6 -2
  47. package/lib/manager/downloadAndInstall.d.ts +1 -0
  48. package/lib/manager/downloadAndInstall.js +4 -0
  49. package/lib/manager/pendingRollback.d.ts +11 -0
  50. package/lib/manager/pendingRollback.js +54 -0
  51. package/lib/manager/reporting.d.ts +1 -0
  52. package/lib/manager/reporting.js +23 -6
  53. package/lib/manager/updateState.d.ts +3 -0
  54. package/lib/manager/updateState.js +1 -0
  55. package/lib/metro.js +3 -0
  56. package/lib/native/bundleDropNative.d.ts +2 -0
  57. package/lib/native/bundleDropNative.js +15 -5
  58. package/lib/patch-engine/installFromPatchSet.js +1 -1
  59. package/lib/patch-engine/patchTransport.d.ts +2 -1
  60. package/lib/patch-engine/patchTransport.js +4 -2
  61. package/lib/runtime/service.d.ts +2 -1
  62. package/lib/runtime/service.js +77 -22
  63. package/lib/scripts/bundle.js +10 -0
  64. package/lib/scripts/canonicalArtifact.d.ts +3 -0
  65. package/lib/scripts/canonicalArtifact.js +3 -1
  66. package/lib/scripts/exportProject.js +11 -0
  67. package/lib/scripts/nativeBuildNumber.d.ts +9 -0
  68. package/lib/scripts/nativeBuildNumber.js +110 -0
  69. package/lib/scripts/runtimeCompatibilityMetadata.d.ts +10 -0
  70. package/lib/scripts/runtimeCompatibilityMetadata.js +13 -0
  71. package/package.json +25 -11
  72. package/third_party/expo-fingerprint/LICENSE +22 -0
  73. package/third_party/expo-fingerprint/NOTICE +5 -0
  74. package/third_party/expo-fingerprint/PROVENANCE.md +41 -0
  75. package/third_party/expo-fingerprint/build/Config.js +122 -0
  76. package/third_party/expo-fingerprint/build/Dedup.js +89 -0
  77. package/third_party/expo-fingerprint/build/ExpoConfig.js +93 -0
  78. package/third_party/expo-fingerprint/build/ExpoConfigLoader.js +201 -0
  79. package/third_party/expo-fingerprint/build/ExpoResolver.js +84 -0
  80. package/third_party/expo-fingerprint/build/Fingerprint.js +111 -0
  81. package/third_party/expo-fingerprint/build/Fingerprint.types.js +3 -0
  82. package/third_party/expo-fingerprint/build/Options.js +140 -0
  83. package/third_party/expo-fingerprint/build/Presets.js +62 -0
  84. package/third_party/expo-fingerprint/build/ProjectWorkflow.js +163 -0
  85. package/third_party/expo-fingerprint/build/Sort.js +46 -0
  86. package/third_party/expo-fingerprint/build/hash/FileHookTransform.js +42 -0
  87. package/third_party/expo-fingerprint/build/hash/Hash.js +264 -0
  88. package/third_party/expo-fingerprint/build/hash/ReactImportsPatcher.js +344 -0
  89. package/third_party/expo-fingerprint/build/index.js +23 -0
  90. package/third_party/expo-fingerprint/build/sourcer/AutolinkingConfig.js +130 -0
  91. package/third_party/expo-fingerprint/build/sourcer/Bare.js +231 -0
  92. package/third_party/expo-fingerprint/build/sourcer/Expo.js +376 -0
  93. package/third_party/expo-fingerprint/build/sourcer/Packages.js +54 -0
  94. package/third_party/expo-fingerprint/build/sourcer/PatchPackage.js +22 -0
  95. package/third_party/expo-fingerprint/build/sourcer/SourceSkips.js +79 -0
  96. package/third_party/expo-fingerprint/build/sourcer/Sourcer.js +58 -0
  97. package/third_party/expo-fingerprint/build/sourcer/Utils.js +129 -0
  98. package/third_party/expo-fingerprint/build/types/module.d.js +2 -0
  99. package/third_party/expo-fingerprint/build/utils/Concurrency.js +47 -0
  100. package/third_party/expo-fingerprint/build/utils/Env.js +28 -0
  101. package/third_party/expo-fingerprint/build/utils/Path.js +161 -0
  102. package/third_party/expo-fingerprint/build/utils/Predicates.js +6 -0
  103. package/third_party/expo-fingerprint/build/utils/Profile.js +41 -0
  104. package/third_party/expo-fingerprint/build/utils/Spawn.js +38 -0
  105. package/third_party/expo-fingerprint/build/utils/SpawnIPC.js +28 -0
  106. package/third_party/expo-fingerprint/scheme-1-contract.json +132 -0
  107. package/third_party/expo-fingerprint/upstream-files.json +37 -0
@@ -1,9 +1,36 @@
1
1
  import Foundation
2
2
  import React
3
+ import UIKit
3
4
 
4
5
  @objc(BundleDropModule)
5
6
  final class BundleDropModule: NSObject {
6
7
 
8
+ private var startupContentObserver: NSObjectProtocol?
9
+
10
+ @objc weak var bridge: RCTBridge?
11
+
12
+ deinit {
13
+ if let startupContentObserver { NotificationCenter.default.removeObserver(startupContentObserver) }
14
+ }
15
+
16
+ private func observeStartupContentIfNeeded() {
17
+ guard startupContentObserver == nil,
18
+ let bridge,
19
+ let url = BundleDropStartupRecoveryAdapter.bundleURL(from: bridge),
20
+ let viewRegistry = bridge.uiManager else { return }
21
+ startupContentObserver = BundleDropStartupRecoveryAdapter.observeRuntimeContent(
22
+ bundleURL: url,
23
+ currentContentRoot: { [weak viewRegistry] in
24
+ guard let viewRegistry else { return nil }
25
+ return BundleDropReactContent.currentRoot(in: viewRegistry)
26
+ },
27
+ ownsRoot: { [weak viewRegistry] root in
28
+ guard let viewRegistry else { return false }
29
+ return BundleDropReactContent.ownsRoot(root, in: viewRegistry)
30
+ }
31
+ )
32
+ }
33
+
7
34
  private static var isReloading = false
8
35
  private static let fm = FileManager.default
9
36
  private static let fileOpsQueue = DispatchQueue(label: "com.bundledrop.file-ops", qos: .userInitiated)
@@ -150,24 +177,13 @@ final class BundleDropModule: NSObject {
150
177
  return
151
178
  }
152
179
 
153
- guard let stagedURL = BundleDropStartupRecoveryAdapter.downloadedBundleURL() else {
154
- print("⚠️ No downloaded bundle found; skipping restart.")
155
- return
156
- }
157
-
158
- let size = BundleDropLocatorCore.fileSize(at: stagedURL)
159
- if size < 1024 {
160
- print("⚠️ Bundle exists but looks invalid (size=\(size)). Skipping restart.")
161
- return
162
- }
163
-
164
180
  guard let url = BundleDropStartupRecoveryAdapter.beginReload() else {
165
- print("⚠️ Downloaded bundle became unavailable; skipping restart.")
181
+ print("⚠️ No validated reload target; skipping restart.")
166
182
  return
167
183
  }
168
184
 
169
185
  Self.isReloading = true
170
- print("🔄 Restarting RN from \(url.path) size=\(size)")
186
+ print("🔄 Restarting RN from \(url.path)")
171
187
 
172
188
  RCTReloadCommandSetBundleURL(url)
173
189
  RCTTriggerReloadCommandListeners("bundle-drop-restart")
@@ -182,6 +198,7 @@ final class BundleDropModule: NSObject {
182
198
 
183
199
  @objc
184
200
  func constantsToExport() -> [String: Any] {
201
+ observeStartupContentIfNeeded()
185
202
  let fm = FileManager.default
186
203
  let docs = fm.urls(for: .documentDirectory, in: .userDomainMask).first?.path ?? ""
187
204
  let lib = fm.urls(for: .libraryDirectory, in: .userDomainMask).first?.path ?? ""
@@ -190,6 +207,7 @@ final class BundleDropModule: NSObject {
190
207
  "DocumentDirectoryPath": docs,
191
208
  "LibraryDirectoryPath": lib,
192
209
  "startupRecoveryProtocolVersion": BundleDropStartupRecoveryAdapter.protocolVersion,
210
+ "nativeRuntimeVersion": BundleDropLocatorCore.getRuntimeVersion() ?? NSNull(),
193
211
  "startupRecoverySelectedHash": BundleDropStartupRecoveryAdapter.capturedSelectedHash() ?? NSNull(),
194
212
  "startupRecoveryAttemptHash": attempt.hash ?? NSNull(),
195
213
  "startupRecoveryAttemptId": attempt.attemptId ?? NSNull(),
@@ -0,0 +1,54 @@
1
+ import Foundation
2
+ import React
3
+ import UIKit
4
+
5
+ /// Checks rendered views against the registry owned by one React runtime.
6
+ enum BundleDropReactContent {
7
+ static func ownsRoot(_ object: AnyObject, in registry: RCTUIManager) -> Bool {
8
+ guard let root = object as? UIView,
9
+ rootClasses.contains(where: { root.isKind(of: $0) }),
10
+ let view = registeredView(root, in: registry),
11
+ !view.subviews.isEmpty else { return false }
12
+ // Fabric reports its component; legacy reports the enclosing RCTRootView.
13
+ return view === root || view.superview === root
14
+ }
15
+
16
+ static func currentRoot(in registry: RCTUIManager) -> UIView? {
17
+ dispatchPrecondition(condition: .onQueue(.main))
18
+ // Lazy routes can import the SDK after the root's one-time content event.
19
+ // Require both a mounted root and a child registered to this same runtime.
20
+ var windows = UIApplication.shared.connectedScenes
21
+ .compactMap { $0 as? UIWindowScene }
22
+ .flatMap(\.windows)
23
+ if windows.isEmpty { windows = UIApplication.shared.windows }
24
+ var pending: [UIView] = windows
25
+ while let view = pending.popLast() {
26
+ if view.window != nil,
27
+ rootClasses.contains(where: { view.isKind(of: $0) }),
28
+ registeredView(view, in: registry) === view,
29
+ hasRegisteredChild(view, in: registry) {
30
+ return view
31
+ }
32
+ pending.append(contentsOf: view.subviews)
33
+ }
34
+ return nil
35
+ }
36
+
37
+ private static var rootClasses: [AnyClass] {
38
+ ["RCTRootComponentView", "RCTRootContentView", "RCTRootView"].compactMap(NSClassFromString)
39
+ }
40
+
41
+ private static func hasRegisteredChild(_ root: UIView, in registry: RCTUIManager) -> Bool {
42
+ var pending = root.subviews
43
+ while let view = pending.popLast() {
44
+ if registeredView(view, in: registry) === view { return true }
45
+ pending.append(contentsOf: view.subviews)
46
+ }
47
+ return false
48
+ }
49
+
50
+ private static func registeredView(_ view: UIView, in registry: RCTUIManager) -> UIView? {
51
+ guard let tag = view.reactTag ?? (view.tag > 0 ? NSNumber(value: view.tag) : nil) else { return nil }
52
+ return registry.view(forReactTag: tag)
53
+ }
54
+ }
@@ -124,6 +124,9 @@ final class BundleDropStartupRecoveryController {
124
124
  private let makeId: () -> String
125
125
  private let failpoint: Failpoint?
126
126
  private let lock = NSRecursiveLock()
127
+ // Process-local and tied to the exact committed rollback. A missing pointer
128
+ // alone must never authorize switching a running React instance to embedded.
129
+ private var embeddedReloadRevision: Int?
127
130
 
128
131
  private var ledgerURL: URL {
129
132
  bundleDropRoot.appendingPathComponent("recovery-ledger.json")
@@ -522,6 +525,38 @@ final class BundleDropStartupRecoveryController {
522
525
  }
523
526
  }
524
527
 
528
+ func prepareReload(embeddedBundleURL: URL?) -> (url: URL, selection: BundleDropStartupSelection)? {
529
+ withLock {
530
+ guard hasExpectedIdentity else { return nil }
531
+ if let current = passiveCurrentBundle() {
532
+ embeddedReloadRevision = nil
533
+ guard BundleDropLocatorCore.fileSize(at: current) >= 1024 else { return nil }
534
+ let selection = selectStartupBundle(beginReload: true)
535
+ guard let url = selection.bundleURL else { return nil }
536
+ return (url, selection)
537
+ }
538
+
539
+ guard let revision = embeddedReloadRevision,
540
+ let ledger = try? readLedgerFromDisk(),
541
+ ledger.revision == revision,
542
+ ledger.phase == .idle,
543
+ ledger.pendingTransition == nil,
544
+ ledger.binaryIdentity == expectedBinaryIdentity,
545
+ ledger.runtimeIdentity == expectedRuntimeVersion,
546
+ !fileManager.fileExists(atPath: bundleDropRoot.appendingPathComponent("current.json").path)
547
+ else {
548
+ embeddedReloadRevision = nil
549
+ return nil
550
+ }
551
+ guard let embeddedBundleURL else { return nil }
552
+ embeddedReloadRevision = nil
553
+ return (
554
+ embeddedBundleURL,
555
+ BundleDropStartupSelection(bundleURL: nil, attemptHash: nil, attemptId: nil)
556
+ )
557
+ }
558
+ }
559
+
525
560
  func setRevokedHashes(_ hashes: [String]) throws {
526
561
  try withLock {
527
562
  guard hashes.allSatisfy(Self.isCanonicalHash) else {
@@ -549,6 +584,8 @@ final class BundleDropStartupRecoveryController {
549
584
  func rollback(forceEmbedded: Bool) throws -> BundleDropStartupRollbackResult {
550
585
  try withLock {
551
586
  var ledger = try readLedgerImportingLegacyState()
587
+ let continuingEmbeddedReload = embeddedReloadRevision == ledger.revision
588
+ embeddedReloadRevision = nil
552
589
  let current = BundleDropOtaResolver.readPointer(
553
590
  named: "current.json",
554
591
  bundleDropRoot: bundleDropRoot,
@@ -578,10 +615,16 @@ final class BundleDropStartupRecoveryController {
578
615
  try commit(&ledger)
579
616
  try failpoint?("afterRollbackPrepared")
580
617
  try completePendingTransition(ledger: &ledger)
618
+ // Transition completion can reject a previous bundle that changed after
619
+ // preparation. Report and authorize only the destination actually committed.
620
+ let committedHash = ledger.stableHash
621
+ if committedHash == nil, current != nil || continuingEmbeddedReload {
622
+ embeddedReloadRevision = ledger.revision
623
+ }
581
624
  return BundleDropStartupRollbackResult(
582
625
  rolledBack: current != nil,
583
- toEmbedded: fallback == nil,
584
- hash: fallback?.hash
626
+ toEmbedded: committedHash == nil,
627
+ hash: committedHash
585
628
  )
586
629
  }
587
630
  }
@@ -688,6 +731,9 @@ final class BundleDropStartupRecoveryController {
688
731
  ledger.stableHash = nil
689
732
  ledger.previousStableHash = nil
690
733
  ledger.pendingTransition = transition
734
+ if transition.kind == "rollback" {
735
+ ledger.phase = .idle
736
+ }
691
737
  if transition.kind == "recovery",
692
738
  let eventIndex = ledger.pendingRecoveryEvents.lastIndex(where: {
693
739
  $0.recoveryTarget == "previous" && $0.recoveredHash == targetHash
@@ -46,11 +46,15 @@ enum BundleDropStartupRecoveryAdapter {
46
46
  }
47
47
 
48
48
  static func beginReload() -> URL? {
49
- guard let controller = defaultController() else { return nil }
49
+ guard BundleDropLocatorCore.hasRuntimeIdentityForOta(),
50
+ BundleDropLocatorCore.isOtaEnabled(),
51
+ let controller = defaultController(),
52
+ let reload = controller.prepareReload(
53
+ embeddedBundleURL: BundleDropLocatorCore.embeddedBundleURL()
54
+ ) else { return nil }
50
55
  installReactLifecycleObservers()
51
- let selection = controller.selectStartupBundle(beginReload: true)
52
- captureStartupSelection(selection)
53
- return selection.bundleURL
56
+ captureStartupSelection(reload.selection)
57
+ return reload.url
54
58
  }
55
59
 
56
60
  static func markHealthy(hash: String, attemptId: String) -> Bool {
@@ -76,6 +80,7 @@ enum BundleDropStartupRecoveryAdapter {
76
80
  static func rollback(forceEmbedded: Bool) throws -> BundleDropStartupRollbackResult {
77
81
  let result = try requireDefaultController().rollback(forceEmbedded: forceEmbedded)
78
82
  clearCapturedAttempt()
83
+ contentBindings.capture(hash: nil, attemptId: nil, bundleURL: nil)
79
84
  return result
80
85
  }
81
86
 
@@ -160,6 +165,33 @@ enum BundleDropStartupRecoveryAdapter {
160
165
  lock.unlock()
161
166
  }
162
167
 
168
+ static func observeRuntimeContent(
169
+ bundleURL: URL,
170
+ currentContentRoot: @escaping () -> AnyObject? = { nil },
171
+ ownsRoot: @escaping (AnyObject) -> Bool
172
+ ) -> NSObjectProtocol? {
173
+ contentBindings.observeRuntimeContent(
174
+ bundleURL: bundleURL, currentContentRoot: currentContentRoot, ownsRoot: ownsRoot
175
+ ) { attempt in
176
+ contentAppeared(attempt)
177
+ }
178
+ }
179
+
180
+ private static func contentAppeared(_ attempt: BundleDropStartupContentBindings.Binding) {
181
+ guard let delay = defaultController()?.markContentAppeared(
182
+ hash: attempt.hash,
183
+ attemptId: attempt.attemptId
184
+ ) else { return }
185
+ let markHealthy = {
186
+ _ = BundleDropStartupRecoveryAdapter.markHealthy(hash: attempt.hash, attemptId: attempt.attemptId)
187
+ }
188
+ if delay <= 0 {
189
+ markHealthy()
190
+ } else {
191
+ DispatchQueue.main.asyncAfter(deadline: .now() + delay, execute: markHealthy)
192
+ }
193
+ }
194
+
163
195
  private static func installReactLifecycleObservers() {
164
196
  lock.lock()
165
197
  guard !observersInstalled else {
@@ -183,41 +215,25 @@ enum BundleDropStartupRecoveryAdapter {
183
215
  queue: nil
184
216
  ) { notification in
185
217
  guard let attempt = contentBindings.binding(for: notification.object) else { return }
186
- let hash = attempt.hash
187
- let attemptId = attempt.attemptId
188
- guard let delay = defaultController()?.markContentAppeared(
189
- hash: hash,
190
- attemptId: attemptId
191
- ) else { return }
192
- let markHealthy = {
193
- _ = BundleDropStartupRecoveryAdapter.markHealthy(hash: hash, attemptId: attemptId)
194
- }
195
- if delay <= 0 {
196
- markHealthy()
197
- } else {
198
- DispatchQueue.main.asyncAfter(deadline: .now() + delay, execute: markHealthy)
199
- }
218
+ contentAppeared(attempt)
200
219
  }
201
220
  }
202
221
 
203
222
  static func bundleURL(from notification: Notification) -> URL? {
204
- let selector = NSSelectorFromString("bundleURL")
205
223
  let providers = [notification.userInfo?["bridge"], notification.object].compactMap { $0 }
206
224
  for provider in providers {
207
- let object = provider as AnyObject
208
- // RCTBridgeProxy forwards -bundleURL but reports responds(to:) as false.
209
- // Checking the concrete Objective-C implementation keeps URL identity
210
- // available in bridgeless RN without accepting an anonymous global event.
211
- guard object.responds(to: selector) ||
212
- class_getInstanceMethod(type(of: object), selector) != nil else {
213
- continue
214
- }
215
- if let url = object.perform(selector)?.takeUnretainedValue() as? URL {
216
- return url
217
- }
225
+ if let url = bundleURL(from: provider as AnyObject) { return url }
218
226
  }
219
227
  return nil
220
228
  }
229
+
230
+ static func bundleURL(from provider: AnyObject) -> URL? {
231
+ let selector = NSSelectorFromString("bundleURL")
232
+ // RCTBridgeProxy implements -bundleURL but can deny responds(to:).
233
+ guard provider.responds(to: selector) ||
234
+ class_getInstanceMethod(type(of: provider), selector) != nil else { return nil }
235
+ return provider.perform(selector)?.takeUnretainedValue() as? URL
236
+ }
221
237
  }
222
238
 
223
239
  /// Associates each React root with the startup attempt that selected its runtime.
@@ -246,6 +262,7 @@ final class BundleDropStartupContentBindings {
246
262
  private var generation: UInt64 = 0
247
263
  private var activeBinding: Binding?
248
264
  private var activeRuntimeLoaded = false
265
+ private var runtimeOwnedGeneration: UInt64?
249
266
  private var roots: [ObjectIdentifier: RootEntry] = [:]
250
267
 
251
268
  func capture(hash: String?, attemptId: String?, bundleURL: URL?) {
@@ -263,6 +280,7 @@ final class BundleDropStartupContentBindings {
263
280
  activeBinding = nil
264
281
  }
265
282
  activeRuntimeLoaded = false
283
+ runtimeOwnedGeneration = nil
266
284
  roots = roots.filter { $0.value.root != nil }
267
285
  }
268
286
 
@@ -286,6 +304,9 @@ final class BundleDropStartupContentBindings {
286
304
  let rootObject = root as AnyObject
287
305
  lock.lock()
288
306
  defer { lock.unlock() }
307
+ // Once a module supplies its own root registry, the global legacy observer
308
+ // must not bypass that runtime ownership check.
309
+ if let activeBinding, runtimeOwnedGeneration == activeBinding.generation { return nil }
289
310
  let identifier = ObjectIdentifier(rootObject)
290
311
  if let existing = roots[identifier], existing.root === rootObject {
291
312
  return existing.binding
@@ -295,6 +316,42 @@ final class BundleDropStartupContentBindings {
295
316
  return activeBinding
296
317
  }
297
318
 
319
+ func observeRuntimeContent(
320
+ bundleURL: URL,
321
+ notificationCenter: NotificationCenter = .default,
322
+ currentContentRoot: @escaping () -> AnyObject? = { nil },
323
+ ownsRoot: @escaping (AnyObject) -> Bool,
324
+ contentAppeared: @escaping (Binding) -> Void
325
+ ) -> NSObjectProtocol? {
326
+ lock.lock()
327
+ guard let attempt = activeBinding,
328
+ Self.normalizedPath(bundleURL) == attempt.bundlePath else {
329
+ lock.unlock()
330
+ return nil
331
+ }
332
+ runtimeOwnedGeneration = attempt.generation
333
+ lock.unlock()
334
+ // Capture the attempt, not mutable global selection. An old module can
335
+ // only report its old attempt, which the ledger rejects after a reload.
336
+ let deliver: (AnyObject) -> Void = { root in
337
+ guard ownsRoot(root) else { return }
338
+ contentAppeared(attempt)
339
+ }
340
+ let observer = notificationCenter.addObserver(
341
+ forName: Notification.Name("RCTContentDidAppearNotification"),
342
+ object: nil,
343
+ queue: .main
344
+ ) { notification in
345
+ guard let root = notification.object else { return }
346
+ deliver(root as AnyObject)
347
+ }
348
+ DispatchQueue.main.async {
349
+ guard let root = currentContentRoot() else { return }
350
+ deliver(root)
351
+ }
352
+ return observer
353
+ }
354
+
298
355
  private static func normalizedPath(_ url: URL) -> String {
299
356
  url.standardizedFileURL.resolvingSymlinksInPath().path
300
357
  }
package/lib/CLI/cli.js CHANGED
@@ -145,12 +145,21 @@ ${chalk_1.default.bold('Examples:')}
145
145
  ${chalk_1.default.gray('bundle-drop sight --compare origin/main --fetch --include .env.production')}
146
146
  `)
147
147
  .action(sight_cli_1.runSightCommand);
148
+ program
149
+ .command('fingerprint')
150
+ .requiredOption('--platform <platform>', 'Platform to inspect: ios or android')
151
+ .option('--output <path>', 'Write the source digest report')
152
+ .option('--compare <path>', 'Compare sources with a previous report')
153
+ .option('--json', 'Print the report as JSON')
154
+ .description('Inspect scheme-1 native runtime fingerprint inputs')
155
+ .action(options => require('./scripts/fingerprint-cli').runFingerprintCli(options));
148
156
  program
149
157
  .command('upload <platform>')
150
158
  .helpGroup('Releases:')
151
159
  .option('--plist-file <path>', 'Path to Info.plist for iOS')
152
160
  .option('--version <version>', 'App version. iOS will fallback to --plist-file; Android can fallback to build.gradle when provided.')
153
161
  .option('--buildgradle-path <path>', 'Optional Android build.gradle path to read versionName')
162
+ .option('--build-number <number>', 'Optional Android versionCode or iOS build number for upload metadata')
154
163
  .option('--channel <name>', 'Target channel name to associate the bundle')
155
164
  .option('--release-notes <text>', 'Release notes (max 2000 chars)')
156
165
  .option('--release-notes-file <path>', 'Read UTF-8 release notes from a file (max 2000 chars)')
@@ -269,10 +269,21 @@ async function inspectExpoProject(projectRoot, platforms) {
269
269
  ? 'Existing Expo Metro configuration is preserved through withBundleDropExpo.'
270
270
  : metro.issue || 'Metro must export withBundleDropExpo(...) and preserve expo/metro-config.',
271
271
  });
272
- const runtimeAuthorities = new Map(platforms.map(platform => [
273
- platform,
274
- (0, expo_1.resolveBundleDropRuntimeVersionAuthority)(projectRoot, platform),
275
- ]));
272
+ let runtimeAuthorities;
273
+ try {
274
+ runtimeAuthorities = new Map(platforms.map(platform => [
275
+ platform,
276
+ (0, expo_1.resolveBundleDropRuntimeVersionAuthority)(projectRoot, platform),
277
+ ]));
278
+ }
279
+ catch (error) {
280
+ checks.push({
281
+ name: 'Runtime authority',
282
+ status: 'error',
283
+ message: error.message,
284
+ });
285
+ return checks;
286
+ }
276
287
  const usesExpoRuntimePolicies = [...runtimeAuthorities.values()]
277
288
  .some(authority => authority.source === 'expo');
278
289
  const identities = new Map();
@@ -283,7 +294,7 @@ async function inspectExpoProject(projectRoot, platforms) {
283
294
  checks.push({
284
295
  name: `${platform} build identity`,
285
296
  status: 'pass',
286
- message: `${runtimeAuthorities.get(platform)?.source === 'expo' ? 'Expo policy' : 'Bundle Drop literal'} ` +
297
+ message: `${runtimeAuthorities.get(platform)?.source === 'expo' ? 'Expo policy' : 'Bundle Drop runtime'} ` +
287
298
  `resolved to ${identity.runtimeVersion}; ` +
288
299
  `${identity.javaScriptEngine}, Expo ${identity.expoSdkVersion}, RN ${identity.reactNativeVersion}.`,
289
300
  });
@@ -402,13 +413,13 @@ const checkBareRuntimeIdentity = (projectRoot, platform) => {
402
413
  return {
403
414
  name: `${platform} runtime identity`,
404
415
  status: 'error',
405
- message: 'Bare projects require a literal Bundle Drop runtime version, not Expo runtime authority.',
416
+ message: 'Bare projects require Bundle Drop runtime authority, not Expo runtime authority.',
406
417
  };
407
418
  }
408
419
  return {
409
420
  name: `${platform} runtime identity`,
410
421
  status: 'pass',
411
- message: `Bundle Drop literal resolved to ${authority.runtimeVersion}.`,
422
+ message: `Bundle Drop runtime resolved to ${authority.runtimeVersion}.`,
412
423
  };
413
424
  }
414
425
  catch (error) {
@@ -19,7 +19,10 @@ var projectType_2 = require("../../../expo/projectType");
19
19
  Object.defineProperty(exports, "setBundleDropProjectType", { enumerable: true, get: function () { return projectType_2.setBundleDropProjectType; } });
20
20
  const PACKAGE_NAME = '@gfean/react-native-bundle-drop';
21
21
  const EXPO_UPDATES = 'expo-updates';
22
- const TRANSIENT_GRADLE_KOTLIN_FINGERPRINT_PATTERN = '**/*-gradle-plugin/.kotlin/**/*';
22
+ const TRANSIENT_GRADLE_KOTLIN_FINGERPRINT_PATTERNS = [
23
+ '**/*-gradle-plugin/.kotlin/**/*',
24
+ '**/android/.kotlin/**/*',
25
+ ];
23
26
  const EXPO_RUNTIME_SOURCE_PATTERN = /runtimeVersion\s*:\s*\{\s*source\s*:\s*['"]expo['"]\s*\}/;
24
27
  const sha256 = (content) => crypto_1.default.createHash('sha256').update(content).digest('hex');
25
28
  const configPluginName = (plugin) => {
@@ -159,13 +162,15 @@ function planExpoProjectConfiguration(params) {
159
162
  }
160
163
  const fingerprintIgnoreFile = (0, safe_file_transaction_1.inspectProjectFile)(params.projectRoot, '.fingerprintignore');
161
164
  const fingerprintIgnore = fingerprintIgnoreFile.exists ? fingerprintIgnoreFile.content : '';
165
+ const existingFingerprintPatterns = fingerprintIgnore.split(/\r?\n/).map(line => line.trim());
166
+ const missingFingerprintPatterns = TRANSIENT_GRADLE_KOTLIN_FINGERPRINT_PATTERNS.filter(pattern => !existingFingerprintPatterns.includes(pattern));
162
167
  if (EXPO_RUNTIME_SOURCE_PATTERN.test(updatedBundleConfig) &&
163
- !fingerprintIgnore.split(/\r?\n/).includes(TRANSIENT_GRADLE_KOTLIN_FINGERPRINT_PATTERN)) {
168
+ missingFingerprintPatterns.length > 0) {
164
169
  changes.push({
165
170
  file: '.fingerprintignore',
166
171
  original: fingerprintIgnoreFile.exists ? fingerprintIgnore : null,
167
172
  updated: `${fingerprintIgnore.trimEnd()}${fingerprintIgnore.trim() ? '\n' : ''}` +
168
- `${TRANSIENT_GRADLE_KOTLIN_FINGERPRINT_PATTERN}\n`,
173
+ `${missingFingerprintPatterns.join('\n')}\n`,
169
174
  reason: 'Exclude transient Gradle Kotlin compiler sessions from Expo runtime fingerprints.',
170
175
  });
171
176
  }
@@ -0,0 +1,12 @@
1
+ import type { NativeFingerprint } from '../../fingerprint/types';
2
+ export declare function compareFingerprintSources(before: NativeFingerprint, after: NativeFingerprint): {
3
+ id: string;
4
+ before: string;
5
+ after: string;
6
+ }[];
7
+ export declare function runFingerprintCli(options: {
8
+ platform: string;
9
+ output?: string;
10
+ compare?: string;
11
+ json?: boolean;
12
+ }): NativeFingerprint;
@@ -0,0 +1,36 @@
1
+ "use strict";
2
+ var __importDefault = (this && this.__importDefault) || function (mod) {
3
+ return (mod && mod.__esModule) ? mod : { "default": mod };
4
+ };
5
+ Object.defineProperty(exports, "__esModule", { value: true });
6
+ exports.compareFingerprintSources = compareFingerprintSources;
7
+ exports.runFingerprintCli = runFingerprintCli;
8
+ const fs_1 = __importDefault(require("fs"));
9
+ const path_1 = __importDefault(require("path"));
10
+ const client_1 = require("../../fingerprint/client");
11
+ function compareFingerprintSources(before, after) {
12
+ if (!Array.isArray(before.sources) || !Array.isArray(after.sources))
13
+ throw new Error('Invalid fingerprint report.');
14
+ const oldSources = new Map(before.sources.map(source => [`${source.type}:${source.id}`, source.hash]));
15
+ const newSources = new Map(after.sources.map(source => [`${source.type}:${source.id}`, source.hash]));
16
+ return [...new Set([...oldSources.keys(), ...newSources.keys()])].sort()
17
+ .filter(id => (oldSources.get(id) ?? null) !== (newSources.get(id) ?? null))
18
+ .map(id => ({ id, before: oldSources.get(id) ?? null, after: newSources.get(id) ?? null }));
19
+ }
20
+ function runFingerprintCli(options) {
21
+ if (options.platform !== 'ios' && options.platform !== 'android')
22
+ throw new Error('Fingerprint platform must be ios or android.');
23
+ const report = (0, client_1.calculateFingerprintSync)(process.cwd(), options.platform);
24
+ if (options.output) {
25
+ const outputPath = path_1.default.resolve(options.output);
26
+ fs_1.default.mkdirSync(path_1.default.dirname(outputPath), { recursive: true });
27
+ fs_1.default.writeFileSync(outputPath, `${JSON.stringify(report, null, 2)}\n`);
28
+ }
29
+ const changes = options.compare
30
+ ? compareFingerprintSources(JSON.parse(fs_1.default.readFileSync(path_1.default.resolve(options.compare), 'utf8')), report)
31
+ : undefined;
32
+ console.log(options.json ? JSON.stringify({ ...report, ...(changes ? { changes } : {}) })
33
+ : `${report.runtimeVersion}\nScheme 1; calculation contract frozen.` +
34
+ (changes ? `\n${JSON.stringify(changes, null, 2)}` : ''));
35
+ return report;
36
+ }
@@ -50,7 +50,9 @@ function writeNativeRuntimeIdentity(options) {
50
50
  const identity = resolveNativeRuntimeIdentity(options.projectRoot, options.platform);
51
51
  const content = `${JSON.stringify(identity)}\n`;
52
52
  if (options.outputPath) {
53
- writeAtomically(options.outputPath, content);
53
+ if (!fs_extra_1.default.existsSync(options.outputPath) || fs_extra_1.default.readFileSync(options.outputPath, 'utf8') !== content) {
54
+ writeAtomically(options.outputPath, content);
55
+ }
54
56
  }
55
57
  return identity;
56
58
  }
@@ -16,6 +16,8 @@ const canonicalArtifact_1 = require("../../scripts/canonicalArtifact");
16
16
  const bundle_1 = require("../../scripts/bundle");
17
17
  const process_1 = require("./sight-compare/process");
18
18
  const assets_1 = require("./sight-compare/assets");
19
+ const config_1 = require("../../fingerprint/config");
20
+ const client_1 = require("../../fingerprint/client");
19
21
  const HERMES_MAGIC = Buffer.from([0xc6, 0x1f, 0xbc, 0x03, 0xc1, 0x03, 0x19, 0x1f]);
20
22
  const unavailable = (reason) => ({ status: 'unavailable', reason });
21
23
  function insideSnapshot(options, candidate) {
@@ -137,16 +139,23 @@ async function measureInstalledSightOta(options) {
137
139
  if (!fs_1.default.existsSync(configPath))
138
140
  return unavailable('This project has no bundle.drop.config.js. Configure Bundle Drop to measure its OTA archive.');
139
141
  const config = (0, module_1.createRequire)(path_1.default.join(options.projectRoot, 'package.json'))(insideSnapshot(options, configPath));
140
- const runtime = config.runtimeVersion?.[options.platform];
141
- if (typeof runtime !== 'string' || !runtime.trim()) {
142
+ const runtimeConfig = config.runtimeVersion;
143
+ const runtime = runtimeConfig?.[options.platform];
144
+ if (!runtimeConfig?.source && runtimeConfig?.compatibilitySource !== 'fingerprint' && (typeof runtime !== 'string' || !runtime.trim())) {
142
145
  return unavailable(`Bundle Drop has no runtime version configured for ${options.platform}. Set runtimeVersion.${options.platform} in bundle.drop.config.js.`);
143
146
  }
147
+ const selection = (0, config_1.selectRuntimeVersion)(runtimeConfig, options.platform);
148
+ if (selection.source === 'expo')
149
+ return unavailable('Bare projects cannot delegate runtime identity to Expo.');
150
+ reason = `Native fingerprint collection failed for ${options.platform} OTA packaging.`;
151
+ runtimeVersion = selection.source === 'fingerprint'
152
+ ? (0, client_1.calculateFingerprintSync)(options.projectRoot, options.platform).runtimeVersion
153
+ : selection.runtimeVersion;
144
154
  reason = `The native ${options.platform} app version could not be resolved unambiguously for Bundle Drop OTA packaging.`;
145
155
  const version = await bareAppVersion(options);
146
156
  if (!version)
147
157
  return unavailable(reason);
148
158
  appVersion = version;
149
- runtimeVersion = runtime;
150
159
  hermes = (0, bundle_1.shouldCompileHermesBytecode)(config, options.platform, options.projectRoot, options.snapshotRoot);
151
160
  }
152
161
  const bundlePath = path_1.default.join(options.workDirectory, 'main.jsbundle');
@@ -12,6 +12,7 @@ type UploadOptions = {
12
12
  sourcemap?: boolean;
13
13
  artifactDir?: string;
14
14
  buildReceipt?: string;
15
+ buildNumber?: string;
15
16
  };
16
17
  type UploadDependencies = {
17
18
  packageRoot: string;