Open-source, secure environment with real-world tools for enterprise-grade agents.
Python agentaiai-agentai-agentscode-interpretercopilotdevelopmentdevtoolsgptgpt-4javascriptllmnextjsopenaipythonreactsoftwaretypescript
feat(docs): Runnable snippets (#123)
Pavel 'Strajk' Dolecek96df77dff478
diff --git a/apps/docs/src/app/getting-started/api-key/APIKey.tsx b/apps/docs/src/app/getting-started/api-key/APIKey.tsxindex 7917fbc71..bfd2a3c82 100644--- a/apps/docs/src/app/getting-started/api-key/APIKey.tsx+++ b/apps/docs/src/app/getting-started/api-key/APIKey.tsx@@ -4,27 +4,16 @@ import clsx from 'clsx'import { Button } from '@/components/Button'import { useApiKey, useUser } from '@/utils/useUser'import { obfuscateKey } from '@/utils/obfuscate'-import { createClientComponentClient } from '@supabase/auth-helpers-nextjs'import { CopyButton } from '@/components/CopyButton'import { usePostHog } from 'posthog-js/react'+import { useSignIn } from '@/utils/useSignIn'function APIKey() {- const supabase = createClientComponentClient()+ const signIn = useSignIn()const { user, isLoading, error } = useUser()const apiKey = useApiKey()const posthog = usePostHog()- async function signInWithGitHub() {- await supabase.auth.signInWithOAuth({- // redirect to GitHub- provider: 'github',- options: {- redirectTo: window.location.href,- scopes: 'email',- },- })- }-return (<div className="flex flex-col items-start justify-start space-y-4">{user ? (@@ -35,7 +24,7 @@ function APIKey() {gap-2 text-xs">- <span className="whitespace-nowrap text-zinc-400 group-hover:opacity-25 font-bold">+ <span className="whitespace-nowrap font-bold text-zinc-400 group-hover:opacity-25">API Key</span><span className="whitespace-nowrap font-mono text-yellow-400 group-hover:opacity-25">@@ -56,13 +45,11 @@ function APIKey() {) : (<><span>You can get your API key by signing up.</span>- <Button onClick={signInWithGitHub}>- Sign up to get your API key- </Button>+ <Button onClick={() => signIn()}>Sign up to get your API key</Button></>)}</div>)}-export default APIKey\ No newline at end of file+export default APIKeydiff --git a/apps/docs/src/app/getting-started/basics/page.mdx b/apps/docs/src/app/getting-started/basics/page.mdxindex dcf6e5009..ecca1a5ce 100644--- a/apps/docs/src/app/getting-started/basics/page.mdx+++ b/apps/docs/src/app/getting-started/basics/page.mdx@@ -21,23 +21,23 @@ There are two main primitives in our SDK that you use to interact with the cloud## Create AI Playground-<CodeGroupAutoload path="basics/init" />+<CodeGroupAutoload path="basics/init" isRunnable={false} />## Get playground URLEach playground is accessible from the internet via a unique URL of that playground.-<CodeGroupAutoload path="basics/get_url" />+<CodeGroupAutoload path="basics/get_url" isRunnable={true} />### Get URL for a specific port inside playgroundBelow is an example showing how to get a URL for a port 3000. If there's any server inside the playground listening on port 3000 this would be its URL.-<CodeGroupAutoload path="basics/get_url_port" />+<CodeGroupAutoload path="basics/get_url_port" isRunnable={true} />## Scan open ports inside playgroundThe following example continuously scan open ports inside the playground and prints new ones to the console.-<CodeGroupAutoload path="basics/scan_ports" />+<CodeGroupAutoload path="basics/scan_ports" isRunnable={true} />## Filesystem@@ -51,14 +51,14 @@ Here are the basic operations you can do with the filesystem inside a cloud play## List directory content-<CodeGroupAutoload path="basics/fs_ls" />+<CodeGroupAutoload path="basics/fs_ls" isRunnable={true} />## Create directoryA creation of a directory will fail if any directory on the path doesn't exist yet.For example, if you want to create a directory `/home/user/new_dir` and `/home/user` doesn't exist yet, you will get an error.-<CodeGroupAutoload path="basics/fs_mkdir" />+<CodeGroupAutoload path="basics/fs_mkdir" isRunnable={false} />## Write to fileWhen writing to a file that doesn't exist, it will get created.@@ -67,13 +67,13 @@ When writing to a file that already exists, it will get overwritten.When writing to a file that's in a directory that doesn't exist, you'll get an error.-<CodeGroupAutoload path="basics/fs_write" />+<CodeGroupAutoload path="basics/fs_write" isRunnable={false} />## Read file-<CodeGroupAutoload path="basics/fs_read" />+<CodeGroupAutoload path="basics/fs_read" isRunnable={true} />## Watch directory for changes-<CodeGroupAutoload path="basics/fs_watch" />+<CodeGroupAutoload path="basics/fs_watch" isRunnable={false} />## Process@@ -85,16 +85,16 @@ Here are the basic operations you can do with the process inside a cloud playgro- [Stream stderr](/getting-started/basics#stream-stderr)## Start process-<CodeGroupAutoload path="basics/process_start" />+<CodeGroupAutoload path="basics/process_start" isRunnable={true} />## Stop process-<CodeGroupAutoload path="basics/process_stop" />+<CodeGroupAutoload path="basics/process_stop" isRunnable={false} />## Stream stdout-<CodeGroupAutoload path="basics/process_stream_stdout" />+<CodeGroupAutoload path="basics/process_stream_stdout" isRunnable={false} />## Send stdin-<CodeGroupAutoload path="basics/process_write_stdin" />+<CodeGroupAutoload path="basics/process_write_stdin" isRunnable={true} />## Stream stderr-<CodeGroupAutoload path="basics/process_stream_stderr" />+<CodeGroupAutoload path="basics/process_stream_stderr" isRunnable={false} />diff --git a/apps/docs/src/app/getting-started/installation/page.mdx b/apps/docs/src/app/getting-started/installation/page.mdxindex 30594dc4b..941d8ca0c 100644--- a/apps/docs/src/app/getting-started/installation/page.mdx+++ b/apps/docs/src/app/getting-started/installation/page.mdx@@ -8,7 +8,7 @@ export const metadata = {We offer SDKs for **JavaScript**, **TypeScript**, and **Python**. The SDKs are runnable both from backend environments (e.g.: servers) and frontend environments (e.g.: webapps).You can install them using the following commands:-<CodeGroup>+<CodeGroup isRunnable={false}>```bash {{ language: 'js' }}npm install @e2b/sdk```diff --git a/apps/docs/src/app/getting-started/sdk-logging/page.mdx b/apps/docs/src/app/getting-started/sdk-logging/page.mdxindex 738a53025..95eba6391 100644--- a/apps/docs/src/app/getting-started/sdk-logging/page.mdx+++ b/apps/docs/src/app/getting-started/sdk-logging/page.mdx@@ -12,4 +12,4 @@ export const metadata = {```</LanguageSpecificText>-<CodeGroupAutoload path="logging/e2b_logging" />+<CodeGroupAutoload path="logging/e2b_logging" isRunnable={false} />diff --git a/apps/docs/src/app/page.mdx b/apps/docs/src/app/page.mdxindex c71c69ce9..d102ffa4a 100644--- a/apps/docs/src/app/page.mdx+++ b/apps/docs/src/app/page.mdx@@ -42,7 +42,7 @@ Our SDK works with any AI agent (no matter what framework you're using), and wit## Quickstart Example-<CodeGroup>+<CodeGroup isRunnable={false}>```bash {{ language: 'js' }}npm i @e2b/sdk@@ -53,5 +53,5 @@ pip install e2b</CodeGroup>-<CodeGroupAutoload path="quickstart" />+<CodeGroupAutoload path="quickstart" isRunnable={false} />diff --git a/apps/docs/src/components/Auth.tsx b/apps/docs/src/components/Auth.tsxindex 59f695127..dab945461 100644--- a/apps/docs/src/components/Auth.tsx+++ b/apps/docs/src/components/Auth.tsx@@ -8,25 +8,16 @@ import clsx from 'clsx'import { HeaderSeparator } from '@/components/HeaderUtils'import { usePostHog } from 'posthog-js/react'import { obfuscateKey } from '@/utils/obfuscate'+import { useSignIn } from '@/utils/useSignIn'export const Auth = function () {const { user, isLoading, error } = useUser()+ const signIn = useSignIn()const apiKey = useApiKey()const posthog = usePostHog()const router = useRouter()const supabase = createClientComponentClient()- async function signInWithGitHub() {- await supabase.auth.signInWithOAuth({- // Redirect to GitHub- provider: 'github',- options: {- redirectTo: window.location.href,- scopes: 'email',- },- })- }-async function signOut() {await supabase.auth.signOut()posthog?.reset(true)@@ -63,7 +54,7 @@ export const Auth = function () {gap-2 text-xs">- <span className="font-bold whitespace-nowrap text-zinc-400 group-hover:opacity-25">+ <span className="whitespace-nowrap font-bold text-zinc-400 group-hover:opacity-25">API Key</span><span className="whitespace-nowrap font-mono text-yellow-400 group-hover:opacity-25">@@ -104,11 +95,7 @@ export const Auth = function () {) : (<div className="flex items-center gap-3">{/* @ts-ignore */}- <Button- onClick={() => signInWithGitHub()}- variant="textTernary"- className="text-xs"- >+ <Button onClick={() => signIn()} variant="textTernary" className="text-xs">Sign up to get your API key</Button>{/* @ts-ignore */}diff --git a/apps/docs/src/components/ButtonLoginToken.tsx b/apps/docs/src/components/ButtonLoginToken.tsxindex a6c101b06..af25ed739 100644--- a/apps/docs/src/components/ButtonLoginToken.tsx+++ b/apps/docs/src/components/ButtonLoginToken.tsx@@ -1,35 +1,19 @@'use client'import { Button } from '@/components/Button'-import { createClientComponentClient } from '@supabase/auth-helpers-nextjs'import { useUser } from '@/utils/useUser'+import { useSignIn } from '@/utils/useSignIn'export function ButtonLoginToken() {- const supabase = createClientComponentClient()const { user, isLoading } = useUser()-- async function signInWithGitHub() {- await supabase.auth.signInWithOAuth({- // redirect to GitHub- provider: 'github',- options: {- redirectTo: window.location.href,- scopes: 'email',- },- })- }+ const signIn = useSignIn()let extraClassName = 'duration-300'if (isLoading) extraClassName += ' opacity-0 pointer-events-none'if (user) return null- // @ts-ignorereturn (- <Button- onClick={() => signInWithGitHub()}- variant="textTernary"- className={extraClassName}- >+ <Button onClick={() => signIn()} variant="textTernary" className={extraClassName}>Sign up to get your API key</Button>)diff --git a/apps/docs/src/components/Code.tsx b/apps/docs/src/components/Code.tsxindex 2fecf59ec..a77f2ead5 100644--- a/apps/docs/src/components/Code.tsx+++ b/apps/docs/src/components/Code.tsx@@ -6,16 +6,22 @@ import {isValidElement,useContext,useEffect,+ useReducer,useRef,useState,} from 'react'import { Tab } from '@headlessui/react'import clsx from 'clsx'import { create } from 'zustand'+import { LoaderIcon, PlayIcon } from 'lucide-react'-import { Tag } from '@/components/Tag'import { CopyButton } from '@/components/CopyButton'-import { languageNames } from '@/utils/consts'+import {useApiKey, useUser} from '@/utils/useUser'+import { ProcessMessage } from '@e2b/sdk'+import { useSessionsStore } from '@/utils/useSessions'+import { useSignIn } from '@/utils/useSignIn'+import { LangShort, languageNames, mdLangToLangShort } from '@/utils/consts'+import { usePostHog } from "posthog-js/react";export function getPanelTitle({title,@@ -33,59 +39,164 @@ export function getPanelTitle({return 'Code'}-function CodePanelHeader({ tag, label }) {- if (!tag && !label) {- return null- }-- return (- <div className="flex h-9 items-center gap-2 border-y border-b-white/7.5 border-t-transparent bg-white/2.5 bg-zinc-900 px-4 dark:border-b-white/5 dark:bg-white/1">- {tag && (- <div className="dark flex">- <Tag variant="small">{tag}</Tag>- </div>- )}- {tag && label && (- <span className="h-0.5 w-0.5 rounded-full bg-zinc-500" />- )}- {label && (- <span className="font-mono text-xs text-zinc-400">{label}</span>- )}- </div>- )-}-function CodePanel({children,- tag,- label,code,+ lang,+ isRunnable = true,}: {children: React.ReactNode- tag?: string- label?: stringcode?: string+ lang?: LangShort+ isRunnable?: boolean}) {- let child = Children.only(children)- if (isValidElement(child)) {- tag = child.props.tag ?? tag- label = child.props.label ?? label- code = child.props.code ?? code+ const signIn = useSignIn()+ const apiKey = useApiKey()+ const posthog = usePostHog()++ const codeGroupContext = useContext(CodeGroupContext)++ const sessionDef = useSessionsStore((s) => s.sessions[lang])+ const initSession = useSessionsStore((s) => s.initSession)+ const { outputLines, dispatch } = useOutputReducer()+ const [isRunning, setIsRunning] = useState(false)++ function appendOutput(out: ProcessMessage) {+ dispatch({ type: 'push', payload: out.line })}- if (!code) {- throw new Error(- '`CodePanel` requires a `code` prop, or a child with a `code` prop.'- )+ function filterAndMaybeAppendOutput(out: ProcessMessage) {+ if (out.line.includes('Cannot refresh session')) return+ if (out.line.includes(`Trying to reconnect`)) return+ console.log(`⚠️ Session stderr ${out.line}`)+ // appendOutput(out) // TODO: Reconsider logging to console after making the runs more stable+ }++ function handleSessionCreationError(err: Error) {+ console.error(err)+ setIsRunning(false)+ dispatch({ type: 'clear' })}+ async function onRun() {+ if (!apiKey) {+ window.alert('You need to sign in to run code snippets')+ void signIn()+ return+ }+ dispatch({ type: 'clear' })+ setIsRunning(true)+ posthog?.capture('run code snippet', {+ language: lang,+ snippetPath: codeGroupContext?.path ?? 'unknown snippet',+ })+++ let session = sessionDef?.session+ try {+ if (!session) {+ if (sessionDef?.promise) {+ console.log(+ `Session for "${lang}" is still opening, waiting...`+ )+ session = await sessionDef.promise+ } else {+ console.log(+ `Session not ready yet for "${lang}", opening...`+ )+ session = await initSession(lang, apiKey)+ }+ }+ } catch (err) {+ handleSessionCreationError(err)+ return+ }++ let runtime = `E2B_API_KEY=${apiKey}`+ if (lang === LangShort.js) {+ runtime += ' node'+ const filename = '/code/index.js'+ await session.filesystem.write(filename, code)+ session.process.start({+ cmd: `${runtime} ${filename}`,+ onStdout: appendOutput,+ onStderr: filterAndMaybeAppendOutput,+ onExit: () => setIsRunning(false), // TODO: Inspect why it's exiting so late+ })+ } else if (lang === LangShort.py) {+ runtime += ' python3'+ const filename = '/main.py'+ await session.filesystem.write(filename, code)+ session.process.start({+ cmd: `${runtime} ${filename}`,+ rootdir: '/code',+ onStdout: appendOutput,+ onStderr: filterAndMaybeAppendOutput,+ onExit: () => setIsRunning(false),+ })+ } else {+ throw new Error('Unsupported runtime for playground')+ }+ }++ let child = Children.only(children)+ if (isValidElement(child)) code = child.props.code ?? code // Get code from child if available+ // @ts-ignore+ if (isValidElement(child)) lang = mdLangToLangShort[child.props.language ?? lang] // Get lang from child if available+ if (!code) throw new Error('`CodePanel` requires a `code` prop, or a child with a `code` prop.')++return (- <div className="group dark:bg-white/2.5">- <CodePanelHeader tag={tag} label={label} />- <div className="relative">- <pre className="overflow-x-auto p-4 text-xs text-white">{children}</pre>- <CopyButton code={code} />+ <div className="group dark:bg-white/2.5 relative">+ <div className="+ absolute+ top-[-40px]+ right-3+ ">+ {(isRunnable) && (+ <button+ className={clsx(`+ group+ flex cursor-pointer+ items-center+ space-x-2 rounded-md bg-transparent p-1 transition-all+ text-xs+ `,+ isRunning && `cursor-wait`+ )}+ disabled={isRunning}+ onClick={onRun}+ >+ {isRunning ? <>+ <span>Running</span>+ <LoaderIcon+ className="h-4 w-4 animate-spin text-emerald-400 transition-all group-hover:text-emerald-300"+ strokeWidth={2.5}+ />+ </> : <>+ <span>Run</span>+ <PlayIcon+ className="h-4 w-4 text-emerald-400 transition-all group-hover:text-emerald-300"+ strokeWidth={2.5}+ />+ </>+ }+ </button>+ )}</div>++ <pre className="overflow-x-auto p-4 text-xs text-white">{children}</pre>+ {(outputLines.length > 0 || isRunning) && (+ <div className="flex max-h-[200px] flex-col items-start justify-start bg-zinc-800 px-4 py-1 font-mono">+ <span className="font-mono text-xs text-zinc-500">+ Output+ </span>+ <pre className="h-full w-full overflow-auto whitespace-pre text-xs text-white">+ {outputLines.join('\n')}+ </pre>+ </div>+ )}+ <CopyButton code={code} /></div>)}@@ -100,37 +211,36 @@ export function CodeGroupHeader({selectedIndex: number}) {let hasTabs = Children.count(children) > 1-- if (!title && !hasTabs) {- return null- }+ if (!title && !hasTabs) return nullreturn (- <div className="flex min-h-[calc(theme(spacing.12)+1px)] flex-wrap items-start gap-x-4 border-b border-zinc-700 bg-zinc-800 px-4 dark:border-zinc-800 dark:bg-transparent">- {title && (- <h3 className="mr-auto pt-3 text-xs font-semibold text-white">- {title}- </h3>- )}- {hasTabs && (- <Tab.List className="-mb-px flex gap-4 text-xs font-medium">- {Children.map(children, (child, childIndex) => (- <Tab- /* Set ID due to bug in Next https://github.com/vercel/next.js/issues/53110 */- /* Should ne fixed after updating Next to > 13.4.12 */- id={`code-tab-${childIndex}`}- className={clsx(- 'border-b py-3 transition ui-not-focus-visible:outline-none',- childIndex === selectedIndex- ? 'border-emerald-500 text-emerald-400'- : 'border-transparent text-zinc-400 hover:text-zinc-300'- )}- >- {getPanelTitle(isValidElement(child) ? child.props : {})}- </Tab>- ))}- </Tab.List>- )}+ <div className="flex min-h-[calc(theme(spacing.12)+1px)] flex-wrap items-center justify-between gap-x-4 border-b border-zinc-700 bg-zinc-800 px-4 dark:border-zinc-800 dark:bg-transparent">+ <div className="flex items-start space-x-4">+ {title && (+ <h3 className="mr-auto pt-3 text-xs font-semibold text-white">+ {title}+ </h3>+ )}+ {hasTabs && (+ <Tab.List className="-mb-px flex gap-4 text-xs font-medium">+ {Children.map(children, (child, childIndex) => (+ <Tab+ /* Set ID due to bug in Next https://github.com/vercel/next.js/issues/53110 */+ /* Should ne fixed after updating Next to > 13.4.12 */+ id={`code-tab-${childIndex}`}+ className={clsx(+ 'border-b py-3 transition ui-not-focus-visible:outline-none',+ childIndex === selectedIndex+ ? 'border-emerald-500 text-emerald-400'+ : 'border-transparent text-zinc-400 hover:text-zinc-300'+ )}+ >+ {getPanelTitle(isValidElement(child) ? child.props : {})}+ </Tab>+ ))}+ </Tab.List>+ )}+ </div></div>)}@@ -146,11 +256,14 @@ function CodeGroupPanels({<Tab.Panels>{/* Set ID due to bug in Next https://github.com/vercel/next.js/issues/53110 */}{/* Should ne fixed after updating Next to > 13.4.12 */}- {Children.map(children, (child, childIndex) => (- <Tab.Panel id={`code-tab-${childIndex}`}>- <CodePanel {...props}>{child}</CodePanel>- </Tab.Panel>- ))}+ {Children.map(children, (child, childIndex) => {++ return (+ <Tab.Panel id={`code-tab-${childIndex}`}>+ <CodePanel {...props}>{child}</CodePanel>+ </Tab.Panel>+ )+ })}</Tab.Panels>)}@@ -212,11 +325,10 @@ export function useTabGroupProps(availableLanguages: Array<string>) {let activeLanguage = [...availableLanguages].sort((a, z) => preferredLanguages.indexOf(z) - preferredLanguages.indexOf(a))[0]+let languageIndex = availableLanguages.indexOf(activeLanguage)let newSelectedIndex = languageIndex === -1 ? selectedIndex : languageIndex- if (newSelectedIndex !== selectedIndex) {- setSelectedIndex(newSelectedIndex)- }+ if (newSelectedIndex !== selectedIndex) setSelectedIndex(newSelectedIndex)let { positionRef, preventLayoutShift } = usePreventLayoutShift()@@ -232,32 +344,61 @@ export function useTabGroupProps(availableLanguages: Array<string>) {}}-const CodeGroupContext = createContext(false)+const CodeGroupContext = createContext(null)++function useOutputReducer() {+ const [outputLines, dispatch] = useReducer(+ (+ state: string[],+ action: {+ type: 'push' | 'clear'+ payload?: string+ }+ ) => {+ switch (action.type) {+ case 'push':+ return [...state, action.payload]+ case 'clear':+ return []+ }+ },+ []+ )+ return { outputLines, dispatch }+}export function CodeGroup({children,title,+ path,...props}: React.ComponentPropsWithoutRef<typeof CodeGroupPanels> & {title?: string+ path?: string // For analytics}) {+ let hasTabs = Children.count(children) > 1+ let containerClassName =+ 'not-prose my-6 overflow-hidden rounded-2xl bg-zinc-900 shadow-md dark:ring-1 dark:ring-white/10'let languages =Children.map(children, (child) =>getPanelTitle(isValidElement(child) ? child.props : {})) ?? []let tabGroupProps = useTabGroupProps(languages)- let hasTabs = Children.count(children) > 1- let containerClassName =- 'not-prose my-6 overflow-hidden rounded-2xl bg-zinc-900 shadow-md dark:ring-1 dark:ring-white/10'+let header = (- <CodeGroupHeader title={title} selectedIndex={tabGroupProps.selectedIndex}>+ <CodeGroupHeader+ title={title}+ selectedIndex={tabGroupProps.selectedIndex}+ >{children}</CodeGroupHeader>)let panels = <CodeGroupPanels {...props}>{children}</CodeGroupPanels>return (- <CodeGroupContext.Provider value={true}>+ <CodeGroupContext.Provider value={{+ path,+ }}>{hasTabs ? (<Tab.Group {...tabGroupProps} className={containerClassName}>{header}@@ -282,7 +423,7 @@ export function Code({// if (children.replace && apiKey) children = children.replace(`{{API_KEY}}`, `${apiKey}`)/* </DYNAMIC-API-REPLACEMENT> */- let isGrouped = useContext(CodeGroupContext)+ let isGrouped = !!useContext(CodeGroupContext)if (isGrouped) {if (typeof children !== 'string') {@@ -312,12 +453,12 @@ export function Pre({/*** Special Component just for MDX files, processed by Remark*/-export function CodeGroupAutoload({ children }) {+export function CodeGroupAutoload({ children, isRunnable = true }) {if (!children) {console.warn(`CodeGroupAutoload: No children provided – something is wrong with your MDX file`)return null}- return <CodeGroup>{children}</CodeGroup>+ return <CodeGroup isRunnable={isRunnable}>{children}</CodeGroup>}diff --git a/apps/docs/src/components/LanguageSpecificText.tsx b/apps/docs/src/components/LanguageSpecificText.tsxindex 519a40874..83e81e0e0 100644--- a/apps/docs/src/components/LanguageSpecificText.tsx+++ b/apps/docs/src/components/LanguageSpecificText.tsx@@ -18,7 +18,10 @@ export function LanguageSpecificText({ children, title }) {let containerClassName ='not-prose my-6 overflow-hidden rounded-2xl bg-zinc-900 shadow-md dark:ring-1 dark:ring-white/10'let header = (- <CodeGroupHeader title={title} selectedIndex={tabGroupProps.selectedIndex}>+ <CodeGroupHeader+ title={title}+ selectedIndex={tabGroupProps.selectedIndex}+ >{children}</CodeGroupHeader>)diff --git a/apps/docs/src/components/Spinner.tsx b/apps/docs/src/components/Spinner.tsxindex 7aad39dde..487c7d36e 100644--- a/apps/docs/src/components/Spinner.tsx+++ b/apps/docs/src/components/Spinner.tsx@@ -4,7 +4,7 @@ import { Loader2 as Loader } from 'lucide-react'// className?: string// }-function Spinner({ className }) {+function Spinner({ className = '' }) {return (<LoaderclassName={`animate-spin ${className ? className : ''}`}@@ -14,3 +14,12 @@ function Spinner({ className }) {}export default Spinner++// TODO: Nicer loading dots, I don't like these much+export function LoadingDots({ className = '' }) {+ return <div className="inline-flex align-middle">+ <span className="circle animate-loaderDots"></span>+ <span className="circle animate-loaderDots animation-delay-200"></span>+ <span className="circle animate-loaderDots animation-delay-400"></span>+ </div>+}diff --git a/apps/docs/src/styles/tailwind.css b/apps/docs/src/styles/tailwind.cssindex 09d51495b..2bcc0d472 100644--- a/apps/docs/src/styles/tailwind.css+++ b/apps/docs/src/styles/tailwind.css@@ -38,6 +38,19 @@}}+@layer utilities {+ .animation-delay-200 {+ animation-delay: 0.2s;+ }+ .animation-delay-400 {+ animation-delay: 0.4s;+ }+}++.circle {+ @apply w-[5px] h-[5px] mx-[2px] relative top-[-1px] bg-gray-500 rounded-full;+}+@tailwind base;@tailwind components;@tailwind utilities;diff --git a/apps/docs/src/utils/consts.ts b/apps/docs/src/utils/consts.tsindex a603cc8a3..9620d818f 100644--- a/apps/docs/src/utils/consts.ts+++ b/apps/docs/src/utils/consts.ts@@ -4,6 +4,28 @@// - use `javascript` for explicitly JavaScript// - use `typescript` for explicitly TypeScript+export enum LangShort {+ js = 'js',+ py = 'py',+}++export const languageToLangShort: Record<string, LangShort> = {+ // TODO: Nicer+ 'JavaScript & TypeScript': LangShort.js,+ JavaScript: LangShort.js,+ TypeScript: LangShort.js,++ Python: LangShort.py,+}++export const mdLangToLangShort: Record<string, LangShort> = {+ js: LangShort.js,+ javascript: LangShort.js,+ ts: LangShort.js,+ typescript: LangShort.js,+ python: LangShort.py,+}+export const languageNames: Record<string, string> = {js: 'JavaScript & TypeScript',ts: '⚠️ FIXME See note in apps/docs/src/utils/consts.ts', // Please avoid using `ts`, see note abovediff --git a/apps/docs/src/utils/promise.ts b/apps/docs/src/utils/promise.tsnew file mode 100644index 000000000..33cbaed01--- /dev/null+++ b/apps/docs/src/utils/promise.ts@@ -0,0 +1,26 @@+export function assertFulfilled<T>(+ item: PromiseSettledResult<T>,+): item is PromiseFulfilledResult<T> {+ return item.status === 'fulfilled'+}++export function assertRejected<T>(+ item: PromiseSettledResult<T>,+): item is PromiseRejectedResult {+ return item.status === 'rejected'+}++export function createDeferredPromise<T = void>() {+ let resolve: (value: T) => void+ let reject: (reason?: any) => void+ const promise = new Promise<T>((res, rej) => {+ resolve = res+ reject = rej+ })++ return {+ resolve: resolve!,+ reject: reject!,+ promise,+ }+}diff --git a/apps/docs/src/utils/useSessions.tsx b/apps/docs/src/utils/useSessions.tsxnew file mode 100644index 000000000..945fab814--- /dev/null+++ b/apps/docs/src/utils/useSessions.tsx@@ -0,0 +1,96 @@+import { Session } from '@e2b/sdk'+import { create } from 'zustand'+import { LangShort } from '@/utils/consts'++function stdHandler({ line, timestamp, error }) {+ const timestampHumanFriendly = new Date(timestamp / 1000000) // timestamp is in nanoseconds+ .toISOString()+ .split('T')[1] // only time, date is not relevant for debugging+ .split('.')[0] // remove ms+ const emoji = error ? 'ERROR' : 'INFO'+ console.log(`☁️ ${timestampHumanFriendly} ${emoji} ${line}`)+}++const envIds = {+ js: 'Nodejs',+ py: 'Python3',+}++const preps = {+ js: `npm init es6 -y && npm install @e2b/sdk`,+ py: `pip install e2b`,+}++// TODO: Consider using immer for easier state updates+export const useSessionsStore = create<SessionsStore>((set, get) => ({+ sessions: {+ js: null,+ py: null,+ },+ initSession: async (lang: LangShort, apiKey: string): Promise<Session> => {+ return new Promise(async (resolve, reject) => {+ const maybeExistingSession = get().sessions[lang]+ if (maybeExistingSession?.session) {+ console.log(`${lang} session already ready`)+ resolve(maybeExistingSession.session)+ return+ } else if (maybeExistingSession?.promise) {+ console.log(`${lang} session in progress, waiting...`)+ await maybeExistingSession.promise+ resolve(maybeExistingSession.session)+ } else {+ console.log(`${lang} session creating...`)+ try {+ const sessionP = Session.create({ id: envIds[lang], apiKey })+ // set promise to store so that other calls to initSession will wait for this one to finish+ set((state) => ({+ sessions: {+ ...state.sessions,+ [lang]: {+ session: null,+ promise: sessionP,+ },+ },+ }))+ const newSession = await sessionP // await creation+ console.log(`${lang} session created, starting prep process...`)+ const proc = await newSession.process.start({+ cmd: preps[lang],+ onStdout: stdHandler,+ onStderr: stdHandler,+ rootdir: '/code',+ })+ await proc.finished // await prep process to finish+ console.log(`${lang} session created and started`)+ // set session to store so it can be used instead of creating a new one+ set((state) => ({+ sessions: {+ ...state.sessions,+ [lang]: {+ session: newSession,+ promise: null,+ },+ },+ }))+ resolve(newSession) // also resolve with the new session for the initSession caller+ } catch (err) {+ console.info(`${lang} session creation failed`, err)+ reject(err)+ }+ }+ })+ },+}))++type SessionMeta = {+ session: Session+ promise: Promise<Session>+}++export type SessionsStore = {+ sessions: {+ js: SessionMeta+ py: SessionMeta+ }+ initSession: (lang: LangShort, apiKey: string) => Promise<Session>+}diff --git a/apps/docs/src/utils/useSignIn.tsx b/apps/docs/src/utils/useSignIn.tsxnew file mode 100644index 000000000..f70d93472--- /dev/null+++ b/apps/docs/src/utils/useSignIn.tsx@@ -0,0 +1,17 @@+'use client'++import { createClientComponentClient } from '@supabase/auth-helpers-nextjs'++// TODO: Maybe consolidate with useUser?+export function useSignIn() {+ const supabase = createClientComponentClient()+ return async function signInWithGitHub() {+ await supabase.auth.signInWithOAuth({+ provider: 'github',+ options: {+ redirectTo: window.location.href,+ scopes: 'email',+ },+ })+ }+}diff --git a/apps/docs/src/utils/useUser.tsx b/apps/docs/src/utils/useUser.tsxindex 5ab487c03..52d86f6e4 100644--- a/apps/docs/src/utils/useUser.tsx+++ b/apps/docs/src/utils/useUser.tsx@@ -1,6 +1,13 @@'use client'-import { useEffect, useState, createContext, useContext, useMemo, useRef } from 'react'+import {+ createContext,+ useContext,+ useEffect,+ useMemo,+ useRef,+ useState,+} from 'react'import { User } from '@supabase/supabase-auth-helpers/react'import { createPagesBrowserClient } from '@supabase/auth-helpers-nextjs'import { type Session } from '@supabase/supabase-js'@@ -9,12 +16,21 @@ import * as Sentry from '@sentry/nextjs'type UserContextType = {isLoading: booleansession: Session | null- user: User & { teams: any[]; apiKeys: any[] } | null+ user: (User & { teams: any[]; apiKeys: any[] }) | nullerror: Error | null}export const UserContext = createContext(undefined)+function stdHandler({ line, timestamp, error }) {+ const timestampHumanFriendly = new Date(timestamp / 1000000) // timestamp is in nanoseconds+ .toISOString()+ .split('T')[1] // only time, date is not relevant for debugging+ .split('.')[0] // remove ms+ const emoji = error ? '🟥' : '🟦'+ console.log(`${emoji} [${timestampHumanFriendly}] ${line}`)+}+export const CustomUserContextProvider = (props) => {const supabase = createPagesBrowserClient()const [session, setSession] = useState(null)@@ -25,6 +41,7 @@ export const CustomUserContextProvider = (props) => {useEffect(() => {mounted.current = true+async function getSession() {const {data: { session },@@ -42,12 +59,12 @@ export const CustomUserContextProvider = (props) => {if (!session) setIsLoading(false) // if session is present, we set setLoading to false in the second useEffect}}+void getSession()return () => {mounted.current = false}- // eslint-disable-next-line react-hooks/exhaustive-deps- }, [])+ }, []) // eslint-disable-line react-hooks/exhaustive-depsuseEffect(() => {const {@@ -98,6 +115,7 @@ export const CustomUserContextProvider = (props) => {})setIsLoading(false)}+if (session) void getUserCustom()// eslint-disable-next-line react-hooks/exhaustive-deps}, [session])diff --git a/apps/docs/tailwind.config.ts b/apps/docs/tailwind.config.tsindex 42ac3fe52..5a3ffefb5 100644--- a/apps/docs/tailwind.config.ts+++ b/apps/docs/tailwind.config.ts@@ -40,6 +40,17 @@ export default {7.5: '0.075',15: '0.15',},+ animation: {+ loaderDots: 'loaderDots 0.5s infinite alternate'+ },+ keyframes: {+ loaderDots: {+ to: {+ opacity: '0.1',+ transform: 'translate3d(0, -0.3rem, 0)' // TODO: More parametric+ }+ }+ }},},plugins: [typographyPlugin, headlessuiPlugin],