package com.contentsquare.rn import com.facebook.react.bridge.Dynamic import com.facebook.react.bridge.ReactApplicationContext import com.facebook.react.bridge.ReactContextBaseJavaModule import com.facebook.react.bridge.ReactMethod import com.facebook.react.bridge.ReadableMap import com.facebook.react.bridge.Promise import com.facebook.react.bridge.WritableMap import com.facebook.react.modules.core.DeviceEventManagerModule import com.contentsquare.rn.csq.HeapAutocaptureWrapperImpl import com.contentsquare.rn.csq.InvocationEventEmitter class HeapReactNativeBridgeModule(reactContext: ReactApplicationContext) : ReactContextBaseJavaModule(reactContext), InvocationEventEmitter { private var listenerCount = 0 private val heapWrapper = HeapAutocaptureWrapperImpl(reactContext, this) override fun getName(): String { return NAME } companion object { const val NAME = "HeapReactNativeBridgeModule" } @ReactMethod fun handleInvocation(method: String, arguments: ReadableMap, promise: Promise) { heapWrapper.handleInvocation(method, arguments, promise) } @ReactMethod fun handleResult(callbackId: String, data: Dynamic?, error: String?) { heapWrapper.handleResult(callbackId, data, error) } @ReactMethod @Suppress("UNUSED_PARAMETER") fun addListener(eventName: String) { listenerCount += 1 heapWrapper.onListenerAdded() } @ReactMethod fun removeListeners(count: Int) { listenerCount -= count heapWrapper.onListenersRemoved(count) } /** * Implementation of InvocationEventEmitter. * Emits invocation events to JavaScript using the old architecture event system. */ override fun sendInvocationEvent(payload: WritableMap) { if (listenerCount == 0) { // Throw exception so CSQAutocapture can handle the error throw IllegalStateException("Bridge has no listeners.") } try { reactApplicationContext .getJSModule(DeviceEventManagerModule.RCTDeviceEventEmitter::class.java) .emit("Invocation", payload) } catch (t: Throwable) { // Event emission failed, rethrow so CSQAutocapture can handle it throw t } } }