nitro icon indicating copy to clipboard operation
nitro copied to clipboard

HybridObject constructors are not constructors on Expo

Open vexcited opened this issue 1 year ago • 8 comments

What's happening?

I wanted to export a HybridObject constructor in my library and use it on another app written with Expo and for some reason I get TypeError: Function is not a constructor when trying to instantiate the hybrid object.

Even though, on a bare React Native project the issue does not happen, thus it also doesn't happen in the example app given in this repository.

Calling DuplexStream() instead of new DuplexStream() does fix the issue but now we got typings issues since it should be a constructor!

Reproduceable Code

// HybridDuplexStream.swift
import Foundation

class HybridDuplexStream: HybridDuplexStreamSpec {
  private static let bufferSize = 64 * 1024

  var inputStream: (any HybridInputStreamSpec)
  var outputStream: (any HybridOutputStreamSpec)

  override init() {
    var inputStreamRef: InputStream?
    var outputStreamRef: OutputStream?

    Stream.getBoundStreams(
      withBufferSize: HybridDuplexStream.bufferSize,
      inputStream: &inputStreamRef,
      outputStream: &outputStreamRef)

    guard let inputStreamRef, let outputStreamRef else {
      fatalError("Could not create streams")
    }

    inputStream = HybridInputStream(stream: inputStreamRef)
    outputStream = HybridOutputStream(stream: outputStreamRef)
  }
}

// streams.nitro.ts
import { getHybridObjectConstructor } from 'react-native-nitro-modules';
export const DuplexStream = getHybridObjectConstructor<DuplexStream>('DuplexStream');

// index.ts
const duplexStream = new DuplexStream();
                     ^^^ TypeError: Function is not a constructor

// --- For example, it happens in https://github.com/Vexcited/react-native-real-fetch/tree/main/examples/expo-app because it's an Expo app (nothing fancy, just ran the official initialization command)
// --- Even though, in a bare project such as https://github.com/Vexcited/react-native-real-fetch/tree/main/examples/bare it does work!

Relevant log output

There's really nothing in Xcode or Android Studio, it's really only happening in the JS runtime.

