diff --git a/js/index.js b/js/index.js new file mode 100644 index 00000000..bf291bb1 --- /dev/null +++ b/js/index.js @@ -0,0 +1,48 @@ +let callbackCounter = 0; +function getUniqueCallbackName() { + return `_callback_${Date.now()}_${callbackCounter++}`; +} + +function exec(command, options) { + if (typeof options === "undefined") { + options = {}; + } + + return new Promise((resolve, reject) => { + // Generate a unique callback function name + const callbackFuncName = getUniqueCallbackName(); + + // Define the success callback function + window[callbackFuncName] = (stdout, stderr) => { + resolve({ stdout, stderr }); + cleanup(callbackFuncName); + }; + + // Define the failure callback function + const errorFuncName = callbackFuncName + "_error"; + window[errorFuncName] = (error) => { + reject(error); + cleanup(callbackFuncName, errorFuncName); + }; + + // Cleanup function to remove the callbacks + function cleanup(successName, errorName = successName) { + delete window[successName]; + if (errorName) { + delete window[errorName]; + } + } + + try { + ksu.exec( + command, + JSON.stringify(options), + callbackFuncName, + errorFuncName + ); + } catch (error) { + reject(error); + cleanup(callbackFuncName, errorFuncName); + } + }); +} diff --git a/js/package.json b/js/package.json new file mode 100644 index 00000000..8b6b5ec8 --- /dev/null +++ b/js/package.json @@ -0,0 +1,25 @@ +{ + "name": "kernelsu", + "version": "1.0.0", + "description": "Library for KernelSU's module WebUI", + "main": "index.js", + "scripts": { + "test": "npm run test" + }, + "repository": { + "type": "git", + "url": "git+https://github.com/tiann/KernelSU.git" + }, + "keywords": [ + "su", + "kernelsu", + "module", + "webui" + ], + "author": "weishu", + "license": "GPL-3.0-or-later", + "bugs": { + "url": "https://github.com/tiann/KernelSU/issues" + }, + "homepage": "https://github.com/tiann/KernelSU#readme" +}