/* THIS FILE IS AUTOGENERATED FROM Worklet.webidl BY Codegen.py - DO NOT EDIT */

#include <type_traits>
#include "AtomList.h"
#include "MainThreadUtils.h"
#include "WorkletBinding.h"
#include "WrapperFactory.h"
#include "js/CallAndConstruct.h"
#include "js/Exception.h"
#include "js/MapAndSet.h"
#include "js/Object.h"
#include "js/PropertyAndElement.h"
#include "js/PropertyDescriptor.h"
#include "js/experimental/JitInfo.h"
#include "mozilla/Atomics.h"
#include "mozilla/OwningNonNull.h"
#include "mozilla/ProfilerLabels.h"
#include "mozilla/dom/BindingCallContext.h"
#include "mozilla/dom/BindingUtils.h"
#include "mozilla/dom/DOMJSClass.h"
#include "mozilla/dom/NonRefcountedDOMObject.h"
#include "mozilla/dom/Promise.h"
#include "mozilla/dom/ScriptSettings.h"
#include "mozilla/dom/SimpleGlobalObject.h"
#include "mozilla/dom/ToJSValue.h"
#include "mozilla/dom/WebIDLPrefs.h"
#include "mozilla/dom/Worklet.h"
#include "mozilla/dom/XrayExpandoClass.h"
#include "nsContentUtils.h"

