-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathruntime.tsx
More file actions
178 lines (165 loc) · 5.39 KB
/
runtime.tsx
File metadata and controls
178 lines (165 loc) · 5.39 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
"use client";
import type { ScriptTarget, CompilerOptions } from "typescript";
import type { VirtualTypeScriptEnvironment } from "@typescript/vfs";
import {
createContext,
ReactNode,
useCallback,
useContext,
useEffect,
useMemo,
useState,
} from "react";
import { ReplOutput } from "../repl";
import { RuntimeContext, RuntimeInfo, UpdatedFile } from "../runtime";
export const compilerOptions: CompilerOptions = {
lib: ["ESNext", "WebWorker"],
target: 10 satisfies ScriptTarget.ES2023,
strict: true,
};
const TypeScriptContext = createContext<{
init: () => void;
tsEnv: VirtualTypeScriptEnvironment | null;
tsVersion?: string;
}>({ init: () => undefined, tsEnv: null });
export function TypeScriptProvider({ children }: { children: ReactNode }) {
const [tsEnv, setTSEnv] = useState<VirtualTypeScriptEnvironment | null>(null);
const [tsVersion, setTSVersion] = useState<string | undefined>(undefined);
const [doInit, setDoInit] = useState(false);
const init = useCallback(() => setDoInit(true), []);
useEffect(() => {
// useEffectはサーバーサイドでは実行されないが、
// typeof window !== "undefined" でガードしないとなぜかesbuildが"typescript"を
// サーバーサイドでのインポート対象とみなしてしまう。
if (doInit && tsEnv === null && typeof window !== "undefined") {
const abortController = new AbortController();
(async () => {
const ts = await import("typescript");
const vfs = await import("@typescript/vfs");
const system = vfs.createSystem(new Map());
const libFiles = vfs.knownLibFilesForCompilerOptions(
compilerOptions,
ts
);
const libFileContents = await Promise.all(
libFiles.map(async (libFile) => {
const response = await fetch(
`/typescript/${ts.version}/${libFile}`,
{ signal: abortController.signal }
);
if (response.ok) {
return response.text();
} else {
return undefined;
}
})
);
libFiles.forEach((libFile, index) => {
const content = libFileContents[index];
if (content !== undefined) {
system.writeFile(`/${libFile}`, content);
}
});
const env = vfs.createVirtualTypeScriptEnvironment(
system,
[],
ts,
compilerOptions
);
setTSEnv(env);
setTSVersion(ts.version);
})();
return () => {
abortController.abort();
};
}
}, [tsEnv, setTSEnv, doInit]);
return (
<TypeScriptContext.Provider value={{ init, tsEnv, tsVersion }}>
{children}
</TypeScriptContext.Provider>
);
}
export function useTypeScript(jsEval: RuntimeContext): RuntimeContext {
const { init: tsInit, tsEnv, tsVersion } = useContext(TypeScriptContext);
const { init: jsInit } = jsEval;
const init = useCallback(() => {
tsInit();
jsInit?.();
}, [tsInit, jsInit]);
const runFiles = useCallback(
async (
filenames: string[],
files: Readonly<Record<string, string>>,
onOutput: (output: ReplOutput | UpdatedFile) => void
) => {
if (tsEnv === null || typeof window === "undefined") {
onOutput({ type: "error", message: "TypeScript is not ready yet." });
return;
} else {
for (const [filename, content] of Object.entries(files)) {
tsEnv.createFile(filename, content);
}
const ts = await import("typescript");
for (const diagnostic of tsEnv.languageService.getSyntacticDiagnostics(
filenames[0]
)) {
onOutput({
type: "error",
message: ts.formatDiagnosticsWithColorAndContext([diagnostic], {
getCurrentDirectory: () => "",
getCanonicalFileName: (f) => f,
getNewLine: () => "\n",
}),
});
}
for (const diagnostic of tsEnv.languageService.getSemanticDiagnostics(
filenames[0]
)) {
onOutput({
type: "error",
message: ts.formatDiagnosticsWithColorAndContext([diagnostic], {
getCurrentDirectory: () => "",
getCanonicalFileName: (f) => f,
getNewLine: () => "\n",
}),
});
}
const emitOutput = tsEnv.languageService.getEmitOutput(filenames[0]);
const emittedFiles: Record<string, string> = Object.fromEntries(
emitOutput.outputFiles.map((of) => [of.name, of.text])
);
for (const [filename, content] of Object.entries(emittedFiles)) {
onOutput({ type: "file", filename, content });
}
for (const filename of Object.keys(emittedFiles)) {
tsEnv.deleteFile(filename);
}
console.log(emitOutput);
await jsEval.runFiles(
[emitOutput.outputFiles[0].name],
{ ...files, ...emittedFiles },
onOutput
);
}
},
[tsEnv, jsEval]
);
const runtimeInfo = useMemo<RuntimeInfo>(
() => ({
prettyLangName: "TypeScript",
version: tsVersion,
}),
[tsVersion]
);
return {
init,
ready: tsEnv !== null,
runFiles,
getCommandlineStr,
runtimeInfo,
};
}
function getCommandlineStr(filenames: string[]) {
return `npx tsc ${filenames.join(" ")} && node ${filenames[0].replace(/\.ts$/, ".js")}`;
}