-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathputer.worker.js
More file actions
244 lines (201 loc) · 7.16 KB
/
puter.worker.js
File metadata and controls
244 lines (201 loc) · 7.16 KB
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
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
const HOSTING_CONFIG_KEY = "roomify_hosting_config";
const PROJECT_PREFIX = "roomify_project_";
const PUBLIC_PREFIX = "roomify_public_";
const USER_PREFIX = "roomify_user_";
const jsonError = (status, message, extra = {}) =>
new Response(JSON.stringify({ error: message, ...extra }), {
status,
headers: {
"Content-Type": "application/json",
"Access-Control-Allow-Origin": "*",
},
});
const jsonOk = (payload) =>
new Response(JSON.stringify(payload), {
status: 200,
headers: {
"Content-Type": "application/json",
"Access-Control-Allow-Origin": "*",
},
});
const sanitizeProjectPayload = (project) => {
if (!project || typeof project !== "object") return project;
const { sourcePath, renderedPath, publicPath, ...rest } = project;
return rest;
};
const getUserId = async (userPuter) => {
try {
const user = await userPuter.auth.getUser();
return user?.uuid || null;
} catch {
return null;
}
};
const getPublicKey = (userId, projectId) => `${PUBLIC_PREFIX}${userId}_${projectId}`;
const deleteKvByPattern = async (kv, pattern) => {
if (!kv) return 0;
let entries = await kv.list(pattern);
if (entries.length === 0) return 0;
await Promise.all(
entries.map((key) => kv.del(key)),
);
return entries.length;
};
const findPublicKeyByProjectId = async (mePuter, projectId) => {
const entries = await mePuter.kv.list(`${PUBLIC_PREFIX}*`, true);
const match = entries.find((entry) => entry?.value?.id === projectId);
return match?.key || null;
};
const resolveUsername = async (mePuter, userId) => {
if (!userId) return null;
const userRecord = await mePuter.kv.get(`${USER_PREFIX}${userId}`);
return userRecord?.username || null;
};
router.get("/api/projects/list", async ({ user }) => {
try {
const mePuter = me.puter;
const userPuter = user.puter;
if (!userPuter) throw new Error("Missing user Puter context.");
const userItems = (await userPuter.kv.list(`${PROJECT_PREFIX}*`, true))
.map(({ value }) => value);
const publicItems = (await mePuter.kv.list(`${PUBLIC_PREFIX}*`, true))
.map(({ value }) => ({ ...value, isPublic: true}));
const ownerIds = [...new Set(publicItems.map((p) => p.ownerId).filter(Boolean))];
const usernames = Object.fromEntries(
await Promise.all(ownerIds.map(async (id) => [id, await resolveUsername(mePuter, id)])),
);
for (const item of publicItems) {
if (item.ownerId && usernames[item.ownerId]) {
item.sharedBy = usernames[item.ownerId];
}
}
const merged = [...userItems, ...publicItems];
merged.sort((a, b) => (b?.timestamp || 0) - (a?.timestamp || 0));
return { projects: merged };
} catch (error) {
return jsonError(500, "Failed to list projects", {
message: error?.message || "Unknown error",
});
}
});
router.get("/api/projects/get", async ({ request, user }) => {
try {
const mePuter = me.puter;
const userPuter = user.puter;
if (!userPuter) return jsonError(401, "Authentication required");
const url = new URL(request.url);
const id = url.searchParams.get("id");
const scope = url.searchParams.get("scope") || "user";
const ownerId = url.searchParams.get("ownerId");
if (!id) return jsonError(400, "Project id required");
if (scope === "private") {
// PRIVATE PROJECT
const key = `${PROJECT_PREFIX}${id}`;
const project = await userPuter.kv.get(key);
if (!project) return jsonError(404, "Project not found");
return { project };
} else {
// PUBLIC PROJECT
const publicKey = ownerId
? getPublicKey(ownerId, id)
: await findPublicKeyByProjectId(mePuter, id);
if (!publicKey) return jsonError(404, "Project not found");
const project = await mePuter.kv.get(publicKey);
if (!project) return jsonError(404, "Project not found");
if (project.ownerId) {
const username = await resolveUsername(mePuter, project.ownerId);
if (username) project.sharedBy = username;
}
return { project };
}
} catch (error) {
return jsonError(500, "Failed to get project", {
message: error?.message || "Unknown error",
});
}
});
router.post("/api/projects/save", async ({ request, user }) => {
try {
const mePuter = me.puter;
const userPuter = user.puter;
if (!userPuter) return jsonError(401, "Authentication required");
const body = await request.json();
const project = body?.project;
const scope = body?.visibility === "public" ? "public" : "private";
if (!project?.id || !project?.sourceImage)
return jsonError(400, "Project id and image required");
const payload = {
...sanitizeProjectPayload(project),
updatedAt: new Date().toISOString(),
};
const userId = await getUserId(userPuter);
if (!userId) return jsonError(401, "User id required");
if (scope === "private") {
// PRIVATE PROJECT
const key = `${PROJECT_PREFIX}${project.id}`;
await userPuter.kv.set(key, payload);
// remove existing public project
const publicKey = getPublicKey(userId, project.id);
await mePuter.kv.del(publicKey);
return { saved: true, id: project.id, project: payload };
} else {
// PUBLIC PROJECT
const publicKey = getPublicKey(userId, project.id);
const userInfo = await userPuter.auth.getUser();
let username = userInfo?.username || userInfo?.name || null;
if (username) await mePuter.kv.set(`${USER_PREFIX}${userId}`, { username });
const publicRecord = {
...payload,
ownerId: userId,
sharedBy: username,
sharedAt: new Date().toISOString(),
};
await mePuter.kv.set(publicKey, publicRecord);
// remove existing private project
const userKey = `${PROJECT_PREFIX}${project.id}`;
await userPuter.kv.del(userKey);
return { saved: true, id: project.id, project: publicRecord };
}
} catch (error) {
return jsonError(500, "Failed to save project", {
message: error?.message || "Unknown error",
});
}
});
router.post("/api/projects/clear", async ({ user }) => {
const userPuter = user.puter;
const mePuter = me.puter;
if (!userPuter) return jsonError(401, "Authentication required");
const userDeleted = userPuter?.kv
? await deleteKvByPattern(userPuter.kv, `${PROJECT_PREFIX}*`)
: 0;
const publicDeleted = mePuter?.kv
? await deleteKvByPattern(mePuter.kv, `${PUBLIC_PREFIX}*`)
: 0;
const usernameDeleted = mePuter?.kv
? await deleteKvByPattern(mePuter.kv, `${USER_PREFIX}*`)
: 0;
return jsonOk({
cleared: userDeleted,
clearedPublic: publicDeleted,
clearedUsernames: usernameDeleted,
});
});
router.post("/api/hosting/clear", async ({ user }) => {
const userPuter = user.puter;
if (!userPuter) return jsonError(401, "Authentication required");
await userPuter.kv.del(HOSTING_CONFIG_KEY);
return jsonOk({ reset: true });
});
router.get("/*path", async ({ params }) => {
return jsonError(404, "Not found", {
path: params.path,
availableEndpoints: [
"/api/projects/list",
"/api/projects/get",
"/api/projects/save",
"/api/projects/clear",
"/api/hosting/clear",
],
});
});