TypeError: Function is not a constructor
    at fromReadableStream (http://localhost:8081/package/src/index.bundle//&platform=ios&lazy=true&inlineSourceMap=false&modulesOnly=true&sourcePaths=url-server&app=ios.fetch.demo&transform.routerRoot=app&transform.engine=hermes&transform.bytecode=1&unstable_transformProfile=hermes-stable&dev=true&minify=false&runModule=true&shallow=true:49:49)
    at ?anon_0_ (http://localhost:8081/package/src/index.bundle//&platform=ios&lazy=true&inlineSourceMap=false&modulesOnly=true&sourcePaths=url-server&app=ios.fetch.demo&transform.routerRoot=app&transform.engine=hermes&transform.bytecode=1&unstable_transformProfile=hermes-stable&dev=true&minify=false&runModule=true&shallow=true:114:48)
    at next (native)
    at asyncGeneratorStep (http://localhost:8081/node_modules/expo-router/entry.bundle//&platform=ios&dev=true&lazy=true&minify=false&inlineSourceMap=false&modulesOnly=false&runModule=true&excludeSource=true&sourcePaths=url-server&app=ios.fetch.demo&transform.routerRoot=app&transform.engine=hermes&transform.bytecode=1&unstable_transformProfile=hermes-stable:9065:19)
    at _next (http://localhost:8081/node_modules/expo-router/entry.bundle//&platform=ios&dev=true&lazy=true&minify=false&inlineSourceMap=false&modulesOnly=false&runModule=true&excludeSource=true&sourcePaths=url-server&app=ios.fetch.demo&transform.routerRoot=app&transform.engine=hermes&transform.bytecode=1&unstable_transformProfile=hermes-stable:9079:29)
    at anonymous (http://localhost:8081/node_modules/expo-router/entry.bundle//&platform=ios&dev=true&lazy=true&minify=false&inlineSourceMap=false&modulesOnly=false&runModule=true&excludeSource=true&sourcePaths=url-server&app=ios.fetch.demo&transform.routerRoot=app&transform.engine=hermes&transform.bytecode=1&unstable_transformProfile=hermes-stable:9084:14)
    at tryCallTwo (address at InternalBytecode.js:1:1222)
    at doResolve (address at InternalBytecode.js:1:2541)
    at Promise (address at InternalBytecode.js:1:1318)
    at anonymous (http://localhost:8081/node_modules/expo-router/entry.bundle//&platform=ios&dev=true&lazy=true&minify=false&inlineSourceMap=false&modulesOnly=false&runModule=true&excludeSource=true&sourcePaths=url-server&app=ios.fetch.demo&transform.routerRoot=app&transform.engine=hermes&transform.bytecode=1&unstable_transformProfile=hermes-stable:9076:25)
    at apply (native)
    at _fetch (http://localhost:8081/package/src/index.bundle//&platform=ios&lazy=true&inlineSourceMap=false&modulesOnly=true&sourcePaths=url-server&app=ios.fetch.demo&transform.routerRoot=app&transform.engine=hermes&transform.bytecode=1&unstable_transformProfile=hermes-stable&dev=true&minify=false&runModule=true&shallow=true:177:24)
    at apply (native)
    at fetch (http://localhost:8081/package/src/index.bundle//&platform=ios&lazy=true&inlineSourceMap=false&modulesOnly=true&sourcePaths=url-server&app=ios.fetch.demo&transform.routerRoot=app&transform.engine=hermes&transform.bytecode=1&unstable_transformProfile=hermes-stable&dev=true&minify=false&runModule=true&shallow=true:104:24)
    at ?anon_0_ (http://localhost:8081/node_modules/expo-router/entry.bundle//&platform=ios&dev=true&lazy=true&minify=false&inlineSourceMap=false&modulesOnly=false&runModule=true&excludeSource=true&sourcePaths=url-server&app=ios.fetch.demo&transform.routerRoot=app&transform.engine=hermes&transform.bytecode=1&unstable_transformProfile=hermes-stable:160456:64)
    at next (native)
    at asyncGeneratorStep (http://localhost:8081/node_modules/expo-router/entry.bundle//&platform=ios&dev=true&lazy=true&minify=false&inlineSourceMap=false&modulesOnly=false&runModule=true&excludeSource=true&sourcePaths=url-server&app=ios.fetch.demo&transform.routerRoot=app&transform.engine=hermes&transform.bytecode=1&unstable_transformProfile=hermes-stable:9065:19)
    at _next (http://localhost:8081/node_modules/expo-router/entry.bundle//&platform=ios&dev=true&lazy=true&minify=false&inlineSourceMap=false&modulesOnly=false&runModule=true&excludeSource=true&sourcePaths=url-server&app=ios.fetch.demo&transform.routerRoot=app&transform.engine=hermes&transform.bytecode=1&unstable_transformProfile=hermes-stable:9079:29)
    at anonymous (http://localhost:8081/node_modules/expo-router/entry.bundle//&platform=ios&dev=true&lazy=true&minify=false&inlineSourceMap=false&modulesOnly=false&runModule=true&excludeSource=true&sourcePaths=url-server&app=ios.fetch.demo&transform.routerRoot=app&transform.engine=hermes&transform.bytecode=1&unstable_transformProfile=hermes-stable:9084:14)
    at tryCallTwo (address at InternalBytecode.js:1:1222)
    at doResolve (address at InternalBytecode.js:1:2541)
    at Promise (address at InternalBytecode.js:1:1318)
    at anonymous (http://localhost:8081/node_modules/expo-router/entry.bundle//&platform=ios&dev=true&lazy=true&minify=false&inlineSourceMap=false&modulesOnly=false&runModule=true&excludeSource=true&sourcePaths=url-server&app=ios.fetch.demo&transform.routerRoot=app&transform.engine=hermes&transform.bytecode=1&unstable_transformProfile=hermes-stable:9076:25)
    at apply (native)
    at handleFetch (http://localhost:8081/node_modules/expo-router/entry.bundle//&platform=ios&dev=true&lazy=true&minify=false&inlineSourceMap=false&modulesOnly=false&runModule=true&excludeSource=true&sourcePaths=url-server&app=ios.fetch.demo&transform.routerRoot=app&transform.engine=hermes&transform.bytecode=1&unstable_transformProfile=hermes-stable:160480:26)
    at _performTransitionSideEffects (http://localhost:8081/node_modules/expo-router/entry.bundle//&platform=ios&dev=true&lazy=true&minify=false&inlineSourceMap=false&modulesOnly=false&runModule=true&excludeSource=true&sourcePaths=url-server&app=ios.fetch.demo&transform.routerRoot=app&transform.engine=hermes&transform.bytecode=1&unstable_transformProfile=hermes-stable:65415:22)
    at _receiveSignal (http://localhost:8081/node_modules/expo-router/entry.bundle//&platform=ios&dev=true&lazy=true&minify=false&inlineSourceMap=false&modulesOnly=false&runModule=true&excludeSource=true&sourcePaths=url-server&app=ios.fetch.demo&transform.routerRoot=app&transform.engine=hermes&transform.bytecode=1&unstable_transformProfile=hermes-stable:65371:45)
    at onResponderRelease (http://localhost:8081/node_modules/expo-router/entry.bundle//&platform=ios&dev=true&lazy=true&minify=false&inlineSourceMap=false&modulesOnly=false&runModule=true&excludeSource=true&sourcePaths=url-server&app=ios.fetch.demo&transform.routerRoot=app&transform.engine=hermes&transform.bytecode=1&unstable_transformProfile=hermes-stable:65230:32)
    at executeDispatch (http://localhost:8081/node_modules/expo-router/entry.bundle//&platform=ios&dev=true&lazy=true&minify=false&inlineSourceMap=false&modulesOnly=false&runModule=true&excludeSource=true&sourcePaths=url-server&app=ios.fetch.demo&transform.routerRoot=app&transform.engine=hermes&transform.bytecode=1&unstable_transformProfile=hermes-stable:16578:17)
    at executeDispatchesAndReleaseTopLevel (http://localhost:8081/node_modules/expo-router/entry.bundle//&platform=ios&dev=true&lazy=true&minify=false&inlineSourceMap=false&modulesOnly=false&runModule=true&excludeSource=true&sourcePaths=url-server&app=ios.fetch.demo&transform.routerRoot=app&transform.engine=hermes&transform.bytecode=1&unstable_transformProfile=hermes-stable:16926:229)
    at forEach (native)
    at forEachAccumulated (http://localhost:8081/node_modules/expo-router/entry.bundle//&platform=ios&dev=true&lazy=true&minify=false&inlineSourceMap=false&modulesOnly=false&runModule=true&excludeSource=true&sourcePaths=url-server&app=ios.fetch.demo&transform.routerRoot=app&transform.engine=hermes&transform.bytecode=1&unstable_transformProfile=hermes-stable:16721:39)
    at anonymous (http://localhost:8081/node_modules/expo-router/entry.bundle//&platform=ios&dev=true&lazy=true&minify=false&inlineSourceMap=false&modulesOnly=false&runModule=true&excludeSource=true&sourcePaths=url-server&app=ios.fetch.demo&transform.routerRoot=app&transform.engine=hermes&transform.bytecode=1&unstable_transformProfile=hermes-stable:16955:29)
    at batchedUpdatesImpl (http://localhost:8081/node_modules/expo-router/entry.bundle//&platform=ios&dev=true&lazy=true&minify=false&inlineSourceMap=false&modulesOnly=false&runModule=true&excludeSource=true&sourcePaths=url-server&app=ios.fetch.demo&transform.routerRoot=app&transform.engine=hermes&transform.bytecode=1&unstable_transformProfile=hermes-stable:25193:18)
    at batchedUpdates$1 (http://localhost:8081/node_modules/expo-router/entry.bundle//&platform=ios&dev=true&lazy=true&minify=false&inlineSourceMap=false&modulesOnly=false&runModule=true&excludeSource=true&sourcePaths=url-server&app=ios.fetch.demo&transform.routerRoot=app&transform.engine=hermes&transform.bytecode=1&unstable_transformProfile=hermes-stable:16916:34)
    at dispatchEvent (http://localhost:8081/node_modules/expo-router/entry.bundle//&platform=ios&dev=true&lazy=true&minify=false&inlineSourceMap=false&modulesOnly=false&runModule=true&excludeSource=true&sourcePaths=url-server&app=ios.fetch.demo&transform.routerRoot=app&transform.engine=hermes&transform.bytecode=1&unstable_transformProfile=hermes-stable:16938:23)

Device

iPhone 16 (iOS 26.0)

Nitro Modules Version

0.28.1

Nitrogen Version

0.28.1

Can you reproduce this issue in the Nitro Example app here?

No, I cannot reproduce the issue in the Example app

Additional information

vexcited avatar Aug 25 '25 00:08 vexcited

Interesting - that needs to be fixed.

mrousavy avatar Aug 25 '25 07:08 mrousavy

Error: Failed to create AudioRecorderPlayer HybridObject: Error: NitroModulesProxy.createHybridObject(...): Couldn't find class com/margelo/nitro/audiorecorderplayer/HybridAudioRecorderPlayer!

  • Make sure the class exists in the specified namespace.
  • Make sure the class is not stripped. If you are using ProGuard, add @Keep and @DoNotStrip annotations to HybridAudioRecorderPlayer.

any solution?

obaid-rehmann avatar Aug 28 '25 15:08 obaid-rehmann

@ObaidHere this is unrelated to this issue. Your issue is that react-native-audio-recorder-player accidentally mis-matched the name in nitro.json. I already said this in this reply: https://github.com/hyochan/react-native-audio-recorder-player/issues/684#issuecomment-3233336411

mrousavy avatar Aug 29 '25 14:08 mrousavy

I think something like https://github.com/mrousavy/nitro/pull/847 would be a great step towards better constructors.

  • It'd allow exposing the actual prototype of a HybridObject, statically, and without having to construct the HybridObject first (limited use-cases, but e.g. x instanceof MyHybridObject)
  • We can build upon that to make new MyHybridObject the default, even in codegen;
    interface MyHybridObject extends HybridObject { }
    interface MyHybridObjectConstructor {
      new(): MyHybridObject
    }
    
    If a ...Constructor is declared for a hybrid object, nitrogen can then warn/error the user if no constructor is autolinked in nitro.json - this prevents mistakes where users forget to add their hybrid objects to autolinking. (cc @Szymon20000 & @hannojg & @SudoPlz & @chrispader)
  • We can take this even further and allow arguments in constructors, because right now I find myself writing Factories a lot:
    // BAD: 2 HybridObjects
    - interface Image extends HybridObject { }
    - interface ImageFactory extends HybridObject {
    -   loadImage(path: string): Image
    - }
    
    // GOOD: 1 HybridObject
    + interface Image extends HybridObject { }
    + interface ImageConstructor {
    +   new(path: string): Image
    + }
    

mrousavy avatar Sep 01 '25 16:09 mrousavy

There's still a lot of gotchas I couldn't really find solutions to yet;

  1. Function overloading will not work (or is super complex & involves a runtime cost), so the point above about avoiding Factories and instead using new Image(...) is only valid if there is exactly one way to create your hybrid object. For Image in react-native-nitro-image, that's not the case as there is loadImageFromFile(…), loadImageFromArrayBuffer(…), loadImageFromURL(…), and so on, so we need a separate Factory anyways. Same goes for async funcs as there are no async constructors in JS.
  2. Exposing prototypes statically has a suuuuper limited use-case (honestly I can't even think of one) and is somewhat hard to implement. For example, for every HybridObject we'd then need a separate class (that is only a static singleton) that represents the prototype:
    class MyHybridObjectSpecPrototype: public Prototype {
    public:
      static MyHybridObjectSpecPrototype shared{};
      void loadHybridMethods() override {
        registerHybridMethod("doSomething", MyHybridObjectSpec::doSomething);
        // this was in MyHybridObjectSpec before, but now moved here
      }
    };
    class MyHybridObjectSpec: public HybridObject {
    public:
      Prototype& getPrototype() override { return MyHybridObjectSpecPrototype::shared; }
      // loadHybridMethods() is gone here - it moved to the MyHybridObjectSpecPrototype class
    public:
      void doSomething();
    };
    
    It's fine if you use nitrogen, but writing specs yourself (e.g. if you just use Nitro core in C++, without nitrogen), it gets a bit annoying) Also it's super hard to make non-breaking, as loadHybridMethods() is now gone and moved to that separate Prototype class - is that really worth it?

mrousavy avatar Sep 01 '25 16:09 mrousavy

Don't have much context on the whole thread here, but to jump in on the original report, which @hirbod made me aware of;

There's a chance here, depending on the Babel setup, that this remains as-is: https://github.com/mrousavy/nitro/blob/961cf3e3732ca0689ec0b08a81f29c5e8b45940a/packages/react-native-nitro-modules/src/Constructor.ts#L29-L37

The referenced lines use an arrow function as a constructor, which would be a possible cause for a TypeError: Function is not a constructor error. I'm assuming TypeScript may be able to catch this usually (although not sure) but the cast on these lines would prevent that.

In Expo, our Babel preset probably doesn't touch the arrow function, hence the issue

kitten avatar Sep 03 '25 13:09 kitten

Thanks @kitten for your reply - this is very helpful!

In the near future, Nitro is going to expose the native Prototype directly, which will be callable as a constructor - so it won't have any JS code for that. In the meantime, I tried fixing it in https://github.com/mrousavy/nitro/pull/859 - @Vexcited can you try if that PR works for you?

mrousavy avatar Sep 04 '25 12:09 mrousavy

Released in 0.29.3! :)

mrousavy avatar Sep 04 '25 13:09 mrousavy