-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.mjs
171 lines (145 loc) · 3.95 KB
/
index.mjs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
import { request as https } from "node:https";
import { writeFile, readFile, mkdir } from "node:fs/promises";
import { existsSync } from "node:fs";
import { join, resolve, dirname } from "node:path";
import { randomUUID } from "node:crypto";
const storagePath = resolve(process.env.STORAGE_PATH);
const publishPath = resolve(process.env.PUBLISH_PATH);
const apiUrl = process.env.API_URL;
const apiKey = process.env.API_KEY;
const apiModel = process.env.API_MODEL;
const systemMessage = process.env.API_SYSTEM_MESSAGE;
const completionOptions = {
method: "POST",
headers: {
"Content-Type": "application/json",
Authorization: "Bearer " + apiKey,
},
};
export default async (req, res, next) => {
const url = new URL(req.url, "http://localhost");
const [action, ...args] = url.pathname.slice(1).split("/");
const route = `${req.method} ${action}`.trim();
const event = { req, res, url, args, next };
switch (route) {
case "GET":
case "GET edit":
return onServeEditor(event);
case "POST run":
return onRun(event);
case "POST publish":
return onPublish(event);
case "POST components":
return onSave(event);
case "GET components":
return onLoad(event);
default:
next();
}
};
async function onServeEditor({ args, req, res, next }) {
console.log("Editing " + args[0]);
if (args[0]) {
req.url = '/';
next();
return;
}
res.writeHead(302, {
location: "/edit/" + randomUUID(),
});
res.end();
}
async function onRun({ req, res }) {
try {
const { history, code, instruction } = JSON.parse(await readStream(req));
const remote = https(apiUrl, completionOptions);
const body = JSON.stringify({
model: apiModel,
messages: [
systemMessage && { role: "system", content: systemMessage },
...history.map((m) => ({ role: "user", content: m })),
{ role: "assistant", content: code },
{ role: "user", content: instruction },
].filter(Boolean),
});
remote.on("response", async (incoming) => {
const body = await readStream(incoming);
const answer = JSON.parse(body).choices[0]?.message.content ?? "";
res.end(answer);
});
remote.write(body);
remote.end();
} catch (error) {
console.log(error);
res.writeHead(500);
res.end();
}
}
async function onPublish({ args, res }) {
const id = args[0];
if (!id) {
badRequest("/publish/:id");
return;
}
const sourcePath = join(storagePath, id);
if (!existsSync(sourcePath)) {
notFound(res);
return;
}
const json = JSON.parse(await readFile(sourcePath, "utf-8"));
const targetPath = join(publishPath, id + ".html");
await writeFile(targetPath, json.snippet);
res.end("OK");
}
async function onSave({ req, res, args }) {
const body = await readStream(req);
const fileId = args[0];
if (!fileId) {
badRequest("/component/:id");
return;
}
const path = join(storagePath, fileId);
await ensureFolder(dirname(path));
await writeFile(path, body);
res.writeHead(202);
res.end();
}
async function onLoad({ res, args }) {
const fileId = args[0];
if (!fileId) {
badRequest("/component/:id");
return;
}
const path = join(storagePath, fileId);
await ensureFolder(dirname(path));
if (!existsSync(path)) {
notFound(res);
return;
}
const body = await readFile(path, "utf-8");
res.writeHead(200, {
"content-type": "application/json",
});
res.end(body);
}
function readStream(stream) {
return new Promise((resolve) => {
const a = [];
stream.on("data", (c) => a.push(c));
stream.on("end", () => {
const buffer = Buffer.concat(a).toString("utf-8");
resolve(buffer);
});
});
}
async function ensureFolder(folder) {
return existsSync(folder) || (await mkdir(folder, { recursive: true }));
}
function notFound(res) {
res.writeHead(404);
res.end("Not found");
}
function badRequest(path) {
res.writeHead(400);
res.end(`Missing parameter: ${path}`);
}