namespace mozilla::dom {

namespace binding_detail {}; // Just to make sure it's known as a namespace
using namespace mozilla::dom::binding_detail;



WorkletOptions::WorkletOptions()
{
  // Safe to pass a null context if we pass a null value
  Init(nullptr, JS::NullHandleValue);
}




bool
WorkletOptions::InitIds(JSContext* cx, WorkletOptionsAtoms* atomsCache)
{
  MOZ_ASSERT(reinterpret_cast<jsid*>(atomsCache)->isVoid());

  // Initialize these in reverse order so that any failure leaves the first one
  // uninitialized.
  if (!atomsCache->credentials_id.init(cx, "credentials")) {
    return false;
  }
  return true;
}

bool
WorkletOptions::Init(BindingCallContext& cx, JS::Handle<JS::Value> val, const char* sourceDescription, bool passedToJSImpl)
{
  // Passing a null JSContext is OK only if we're initing from null,
  // Since in that case we will not have to do any property gets
  // Also evaluate isNullOrUndefined in order to avoid false-positive
  // checkers by static analysis tools
  MOZ_ASSERT_IF(!cx, val.isNull() && val.isNullOrUndefined());
  WorkletOptionsAtoms* atomsCache = nullptr;
  if (cx) {
    atomsCache = GetAtomCache<WorkletOptionsAtoms>(cx);
    if (reinterpret_cast<jsid*>(atomsCache)->isVoid() &&
        !InitIds(cx, atomsCache)) {
      return false;
    }
  }

  if (!IsConvertibleToDictionary(val)) {
    return cx.ThrowErrorMessage<MSG_CONVERSION_ERROR>(sourceDescription, "dictionary");
  }

  bool isNull = val.isNullOrUndefined();
  // We only need these if !isNull, in which case we have |cx|.
  Maybe<JS::Rooted<JSObject *> > object;
  Maybe<JS::Rooted<JS::Value> > temp;
  if (!isNull) {
    MOZ_ASSERT(cx);
    object.emplace(cx, &val.toObject());
    temp.emplace(cx);
  }
  if (!isNull) {
    if (!JS_GetPropertyById(cx, *object, atomsCache->credentials_id, temp.ptr())) {
      return false;
    }
  }
  if (!isNull && !temp->isUndefined()) {
    {
      int index;
      if (!binding_detail::FindEnumStringIndex<true>(cx, temp.ref(),
                                                                         binding_detail::EnumStrings<RequestCredentials>::Values,
                                                                         "RequestCredentials", "'credentials' member of WorkletOptions",
                                                                         &index)) {
        return false;
      }
      MOZ_ASSERT(index >= 0);
      mCredentials = static_cast<RequestCredentials>(index);
    }
  } else {
    mCredentials = RequestCredentials::Same_origin;
  }
  mIsAnyMemberPresent = true;
  return true;
}

bool
WorkletOptions::Init(JSContext* cx_, JS::Handle<JS::Value> val, const char* sourceDescription, bool passedToJSImpl)
{
  // We don't want to use sourceDescription for our context here;
  // that's not really what it's formatted for.
  BindingCallContext cx(cx_, nullptr);
  return Init(cx, val, sourceDescription, passedToJSImpl);
}

void
WorkletOptions::TraceDictionary(JSTracer* trc)
{
}

WorkletOptions&
WorkletOptions::operator=(const WorkletOptions& aOther)
{
  DictionaryBase::operator=(aOther);
  mCredentials = aOther.mCredentials;
  return *this;
}


namespace Worklet_Binding {

MOZ_CAN_RUN_SCRIPT static bool
addModule(JSContext* cx_, JS::Handle<JSObject*> obj, void* void_self, const JSJitMethodCallArgs& args)
{
  BindingCallContext cx(cx_, "Worklet.addModule");
  AUTO_PROFILER_LABEL_DYNAMIC_FAST(
    "Worklet", "addModule", DOM, cx,
    uint32_t(js::ProfilingStackFrame::Flags::STRING_TEMPLATE_METHOD) |
    uint32_t(js::ProfilingStackFrame::Flags::RELEVANT_FOR_JS));

  auto* self = static_cast<mozilla::dom::Worklet*>(void_self);
  if (!args.requireAtLeast(cx, "Worklet.addModule", 1)) {
    return false;
  }
  binding_detail::FakeString<char16_t> arg0;
  if (!ConvertJSValueToString(cx, args[0], eStringify, eStringify, arg0)) {
    return false;
  }
  if (!NormalizeUSVString(arg0)) {
    JS_ReportOutOfMemory(cx);
    return false;
  }
  binding_detail::FastWorkletOptions arg1;
  if (!arg1.Init(cx, (args.hasDefined(1)) ? args[1] : JS::NullHandleValue, "Argument 2", false)) {
    return false;
  }
  FastErrorResult rv;
  auto result(StrongOrRawPtr<Promise>(MOZ_KnownLive(self)->AddModule(cx, Constify(arg0), Constify(arg1), nsContentUtils::IsSystemCaller(cx) ? CallerType::System : CallerType::NonSystem, rv)));
  if (MOZ_UNLIKELY(rv.MaybeSetPendingException(cx, "Worklet.addModule"))) {
    return false;
  }
  MOZ_ASSERT(!JS_IsExceptionPending(cx));
  static_assert(!std::is_pointer_v<decltype(result)>,
                "NewObject implies that we need to keep the object alive with a strong reference.");
  if (!ToJSValue(cx, result, args.rval())) {
    return false;
  }
  return true;
}

MOZ_CAN_RUN_SCRIPT static bool
addModule_promiseWrapper(JSContext* cx, JS::Handle<JSObject*> obj, void* void_self, const JSJitMethodCallArgs& args)
{
  bool ok = addModule(cx, obj, void_self, args);
  if (ok) {
    return true;
  }
  return ConvertExceptionToPromise(cx, args.rval());
}

static const JSJitInfo addModule_methodinfo = {
  { (JSJitGetterOp)addModule_promiseWrapper },
  { prototypes::id::Worklet },
  { PrototypeTraits<prototypes::id::Worklet>::Depth },
  JSJitInfo::Method,
  JSJitInfo::AliasEverything, /* aliasSet.  Not relevant for setters. */
  JSVAL_TYPE_OBJECT,  /* returnType.  Not relevant for setters. */
  false,  /* isInfallible. False in setters. */
  false,  /* isMovable.  Not relevant for setters. */
  false, /* isEliminatable.  Not relevant for setters. */
  false, /* isAlwaysInSlot.  Only relevant for getters. */
  false, /* isLazilyCachedInSlot.  Only relevant for getters. */
  false,  /* isTypedMethod.  Only relevant for methods. */
  0   /* Reserved slot index, if we're stored in a slot, else 0. */
};

static void
_finalize(JS::GCContext* gcx, JSObject* obj)
{
  mozilla::dom::Worklet* self = UnwrapPossiblyNotInitializedDOMObject<mozilla::dom::Worklet>(obj);
  if (self) {
    JS::SetReservedSlot(obj, DOM_OBJECT_SLOT, JS::UndefinedValue());
    ClearWrapper(self, self, obj);
    if (size_t mallocBytes = BindingJSObjectMallocBytes(self)) {
      JS::RemoveAssociatedMemory(obj, mallocBytes,
                                 JS::MemoryUse::DOMBinding);
    }
    AddForDeferredFinalization<mozilla::dom::Worklet>(self);
  }
}

MOZ_GLOBINIT static const JSFunctionSpec sMethods_specs[] = {
  JS_FNSPEC("addModule", (GenericMethod<NormalThisPolicy, ConvertExceptionsToPromises>), reinterpret_cast<const JSJitInfo*>(&addModule_methodinfo), 1, JSPROP_ENUMERATE, nullptr),
  JS_FS_END
};

static const PrefableDisablers sMethods_disablers0 = {
  WebIDLPrefIndex::NoPref, 0, true, OriginTrial(0), nullptr
};

static const Prefable<const JSFunctionSpec> sMethods[] = {
  { &sMethods_disablers0, &sMethods_specs[0] },
  { nullptr, nullptr }
};

static_assert(1 <= 1ull << NUM_BITS_PROPERTY_INFO_PREF_INDEX,
    "We have a prefable index that is >= (1 << NUM_BITS_PROPERTY_INFO_PREF_INDEX)");
static_assert(1 <= 1ull << NUM_BITS_PROPERTY_INFO_SPEC_INDEX,
    "We have a spec index that is >= (1 << NUM_BITS_PROPERTY_INFO_SPEC_INDEX)");


static uint16_t sNativeProperties_sortedPropertyIndices[1];
static PropertyInfo sNativeProperties_propertyInfos[1];

static const NativePropertiesN<1> sNativeProperties = {
  false, 0,
  false, 0,
  true,  0 /* sMethods */,
  false, 0,
  false, 0,
  false, 0,
  false, 0,
  -1,
  1,
  sNativeProperties_sortedPropertyIndices,
  {
    { sMethods, &sNativeProperties_propertyInfos[0] }
  }
};
static_assert(1 < 1ull << (CHAR_BIT * sizeof(sNativeProperties.propertyInfoCount)),
    "We have a property info count that is oversized");

bool sNativePropertiesInited = false;
const NativePropertyHooks sNativePropertyHooks = {
  nullptr,
  { sNativeProperties.Upcast(), nullptr, &sNativePropertiesInited },
  prototypes::id::Worklet,
  constructors::id::Worklet,
  &DefaultXrayExpandoObjectClass
};

static const DOMInterfaceInfo sInterfaceObjectInfo = {
  { ThrowingConstructor, &sNativePropertyHooks },
  JS::GetRealmFunctionPrototypeHandle,
  PrototypeTraits<prototypes::id::Worklet>::Depth,
  prototypes::id::Worklet,
  true,
  0,
  "Worklet",
};

static const DOMIfaceAndProtoJSClass sPrototypeClass = {
  {
    "WorkletPrototype",
    JSCLASS_IS_DOMIFACEANDPROTOJSCLASS | JSCLASS_HAS_RESERVED_SLOTS(DOM_INTERFACE_PROTO_SLOTS_BASE),
    JS_NULL_CLASS_OPS,
    JS_NULL_CLASS_SPEC,
    JS_NULL_CLASS_EXT,
    JS_NULL_OBJECT_OPS
  },
  eInterfacePrototype,
  prototypes::id::Worklet,
  PrototypeTraits<prototypes::id::Worklet>::Depth,
  &sNativePropertyHooks,
  JS::GetRealmObjectPrototype
};

bool
ConstructorEnabled(JSContext* aCx, JS::Handle<JSObject*> aObj)
{
  return mozilla::dom::IsSecureContextOrObjectIsFromSecureContext(aCx, aObj);
}

static const JSClassOps sClassOps = {
  nullptr,               /* addProperty */
  nullptr,               /* delProperty */
  nullptr,               /* enumerate */
  nullptr, /* newEnumerate */
  nullptr, /* resolve */
  nullptr, /* mayResolve */
  _finalize, /* finalize */
  nullptr, /* call */
  nullptr,               /* construct */
  nullptr, /* trace */
};

static const DOMJSClass sClass = {
  { "Worklet",
    JSCLASS_IS_DOMJSCLASS | JSCLASS_FOREGROUND_FINALIZE | JSCLASS_HAS_RESERVED_SLOTS(1) | JSCLASS_PRESERVES_WRAPPER,
    &sClassOps,
    JS_NULL_CLASS_SPEC,
    &NativeTypeHelpers<mozilla::dom::Worklet>::sClassExtension,
    JS_NULL_OBJECT_OPS
  },
  { prototypes::id::Worklet, prototypes::id::_ID_Count, prototypes::id::_ID_Count, prototypes::id::_ID_Count, prototypes::id::_ID_Count, prototypes::id::_ID_Count, prototypes::id::_ID_Count, prototypes::id::_ID_Count },
  std::is_base_of_v<nsISupports, mozilla::dom::Worklet>,
  &sNativePropertyHooks,
  FindAssociatedGlobalForNative<mozilla::dom::Worklet>::Get,
  GetProtoObjectHandle,
  GetCCParticipant<mozilla::dom::Worklet>::Get(),
  nullptr,
  NativeTypeHelpers<mozilla::dom::Worklet>::GetWrapperCache
};
static_assert(1 == DOM_INSTANCE_RESERVED_SLOTS,
              "Must have the right minimal number of reserved slots.");
static_assert(1 >= 1,
              "Must have enough reserved slots.");

bool
Wrap(JSContext* aCx, mozilla::dom::Worklet* aObject, nsWrapperCache* aCache, JS::Handle<JSObject*> aGivenProto, JS::MutableHandle<JSObject*> aReflector)
{
  static_assert(!std::is_base_of_v<NonRefcountedDOMObject, mozilla::dom::Worklet>,
                "Shouldn't have wrappercached things that are not refcounted.");
  static_assert(std::is_same_v<decltype(aObject), mozilla::dom::Worklet*>);
  MOZ_ASSERT(ToSupportsIsCorrect(aObject));
  MOZ_ASSERT_IF(aGivenProto, js::IsObjectInContextCompartment(aGivenProto, aCx));
  MOZ_ASSERT(!aCache->GetWrapper(),
             "You should probably not be using Wrap() directly; use "
             "GetOrCreateDOMReflector instead");

  MOZ_ASSERT(ToSupportsIsOnPrimaryInheritanceChain(aObject, aCache),
             "nsISupports must be on our primary inheritance chain");

  // If the wrapper cache contains a dead reflector then finalize that
  // now, ensuring that the finalizer for the old reflector always
  // runs before the new reflector is created and attached. This
  // avoids the awkward situation where there are multiple reflector
  // objects that contain pointers to the same native.

  if (JSObject* oldReflector = aCache->GetWrapperMaybeDead()) {
    _finalize(nullptr /* unused */, oldReflector);
    MOZ_ASSERT(!aCache->GetWrapperMaybeDead());
  }

  JS::Rooted<JSObject*> global(aCx, FindAssociatedGlobal(aCx, aObject->GetParentObject()));
  if (!global) {
    return false;
  }
  MOZ_ASSERT(JS_IsGlobalObject(global));
  JS::AssertObjectIsNotGray(global);

  // That might have ended up wrapping us already, due to the wonders
  // of XBL.  Check for that, and bail out as needed.
  aReflector.set(aCache->GetWrapper());
  if (aReflector) {
#ifdef DEBUG
    AssertReflectorHasGivenProto(aCx, aReflector, aGivenProto);
#endif // DEBUG
    return true;
  }

  JSAutoRealm ar(aCx, global);
  JS::Handle<JSObject*> canonicalProto = GetProtoObjectHandle(aCx);
  if (!canonicalProto) {
    return false;
  }
  JS::Rooted<JSObject*> proto(aCx);
  if (aGivenProto) {
    proto = aGivenProto;
    // Unfortunately, while aGivenProto was in the compartment of aCx
    // coming in, we changed compartments to that of "parent" so may need
    // to wrap the proto here.
    if (js::GetContextCompartment(aCx) != JS::GetCompartment(proto)) {
      if (!JS_WrapObject(aCx, &proto)) {
        return false;
      }
    }
  } else {
    proto = canonicalProto;
  }

  BindingJSObjectCreator<mozilla::dom::Worklet> creator(aCx);
  creator.CreateObject(aCx, sClass.ToJSClass(), proto, aObject, aReflector);
  if (!aReflector) {
    return false;
  }

  aCache->SetWrapper(aReflector);
  creator.InitializationSucceeded();

  MOZ_ASSERT(aCache->GetWrapperPreserveColor() &&
             aCache->GetWrapperPreserveColor() == aReflector);
  // If proto != canonicalProto, we have to preserve our wrapper;
  // otherwise we won't be able to properly recreate it later, since
  // we won't know what proto to use.  Note that we don't check
  // aGivenProto here, since it's entirely possible (and even
  // somewhat common) to have a non-null aGivenProto which is the
  // same as canonicalProto.
  if (proto != canonicalProto) {
    PreserveWrapper(aObject);
  }

  return true;
}

void
CreateInterfaceObjects(JSContext* aCx, JS::Handle<JSObject*> aGlobal, ProtoAndIfaceCache& aProtoAndIfaceCache, DefineInterfaceProperty aDefineOnGlobal)
{
  JS::Heap<JSObject*>* protoCache = &aProtoAndIfaceCache.EntrySlotOrCreate(prototypes::id::Worklet);
  JS::Heap<JSObject*>* interfaceCache = &aProtoAndIfaceCache.EntrySlotOrCreate(constructors::id::Worklet);

  JS::Handle<JSObject*> parentProto(JS::GetRealmObjectPrototypeHandle(aCx));
  if (!parentProto) {
    return;
  }

  JS::Handle<JSObject*> constructorProto(JS::GetRealmFunctionPrototypeHandle(aCx));
  if (!constructorProto) {
    return;
  }

  dom::CreateInterfaceObjects(aCx, aGlobal, parentProto,
                              &sPrototypeClass, protoCache,
                              constructorProto, &sInterfaceObjectInfo, 0, false, Span<const LegacyFactoryFunction, 0>{},
                              interfaceCache,
                              sNativeProperties.Upcast(),
                              nullptr,
                              "Worklet",
                              ShouldExpose<Worklet_Binding::ConstructorEnabled>(aCx, aGlobal, aDefineOnGlobal),
                              nullptr,
                              false,
                              nullptr);
}

JS::Handle<JSObject*>
GetProtoObjectHandle(JSContext* aCx)
{
  /* Get the interface prototype object for this class.  This will create the
     object as needed. */
  return GetPerInterfaceObjectHandle(aCx, prototypes::id::Worklet,
                                     &CreateInterfaceObjects,
                                     DefineInterfaceProperty::CheckExposure);

}

JSObject*
GetProtoObject(JSContext* aCx)
{
  return GetProtoObjectHandle(aCx);
}

JS::Handle<JSObject*>
GetConstructorObjectHandle(JSContext* aCx)
{
  /* Get the interface object for this class.  This will create the object as
     needed. */

  return GetPerInterfaceObjectHandle(aCx, constructors::id::Worklet,
                                     &CreateInterfaceObjects,
                                     DefineInterfaceProperty::CheckExposure);
}

} // namespace Worklet_Binding



} // namespace mozilla::dom
