/// <summary> /// Releases a reference to a module record /// </summary> /// <remarks> /// Removes a reference to a module record that was created by <code>AddRef</code>. /// </remarks> /// <returns>The object's new reference count</returns> public uint Release() { uint count; JsErrorHelpers.ThrowIfError(NativeMethods.JsModuleRecordRelease(this, out count)); return(count); }
/// <summary> /// Adds a reference to a script context /// </summary> /// <remarks> /// Calling AddRef ensures that the context will not be freed until Release is called. /// </remarks> /// <returns>The object's new reference count</returns> public uint AddRef() { uint count; JsErrorHelpers.ThrowIfError(NativeMethods.JsContextAddRef(this, out count)); return(count); }
/// <summary> /// Returns a metadata relating to the exception that caused the runtime of the current context /// to be in the exception state and resets the exception state for that runtime. The metadata /// includes a reference to the exception itself. /// </summary> /// <remarks> /// <para> /// If the runtime of the current context is not in an exception state, this API will throw /// <see cref="JsErrorCode.InvalidArgument"/>. If the runtime is disabled, this will return /// an exception indicating that the script was terminated, but it will not clear the exception /// (the exception will be cleared if the runtime is re-enabled using /// <c>JsEnableRuntimeExecution</c>). /// </para> /// <para> /// The metadata value is a javascript object with the following properties: <c>exception</c>, the /// thrown exception object; <c>line</c>, the 0 indexed line number where the exception was thrown; /// <c>column</c>, the 0 indexed column number where the exception was thrown; <c>length</c>, the /// source-length of the cause of the exception; <c>source</c>, a string containing the line of /// source code where the exception was thrown; and <c>url</c>, a string containing the name of /// the script file containing the code that threw the exception. /// </para> /// <para> /// Requires an active script context. /// </para> /// </remarks> /// <returns>The exception metadata for the runtime of the current context</returns> public static JsValue GetAndClearExceptionWithMetadata() { JsValue metadata; JsErrorHelpers.ThrowIfError(NativeMethods.JsGetAndClearExceptionWithMetadata(out metadata)); return(metadata); }
/// <summary> /// Returns a exception that caused the runtime of the current context to be in the /// exception state and resets the exception state for that runtime /// </summary> /// <remarks> /// <para> /// If the runtime of the current context is not in an exception state, this API will throw /// <see cref="JsErrorCode.InvalidArgument"/>. If the runtime is disabled, this will return /// an exception indicating that the script was terminated, but it will not clear the exception /// (the exception will be cleared if the runtime is re-enabled using /// <c>JsEnableRuntimeExecution</c>). /// </para> /// <para> /// Requires an active script context. /// </para> /// </remarks> /// <returns>The exception for the runtime of the current context</returns> public static JsValue GetAndClearException() { JsValue exception; JsErrorHelpers.ThrowIfError(NativeMethods.JsGetAndClearException(out exception)); return(exception); }
/// <summary> /// Tells the runtime to do any idle processing it need to do /// </summary> /// <remarks> /// <para> /// If idle processing has been enabled for the current runtime, calling <c>Idle</c> will /// inform the current runtime that the host is idle and that the runtime can perform /// memory cleanup tasks. /// </para> /// <para> /// <c>Idle</c> will also return the number of system ticks until there will be more idle work /// for the runtime to do. Calling <c>Idle</c> before this number of ticks has passed will do /// no work. /// </para> /// <para> /// Requires an active script context. /// </para> /// </remarks> /// <returns> /// The next system tick when there will be more idle work to do. Returns the /// maximum number of ticks if there no upcoming idle work to do. /// </returns> public static uint Idle() { uint ticks; JsErrorHelpers.ThrowIfError(NativeMethods.JsIdle(out ticks)); return(ticks); }
/// <summary> /// Sets a user implemented callback to fetch imported modules dynamically in scripts /// </summary> /// <param name="fetchImportedModuleFromScriptCallback">The callback function being set</param> public void SetFetchImportedModuleFromScriptCallback( JsFetchImportedModuleFromScriptCallback fetchImportedModuleFromScriptCallback) { JsErrorHelpers.ThrowIfError(NativeMethods.JsSetModuleHostInfo(this, JsModuleHostInfoKind.FetchImportedModuleFromScriptCallback, Marshal.GetFunctionPointerForDelegate(fetchImportedModuleFromScriptCallback) )); }
/// <summary> /// Disposes a runtime /// </summary> /// <remarks> /// Once a runtime has been disposed, all resources owned by it are invalid and cannot be used. /// If the runtime is active (i.e. it is set to be current on a particular thread), it cannot /// be disposed. /// </remarks> public void Dispose() { if (IsValid) { JsErrorHelpers.ThrowIfError(NativeMethods.JsDisposeRuntime(this)); } _handle = IntPtr.Zero; }
/// <summary> /// Invokes a function as a constructor /// </summary> /// <remarks> /// Requires an active script context. /// </remarks> /// <param name="arguments">The arguments to the call</param> /// <returns>The <c>Value</c> returned from the function invocation</returns> public JsValue ConstructObject(params JsValue[] arguments) { JsValue returnReference; if (arguments.Length > ushort.MaxValue) { throw new ArgumentOutOfRangeException(nameof(arguments)); } JsErrorHelpers.ThrowIfError(NativeMethods.JsConstructObject(this, arguments, (ushort)arguments.Length, out returnReference)); return(returnReference); }
/// <summary> /// Creates a <c>String</c> value from a string pointer /// </summary> /// <remarks> /// Requires an active script context. /// </remarks> /// <param name="value">The string to convert to a <c>String</c> value</param> /// <returns>The new <c>String</c> value</returns> public static JsValue FromString(string value) { JsValue reference; JsErrorCode errorCode; if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows)) { var stringLength = new UIntPtr((uint)value.Length); errorCode = NativeMethods.JsCreateStringUtf16(value, stringLength, out reference); } else { var byteCount = new UIntPtr((uint)Encoding.UTF8.GetByteCount(value)); errorCode = NativeMethods.JsCreateString(value, byteCount, out reference); } JsErrorHelpers.ThrowIfError(errorCode); return(reference); }
/// <summary> /// Creates a Javascript <c>ArrayBuffer</c> object to access external memory /// </summary> /// <remarks>Requires an active script context.</remarks> /// <param name="buffer">Buffer for an external memory</param> /// <returns>The new <c>ArrayBuffer</c> object</returns> public static JsValue CreateExternalArrayBuffer(byte[] buffer) { if (buffer == null) { throw new ArgumentNullException(nameof(buffer)); } int bufferLength = buffer.Length; IntPtr bufferPtr = Marshal.AllocHGlobal(bufferLength + 1); Marshal.Copy(buffer, 0, bufferPtr, bufferLength); Marshal.WriteByte(bufferPtr, bufferLength, 0); JsValue reference; JsErrorCode errorCode = NativeMethods.JsCreateExternalArrayBuffer(bufferPtr, (uint)bufferLength, DefaultExternalBufferFinalizeCallback.Instance, bufferPtr, out reference); JsErrorHelpers.ThrowIfError(errorCode); return(reference); }
/// <summary> /// Serializes a parsed script to a buffer than can be reused /// </summary> /// <remarks> /// <para> /// <c>SerializeScript</c> parses a script and then stores the parsed form of the script in a /// runtime-independent format. The serialized script then can be deserialized in any /// runtime without requiring the script to be re-parsed. /// </para> /// <para> /// Requires an active script context. /// </para> /// </remarks> /// <param name="script">The script to serialize</param> /// <param name="parseAttributes">Attribute mask for parsing the script</param> /// <returns>The buffer to put the serialized script into</returns> public static byte[] SerializeScript(string script, ref JsParseScriptAttributes parseAttributes) { JsValue scriptValue = JsValue.FromString(script); scriptValue.AddRef(); JsValue bufferValue; try { JsErrorCode errorCode = NativeMethods.JsSerialize(scriptValue, out bufferValue, parseAttributes); JsErrorHelpers.ThrowIfError(errorCode); } finally { scriptValue.Release(); } byte[] buffer = bufferValue.ArrayBufferBytes; return(buffer); }
/// <summary> /// Gets a property ID associated with the name /// </summary> /// <remarks> /// <para> /// Property IDs are specific to a context and cannot be used across contexts. /// </para> /// <para> /// Requires an active script context. /// </para> /// </remarks> /// <param name="name">The name of the property ID to get or create. /// The name may consist of only digits.</param> /// <returns>The property ID in this runtime for the given name</returns> public static JsPropertyId FromString(string name) { string processedName; int byteCount; if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows)) { processedName = EncodingHelpers.UnicodeToAnsi(name, out byteCount); } else { processedName = name; byteCount = Encoding.UTF8.GetByteCount(processedName); } JsPropertyId id; UIntPtr length = new UIntPtr((uint)byteCount); JsErrorCode errorCode = NativeMethods.JsCreatePropertyId(processedName, length, out id); JsErrorHelpers.ThrowIfError(errorCode); return(id); }
/// <summary> /// Sets a callback function that is called by the runtime before garbage collection /// </summary> /// <remarks> /// <para> /// The callback is invoked on the current runtime execution thread, therefore execution is /// blocked until the callback completes. /// </para> /// <para> /// The callback can be used by hosts to prepare for garbage collection. For example, by /// releasing unnecessary references on Chakra objects. /// </para> /// </remarks> /// <param name="callbackState">User provided state that will be passed back to the callback</param> /// <param name="beforeCollectCallback">The callback function being set</param> public void SetBeforeCollectCallback(IntPtr callbackState, JsBeforeCollectCallback beforeCollectCallback) { JsErrorHelpers.ThrowIfError(NativeMethods.JsSetRuntimeBeforeCollectCallback(this, callbackState, beforeCollectCallback)); }
/// <summary> /// Sets a memory allocation callback for specified runtime /// </summary> /// <remarks> /// <para> /// Registering a memory allocation callback will cause the runtime to call back to the host /// whenever it acquires memory from, or releases memory to, the OS. The callback routine is /// called before the runtime memory manager allocates a block of memory. The allocation will /// be rejected if the callback returns false. The runtime memory manager will also invoke the /// callback routine after freeing a block of memory, as well as after allocation failures. /// </para> /// <para> /// The callback is invoked on the current runtime execution thread, therefore execution is /// blocked until the callback completes. /// </para> /// <para> /// The return value of the callback is not stored; previously rejected allocations will not /// prevent the runtime from invoking the callback again later for new memory allocations. /// </para> /// </remarks> /// <param name="callbackState"> /// User provided state that will be passed back to the callback. /// </param> /// <param name="allocationCallback"> /// Memory allocation callback to be called for memory allocation events. /// </param> public void SetMemoryAllocationCallback(IntPtr callbackState, JsMemoryAllocationCallback allocationCallback) { JsErrorHelpers.ThrowIfError(NativeMethods.JsSetRuntimeMemoryAllocationCallback(this, callbackState, allocationCallback)); }
/// <summary> /// Performs a full garbage collection /// </summary> public void CollectGarbage() { JsErrorHelpers.ThrowIfError(NativeMethods.JsCollectGarbage(this)); }
/// <summary> /// Sets a promise continuation callback function that is called by the context when a task /// needs to be queued for future execution /// </summary> /// <remarks> /// <para> /// Requires an active script context. /// </para> /// </remarks> /// <param name="promiseContinuationCallback">The callback function being set</param> /// <param name="callbackState">User provided state that will be passed back to the callback</param> public static void SetPromiseContinuationCallback(JsPromiseContinuationCallback promiseContinuationCallback, IntPtr callbackState) { JsErrorHelpers.ThrowIfError(NativeMethods.JsSetPromiseContinuationCallback(promiseContinuationCallback, callbackState)); }
/// <summary> /// Sets an object's property /// </summary> /// <remarks> /// Requires an active script context. /// </remarks> /// <param name="id">The ID of the property</param> /// <param name="value">The new value of the property</param> /// <param name="useStrictRules">The property set should follow strict mode rules</param> public void SetProperty(JsPropertyId id, JsValue value, bool useStrictRules) { JsErrorHelpers.ThrowIfError(NativeMethods.JsSetProperty(this, id, value, useStrictRules)); }
/// <summary> /// Sets an object to not be extensible /// </summary> /// <remarks> /// Requires an active script context /// </remarks> public void PreventExtension() { JsErrorHelpers.ThrowIfError(NativeMethods.JsPreventExtension(this)); }
/// <summary> /// Retrieves a string pointer of a <c>String</c> value /// </summary> /// <remarks> /// <para> /// This function retrieves the string pointer of a <c>String</c> value. It will fail with /// <c>InvalidArgument</c> if the type of the value is not <c>String</c>. /// </para> /// <para> /// Requires an active script context. /// </para> /// </remarks> /// <returns>The string</returns> public new string ToString() { string result; JsErrorCode errorCode; if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows)) { int start = 0; int length = int.MaxValue; char[] buffer = null; UIntPtr written; errorCode = NativeMethods.JsCopyStringUtf16(this, start, length, buffer, out written); JsErrorHelpers.ThrowIfError(errorCode); var charArrayPool = ArrayPool <char> .Shared; length = (int)written; buffer = charArrayPool.Rent(length + 1); buffer[length] = '\0'; try { errorCode = NativeMethods.JsCopyStringUtf16(this, start, length, buffer, out written); JsErrorHelpers.ThrowIfError(errorCode); result = new string(buffer, start, length); } finally { charArrayPool.Return(buffer); } } else { byte[] buffer = null; UIntPtr bufferSize = UIntPtr.Zero; UIntPtr length; errorCode = NativeMethods.JsCopyString(this, buffer, bufferSize, out length); JsErrorHelpers.ThrowIfError(errorCode); var byteArrayPool = ArrayPool <byte> .Shared; bufferSize = length; int bufferLength = (int)bufferSize; buffer = byteArrayPool.Rent(bufferLength + 1); buffer[bufferLength] = 0; try { errorCode = NativeMethods.JsCopyString(this, buffer, bufferSize, out length); JsErrorHelpers.ThrowIfError(errorCode); result = Encoding.UTF8.GetString(buffer, 0, bufferLength); } finally { byteArrayPool.Return(buffer); } } return(result); }
/// <summary> /// Deletes d value at the specified index of an object /// </summary> /// <remarks> /// Requires an active script context. /// </remarks> /// <param name="index">The index to delete</param> public void DeleteIndexedProperty(JsValue index) { JsErrorHelpers.ThrowIfError(NativeMethods.JsDeleteIndexedProperty(this, index)); }
/// <summary> /// Sets a value at the specified index of an object /// </summary> /// <remarks> /// Requires an active script context. /// </remarks> /// <param name="index">The index to set</param> /// <param name="value">The value to set</param> public void SetIndexedProperty(JsValue index, JsValue value) { JsErrorHelpers.ThrowIfError(NativeMethods.JsSetIndexedProperty(this, index, value)); }
/// <summary> /// Sets a runtime of the current context to an exception state /// </summary> /// <remarks> /// <para> /// If the runtime of the current context is already in an exception state, this API will /// throw <c>JsErrorInExceptionState</c>. /// </para> /// <para> /// Requires an active script context. /// </para> /// </remarks> /// <param name="exception">The JavaScript exception to set for the runtime of the current context</param> public static void SetException(JsValue exception) { JsErrorHelpers.ThrowIfError(NativeMethods.JsSetException(exception)); }