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(export): support private sandboxes in workspace #1136

Merged
merged 4 commits into from
May 29, 2024
Merged
Show file tree
Hide file tree
Changes from 3 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
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ import LZString from "lz-string";
import * as React from "react";

import { useSandpack } from "../../../hooks/useSandpack";
import type { SandboxEnvironment } from "../../../types";
import type { SandboxEnvironment, SandpackState } from "../../../types";

// eslint-disable-next-line @typescript-eslint/no-explicit-any
const getParameters = (parameters: Record<string, any>): string =>
Expand Down Expand Up @@ -47,19 +47,70 @@ export const UnstyledOpenInCodeSandboxButton: React.FC<
React.HtmlHTMLAttributes<unknown>
> = ({ children, ...props }) => {
const { sandpack } = useSandpack();
const formRef = React.useRef<HTMLFormElement>(null);

if (sandpack.exportOptions) {
return <ExportToWorkspaceButton state={sandpack} {...props} />;
}

return <RegularExportButton state={sandpack} {...props} />;
};

export const ExportToWorkspaceButton: React.FC<
React.HtmlHTMLAttributes<unknown> & { state: SandpackState }
> = ({ children, state, ...props }) => {
const submit = async () => {
if (!state.exportOptions?.apiToken) {
throw new Error("Missing `apiToken` property");
}

const response = await fetch("https://api.codesandbox.io/sandbox", {
method: "POST",
body: JSON.stringify({
files: state.files,
privacy: state.exportOptions.privacy === "public" ? 0 : 2,
}),
headers: {
Authorization: `Bearer ${state.exportOptions.apiToken}`,
"Content-Type": "application/json",
"X-CSB-API-Version": "2023-07-01",
},
});

const data: { data: { alias: string } } = await response.json();

window.open(
`https://codesandbox.io/p/sandbox/${data.data.alias}?file=/src/App.js&utm-source=storybook-addon`,
"_blank"
);
};

return (
<button
onClick={submit}
title="Export to workspace in CodeSandbox"
type="button"
{...props}
>
{children}
</button>
);
};

const RegularExportButton: React.FC<
React.HtmlHTMLAttributes<unknown> & { state: SandpackState }
> = ({ children, state, ...props }) => {
const formRef = React.useRef<HTMLFormElement>(null);
const [paramsValues, setParamsValues] = React.useState<URLSearchParams>();

React.useEffect(
function debounce() {
const timer = setTimeout(() => {
const params = getFileParameters(sandpack.files, sandpack.environment);
const params = getFileParameters(state.files, state.environment);

const searchParams = new URLSearchParams({
parameters: params,
query: new URLSearchParams({
file: sandpack.activeFile,
file: state.activeFile,
utm_medium: "sandpack",
}).toString(),
});
Expand All @@ -71,7 +122,7 @@ export const UnstyledOpenInCodeSandboxButton: React.FC<
clearTimeout(timer);
};
},
[sandpack.activeFile, sandpack.environment, sandpack.files]
[state.activeFile, state.environment, state.files]
);

/**
Expand All @@ -96,9 +147,7 @@ export const UnstyledOpenInCodeSandboxButton: React.FC<
<input
name="environment"
type="hidden"
value={
sandpack.environment === "node" ? "server" : sandpack.environment
}
value={state.environment === "node" ? "server" : state.environment}
/>
{Array.from(
paramsValues as unknown as Array<[string, string]>,
Expand All @@ -115,7 +164,7 @@ export const UnstyledOpenInCodeSandboxButton: React.FC<
return (
<a
href={`${CSB_URL}?${paramsValues?.toString()}&environment=${
sandpack.environment === "node" ? "server" : sandpack.environment
state.environment === "node" ? "server" : state.environment
}`}
rel="noreferrer noopener"
target="_blank"
Expand Down
2 changes: 2 additions & 0 deletions sandpack-react/src/contexts/sandpackContext.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,8 @@ export const SandpackProvider: React.FC<SandpackProviderProps> = (props) => {
...clientOperations,

autoReload: props.options?.autoReload ?? true,
teamId: props?.teamId,
exportOptions: props?.customSetup?.exportOptions,

listen: addListener,
dispatch: dispatchMessage,
Expand Down
2 changes: 0 additions & 2 deletions sandpack-react/src/contexts/utils/useAppState.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,6 @@ import { getSandpackStateFromProps } from "../../utils/sandpackUtils";

interface SandpackAppState {
editorState: "pristine" | "dirty";
teamId?: string;
}

type UseAppState = (
Expand All @@ -18,7 +17,6 @@ type UseAppState = (
export const useAppState: UseAppState = (props, files) => {
const [state, setState] = useState<SandpackAppState>({
editorState: "pristine",
teamId: props.teamId,
});

const originalStateFromProps = getSandpackStateFromProps(props);
Expand Down
19 changes: 19 additions & 0 deletions sandpack-react/src/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -241,6 +241,24 @@ export interface SandpackSetup {
* ```
*/
npmRegistries?: NpmRegistry[];

exportOptions?: SandpackExportOptions;
}

interface SandpackExportOptions {
/**
* Workspace API key from codesandbox.io/t/permissions.
* When set, the sandbox will be create inside the given workspace id.
*/
apiToken: string;

/**
* The default visibility of the new sandboxes inside the workspace.
*
* @note Use `private` if there is a private registry or private NPM
* configured in your workspace.
*/
privacy: "private" | "public";
}

/**
Expand Down Expand Up @@ -561,6 +579,7 @@ export interface SandpackState {
*/
editorState: EditorState;
teamId?: string;
exportOptions?: SandpackExportOptions;
error: SandpackError | null;
files: SandpackBundlerFiles;
environment?: SandboxEnvironment;
Expand Down
23 changes: 23 additions & 0 deletions website/docs/src/pages/getting-started/private-packages.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -60,6 +60,29 @@ export default function App() {
<img src="/docs/private-package-loaded.png" />



## Exporting sandboxes

Once Sandpack is configured, you can use the "Open in CodeSandbox" button to export sandboxes to CodeSandbox effortlessly. However in order to seamless export the sandbox, you need to provide a CodeSandbox API key that will be used to create a sandbox inside your workspace.

1. Generate a API token in your dashboard: [codesandbox.io/t/permissions](https://codesandbox.io/t/permissions.).
danilowoz marked this conversation as resolved.
Show resolved Hide resolved
2. Use the generate token to setup your Sandpack instance:

```jsx
<Sandpack
customSetup={{
exportOptions: {
apiToken: "<API-TOKEN>",
privacy: "private", // "public" | "private"
}
}}
/>
```

<Callout emoji="⭐️">
This sandbox will be created inside the given workspace and can be shared with team members.
</Callout>

## Security

It is important to us to ensure that the information and tokens of the npm registry are kept private. As such, we have added some extra measures to prevent any type of leakage.
Expand Down
Loading