Compare commits
12 Commits
e2b-test
...
fix/max-sa
Author | SHA1 | Date | |
---|---|---|---|
ba0fab6856 | |||
186d765682 | |||
2994a4d291 | |||
85ebfe4161 | |||
cfed8a225e | |||
e7dd3238df | |||
530aa2ff53 | |||
3c4850ee72 | |||
e3b2d882dd | |||
0df074924f | |||
e5b320d1c5 | |||
b561f1e962 |
@ -1,19 +0,0 @@
|
||||
# e2b template build --name "terminal"
|
||||
|
||||
# Use a Debian-based base image
|
||||
FROM ubuntu:22.04
|
||||
|
||||
# Install dependencies and customize sandbox
|
||||
RUN apt update \
|
||||
&& apt install -y sudo
|
||||
|
||||
# Install xterm
|
||||
RUN apt update \
|
||||
&& apt install -y xterm
|
||||
|
||||
RUN apt update \
|
||||
&& apt install -y tmux screen
|
||||
|
||||
# Clean up
|
||||
RUN apt clean \
|
||||
&& rm -rf /var/lib/apt/lists/*
|
@ -1,14 +0,0 @@
|
||||
# This is a config for E2B sandbox template.
|
||||
# You can use 'template_id' (ne8xtb57tq5xw9vwhdyc) or 'template_name (terminal) from this config to spawn a sandbox:
|
||||
|
||||
# Python SDK
|
||||
# from e2b import Sandbox
|
||||
# sandbox = Sandbox(template='terminal')
|
||||
|
||||
# JS SDK
|
||||
# import { Sandbox } from 'e2b'
|
||||
# const sandbox = await Sandbox.create({ template: 'terminal' })
|
||||
|
||||
dockerfile = "e2b.Dockerfile"
|
||||
template_name = "terminal"
|
||||
template_id = "ne8xtb57tq5xw9vwhdyc"
|
@ -110,12 +110,17 @@ export default {
|
||||
const body = await request.json()
|
||||
const { type, name, userId, visibility } = initSchema.parse(body)
|
||||
|
||||
const allSandboxes = await db.select().from(sandbox).all()
|
||||
if (allSandboxes.length >= 8) {
|
||||
return new Response("You reached the maximum # of sandboxes.", {
|
||||
status: 400,
|
||||
})
|
||||
}
|
||||
const userSandboxes = await db
|
||||
.select()
|
||||
.from(sandbox)
|
||||
.where(eq(sandbox.userId, userId))
|
||||
.all();
|
||||
|
||||
if (userSandboxes.length >= 8) {
|
||||
return new Response("You reached the maximum # of sandboxes.", {
|
||||
status: 400,
|
||||
});
|
||||
}
|
||||
|
||||
const sb = await db
|
||||
.insert(sandbox)
|
||||
|
@ -31,8 +31,8 @@ export const sandbox = sqliteTable("sandbox", {
|
||||
createdAt: integer("createdAt", { mode: "timestamp_ms" }),
|
||||
userId: text("user_id")
|
||||
.notNull()
|
||||
.references(() => user.id),
|
||||
});
|
||||
.references(() => user.id, { onDelete: "cascade" }),
|
||||
});
|
||||
|
||||
export type Sandbox = typeof sandbox.$inferSelect;
|
||||
|
||||
|
50
backend/server/package-lock.json
generated
50
backend/server/package-lock.json
generated
@ -9,12 +9,11 @@
|
||||
"version": "1.0.0",
|
||||
"license": "ISC",
|
||||
"dependencies": {
|
||||
"@e2b/code-interpreter": "^0.0.7",
|
||||
"concurrently": "^8.2.2",
|
||||
"cors": "^2.8.5",
|
||||
"dotenv": "^16.4.5",
|
||||
"e2b": "^0.16.1",
|
||||
"express": "^4.19.2",
|
||||
"node-pty": "^1.0.0",
|
||||
"rate-limiter-flexible": "^5.0.3",
|
||||
"socket.io": "^4.7.5",
|
||||
"zod": "^3.22.4"
|
||||
@ -51,39 +50,6 @@
|
||||
"node": ">=12"
|
||||
}
|
||||
},
|
||||
"node_modules/@e2b/code-interpreter": {
|
||||
"version": "0.0.7",
|
||||
"resolved": "https://registry.npmjs.org/@e2b/code-interpreter/-/code-interpreter-0.0.7.tgz",
|
||||
"integrity": "sha512-e8nAY4zXU2b9nKthqq/pCPlTVD7f01dtzCtvabWmhlx7Wq+AUln14Q1Wf+uRVJXHkwS9BDv2CupdZpUChsjoCA==",
|
||||
"dependencies": {
|
||||
"e2b": "^0.16.1",
|
||||
"isomorphic-ws": "^5.0.0",
|
||||
"ws": "^8.15.1"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">=18"
|
||||
}
|
||||
},
|
||||
"node_modules/@e2b/code-interpreter/node_modules/ws": {
|
||||
"version": "8.17.0",
|
||||
"resolved": "https://registry.npmjs.org/ws/-/ws-8.17.0.tgz",
|
||||
"integrity": "sha512-uJq6108EgZMAl20KagGkzCKfMEjxmKvZHG7Tlq0Z6nOky7YF7aq4mOx6xK8TJ/i1LeK4Qus7INktacctDgY8Ow==",
|
||||
"engines": {
|
||||
"node": ">=10.0.0"
|
||||
},
|
||||
"peerDependencies": {
|
||||
"bufferutil": "^4.0.1",
|
||||
"utf-8-validate": ">=5.0.2"
|
||||
},
|
||||
"peerDependenciesMeta": {
|
||||
"bufferutil": {
|
||||
"optional": true
|
||||
},
|
||||
"utf-8-validate": {
|
||||
"optional": true
|
||||
}
|
||||
}
|
||||
},
|
||||
"node_modules/@jridgewell/resolve-uri": {
|
||||
"version": "3.1.2",
|
||||
"resolved": "https://registry.npmjs.org/@jridgewell/resolve-uri/-/resolve-uri-3.1.2.tgz",
|
||||
@ -1281,11 +1247,6 @@
|
||||
"resolved": "https://registry.npmjs.org/ms/-/ms-2.0.0.tgz",
|
||||
"integrity": "sha512-Tpp60P6IUJDTuOq/5Z8cdskzJujfwqfOTkrwIwj7IRISpnkJnT6SyJ4PCPnGMoFjC9ddhal5KVIYtAt97ix05A=="
|
||||
},
|
||||
"node_modules/nan": {
|
||||
"version": "2.19.0",
|
||||
"resolved": "https://registry.npmjs.org/nan/-/nan-2.19.0.tgz",
|
||||
"integrity": "sha512-nO1xXxfh/RWNxfd/XPfbIfFk5vgLsAxUR9y5O0cHMJu/AW9U95JLXqthYHjEp+8gQ5p96K9jUp8nbVOxCdRbtw=="
|
||||
},
|
||||
"node_modules/negotiator": {
|
||||
"version": "0.6.3",
|
||||
"resolved": "https://registry.npmjs.org/negotiator/-/negotiator-0.6.3.tgz",
|
||||
@ -1305,15 +1266,6 @@
|
||||
"node-gyp-build-test": "build-test.js"
|
||||
}
|
||||
},
|
||||
"node_modules/node-pty": {
|
||||
"version": "1.0.0",
|
||||
"resolved": "https://registry.npmjs.org/node-pty/-/node-pty-1.0.0.tgz",
|
||||
"integrity": "sha512-wtBMWWS7dFZm/VgqElrTvtfMq4GzJ6+edFI0Y0zyzygUSZMgZdraDUMUhCIvkjhJjme15qWmbyJbtAx4ot4uZA==",
|
||||
"hasInstallScript": true,
|
||||
"dependencies": {
|
||||
"nan": "^2.17.0"
|
||||
}
|
||||
},
|
||||
"node_modules/nodemon": {
|
||||
"version": "3.1.0",
|
||||
"resolved": "https://registry.npmjs.org/nodemon/-/nodemon-3.1.0.tgz",
|
||||
|
@ -11,12 +11,11 @@
|
||||
"author": "",
|
||||
"license": "ISC",
|
||||
"dependencies": {
|
||||
"@e2b/code-interpreter": "^0.0.7",
|
||||
"concurrently": "^8.2.2",
|
||||
"cors": "^2.8.5",
|
||||
"dotenv": "^16.4.5",
|
||||
"e2b": "^0.16.1",
|
||||
"express": "^4.19.2",
|
||||
"node-pty": "^1.0.0",
|
||||
"rate-limiter-flexible": "^5.0.3",
|
||||
"socket.io": "^4.7.5",
|
||||
"zod": "^3.22.4"
|
||||
|
177
backend/server/src/fileoperations.ts
Normal file
177
backend/server/src/fileoperations.ts
Normal file
@ -0,0 +1,177 @@
|
||||
import * as dotenv from "dotenv";
|
||||
import {
|
||||
R2FileBody,
|
||||
R2Files,
|
||||
Sandbox,
|
||||
TFile,
|
||||
TFileData,
|
||||
TFolder,
|
||||
} from "./types";
|
||||
|
||||
dotenv.config();
|
||||
|
||||
export const getSandboxFiles = async (id: string) => {
|
||||
const res = await fetch(
|
||||
`${process.env.STORAGE_WORKER_URL}/api?sandboxId=${id}`,
|
||||
{
|
||||
headers: {
|
||||
Authorization: `${process.env.WORKERS_KEY}`,
|
||||
},
|
||||
}
|
||||
);
|
||||
const data: R2Files = await res.json();
|
||||
|
||||
const paths = data.objects.map((obj) => obj.key);
|
||||
const processedFiles = await processFiles(paths, id);
|
||||
return processedFiles;
|
||||
};
|
||||
|
||||
export const getFolder = async (folderId: string) => {
|
||||
const res = await fetch(
|
||||
`${process.env.STORAGE_WORKER_URL}/api?folderId=${folderId}`,
|
||||
{
|
||||
headers: {
|
||||
Authorization: `${process.env.WORKERS_KEY}`,
|
||||
},
|
||||
}
|
||||
);
|
||||
const data: R2Files = await res.json();
|
||||
|
||||
return data.objects.map((obj) => obj.key);
|
||||
};
|
||||
|
||||
const processFiles = async (paths: string[], id: string) => {
|
||||
const root: TFolder = { id: "/", type: "folder", name: "/", children: [] };
|
||||
const fileData: TFileData[] = [];
|
||||
|
||||
paths.forEach((path) => {
|
||||
const allParts = path.split("/");
|
||||
if (allParts[1] !== id) {
|
||||
return;
|
||||
}
|
||||
|
||||
const parts = allParts.slice(2);
|
||||
let current: TFolder = root;
|
||||
|
||||
for (let i = 0; i < parts.length; i++) {
|
||||
const part = parts[i];
|
||||
const isFile = i === parts.length - 1 && part.includes(".");
|
||||
const existing = current.children.find((child) => child.name === part);
|
||||
|
||||
if (existing) {
|
||||
if (!isFile) {
|
||||
current = existing as TFolder;
|
||||
}
|
||||
} else {
|
||||
if (isFile) {
|
||||
const file: TFile = { id: path, type: "file", name: part };
|
||||
current.children.push(file);
|
||||
fileData.push({ id: path, data: "" });
|
||||
} else {
|
||||
const folder: TFolder = {
|
||||
// id: path, // todo: wrong id. for example, folder "src" ID is: projects/a7vgttfqbgy403ratp7du3ln/src/App.css
|
||||
id: `projects/${id}/${parts.slice(0, i + 1).join("/")}`,
|
||||
type: "folder",
|
||||
name: part,
|
||||
children: [],
|
||||
};
|
||||
current.children.push(folder);
|
||||
current = folder;
|
||||
}
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
await Promise.all(
|
||||
fileData.map(async (file) => {
|
||||
const data = await fetchFileContent(file.id);
|
||||
file.data = data;
|
||||
})
|
||||
);
|
||||
|
||||
return {
|
||||
files: root.children,
|
||||
fileData,
|
||||
};
|
||||
};
|
||||
|
||||
const fetchFileContent = async (fileId: string): Promise<string> => {
|
||||
try {
|
||||
const fileRes = await fetch(
|
||||
`${process.env.STORAGE_WORKER_URL}/api?fileId=${fileId}`,
|
||||
{
|
||||
headers: {
|
||||
Authorization: `${process.env.WORKERS_KEY}`,
|
||||
},
|
||||
}
|
||||
);
|
||||
return await fileRes.text();
|
||||
} catch (error) {
|
||||
console.error("ERROR fetching file:", error);
|
||||
return "";
|
||||
}
|
||||
};
|
||||
|
||||
export const createFile = async (fileId: string) => {
|
||||
const res = await fetch(`${process.env.STORAGE_WORKER_URL}/api`, {
|
||||
method: "POST",
|
||||
headers: {
|
||||
"Content-Type": "application/json",
|
||||
Authorization: `${process.env.WORKERS_KEY}`,
|
||||
},
|
||||
body: JSON.stringify({ fileId }),
|
||||
});
|
||||
return res.ok;
|
||||
};
|
||||
|
||||
export const renameFile = async (
|
||||
fileId: string,
|
||||
newFileId: string,
|
||||
data: string
|
||||
) => {
|
||||
const res = await fetch(`${process.env.STORAGE_WORKER_URL}/api/rename`, {
|
||||
method: "POST",
|
||||
headers: {
|
||||
"Content-Type": "application/json",
|
||||
Authorization: `${process.env.WORKERS_KEY}`,
|
||||
},
|
||||
body: JSON.stringify({ fileId, newFileId, data }),
|
||||
});
|
||||
return res.ok;
|
||||
};
|
||||
|
||||
export const saveFile = async (fileId: string, data: string) => {
|
||||
const res = await fetch(`${process.env.STORAGE_WORKER_URL}/api/save`, {
|
||||
method: "POST",
|
||||
headers: {
|
||||
"Content-Type": "application/json",
|
||||
Authorization: `${process.env.WORKERS_KEY}`,
|
||||
},
|
||||
body: JSON.stringify({ fileId, data }),
|
||||
});
|
||||
return res.ok;
|
||||
};
|
||||
|
||||
export const deleteFile = async (fileId: string) => {
|
||||
const res = await fetch(`${process.env.STORAGE_WORKER_URL}/api`, {
|
||||
method: "DELETE",
|
||||
headers: {
|
||||
"Content-Type": "application/json",
|
||||
Authorization: `${process.env.WORKERS_KEY}`,
|
||||
},
|
||||
body: JSON.stringify({ fileId }),
|
||||
});
|
||||
return res.ok;
|
||||
};
|
||||
|
||||
export const getProjectSize = async (id: string) => {
|
||||
const res = await fetch(
|
||||
`${process.env.STORAGE_WORKER_URL}/api/size?sandboxId=${id}`,
|
||||
{
|
||||
headers: {
|
||||
Authorization: `${process.env.WORKERS_KEY}`,
|
||||
},
|
||||
}
|
||||
);
|
||||
return (await res.json()).size;
|
||||
};
|
@ -1,4 +1,3 @@
|
||||
import fs from "fs";
|
||||
import os from "os";
|
||||
import path from "path";
|
||||
import cors from "cors";
|
||||
@ -17,8 +16,9 @@ import {
|
||||
getSandboxFiles,
|
||||
renameFile,
|
||||
saveFile,
|
||||
} from "./utils";
|
||||
import { Sandbox, Process, ProcessMessage } from "e2b";
|
||||
} from "./fileoperations";
|
||||
import { LockManager } from "./utils";
|
||||
import { Sandbox, Terminal, FilesystemManager } from "e2b";
|
||||
import {
|
||||
MAX_BODY_SIZE,
|
||||
createFileRL,
|
||||
@ -43,14 +43,17 @@ const io = new Server(httpServer, {
|
||||
let inactivityTimeout: NodeJS.Timeout | null = null;
|
||||
let isOwnerConnected = false;
|
||||
|
||||
const terminals: {
|
||||
[id: string]: Process;
|
||||
} = {};
|
||||
const containers: {
|
||||
[id: string]: Sandbox;
|
||||
} = {};
|
||||
const containers: Record<string, Sandbox> = {};
|
||||
const connections: Record<string, number> = {};
|
||||
const terminals: Record<string, Terminal> = {};
|
||||
|
||||
const dirName = path.join(__dirname, "..");
|
||||
const dirName = "/home/user";
|
||||
|
||||
const moveFile = async (filesystem: FilesystemManager, filePath: string, newFilePath: string) => {
|
||||
const fileContents = await filesystem.readBytes(filePath)
|
||||
await filesystem.writeBytes(newFilePath, fileContents);
|
||||
await filesystem.remove(filePath);
|
||||
}
|
||||
|
||||
io.use(async (socket, next) => {
|
||||
const handshakeSchema = z.object({
|
||||
@ -103,30 +106,6 @@ io.use(async (socket, next) => {
|
||||
next();
|
||||
});
|
||||
|
||||
class LockManager {
|
||||
private locks: { [key: string]: Promise<any> };
|
||||
|
||||
constructor() {
|
||||
this.locks = {};
|
||||
}
|
||||
|
||||
async acquireLock<T>(key: string, task: () => Promise<T>): Promise<T> {
|
||||
if (!this.locks[key]) {
|
||||
this.locks[key] = new Promise<T>(async (resolve, reject) => {
|
||||
try {
|
||||
const result = await task();
|
||||
resolve(result);
|
||||
} catch (error) {
|
||||
reject(error);
|
||||
} finally {
|
||||
delete this.locks[key];
|
||||
}
|
||||
});
|
||||
}
|
||||
return await this.locks[key];
|
||||
}
|
||||
}
|
||||
|
||||
const lockManager = new LockManager();
|
||||
|
||||
io.on("connection", async (socket) => {
|
||||
@ -140,6 +119,7 @@ io.on("connection", async (socket) => {
|
||||
|
||||
if (data.isOwner) {
|
||||
isOwnerConnected = true;
|
||||
connections[data.sandboxId] = (connections[data.sandboxId] ?? 0) + 1;
|
||||
} else {
|
||||
if (!isOwnerConnected) {
|
||||
socket.emit("disableAccess", "The sandbox owner is not connected.");
|
||||
@ -148,23 +128,31 @@ io.on("connection", async (socket) => {
|
||||
}
|
||||
|
||||
await lockManager.acquireLock(data.sandboxId, async () => {
|
||||
if (!containers[data.sandboxId]) {
|
||||
console.log("Creating container ", data.sandboxId);
|
||||
containers[data.sandboxId] = await Sandbox.create({
|
||||
template: "terminal",
|
||||
});
|
||||
console.log("Created.");
|
||||
try {
|
||||
if (!containers[data.sandboxId]) {
|
||||
containers[data.sandboxId] = await Sandbox.create();
|
||||
console.log("Created container ", data.sandboxId);
|
||||
io.emit("previewURL", "https://" + containers[data.sandboxId].getHostname(5173));
|
||||
}
|
||||
} catch (error) {
|
||||
console.error("Error creating container ", data.sandboxId, error);
|
||||
}
|
||||
});
|
||||
|
||||
// Change the owner of the project directory to user
|
||||
const fixPermissions = async () => {
|
||||
await containers[data.sandboxId].process.startAndWait(
|
||||
`sudo chown -R user "${path.join(dirName, "projects", data.sandboxId)}"`
|
||||
);
|
||||
}
|
||||
|
||||
const sandboxFiles = await getSandboxFiles(data.sandboxId);
|
||||
sandboxFiles.fileData.forEach((file) => {
|
||||
sandboxFiles.fileData.forEach(async (file) => {
|
||||
const filePath = path.join(dirName, file.id);
|
||||
fs.mkdirSync(path.dirname(filePath), { recursive: true });
|
||||
fs.writeFile(filePath, file.data, function (err) {
|
||||
if (err) throw err;
|
||||
});
|
||||
await containers[data.sandboxId].filesystem.makeDir(path.dirname(filePath));
|
||||
await containers[data.sandboxId].filesystem.write(filePath, file.data);
|
||||
});
|
||||
fixPermissions();
|
||||
|
||||
socket.emit("loaded", sandboxFiles.files);
|
||||
|
||||
@ -197,9 +185,8 @@ io.on("connection", async (socket) => {
|
||||
if (!file) return;
|
||||
file.data = body;
|
||||
|
||||
fs.writeFile(path.join(dirName, file.id), body, function (err) {
|
||||
if (err) throw err;
|
||||
});
|
||||
await containers[data.sandboxId].filesystem.write(path.join(dirName, file.id), body);
|
||||
fixPermissions();
|
||||
await saveFile(fileId, body);
|
||||
} catch (e) {
|
||||
io.emit("rateLimit", "Rate limited: file saving. Please slow down.");
|
||||
@ -213,13 +200,12 @@ io.on("connection", async (socket) => {
|
||||
const parts = fileId.split("/");
|
||||
const newFileId = folderId + "/" + parts.pop();
|
||||
|
||||
fs.rename(
|
||||
await moveFile(
|
||||
containers[data.sandboxId].filesystem,
|
||||
path.join(dirName, fileId),
|
||||
path.join(dirName, newFileId),
|
||||
function (err) {
|
||||
if (err) throw err;
|
||||
}
|
||||
);
|
||||
path.join(dirName, newFileId)
|
||||
)
|
||||
fixPermissions();
|
||||
|
||||
file.id = newFileId;
|
||||
|
||||
@ -245,9 +231,8 @@ io.on("connection", async (socket) => {
|
||||
|
||||
const id = `projects/${data.sandboxId}/${name}`;
|
||||
|
||||
fs.writeFile(path.join(dirName, id), "", function (err) {
|
||||
if (err) throw err;
|
||||
});
|
||||
await containers[data.sandboxId].filesystem.write(path.join(dirName, id), "");
|
||||
fixPermissions();
|
||||
|
||||
sandboxFiles.files.push({
|
||||
id,
|
||||
@ -274,9 +259,7 @@ io.on("connection", async (socket) => {
|
||||
|
||||
const id = `projects/${data.sandboxId}/${name}`;
|
||||
|
||||
fs.mkdir(path.join(dirName, id), { recursive: true }, function (err) {
|
||||
if (err) throw err;
|
||||
});
|
||||
await containers[data.sandboxId].filesystem.makeDir(path.join(dirName, id));
|
||||
|
||||
callback();
|
||||
} catch (e) {
|
||||
@ -296,13 +279,13 @@ io.on("connection", async (socket) => {
|
||||
const newFileId =
|
||||
parts.slice(0, parts.length - 1).join("/") + "/" + newName;
|
||||
|
||||
fs.rename(
|
||||
|
||||
await moveFile(
|
||||
containers[data.sandboxId].filesystem,
|
||||
path.join(dirName, fileId),
|
||||
path.join(dirName, newFileId),
|
||||
function (err) {
|
||||
if (err) throw err;
|
||||
}
|
||||
);
|
||||
path.join(dirName, newFileId)
|
||||
)
|
||||
fixPermissions();
|
||||
await renameFile(fileId, newFileId, file.data);
|
||||
} catch (e) {
|
||||
io.emit("rateLimit", "Rate limited: file renaming. Please slow down.");
|
||||
@ -316,9 +299,7 @@ io.on("connection", async (socket) => {
|
||||
const file = sandboxFiles.fileData.find((f) => f.id === fileId);
|
||||
if (!file) return;
|
||||
|
||||
fs.unlink(path.join(dirName, fileId), function (err) {
|
||||
if (err) throw err;
|
||||
});
|
||||
await containers[data.sandboxId].filesystem.remove(path.join(dirName, fileId));
|
||||
sandboxFiles.fileData = sandboxFiles.fileData.filter(
|
||||
(f) => f.id !== fileId
|
||||
);
|
||||
@ -341,9 +322,7 @@ io.on("connection", async (socket) => {
|
||||
|
||||
await Promise.all(
|
||||
files.map(async (file) => {
|
||||
fs.unlink(path.join(dirName, file), function (err) {
|
||||
if (err) throw err;
|
||||
});
|
||||
await containers[data.sandboxId].filesystem.remove(path.join(dirName, file));
|
||||
|
||||
sandboxFiles.fileData = sandboxFiles.fileData.filter(
|
||||
(f) => f.id !== file
|
||||
@ -358,56 +337,35 @@ io.on("connection", async (socket) => {
|
||||
callback(newFiles.files);
|
||||
});
|
||||
|
||||
function toBackslashNotation(input: string) {
|
||||
return input
|
||||
.replace(/\\/g, "\\\\") // Escape backslashes
|
||||
.replace(/\n/g, "\\n") // Escape newlines
|
||||
.replace(/\r/g, "\\r") // Escape carriage returns
|
||||
.replace(/\t/g, "\\t") // Escape tabs
|
||||
.replace(/"/g, '\\"') // Escape double quotes
|
||||
.replace(/'/g, "\\'") // Escape single quotes
|
||||
.replace(/\f/g, "\\f") // Escape form feeds
|
||||
.replace(/\b/g, "\\b") // Escape backspaces
|
||||
.replace(/\v/g, "\\v") // Escape vertical tabs
|
||||
.replace(/\0/g, "\\0") // Escape null characters
|
||||
.replace(/\a/g, "\\a") // Escape alert (bell)
|
||||
.replace(/\e/g, "\\e"); // Escape escape
|
||||
}
|
||||
|
||||
socket.on("createTerminal", async (id: string, callback) => {
|
||||
if (terminals[id] || Object.keys(terminals).length >= 4) {
|
||||
return;
|
||||
}
|
||||
|
||||
const onData = (data: ProcessMessage) => {
|
||||
console.log("process", toBackslashNotation(data.toString()));
|
||||
io.emit("terminalResponse", {
|
||||
id,
|
||||
data: data.toString() + "\r\n",
|
||||
});
|
||||
};
|
||||
|
||||
await lockManager.acquireLock(data.sandboxId, async () => {
|
||||
console.log("Creating terminal", id);
|
||||
terminals[id] = await containers[data.sandboxId].process.start({
|
||||
cmd: 'TERM=xterm script -c "screen" /dev/null', // xterm vt100
|
||||
onStdout: onData,
|
||||
onStderr: onData,
|
||||
onExit: (code) => console.log("exit :(", code),
|
||||
});
|
||||
await terminals[id].sendStdin("clear\r\n");
|
||||
await terminals[id].sendStdin("export PS1='user> '\r\n");
|
||||
await terminals[id].sendStdin("clear\r\n");
|
||||
console.log("Created terminal", id);
|
||||
try {
|
||||
terminals[id] = await containers[data.sandboxId].terminal.start({
|
||||
onData: (data: string) => {
|
||||
io.emit("terminalResponse", { id, data });
|
||||
},
|
||||
size: { cols: 80, rows: 20 },
|
||||
onExit: () => console.log("Terminal exited", id),
|
||||
});
|
||||
await terminals[id].sendData(`cd "${path.join(dirName, "projects", data.sandboxId)}"\r`)
|
||||
await terminals[id].sendData("export PS1='user> '\rclear\r");
|
||||
console.log("Created terminal", id);
|
||||
} catch (error) {
|
||||
console.error("Error creating terminal ", id, error);
|
||||
}
|
||||
});
|
||||
|
||||
callback();
|
||||
});
|
||||
|
||||
socket.on("resizeTerminal", (dimensions: { cols: number; rows: number }) => {
|
||||
/*Object.values(terminals).forEach((t) => {
|
||||
t.terminal.resize(dimensions.cols, dimensions.rows);
|
||||
});*/
|
||||
Object.values(terminals).forEach((t) => {
|
||||
t.resize(dimensions);
|
||||
});
|
||||
});
|
||||
|
||||
socket.on("terminalData", (id: string, data: string) => {
|
||||
@ -416,8 +374,7 @@ io.on("connection", async (socket) => {
|
||||
}
|
||||
|
||||
try {
|
||||
console.log(`Writing ${toBackslashNotation(data)} to ${id}`);
|
||||
terminals[id].sendStdin(data);
|
||||
terminals[id].sendData(data);
|
||||
} catch (e) {
|
||||
console.log("Error writing to terminal", e);
|
||||
}
|
||||
@ -481,18 +438,26 @@ io.on("connection", async (socket) => {
|
||||
|
||||
socket.on("disconnect", async () => {
|
||||
if (data.isOwner) {
|
||||
Object.entries(terminals).forEach((t) => {
|
||||
const terminal = t[1];
|
||||
terminal.kill();
|
||||
delete terminals[t[0]];
|
||||
});
|
||||
connections[data.sandboxId]--;
|
||||
}
|
||||
|
||||
if (data.isOwner && connections[data.sandboxId] <= 0) {
|
||||
await Promise.all(
|
||||
Object.entries(terminals).map(async ([key, terminal]) => {
|
||||
await terminal.kill();
|
||||
delete terminals[key];
|
||||
})
|
||||
);
|
||||
|
||||
await lockManager.acquireLock(data.sandboxId, async () => {
|
||||
if (containers[data.sandboxId]) {
|
||||
console.log("Closing container", data.sandboxId);
|
||||
await containers[data.sandboxId].close();
|
||||
delete containers[data.sandboxId];
|
||||
console.log("Closed");
|
||||
try {
|
||||
if (containers[data.sandboxId]) {
|
||||
await containers[data.sandboxId].close();
|
||||
delete containers[data.sandboxId];
|
||||
console.log("Closed container", data.sandboxId);
|
||||
}
|
||||
} catch (error) {
|
||||
console.error("Error closing container ", data.sandboxId, error);
|
||||
}
|
||||
});
|
||||
|
||||
|
@ -1,177 +1,23 @@
|
||||
import * as dotenv from "dotenv";
|
||||
import {
|
||||
R2FileBody,
|
||||
R2Files,
|
||||
Sandbox,
|
||||
TFile,
|
||||
TFileData,
|
||||
TFolder,
|
||||
} from "./types";
|
||||
export class LockManager {
|
||||
private locks: { [key: string]: Promise<any> };
|
||||
|
||||
dotenv.config();
|
||||
|
||||
export const getSandboxFiles = async (id: string) => {
|
||||
const res = await fetch(
|
||||
`${process.env.STORAGE_WORKER_URL}/api?sandboxId=${id}`,
|
||||
{
|
||||
headers: {
|
||||
Authorization: `${process.env.WORKERS_KEY}`,
|
||||
},
|
||||
}
|
||||
);
|
||||
const data: R2Files = await res.json();
|
||||
|
||||
const paths = data.objects.map((obj) => obj.key);
|
||||
const processedFiles = await processFiles(paths, id);
|
||||
return processedFiles;
|
||||
};
|
||||
|
||||
export const getFolder = async (folderId: string) => {
|
||||
const res = await fetch(
|
||||
`${process.env.STORAGE_WORKER_URL}/api?folderId=${folderId}`,
|
||||
{
|
||||
headers: {
|
||||
Authorization: `${process.env.WORKERS_KEY}`,
|
||||
},
|
||||
}
|
||||
);
|
||||
const data: R2Files = await res.json();
|
||||
|
||||
return data.objects.map((obj) => obj.key);
|
||||
};
|
||||
|
||||
const processFiles = async (paths: string[], id: string) => {
|
||||
const root: TFolder = { id: "/", type: "folder", name: "/", children: [] };
|
||||
const fileData: TFileData[] = [];
|
||||
|
||||
paths.forEach((path) => {
|
||||
const allParts = path.split("/");
|
||||
if (allParts[1] !== id) {
|
||||
return;
|
||||
}
|
||||
|
||||
const parts = allParts.slice(2);
|
||||
let current: TFolder = root;
|
||||
|
||||
for (let i = 0; i < parts.length; i++) {
|
||||
const part = parts[i];
|
||||
const isFile = i === parts.length - 1 && part.includes(".");
|
||||
const existing = current.children.find((child) => child.name === part);
|
||||
|
||||
if (existing) {
|
||||
if (!isFile) {
|
||||
current = existing as TFolder;
|
||||
}
|
||||
} else {
|
||||
if (isFile) {
|
||||
const file: TFile = { id: path, type: "file", name: part };
|
||||
current.children.push(file);
|
||||
fileData.push({ id: path, data: "" });
|
||||
} else {
|
||||
const folder: TFolder = {
|
||||
// id: path, // todo: wrong id. for example, folder "src" ID is: projects/a7vgttfqbgy403ratp7du3ln/src/App.css
|
||||
id: `projects/${id}/${parts.slice(0, i + 1).join("/")}`,
|
||||
type: "folder",
|
||||
name: part,
|
||||
children: [],
|
||||
};
|
||||
current.children.push(folder);
|
||||
current = folder;
|
||||
}
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
await Promise.all(
|
||||
fileData.map(async (file) => {
|
||||
const data = await fetchFileContent(file.id);
|
||||
file.data = data;
|
||||
})
|
||||
);
|
||||
|
||||
return {
|
||||
files: root.children,
|
||||
fileData,
|
||||
};
|
||||
};
|
||||
|
||||
const fetchFileContent = async (fileId: string): Promise<string> => {
|
||||
try {
|
||||
const fileRes = await fetch(
|
||||
`${process.env.STORAGE_WORKER_URL}/api?fileId=${fileId}`,
|
||||
{
|
||||
headers: {
|
||||
Authorization: `${process.env.WORKERS_KEY}`,
|
||||
},
|
||||
}
|
||||
);
|
||||
return await fileRes.text();
|
||||
} catch (error) {
|
||||
console.error("ERROR fetching file:", error);
|
||||
return "";
|
||||
constructor() {
|
||||
this.locks = {};
|
||||
}
|
||||
};
|
||||
|
||||
export const createFile = async (fileId: string) => {
|
||||
const res = await fetch(`${process.env.STORAGE_WORKER_URL}/api`, {
|
||||
method: "POST",
|
||||
headers: {
|
||||
"Content-Type": "application/json",
|
||||
Authorization: `${process.env.WORKERS_KEY}`,
|
||||
},
|
||||
body: JSON.stringify({ fileId }),
|
||||
});
|
||||
return res.ok;
|
||||
};
|
||||
|
||||
export const renameFile = async (
|
||||
fileId: string,
|
||||
newFileId: string,
|
||||
data: string
|
||||
) => {
|
||||
const res = await fetch(`${process.env.STORAGE_WORKER_URL}/api/rename`, {
|
||||
method: "POST",
|
||||
headers: {
|
||||
"Content-Type": "application/json",
|
||||
Authorization: `${process.env.WORKERS_KEY}`,
|
||||
},
|
||||
body: JSON.stringify({ fileId, newFileId, data }),
|
||||
});
|
||||
return res.ok;
|
||||
};
|
||||
|
||||
export const saveFile = async (fileId: string, data: string) => {
|
||||
const res = await fetch(`${process.env.STORAGE_WORKER_URL}/api/save`, {
|
||||
method: "POST",
|
||||
headers: {
|
||||
"Content-Type": "application/json",
|
||||
Authorization: `${process.env.WORKERS_KEY}`,
|
||||
},
|
||||
body: JSON.stringify({ fileId, data }),
|
||||
});
|
||||
return res.ok;
|
||||
};
|
||||
|
||||
export const deleteFile = async (fileId: string) => {
|
||||
const res = await fetch(`${process.env.STORAGE_WORKER_URL}/api`, {
|
||||
method: "DELETE",
|
||||
headers: {
|
||||
"Content-Type": "application/json",
|
||||
Authorization: `${process.env.WORKERS_KEY}`,
|
||||
},
|
||||
body: JSON.stringify({ fileId }),
|
||||
});
|
||||
return res.ok;
|
||||
};
|
||||
|
||||
export const getProjectSize = async (id: string) => {
|
||||
const res = await fetch(
|
||||
`${process.env.STORAGE_WORKER_URL}/api/size?sandboxId=${id}`,
|
||||
{
|
||||
headers: {
|
||||
Authorization: `${process.env.WORKERS_KEY}`,
|
||||
},
|
||||
async acquireLock<T>(key: string, task: () => Promise<T>): Promise<T> {
|
||||
if (!this.locks[key]) {
|
||||
this.locks[key] = new Promise<T>(async (resolve, reject) => {
|
||||
try {
|
||||
const result = await task();
|
||||
resolve(result);
|
||||
} catch (error) {
|
||||
reject(error);
|
||||
} finally {
|
||||
delete this.locks[key];
|
||||
}
|
||||
});
|
||||
}
|
||||
);
|
||||
return (await res.json()).size;
|
||||
};
|
||||
return await this.locks[key];
|
||||
}
|
||||
}
|
@ -1,9 +1,9 @@
|
||||
"use client"
|
||||
|
||||
import { useEffect, useRef, useState } from "react"
|
||||
import { SetStateAction, useCallback, useEffect, useRef, useState } from "react"
|
||||
import monaco from "monaco-editor"
|
||||
import Editor, { BeforeMount, OnMount } from "@monaco-editor/react"
|
||||
import { io } from "socket.io-client"
|
||||
import { Socket, io } from "socket.io-client"
|
||||
import { toast } from "sonner"
|
||||
import { useClerk } from "@clerk/nextjs"
|
||||
|
||||
@ -23,7 +23,7 @@ import Tab from "../ui/tab"
|
||||
import Sidebar from "./sidebar"
|
||||
import GenerateInput from "./generate"
|
||||
import { Sandbox, User, TFile, TFolder, TTab } from "@/lib/types"
|
||||
import { addNew, processFileType, validateName } from "@/lib/utils"
|
||||
import { addNew, processFileType, validateName, debounce } from "@/lib/utils"
|
||||
import { Cursors } from "./live/cursors"
|
||||
import { Terminal } from "@xterm/xterm"
|
||||
import DisableAccessModal from "./live/disableModal"
|
||||
@ -41,12 +41,16 @@ export default function CodeEditor({
|
||||
sandboxData: Sandbox
|
||||
reactDefinitionFile: string
|
||||
}) {
|
||||
const socket = io(
|
||||
`http://localhost:${process.env.NEXT_PUBLIC_SERVER_PORT}?userId=${userData.id}&sandboxId=${sandboxData.id}`,
|
||||
{
|
||||
timeout: 2000,
|
||||
}
|
||||
)
|
||||
const socketRef = useRef<Socket | null>(null);
|
||||
|
||||
// Initialize socket connection if it doesn't exist
|
||||
if (!socketRef.current) {
|
||||
socketRef.current = io(
|
||||
`http://localhost:${process.env.NEXT_PUBLIC_SERVER_PORT}?userId=${userData.id}&sandboxId=${sandboxData.id}`,
|
||||
{
|
||||
timeout: 2000,
|
||||
}
|
||||
);}
|
||||
|
||||
const [isPreviewCollapsed, setIsPreviewCollapsed] = useState(true)
|
||||
const [disableAccess, setDisableAccess] = useState({
|
||||
@ -90,6 +94,9 @@ export default function CodeEditor({
|
||||
}[]
|
||||
>([])
|
||||
|
||||
// Preview state
|
||||
const [previewURL, setPreviewURL] = useState<string>("");
|
||||
|
||||
const isOwner = sandboxData.userId === userData.id
|
||||
const clerk = useClerk()
|
||||
|
||||
@ -290,26 +297,33 @@ export default function CodeEditor({
|
||||
}, [decorations.options])
|
||||
|
||||
// Save file keybinding logic effect
|
||||
const debouncedSaveData = useCallback(
|
||||
debounce((value: string | undefined, activeFileId: string | undefined) => {
|
||||
setTabs((prev) =>
|
||||
prev.map((tab) =>
|
||||
tab.id === activeFileId ? { ...tab, saved: true } : tab
|
||||
)
|
||||
);
|
||||
console.log(`Saving file...${activeFileId}`);
|
||||
console.log(`Saving file...${value}`);
|
||||
socketRef.current?.emit("saveFile", activeFileId, value);
|
||||
}, Number(process.env.FILE_SAVE_DEBOUNCE_DELAY)||1000),
|
||||
[socketRef]
|
||||
);
|
||||
|
||||
useEffect(() => {
|
||||
const down = (e: KeyboardEvent) => {
|
||||
if (e.key === "s" && (e.metaKey || e.ctrlKey)) {
|
||||
e.preventDefault()
|
||||
|
||||
setTabs((prev) =>
|
||||
prev.map((tab) =>
|
||||
tab.id === activeFileId ? { ...tab, saved: true } : tab
|
||||
)
|
||||
)
|
||||
|
||||
socket.emit("saveFile", activeFileId, editorRef?.getValue())
|
||||
e.preventDefault();
|
||||
debouncedSaveData(editorRef?.getValue(), activeFileId);
|
||||
}
|
||||
}
|
||||
document.addEventListener("keydown", down)
|
||||
};
|
||||
document.addEventListener("keydown", down);
|
||||
|
||||
return () => {
|
||||
document.removeEventListener("keydown", down)
|
||||
}
|
||||
}, [tabs, activeFileId])
|
||||
document.removeEventListener("keydown", down);
|
||||
};
|
||||
}, [activeFileId, tabs, debouncedSaveData]);
|
||||
|
||||
// Liveblocks live collaboration setup effect
|
||||
useEffect(() => {
|
||||
@ -358,10 +372,10 @@ export default function CodeEditor({
|
||||
|
||||
// Connection/disconnection effect
|
||||
useEffect(() => {
|
||||
socket.connect()
|
||||
socketRef.current?.connect()
|
||||
|
||||
return () => {
|
||||
socket.disconnect()
|
||||
socketRef.current?.disconnect()
|
||||
}
|
||||
}, [])
|
||||
|
||||
@ -396,20 +410,22 @@ export default function CodeEditor({
|
||||
})
|
||||
}
|
||||
|
||||
socket.on("connect", onConnect)
|
||||
socket.on("disconnect", onDisconnect)
|
||||
socket.on("loaded", onLoadedEvent)
|
||||
socket.on("rateLimit", onRateLimit)
|
||||
socket.on("terminalResponse", onTerminalResponse)
|
||||
socket.on("disableAccess", onDisableAccess)
|
||||
socketRef.current?.on("connect", onConnect)
|
||||
socketRef.current?.on("disconnect", onDisconnect)
|
||||
socketRef.current?.on("loaded", onLoadedEvent)
|
||||
socketRef.current?.on("rateLimit", onRateLimit)
|
||||
socketRef.current?.on("terminalResponse", onTerminalResponse)
|
||||
socketRef.current?.on("disableAccess", onDisableAccess)
|
||||
socketRef.current?.on("previewURL", setPreviewURL)
|
||||
|
||||
return () => {
|
||||
socket.off("connect", onConnect)
|
||||
socket.off("disconnect", onDisconnect)
|
||||
socket.off("loaded", onLoadedEvent)
|
||||
socket.off("rateLimit", onRateLimit)
|
||||
socket.off("terminalResponse", onTerminalResponse)
|
||||
socket.off("disableAccess", onDisableAccess)
|
||||
socketRef.current?.off("connect", onConnect)
|
||||
socketRef.current?.off("disconnect", onDisconnect)
|
||||
socketRef.current?.off("loaded", onLoadedEvent)
|
||||
socketRef.current?.off("rateLimit", onRateLimit)
|
||||
socketRef.current?.off("terminalResponse", onTerminalResponse)
|
||||
socketRef.current?.off("disableAccess", onDisableAccess)
|
||||
socketRef.current?.off("previewURL", setPreviewURL)
|
||||
}
|
||||
// }, []);
|
||||
}, [terminals])
|
||||
@ -417,31 +433,44 @@ export default function CodeEditor({
|
||||
// Helper functions for tabs:
|
||||
|
||||
// Select file and load content
|
||||
const selectFile = (tab: TTab) => {
|
||||
if (tab.id === activeFileId) return
|
||||
|
||||
setGenerate((prev) => {
|
||||
return {
|
||||
...prev,
|
||||
show: false,
|
||||
}
|
||||
})
|
||||
const exists = tabs.find((t) => t.id === tab.id)
|
||||
// Initialize debounced function once
|
||||
const fileCache = useRef(new Map());
|
||||
|
||||
// Debounced function to get file content
|
||||
const debouncedGetFile = useCallback(
|
||||
debounce((tabId, callback) => {
|
||||
socketRef.current?.emit('getFile', tabId, callback);
|
||||
}, 300), // 300ms debounce delay, adjust as needed
|
||||
[]
|
||||
);
|
||||
|
||||
const selectFile = useCallback((tab: TTab) => {
|
||||
if (tab.id === activeFileId) return;
|
||||
|
||||
setGenerate((prev) => ({ ...prev, show: false }));
|
||||
|
||||
const exists = tabs.find((t) => t.id === tab.id);
|
||||
setTabs((prev) => {
|
||||
if (exists) {
|
||||
setActiveFileId(exists.id)
|
||||
return prev
|
||||
setActiveFileId(exists.id);
|
||||
return prev;
|
||||
}
|
||||
return [...prev, tab]
|
||||
})
|
||||
return [...prev, tab];
|
||||
});
|
||||
|
||||
socket.emit("getFile", tab.id, (response: string) => {
|
||||
setActiveFileContent(response)
|
||||
})
|
||||
setEditorLanguage(processFileType(tab.name))
|
||||
setActiveFileId(tab.id)
|
||||
}
|
||||
if (fileCache.current.has(tab.id)) {
|
||||
setActiveFileContent(fileCache.current.get(tab.id));
|
||||
} else {
|
||||
debouncedGetFile(tab.id, (response: SetStateAction<string>) => {
|
||||
fileCache.current.set(tab.id, response);
|
||||
setActiveFileContent(response);
|
||||
});
|
||||
}
|
||||
|
||||
setEditorLanguage(processFileType(tab.name));
|
||||
setActiveFileId(tab.id);
|
||||
}, [activeFileId, tabs, debouncedGetFile]);
|
||||
|
||||
// Close tab and remove from tabs
|
||||
const closeTab = (id: string) => {
|
||||
@ -515,7 +544,7 @@ export default function CodeEditor({
|
||||
return false
|
||||
}
|
||||
|
||||
socket.emit("renameFile", id, newName)
|
||||
socketRef.current?.emit("renameFile", id, newName)
|
||||
setTabs((prev) =>
|
||||
prev.map((tab) => (tab.id === id ? { ...tab, name: newName } : tab))
|
||||
)
|
||||
@ -524,7 +553,7 @@ export default function CodeEditor({
|
||||
}
|
||||
|
||||
const handleDeleteFile = (file: TFile) => {
|
||||
socket.emit("deleteFile", file.id, (response: (TFolder | TFile)[]) => {
|
||||
socketRef.current?.emit("deleteFile", file.id, (response: (TFolder | TFile)[]) => {
|
||||
setFiles(response)
|
||||
})
|
||||
closeTab(file.id)
|
||||
@ -534,11 +563,11 @@ export default function CodeEditor({
|
||||
setDeletingFolderId(folder.id)
|
||||
console.log("deleting folder", folder.id)
|
||||
|
||||
socket.emit("getFolder", folder.id, (response: string[]) =>
|
||||
socketRef.current?.emit("getFolder", folder.id, (response: string[]) =>
|
||||
closeTabs(response)
|
||||
)
|
||||
|
||||
socket.emit("deleteFolder", folder.id, (response: (TFolder | TFile)[]) => {
|
||||
socketRef.current?.emit("deleteFolder", folder.id, (response: (TFolder | TFile)[]) => {
|
||||
setFiles(response)
|
||||
setDeletingFolderId("")
|
||||
})
|
||||
@ -565,7 +594,7 @@ export default function CodeEditor({
|
||||
{generate.show && ai ? (
|
||||
<GenerateInput
|
||||
user={userData}
|
||||
socket={socket}
|
||||
socket={socketRef.current}
|
||||
width={generate.width - 90}
|
||||
data={{
|
||||
fileName: tabs.find((t) => t.id === activeFileId)?.name ?? "",
|
||||
@ -625,7 +654,7 @@ export default function CodeEditor({
|
||||
handleRename={handleRename}
|
||||
handleDeleteFile={handleDeleteFile}
|
||||
handleDeleteFolder={handleDeleteFolder}
|
||||
socket={socket}
|
||||
socket={socketRef.current}
|
||||
setFiles={setFiles}
|
||||
addNew={(name, type) => addNew(name, type, setFiles, sandboxData)}
|
||||
deletingFolderId={deletingFolderId}
|
||||
@ -745,6 +774,7 @@ export default function CodeEditor({
|
||||
previewPanelRef.current?.expand()
|
||||
setIsPreviewCollapsed(false)
|
||||
}}
|
||||
src={previewURL}
|
||||
/>
|
||||
</ResizablePanel>
|
||||
<ResizableHandle />
|
||||
@ -757,7 +787,7 @@ export default function CodeEditor({
|
||||
<Terminals
|
||||
terminals={terminals}
|
||||
setTerminals={setTerminals}
|
||||
socket={socket}
|
||||
socket={socketRef.current}
|
||||
/>
|
||||
) : (
|
||||
<div className="w-full h-full flex items-center justify-center text-lg font-medium text-muted-foreground/50 select-none">
|
||||
@ -772,3 +802,4 @@ export default function CodeEditor({
|
||||
</>
|
||||
)
|
||||
}
|
||||
|
||||
|
@ -15,9 +15,11 @@ import { toast } from "sonner"
|
||||
export default function PreviewWindow({
|
||||
collapsed,
|
||||
open,
|
||||
src
|
||||
}: {
|
||||
collapsed: boolean
|
||||
open: () => void
|
||||
src: string
|
||||
}) {
|
||||
const ref = useRef<HTMLIFrameElement>(null)
|
||||
const [iframeKey, setIframeKey] = useState(0)
|
||||
@ -45,7 +47,7 @@ export default function PreviewWindow({
|
||||
|
||||
<PreviewButton
|
||||
onClick={() => {
|
||||
navigator.clipboard.writeText(`http://localhost:5173`)
|
||||
navigator.clipboard.writeText(src)
|
||||
toast.info("Copied preview link to clipboard")
|
||||
}}
|
||||
>
|
||||
@ -73,7 +75,7 @@ export default function PreviewWindow({
|
||||
ref={ref}
|
||||
width={"100%"}
|
||||
height={"100%"}
|
||||
src={`http://localhost:5173`}
|
||||
src={src}
|
||||
/>
|
||||
</div>
|
||||
)}
|
||||
|
@ -61,3 +61,13 @@ export function addNew(
|
||||
])
|
||||
}
|
||||
}
|
||||
|
||||
export function debounce<T extends (...args: any[]) => void>(func: T, wait: number): T {
|
||||
let timeout: NodeJS.Timeout | null = null;
|
||||
return function (...args: Parameters<T>) {
|
||||
if (timeout) {
|
||||
clearTimeout(timeout);
|
||||
}
|
||||
timeout = setTimeout(() => func(...args), wait);
|
||||
} as T;
|
||||
}
|
Reference in New Issue
Block a user