js: Add jsapi package

This commit is contained in:
weishu
2024-02-22 20:42:15 +08:00
parent f20ccc1728
commit 811c68cac0
2 changed files with 73 additions and 0 deletions

48
js/index.js Normal file
View File

@@ -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);
}
});
}

25
js/package.json Normal file
View File

@@ -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"
}