Created
September 7, 2023 14:59
-
-
Save johnlindquist/46a249045959a31e0929ff23691a0960 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* | |
# Script Hub | |
You can access this on your phone from: | |
http://kit.local | |
Run a script by going to http://kit.local/my-script-name | |
*/ | |
// Name: Script Hub | |
// Background: auto | |
import "@johnlindquist/kit" | |
import express from "express" | |
import { Responder } from "@homebridge/ciao" | |
import detect from "detect-port" | |
import httpProxy from "http-proxy" | |
const expressPort = await detect(3000) | |
const ciaoPort = 80 | |
const app = express() | |
app.get("/", (req, res) => { | |
// You could build a UI here to list all the scripts | |
// For example, loop through all the files in kenvPath("scripts") | |
// Then click on one to send it to kit.local/my-script-name | |
res.send(`<h1>Run a script by going to http://kit.local/my-script-name</h1>`) | |
}) | |
app.get("/:script", async (req, res) => { | |
const script = req.params.script | |
const scriptPath = kenvPath("scripts", `${script}.js`) | |
const scriptExists = await isFile(scriptPath) | |
if (!scriptExists) { | |
const message = `Script ${script} does not exist` | |
console.log(message) | |
res.send(message) | |
return | |
} | |
res.send(`Running script: ${script}`) | |
const child = spawn( | |
knodePath("bin", "node"), | |
[ | |
"--experimental-loader", | |
kitPath("build", "loader.js"), | |
kitPath("run", "terminal.js"), | |
kenvPath("scripts", `${script}.js`), | |
], | |
{ | |
env: { | |
...process.env, | |
NODE_NO_WARNINGS: "1", | |
KENV: kenvPath(), | |
}, | |
shell: "/bin/sh", | |
} | |
) | |
child.stdout.on("data", data => { | |
console.log(`stdout: ${data}`) | |
}) | |
child.stderr.on("data", data => { | |
console.error(`stderr: ${data}`) | |
}) | |
child.on("close", code => { | |
console.log(`child process exited with code ${code}`) | |
}) | |
}) | |
app.listen(expressPort, () => { | |
console.log(`Express server running on http://localhost:${expressPort}`) | |
}) | |
const proxy = httpProxy.createProxyServer() | |
const proxyServer = express() | |
proxyServer.all("*", (req, res) => { | |
proxy.web(req, res, { target: `http://localhost:${expressPort}` }) | |
}) | |
proxyServer.listen(ciaoPort, () => { | |
console.log(`Proxy running on http://localhost:${ciaoPort}`) | |
}) | |
const responder = new Responder() | |
const httpService = responder.createService({ | |
name: "kit", | |
type: "http", | |
port: ciaoPort, | |
}) | |
httpService.advertise() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment