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: Accept Uint8Array as file code alongside string #773

Draft
wants to merge 1 commit into
base: main
Choose a base branch
from
Draft
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
3 changes: 2 additions & 1 deletion sandpack-client/src/clients/runtime/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@ import {
extractErrorDetails,
createPackageJSON,
addPackageJSONIfNeeded,
codeToString,
} from "../../utils";
import { SandpackClient } from "../base";

Expand Down Expand Up @@ -199,7 +200,7 @@ export class SandpackRuntime extends SandpackClient {
)
);
try {
packageJSON = JSON.parse(files["/package.json"].code);
packageJSON = JSON.parse(codeToString(files["/package.json"].code));
} catch (e) {
console.error(
createError(
Expand Down
2 changes: 1 addition & 1 deletion sandpack-client/src/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -80,7 +80,7 @@ export interface SandboxSetup {
}

export interface SandpackBundlerFile {
code: string;
code: string | Uint8Array;
hidden?: boolean;
active?: boolean;
readOnly?: boolean;
Expand Down
16 changes: 10 additions & 6 deletions sandpack-client/src/utils.test.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { addPackageJSONIfNeeded, normalizePath } from "./utils";
import { addPackageJSONIfNeeded, codeToString, normalizePath } from "./utils";

const files = {
"/package.json": {
Expand All @@ -15,7 +15,9 @@ describe(addPackageJSONIfNeeded, () => {
test("it merges the package.json - dependencies", () => {
const output = addPackageJSONIfNeeded(files, { foo: "*" });

expect(JSON.parse(output["/package.json"].code).dependencies).toEqual({
expect(
JSON.parse(codeToString(output["/package.json"].code)).dependencies
).toEqual({
baz: "*",
foo: "*",
});
Expand All @@ -24,7 +26,9 @@ describe(addPackageJSONIfNeeded, () => {
test("it merges the package.json - dev-dependencies", () => {
const output = addPackageJSONIfNeeded(files, undefined, { foo: "*" });

expect(JSON.parse(output["/package.json"].code).devDependencies).toEqual({
expect(
JSON.parse(codeToString(output["/package.json"].code)).devDependencies
).toEqual({
baz: "*",
foo: "*",
});
Expand All @@ -38,7 +42,7 @@ describe(addPackageJSONIfNeeded, () => {
"new-entry.js"
);

expect(JSON.parse(output["/package.json"].code).main).toEqual(
expect(JSON.parse(codeToString(output["/package.json"].code)).main).toEqual(
"new-entry.js"
);
});
Expand All @@ -59,7 +63,7 @@ describe(addPackageJSONIfNeeded, () => {
"new-entry.js"
);

expect(JSON.parse(output["/package.json"].code).main).toEqual(
expect(JSON.parse(codeToString(output["/package.json"].code)).main).toEqual(
"new-entry.js"
);
});
Expand Down Expand Up @@ -91,7 +95,7 @@ describe(addPackageJSONIfNeeded, () => {
"new-entry.ts"
);

expect(JSON.parse(output["/package.json"].code)).toEqual({
expect(JSON.parse(codeToString(output["/package.json"].code))).toEqual({
main: "new-entry.ts",
dependencies: { baz: "*", foo: "*" },
devDependencies: { baz: "*", foo: "*" },
Expand Down
11 changes: 10 additions & 1 deletion sandpack-client/src/utils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,15 @@ export function nullthrows<T>(value?: T | null, err = "Value is nullish"): T {
return value;
}

export function codeToString(code: string | Uint8Array): string {
if (typeof code === "string") {
return code;
} else {
const decoder = new TextDecoder();
return decoder.decode(code);
}
}
Comment on lines +20 to +27
Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

There is also readBuffer function in node runtime utils that do the same thing but using Buffer.from(Uint8Array).toString('utf-8') instead of TextDecoder. Should I remove this and update readBuffer implementation to use TextDecoder so it can be used outside nodebox?


const DEPENDENCY_ERROR_MESSAGE = `"dependencies" was not specified - provide either a package.json or a "dependencies" value`;
const ENTRY_ERROR_MESSAGE = `"entry" was not specified - provide either a package.json with the "main" field or an "entry" value`;

Expand Down Expand Up @@ -65,7 +74,7 @@ export function addPackageJSONIfNeeded(
* Merge package json with custom setup
*/
if (packageJsonFile) {
const packageJsonContent = JSON.parse(packageJsonFile.code);
const packageJsonContent = JSON.parse(codeToString(packageJsonFile.code));

nullthrows(
!(!dependencies && !packageJsonContent.dependencies),
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ import * as React from "react";

import { useSandpack } from "../../../hooks/useSandpack";
import type { SandboxEnvironment } from "../../../types";
import { codeToString } from "../../../utils/stringUtils";

// eslint-disable-next-line @typescript-eslint/no-explicit-any
const getParameters = (parameters: Record<string, any>): string =>
Expand All @@ -28,10 +29,11 @@ const getFileParameters = (
>;

const normalizedFiles = Object.keys(files).reduce((prev, next) => {
const code = files[next].code;
const fileName = next.replace("/", "");
const value = {
content: files[next].code,
isBinary: false,
content: codeToString(code),
isBinary: code instanceof Uint8Array,
};

return { ...prev, [fileName]: value };
Expand Down
4 changes: 3 additions & 1 deletion sandpack-react/src/hooks/useActiveCode.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
import { codeToString } from "../utils/stringUtils";

import { useSandpack } from "./useSandpack";

/**
Expand All @@ -14,7 +16,7 @@ export const useActiveCode = (): {
const { sandpack } = useSandpack();

return {
code: sandpack.files[sandpack.activeFile]?.code,
code: codeToString(sandpack.files[sandpack.activeFile]?.code),
readOnly: sandpack.files[sandpack.activeFile]?.readOnly ?? false,
updateCode: sandpack.updateCurrentFile,
};
Expand Down
4 changes: 2 additions & 2 deletions sandpack-react/src/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -236,7 +236,7 @@ export type SandpackPredefinedTemplate = keyof typeof SANDBOX_TEMPLATES;
* @category Setup
*/
export interface SandpackFile {
code: string;
code: string | Uint8Array;
hidden?: boolean;
active?: boolean;
readOnly?: boolean;
Expand Down Expand Up @@ -591,7 +591,7 @@ export interface SandboxTemplate {
environment: SandboxEnvironment;
}

export type SandpackFiles = Record<string, string | SandpackFile>;
export type SandpackFiles = Record<string, string | Uint8Array | SandpackFile>;

/**
* Custom properties to be used in the SandpackCodeEditor component,
Expand Down
2 changes: 1 addition & 1 deletion sandpack-react/src/utils/sandpackUtils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -53,7 +53,7 @@ export const getSandpackStateFromProps = (
// extract open and active files from the custom input files
Object.keys(normalizedFilesPath).forEach((filePath) => {
const file = normalizedFilesPath[filePath];
if (typeof file === "string") {
if (typeof file === "string" || file instanceof Uint8Array) {
visibleFiles.push(filePath);
return;
}
Expand Down
9 changes: 9 additions & 0 deletions sandpack-react/src/utils/stringUtils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -53,6 +53,15 @@ export const calculateNearestUniquePath = (
return resultPathParts.join("/");
};

export function codeToString(code: string | Uint8Array): string {
if (typeof code === "string") {
return code;
} else {
const decoder = new TextDecoder();
return decoder.decode(code);
}
}

export const hexToRGB = (
hex: string
): { red: number; green: number; blue: number } => {
Expand Down