Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: codesandbox sdk support #1249

Open
wants to merge 12 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 4 additions & 0 deletions .codesandbox/tasks.json
Original file line number Diff line number Diff line change
Expand Up @@ -63,6 +63,10 @@
"pr-link": "direct"
}
},
"dev:nextjs": {
"name": "Dev: Nextjs example",
"command": "yarn dev:nextjs"
},
"dev:website-landing": {
"name": "Dev: Website landing",
"command": "yarn dev:landing"
Expand Down
22 changes: 22 additions & 0 deletions examples/nextjs-app-dir/app/api/sandbox/[id]/route.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
import { CodeSandbox } from "@codesandbox/sdk";

type Params = { params: { id: string } };

const apiKey = process.env.CSB_API_TOKEN as string;
const sdk = new CodeSandbox(apiKey, {});

export const GET = async (_req: Request, { params }: Params) => {
const templateId = params.id;
const data = await sdk.sandbox.start(templateId);

return new Response(JSON.stringify(data), { status: 200 });
};

export const POST = async (_req: Request, { params }: Params) => {
const templateId = params.id;

const sandbox = await sdk.sandbox.create({ template: templateId });
const data = await sdk.sandbox.start(sandbox.id);

return new Response(JSON.stringify(data), { status: 200 });
};
48 changes: 42 additions & 6 deletions examples/nextjs-app-dir/components/sandpack-examples.tsx
Original file line number Diff line number Diff line change
@@ -1,16 +1,52 @@
import { Sandpack } from "@codesandbox/sandpack-react";
import { githubLight, sandpackDark } from "@codesandbox/sandpack-themes";
"use client";
import {
Sandpack,
SandpackCodeEditor,
SandpackFileExplorer,
SandpackLayout,
SandpackPreview,
SandpackProvider,
} from "@codesandbox/sandpack-react";
import { useState } from "react";

const TEMPLATES = ["vite-react-ts", "nextjs", "rust", "python", "node"];

/**
* The only reason this is a separate import, is so
* we don't need to make the full page 'use client', but only this copmponent.
*/
export const SandpackExamples = () => {
const [state, setState] = useState(
window.localStorage["template"] || TEMPLATES[0]
);

return (
<>
<Sandpack />
<Sandpack theme="dark" />
<Sandpack theme={githubLight} template="nextjs" />
<Sandpack options={{ readOnly: true }} theme={sandpackDark} />
<select
value={state}
onChange={(event) => {
window.localStorage["template"] = event.target.value;
setState(event.target.value);
}}
>
{TEMPLATES.map((item) => (
<option value={item}>{item}</option>
))}
</select>

<SandpackProvider
key={state}
template={state}
options={{
vmEnvironmentApiUrl: (id) => `/api/sandbox/${id}`,
}}
>
<SandpackLayout style={{ "--sp-layout-height": "500px" }}>
<SandpackFileExplorer />
<SandpackCodeEditor closableTabs />
<SandpackPreview />
</SandpackLayout>
</SandpackProvider>
</>
);
};
2 changes: 1 addition & 1 deletion examples/nextjs-app-dir/next-env.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,4 +2,4 @@
/// <reference types="next/image-types/global" />

// NOTE: This file should not be edited
// see https://nextjs.org/docs/basic-features/typescript for more information.
// see https://nextjs.org/docs/app/building-your-application/configuring/typescript for more information.
4 changes: 3 additions & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@
"sandpack-client",
"sandpack-react",
"sandpack-themes",
"examples/nextjs-app-dir",
"website/*"
],
"nohoist": [
Expand All @@ -26,7 +27,8 @@
"dev:docs": "yarn workspace sandpack-docs dev",
"dev:react": "turbo run dev --filter=@codesandbox/sandpack-react --filter=@codesandbox/sandpack-client",
"dev:landing": "yarn workspace sandpack-landing dev -p 3001",
"dev:theme": "yarn workspace sandpack-theme dev -p 3002"
"dev:theme": "yarn workspace sandpack-theme dev -p 3002",
"dev:nextjs": "yarn workspace nextjs-app-dir dev"
},
"repository": {
"type": "git",
Expand Down
1 change: 1 addition & 0 deletions sandpack-client/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -56,6 +56,7 @@
],
"dependencies": {
"@codesandbox/nodebox": "0.1.8",
"@codesandbox/sdk": "0.0.0-alpha.8",
"buffer": "^6.0.3",
"dequal": "^2.0.2",
"mime-db": "^1.52.0",
Expand Down
2 changes: 1 addition & 1 deletion sandpack-client/src/clients/event-emitter.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ import type {

export class EventEmitter {
private listeners: Record<number, ListenerFunction> = {};
private listenersCount = 0;
public listenersCount = 0;

readonly channelId: number = Math.floor(Math.random() * 1000000);

Expand Down
4 changes: 4 additions & 0 deletions sandpack-client/src/clients/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,10 @@ export async function loadSandpackClient(
Client = await import("./static").then((m) => m.SandpackStatic);
break;

case "vm":
Client = await import("./vm").then((m) => m.SandpackVM);
break;

default:
Client = await import("./runtime").then((m) => m.SandpackRuntime);
}
Expand Down
61 changes: 61 additions & 0 deletions sandpack-client/src/clients/vm/client.utils.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,61 @@
import { findStartScriptPackageJson } from "./client.utils";

describe(findStartScriptPackageJson, () => {
it("should parse a regular command", () => {
expect(
findStartScriptPackageJson(JSON.stringify({ scripts: { start: "node" } }))
).toEqual(["node", [], { env: {} }]);
});

it("should parse a regular command with arguments", () => {
expect(
findStartScriptPackageJson(
JSON.stringify({ scripts: { start: "node dev --foo" } })
)
).toEqual(["node", ["dev", "--foo"], { env: {} }]);
});

it("should get dev script first", () => {
expect(
findStartScriptPackageJson(
JSON.stringify({
scripts: { start: "node start --foo", dev: "node dev --foo" },
})
)
).toEqual(["node", ["dev", "--foo"], { env: {} }]);
});

it("should parse env vars", () => {
expect(
findStartScriptPackageJson(
JSON.stringify({
scripts: { start: "NODE=1 ANOTHER=2 node start --foo" },
})
)
).toEqual([
"node",
["start", "--foo"],
{ env: { NODE: "1", ANOTHER: "2" } },
]);
});

it("should parse a single env var", () => {
expect(
findStartScriptPackageJson(
JSON.stringify({
scripts: { start: "NODE=1 node start --foo" },
})
)
).toEqual(["node", ["start", "--foo"], { env: { NODE: "1" } }]);
});

it("should parse a single env var and a single commmand", () => {
expect(
findStartScriptPackageJson(
JSON.stringify({
scripts: { start: "NODE=1 node" },
})
)
).toEqual(["node", [], { env: { NODE: "1" } }]);
});
});
139 changes: 139 additions & 0 deletions sandpack-client/src/clients/vm/client.utils.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,139 @@
import type { SandboxWithoutClient } from "@codesandbox/sdk/dist/esm/sandbox";

import { createError } from "../..";
import type { SandpackBundlerFiles } from "../../";

let counter = 0;

export function generateRandomId() {
const now = Date.now();
const randomNumber = Math.round(Math.random() * 10000);
const count = (counter += 1);
return (+`${now}${randomNumber}${count}`).toString(16);
}

export const writeBuffer = (content: string | Uint8Array): Uint8Array => {
if (typeof content === "string") {
return new TextEncoder().encode(content);
} else {
return content;
}
};

export const readBuffer = (content: string | Uint8Array): string => {
if (typeof content === "string") {
return content;
} else {
return new TextDecoder().decode(content);
}
};

export const fromBundlerFilesToFS = (
files: SandpackBundlerFiles
): Record<string, Uint8Array> => {
return Object.entries(files).reduce<Record<string, Uint8Array>>(
(acc, [key, value]) => {
acc[key] = writeBuffer(value.code);

return acc;
},
{}
);
};

export const getMessageFromError = (error: Error | string): string => {
if (typeof error === "string") return error;

if (typeof error === "object" && "message" in error) {
return error.message;
}

return createError(
"The server could not be reached. Make sure that the node script is running and that a port has been started."
);
};

export async function scanDirectory(
dirPath: string,
fs: SandboxWithoutClient["fs"]
) {
const IGNORED_DIRS = new Set([
"node_modules",
".git",
"dist",
"build",
"coverage",
".cache",
".next",
".nuxt",
".output",
".vscode",
".idea",
".devcontainer",
".codesandbox",
"yarn.lock",
"pnpm-lock.yaml",
]);

const TYPES = {
FILE: 0,
FOLDER: 1,
};

const results: Array<{ path: string; content: Uint8Array }> = [];

try {
const entries = await fs.readdir(dirPath);

for (const entry of entries) {
const fullPath = dirPath + "/" + entry.name;

if (entry.isSymlink || IGNORED_DIRS.has(entry.name)) {
continue;
}

if (entry.type === TYPES.FILE) {
results.push({
path: fullPath,
content: await fs.readFile(fullPath),
});
}

// Recursively scan subdirectories
if (entry.type === TYPES.FOLDER) {
const subDirResults = await scanDirectory(fullPath, fs);
results.push(...subDirResults);
}
}

return results;
} catch (error) {
console.error(`Error scanning directory ${dirPath}:`, error);
throw error;
}
}

let groupId = 1;
export const createLogGroup = (group: string) => {
let logId = 1;

// eslint-disable-next-line no-console
console.group(`[${groupId++}]: ${group}`);

return {
// eslint-disable-next-line no-console
groupEnd: () => console.groupEnd(),
log: (...args: unknown[]): void => {
// eslint-disable-next-line no-console
console.debug(`[${logId++}]:`, ...args);
},
};
};

export const throwIfTimeout = (timeout: number) => {
return new Promise((_, reject) =>
setTimeout(() => {
reject(new Error(`Timeout of ${timeout}ms exceeded`));
}, timeout)
);
};
Loading
Loading