open-index/open-npm huggingface dataset:
npm package: @kalphax/core
Description: Add the following code to your Electron project.
Latest version: 1.2.1

# Kalphax

### Project Setup

Add the following code to your Electron project.

_declarations.d.ts_
```
import { Bridge } from '@kalphax/core';

declare global {
    interface Window {
        [x: string]: <T>() => Promise<T>;
    }
}
```

_main.ts (Electron main process)_
```
ipcMain.on('to.myFunction', (event, value: string) => {
    // ...
    return `You provided value: ${value}`;
});
```

_preload.ts (Electron preloader)_
```
import { contextBridge } from 'electron';

contextBridge.exposeInMainWorld('api', {
    myFunction: async (value: string): Promise<string> => {
        // Spawn a bridge with the following channels
        const myBridge = new Bridge({
            channels: {
                senders: ['to.myFunction'],
                receivers: ['from.myFunction']
            }
        });
        
        // Give the signal to ipcMain to run myFunction
        myBridge.send<string>('to.myFunction', value);

        // Wait for ipcMain to finish its process and return a value
        const result = await myBridge.receive<string>('from.myFunction');

        // Unsubscribe all listeners
        myBridge.dispose();

        return result;
    }
});
```

-----

### Accessing a bridge

Accessing a property from your bridge is easy. Simply call `window.api.<property>`. For instance, if your context bridge looks like the one in the example above, you would call `window.api.myFunction.send` and `window.api.myFunction.receive`.

Here are some examples on how to utilize the IPC bridge.

##### Vanilla
```
<body>
    <div id="myFunctionResult"></div>

    <script type="text/javascript">
        window.addEventListener('DOMContentLoaded', function() {
            window.api.myFunction().then(data => {
                document.getElementById('myFunctionResult').innerText = data;
            });
        });
    </script>
</body>
```

##### React
```
import React, { useState } from 'react';

const MyComponent = () => {
    const [loading, setLoading] = useState<boolean>(true);
    const [runningMyFunction, setRunningMyFunction] = useState<boolean>(false);
    const [errorMyFunction, setErrorMyFunction] = useState<boolean>(false);
    const [myFunctionResult, setMyFunctionResult] = useState<string>();

    if (loading && !fetchingUniqueId) {
        setFetchingUniqueId(true);
        window.api.myFunction('from.myFunction')
            .then((data: string) => setMyFunctionResult(data))
            .catch(() => setErrorMyFunction(true))
            .finally(() => setRunningMyFunction(false));
    }

    if (loading && myFunctionResult !== undefined || errorMyFunction) {
        setLoading(false);
    }

    return (
        <div>{myFunctionResult}</div>
    )
}
```