Skip to content

Commit

Permalink
feat(dev): support for /_vfs.json (#809)
Browse files Browse the repository at this point in the history
  • Loading branch information
antfu authored and pi0 committed Jan 16, 2023
1 parent b631d84 commit fb65747
Show file tree
Hide file tree
Showing 2 changed files with 45 additions and 22 deletions.
1 change: 1 addition & 0 deletions .eslintrc
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@
"quotes": 0,
"keyword-spacing": 0,
"no-undef": 0,
"indent": 0,
"unicorn/catch-error-name": 0,
"unicorn/no-null": 0,
"unicorn/no-useless-undefined": 0,
Expand Down
66 changes: 44 additions & 22 deletions src/dev/vfs.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,10 +8,41 @@ export function createVFSHandler(nitro: Nitro) {
...nitro.options.virtual,
};

const url = event.node.req.url || "";
const isJson =
event.node.req.headers.accept?.includes("application/json") ||
url.startsWith(".json");
const id = decodeURIComponent(url.replace(/^(\.json)?\/?/, "") || "");

if (id && !(id in vfsEntries)) {
throw createError({ message: "File not found", statusCode: 404 });
}

let content = id ? vfsEntries[id] : undefined;
if (typeof content === "function") {
content = await content();
}

if (isJson) {
return {
rootDir: nitro.options.rootDir,
entries: Object.keys(vfsEntries).map((id) => ({
id,
path: "/_vfs.json/" + encodeURIComponent(id),
})),
current: id
? {
id,
content,
}
: null,
};
}

const items = Object.keys(vfsEntries)
.map((key) => {
const linkClass =
event.req.url === `/${encodeURIComponent(key)}`
url === `/${encodeURIComponent(key)}`
? "bg-gray-700 text-white"
: "hover:bg-gray-800 text-gray-200";
return `<li class="flex flex-nowrap"><a href="/_vfs/${encodeURIComponent(
Expand All @@ -22,38 +53,29 @@ export function createVFSHandler(nitro: Nitro) {
)}</a></li>`;
})
.join("\n");

const files = `
<div>
<p class="bg-gray-700 text-white text-bold border-b border-gray-500 text-center">virtual files</p>
<ul class="flex flex-col">${items}</ul>
</div>
`;

const id = decodeURIComponent(event.req.url?.slice(1) || "");

let file = "";
if (id in vfsEntries) {
let contents = vfsEntries[id];
if (typeof contents === "function") {
contents = await contents();
}
file = editorTemplate({
readOnly: true,
language: id.endsWith("html") ? "html" : "javascript",
theme: "vs-dark",
value: contents,
wordWrap: "wordWrapColumn",
wordWrapColumn: 80,
});
} else if (id) {
throw createError({ message: "File not found", statusCode: 404 });
} else {
file = `
const file = id
? editorTemplate({
readOnly: true,
language: id.endsWith("html") ? "html" : "javascript",
theme: "vs-dark",
value: content,
wordWrap: "wordWrapColumn",
wordWrapColumn: 80,
})
: `
<div class="m-2">
<h1 class="text-white">Select a virtual file to inspect</h1>
</div>
`;
}

return `
<!doctype html>
<html>
Expand Down

0 comments on commit fb65747

Please sign in to comment.