# Worklet Runtime

Worklet runtime is a script bundled independently to other scripts running on the main thread, providing the environment for new worklet. Worklet runtime controls the lifecycle of all worklet functions and worklet values and offers entrance to worklet calls.

Worklet runtime is released as part of "react" package as a compiled script. In the user code compiling process, a worklet_post_process swc plugin will be run to check if any worklet functions are used. If yes, a `__LoadLepusChunk` command will be inserted into lepus.js, and the worklet runtime will be inserted into tasm.json as a lepus chunk.

## How worklet runtime interacts with other contexts

**Worklet runtime offers several global functions:**

```ts
/**
 * Entrance of any worklet calls.
 * Native event touch handler will call this function.
 * @param ctx worklet object.
 * @param params worklet params.
 */
function runWorklet(ctx: Worklet, params: ClosureValueType[]): void;

/**
 * Register a worklet function, allowing it to be executed by `runWorklet()`.
 * This is called in lepus.js.
 * @param type worklet type, 'main-thread' or 'ui'
 * @param id worklet hash
 * @param worklet worklet function
 */
function registerWorklet(type: string, id: string, worklet: Function): void;

/**
 * Create an element instance of the given element node, then set worklet value to it.
 * This is called in `snapshotContextUpdateWorkletRef`.
 * @param handle handle of the worklet value.
 * @param element the element node.
 */
function updateWorkletRef(
  handle: WorkletValueImpl<Element>,
  element: ElementNode,
): void;
```

**Worklet runtime listens two events from JS Context:**

`Lynx.Worklet.runWorklet`: dispatched when `runOnMainThread()` is called. Worklet runtime then runs the given worklet object.

`Lynx.Worklet.workletValueDestroy`: dispatched when worklet value object in JS context is released. Worklet runtime then removes the worklet value object from the worklet value map.

**Worklet runtime dispatches one event to JS context:**

`Lynx.Worklet.removeJsWorklets`: dispatched when worklet object is released on the main thread. JS context then removes the `execId->workletObject` relationship from a map, resulting a de-ref to the `workletObject` in JS context.
