defineClass<T extends Object> method

JsFunction defineClass<T extends Object>(
  1. String name, {
  2. required T constructor(
    1. JsArguments
    ),
  3. Map<String, Object? Function(T, JsArguments)> methods = const {},
  4. Map<String, Object? Function(T)> getters = const {},
  5. Map<String, void Function(T, JsArguments)> setters = const {},
  6. Map<String, Object? Function(JsArguments)> staticMethods = const {},
  7. Map<String, Object? Function()> staticGetters = const {},
  8. Map<String, void Function(JsArguments)> staticSetters = const {},
  9. void finalize(
    1. T
    )?,
})

Defines a JavaScript class whose instances own Dart objects of type T.

Static members belong to the constructor rather than its prototype. Finalizers run after a JS wrapper is collected, or during environment cleanup. Rewrapping an identity-cached object before its old GC notification arrives does not finalize the new wrapper. Cleanup finalizers must not access JavaScript.

Implementation

JsFunction defineClass<T extends Object>(
  String name, {
  required T Function(JsArguments) constructor,
  Map<String, Object? Function(T, JsArguments)> methods = const {},
  Map<String, Object? Function(T)> getters = const {},
  Map<String, void Function(T, JsArguments)> setters = const {},
  Map<String, Object? Function(JsArguments)> staticMethods = const {},
  Map<String, Object? Function()> staticGetters = const {},
  Map<String, void Function(JsArguments)> staticSetters = const {},
  void Function(T)? finalize,
}) {
  final (nativeName, length) = _functionName(name);
  final keys = {...methods.keys, ...getters.keys, ...setters.keys};
  final staticKeys = {
    ...staticMethods.keys,
    ...staticGetters.keys,
    ...staticSetters.keys,
  };
  if (staticKeys.contains('prototype')) {
    throw ArgumentError('Static member prototype is reserved by JavaScript');
  }
  for (final (methodNames, getterNames, setterNames) in [
    (methods.keys, getters.keys, setters.keys),
    (staticMethods.keys, staticGetters.keys, staticSetters.keys),
  ]) {
    for (final key in methodNames) {
      if (getterNames.contains(key) || setterNames.contains(key)) {
        throw ArgumentError('Member $key is both a method and an accessor');
      }
    }
  }
  final definition = _ClassDefinition((value) => value is T);
  final registrations = <int>[];
  int register(node.NapiValue Function(JsArguments, node.NapiValue) body) {
    final token = _nextToken++;
    _callbacks[token] = body;
    registrations.add(token);
    return token;
  }

  final constructorToken = register((arguments, self) {
    final value = definition.pending.isEmpty
        ? constructor(arguments)
        : definition.pending.removeLast().value as T;
    final selected = definition.select(value);
    if (!identical(selected, definition)) {
      return _wrapObject(value, selected)._handle;
    }
    return _bindObject(
      value,
      definition,
      self,
      finalize == null ? null : () => finalize(value),
    );
  });
  final propertyCount = keys.length + staticKeys.length - methods.length;
  final properties = _arena<node.NapiPropertyDescriptor>(
    propertyCount + methods.length,
  );
  var index = 0;
  var methodIndex = propertyCount;
  JsReference<JsFunction>? retained;
  try {
    for (final isStatic in [false, true]) {
      for (final key in isStatic ? staticKeys : keys) {
        final descriptor =
            properties[!isStatic && methods.containsKey(key)
                ? methodIndex++
                : index++];
        final attributes =
            node.napiConfigurable | (isStatic ? node.napiStatic : 0);
        descriptor
          ..name = _encode(key)
          ..attributes = attributes;
        if (isStatic
            ? staticMethods.containsKey(key)
            : methods.containsKey(key)) {
          final token = register((args, self) {
            if (isStatic) return _encode(staticMethods[key]!(args));
            final object = _boundObject<T>(self);
            final specialized =
                object.definition.specializations?[definition]?.methods[key];
            return _encode(
              specialized == null
                  ? methods[key]!(object.value as T, args)
                  : specialized(object.value, args),
            );
          });
          final data = _callbackData(token);
          descriptor.attributes = attributes | node.napiWritable;
          if (isStatic) {
            descriptor
              ..method = _runtime.callback
              ..data = data;
          } else {
            final handle = _result(
              (out) => node.napiCreateFunction(
                _handle,
                nullptr,
                0,
                _runtime.callback,
                data,
                out,
              ),
            );
            _nameFunction(handle, key);
            descriptor.value = handle;
          }
          continue;
        }
        // Getter/setter functions have independent entry points: JS can call an
        // accessor directly with any argument count.
        final token = _nextToken++;
        registrations.add(token);
        descriptor.data = _callbackData(token, accessor: true);
        if (isStatic
            ? staticGetters.containsKey(key)
            : getters.containsKey(key)) {
          _getters[token] = (args, self) {
            if (isStatic) return _encode(staticGetters[key]!());
            final object = _boundObject<T>(self);
            final specialized =
                object.definition.specializations?[definition]?.getters[key];
            return _encode(
              specialized == null
                  ? getters[key]!(object.value as T)
                  : specialized(object.value),
            );
          };
          descriptor.getter = _runtime.callback;
        }
        if (isStatic
            ? staticSetters.containsKey(key)
            : setters.containsKey(key)) {
          _setters[token] = (args, self) {
            if (isStatic) {
              staticSetters[key]!(args);
            } else {
              final object = _boundObject<T>(self);
              final specialized = object
                  .definition
                  .specializations?[definition]
                  ?.setters[key];
              if (specialized == null) {
                setters[key]!(object.value as T, args);
              } else {
                specialized(object.value, args);
              }
            }
            return _encode(undefined);
          };
          descriptor.setter = _runtime.setter;
        }
      }
    }
    final handle = _result(
      (out) => node.napiDefineClass(
        _handle,
        nativeName,
        length,
        _runtime.callback,
        _callbackData(constructorToken),
        propertyCount,
        properties,
        out,
      ),
    );
    final function = JsFunction._(this, handle, _scope!);
    if (methods.isNotEmpty) {
      final prototype = function.get<JsObject>('prototype');
      _check(
        node.napiDefineProperties(
          _handle,
          prototype._handle,
          methods.length,
          properties + propertyCount,
        ),
      );
    }
    if (!staticKeys.contains('name')) _nameFunction(handle, name);
    retained = function.retain();
    definition.constructor = retained;
    _classes.update(T, (_) => null, ifAbsent: () => definition);
    // Only this registration requires new; ordinary functions remain callable.
    _constructors.add(constructorToken);
    return function;
  } catch (_) {
    retained?.dispose();
    for (final token in registrations) {
      _callbacks.remove(token);
      _getters.remove(token);
      _setters.remove(token);
    }
    rethrow;
  }
}