@innovatorved/code-lab 0.1.13 → 0.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (80) hide show
  1. package/ARCHITECTURE.md +12 -7
  2. package/CHANGELOG.md +134 -0
  3. package/README.md +59 -9
  4. package/dist/code-lab.css +198 -0
  5. package/dist/code-lab.d.ts +37 -7
  6. package/dist/code-lab.esm.js +20444 -1278
  7. package/dist/code-lab.js +20439 -1276
  8. package/dist/extensions/cpp.d.ts +145 -0
  9. package/dist/extensions/cpp.esm.js +5932 -0
  10. package/dist/extensions/cpp.js +5951 -0
  11. package/dist/extensions/guided-lab.esm.js +86 -6
  12. package/dist/extensions/guided-lab.js +87 -6
  13. package/dist/extensions/javascript.d.ts +24 -0
  14. package/dist/extensions/javascript.esm.js +36 -0
  15. package/dist/extensions/javascript.js +59 -0
  16. package/dist/extensions/python.d.ts +92 -0
  17. package/dist/extensions/python.esm.js +5476 -0
  18. package/dist/extensions/python.js +5495 -0
  19. package/dist/extensions/typescript.d.ts +36 -0
  20. package/dist/extensions/typescript.esm.js +55 -0
  21. package/dist/extensions/typescript.js +78 -0
  22. package/dist/index.d.ts +9 -3
  23. package/dist/preview-sw.js +1 -1
  24. package/dist/runtime/index.d.ts +4 -0
  25. package/dist/runtime/module-loader.d.ts +11 -0
  26. package/dist/runtime/test-harness.d.ts +24 -0
  27. package/dist/runtime/vfs.d.ts +31 -0
  28. package/dist/runtime/wasi-host.d.ts +33 -0
  29. package/dist/runtime.d.ts +6 -0
  30. package/dist/runtime.esm.js +920 -15
  31. package/dist/runtime.js +914 -15
  32. package/dist/schemas.d.ts +237 -25
  33. package/dist/schemas.esm.js +85 -6
  34. package/dist/schemas.js +85 -6
  35. package/dist/shell/coreutils/compilers-cli.d.ts +24 -0
  36. package/dist/shell/index.d.ts +4 -0
  37. package/dist/shell/lexer-parser.d.ts +26 -0
  38. package/dist/shell.esm.js +289 -4
  39. package/dist/shell.js +289 -4
  40. package/dist/terminal.esm.js +1 -1
  41. package/dist/terminal.js +1 -1
  42. package/dist/workbench/command-palette.d.ts +10 -0
  43. package/dist/workbench/diff-editor.d.ts +26 -0
  44. package/dist/workbench/drawer.d.ts +18 -0
  45. package/dist/workbench/editor.d.ts +11 -0
  46. package/dist/workbench/file-tree.d.ts +11 -0
  47. package/dist/workbench/guided-pane.d.ts +11 -0
  48. package/dist/workbench/icons.d.ts +5 -0
  49. package/dist/workbench/index.d.ts +39 -0
  50. package/dist/workbench/share.d.ts +21 -0
  51. package/dist/workbench/styles.d.ts +4 -0
  52. package/dist/workbench/toolbar.d.ts +17 -0
  53. package/dist/workbench.d.ts +6 -1
  54. package/package.json +33 -3
  55. package/src/code-lab.css +198 -0
  56. package/src/extensions/cpp.ts +1786 -0
  57. package/src/extensions/guided-lab.ts +10 -0
  58. package/src/extensions/javascript.ts +54 -0
  59. package/src/extensions/python.ts +1293 -0
  60. package/src/extensions/typescript.ts +85 -0
  61. package/src/index.ts +66 -3
  62. package/src/runtime/index.ts +5 -0
  63. package/src/runtime/test-harness.ts +57 -0
  64. package/src/runtime.ts +915 -14
  65. package/src/schemas.ts +94 -7
  66. package/src/shell/coreutils/compilers-cli.ts +103 -0
  67. package/src/shell/index.ts +5 -0
  68. package/src/shell.ts +288 -3
  69. package/src/workbench/command-palette.ts +140 -0
  70. package/src/workbench/diff-editor.ts +216 -0
  71. package/src/workbench/drawer.ts +148 -0
  72. package/src/workbench/editor.ts +49 -0
  73. package/src/workbench/file-tree.ts +51 -0
  74. package/src/workbench/guided-pane.ts +33 -0
  75. package/src/workbench/icons.ts +48 -0
  76. package/src/workbench/index.ts +38 -0
  77. package/src/workbench/share.ts +99 -0
  78. package/src/workbench/styles.ts +200 -0
  79. package/src/workbench/toolbar.ts +171 -0
  80. package/src/workbench.ts +1016 -78
package/src/schemas.ts CHANGED
@@ -1,7 +1,7 @@
1
1
  import { z } from 'zod';
2
2
 
3
3
  /**
4
- * Zod Schemas and Inferred TypeScript Types for code-lab v0.1.10
4
+ * Zod Schemas and Inferred TypeScript Types for code-lab v0.2.0
5
5
  */
6
6
 
7
7
  // ── 1. Guided Step ──────────────────────────────────────────────────────────
@@ -22,8 +22,12 @@ export type GuidedStep = z.infer<typeof GuidedStepSchema>;
22
22
 
23
23
  // ── 2. Language Bundle ──────────────────────────────────────────────────────
24
24
 
25
+ export const LanguageIdSchema = z.enum(['js', 'ts', 'cpp', 'py']);
26
+ export type LanguageId = z.infer<typeof LanguageIdSchema>;
27
+ export const LanguageEnum = LanguageIdSchema;
28
+
25
29
  export const LanguageBundleSchema = z.object({
26
- language: z.enum(['js', 'ts']).default('js'),
30
+ language: LanguageIdSchema.default('js'),
27
31
  files: z.record(z.string()).default({}),
28
32
  starterFiles: z.record(z.string()).optional(),
29
33
  solutionFiles: z.record(z.string()).optional(),
@@ -39,13 +43,22 @@ export const GuidedLabExtensionOptionsSchema = z.object({
39
43
  steps: z.array(GuidedStepSchema).default([]),
40
44
  stepIndex: z.number().int().nonnegative().default(0),
41
45
  mode: z.enum(['guided', 'sandbox']).default('guided'),
42
- language: z.enum(['js', 'ts']).optional(),
43
- lang: z.enum(['js', 'ts']).optional(),
46
+ language: LanguageIdSchema.optional(),
47
+ lang: LanguageIdSchema.optional(),
44
48
  starterFiles: z.record(z.string()).optional(),
45
49
  solutionFiles: z.record(z.string()).optional(),
46
50
  tsStarterFiles: z.record(z.string()).optional(),
47
51
  tsSolutionFiles: z.record(z.string()).optional(),
48
52
  tsFiles: z.record(z.string()).optional(),
53
+ cppStarterFiles: z.record(z.string()).optional(),
54
+ cppSolutionFiles: z.record(z.string()).optional(),
55
+ cppFiles: z.record(z.string()).optional(),
56
+ pyStarterFiles: z.record(z.string()).optional(),
57
+ pySolutionFiles: z.record(z.string()).optional(),
58
+ pyFiles: z.record(z.string()).optional(),
59
+ pyEntry: z.string().optional(),
60
+ pyTestEntry: z.string().optional(),
61
+ pyTestCode: z.string().optional(),
49
62
  summary: z.string().optional(),
50
63
  onStepComplete: z.function().args(GuidedStepSchema, z.number()).returns(z.void()).optional(),
51
64
  onLabComplete: z.function().args(z.string()).returns(z.void()).optional()
@@ -53,6 +66,69 @@ export const GuidedLabExtensionOptionsSchema = z.object({
53
66
 
54
67
  export type GuidedLabExtensionOptions = z.infer<typeof GuidedLabExtensionOptionsSchema>;
55
68
 
69
+ export const CppToolchainProgressSchema = z.object({
70
+ stage: z.enum(['downloading', 'caching', 'extracting', 'compiling', 'linking', 'ready']),
71
+ loadedBytes: z.number().optional(),
72
+ totalBytes: z.number().optional(),
73
+ percent: z.number().optional(),
74
+ message: z.string().optional()
75
+ });
76
+
77
+ export type CppToolchainProgress = z.infer<typeof CppToolchainProgressSchema>;
78
+
79
+ export const CppExtensionOptionsSchema = z.object({
80
+ toolchainUrl: z.string().optional(),
81
+ clangWasmUrl: z.string().optional(),
82
+ clangUrl: z.string().optional(),
83
+ lldWasmUrl: z.string().optional(),
84
+ lldUrl: z.string().optional(),
85
+ sysrootTarUrl: z.string().optional(),
86
+ sysrootUrl: z.string().optional(),
87
+ cacheInIndexedDB: z.boolean().default(true),
88
+ preload: z.boolean().default(false),
89
+ std: z.enum(['c++17', 'c++20', 'c++23']).default('c++20'),
90
+ optLevel: z.enum(['-O0', '-O1', '-O2', '-O3']).default('-O2'),
91
+ flags: z.array(z.string()).default(['-O2', '-Wall', '-Wextra']),
92
+ headers: z.record(z.string()).optional(),
93
+ extraHeaders: z.record(z.string()).optional(),
94
+ files: z.record(z.string()).optional(),
95
+ starterFiles: z.record(z.string()).optional(),
96
+ solutionFiles: z.record(z.string()).optional(),
97
+ onProgress: z.function().args(z.any()).returns(z.void()).optional()
98
+ });
99
+
100
+ export type CppExtensionOptions = z.infer<typeof CppExtensionOptionsSchema>;
101
+
102
+ export const PythonToolchainProgressSchema = z.object({
103
+ stage: z.enum(['downloading', 'caching', 'extracting', 'initializing', 'ready']),
104
+ loadedBytes: z.number().optional(),
105
+ totalBytes: z.number().optional(),
106
+ percent: z.number().optional(),
107
+ message: z.string().optional()
108
+ });
109
+
110
+ export type PythonToolchainProgress = z.infer<typeof PythonToolchainProgressSchema>;
111
+
112
+ export const PythonExtensionOptionsSchema = z.object({
113
+ cdnBaseUrl: z.string().optional(),
114
+ indexUrl: z.string().optional(),
115
+ pyodideIndexUrl: z.string().optional(),
116
+ cacheInIndexedDB: z.boolean().default(true),
117
+ preload: z.boolean().default(false),
118
+ activate: z.boolean().optional(),
119
+ entry: z.string().default('main.py'),
120
+ testEntry: z.string().default('test.py'),
121
+ packages: z.array(z.string()).optional(),
122
+ preloadPackages: z.array(z.string()).optional(),
123
+ compilerMemoryLimitMb: z.number().optional(),
124
+ files: z.record(z.string()).optional(),
125
+ starterFiles: z.record(z.string()).optional(),
126
+ solutionFiles: z.record(z.string()).optional(),
127
+ onProgress: z.function().args(z.any()).returns(z.void()).optional()
128
+ });
129
+
130
+ export type PythonExtensionOptions = z.infer<typeof PythonExtensionOptionsSchema>;
131
+
56
132
  // ── 4. GitHub Clone Options & Progress ──────────────────────────────────────
57
133
 
58
134
  export const CloneProgressPhaseSchema = z.enum([
@@ -127,7 +203,7 @@ export const WorkspaceSnapshotSchema = z.object({
127
203
  openTabs: z.array(z.string()).default([]),
128
204
  activeFile: z.string().nullable().optional(),
129
205
  mode: z.enum(['guided', 'sandbox']).optional(),
130
- lang: z.enum(['js', 'ts']).optional(),
206
+ lang: LanguageIdSchema.optional(),
131
207
  labId: z.string().optional()
132
208
  });
133
209
 
@@ -168,10 +244,21 @@ export const WorkbenchOptionsSchema = z.object({
168
244
  tsFiles: z.record(z.string()).optional(),
169
245
  tsStarterFiles: z.record(z.string()).optional(),
170
246
  tsSolutionFiles: z.record(z.string()).optional(),
247
+ cppFiles: z.record(z.string()).optional(),
248
+ cppStarterFiles: z.record(z.string()).optional(),
249
+ cppSolutionFiles: z.record(z.string()).optional(),
250
+ pyFiles: z.record(z.string()).optional(),
251
+ pyStarterFiles: z.record(z.string()).optional(),
252
+ pySolutionFiles: z.record(z.string()).optional(),
253
+ pyEntry: z.string().optional().default('main.py'),
254
+ pyTestEntry: z.string().optional().default('test.py'),
255
+ pyTestCode: z.string().optional(),
256
+ showWebPreview: z.boolean().optional(),
257
+ stdin: z.string().optional(),
171
258
  guided: z.any().optional(),
172
259
  mode: z.enum(['guided', 'sandbox']).optional(),
173
- language: z.enum(['js', 'ts']).optional(),
174
- lang: z.enum(['js', 'ts']).optional(),
260
+ language: LanguageIdSchema.optional(),
261
+ lang: LanguageIdSchema.optional(),
175
262
  stepIndex: z.number().int().optional(),
176
263
  onStepComplete: z.function().args(z.any(), z.number()).returns(z.void()).optional(),
177
264
  onLabComplete: z.function().args(z.string()).returns(z.void()).optional()
@@ -0,0 +1,103 @@
1
+ /**
2
+ * @innovatorved/code-lab — Shell Compiler Coreutils
3
+ * Provides `node`, `tsx`, `tsc`, `g++`, `clang++`, `python`, `python3`, `pytest`, `pip`.
4
+ */
5
+
6
+ export interface ShellExecutionContext {
7
+ vfs: any;
8
+ cwd: string;
9
+ env: Record<string, string>;
10
+ resolvePath: (p: string) => string;
11
+ onStdout?: (text: string) => void;
12
+ onStderr?: (text: string) => void;
13
+ shell?: any;
14
+ }
15
+
16
+ export interface ShellExecResult {
17
+ code: number;
18
+ stdout: string;
19
+ stderr: string;
20
+ }
21
+
22
+ export const COMPILER_COREUTILS = {
23
+ async python3(args: string[], ctx: ShellExecutionContext): Promise<ShellExecResult> {
24
+ if (args.length === 0) {
25
+ return { code: 0, stdout: 'Python 3.12.8 (CPython WebAssembly via Pyodide)\n', stderr: '' };
26
+ }
27
+
28
+ if (args[0] === '--version' || args[0] === '-V') {
29
+ return { code: 0, stdout: 'Python 3.12.8 (CPython WebAssembly via Pyodide)\n', stderr: '' };
30
+ }
31
+
32
+ let codeToRun: string | undefined;
33
+ let entryFile: string | undefined;
34
+
35
+ if (args[0] === '-c' && args.length > 1) {
36
+ codeToRun = args[1];
37
+ } else if (!args[0].startsWith('-')) {
38
+ entryFile = ctx.resolvePath(args[0]);
39
+ }
40
+
41
+ const pyCompiler =
42
+ (ctx.shell && ctx.shell.options && ctx.shell.options.pythonCompiler) ||
43
+ (typeof globalThis !== 'undefined' && (globalThis as any).__codelabPythonCompiler) ||
44
+ (typeof window !== 'undefined' && (window as any).__codelabPythonCompiler);
45
+
46
+ if (typeof pyCompiler !== 'function') {
47
+ return {
48
+ code: 1,
49
+ stdout: '',
50
+ stderr: 'python3: Python WebAssembly toolchain is not loaded. Enable pythonExtension from "@innovatorved/code-lab/extensions/python".\n'
51
+ };
52
+ }
53
+
54
+ let stdoutAcc = '';
55
+ let stderrAcc = '';
56
+
57
+ const res = await pyCompiler({
58
+ entry: entryFile,
59
+ source: codeToRun,
60
+ vfs: ctx.vfs,
61
+ onStdout: (t: string) => {
62
+ stdoutAcc += t;
63
+ if (ctx.onStdout) ctx.onStdout(t);
64
+ },
65
+ onStderr: (t: string) => {
66
+ stderrAcc += t;
67
+ if (ctx.onStderr) ctx.onStderr(t);
68
+ }
69
+ });
70
+
71
+ return {
72
+ code: res.ok ? 0 : (res.exitCode || 1),
73
+ stdout: stdoutAcc,
74
+ stderr: stderrAcc
75
+ };
76
+ },
77
+
78
+ async python(args: string[], ctx: ShellExecutionContext): Promise<ShellExecResult> {
79
+ return COMPILER_COREUTILS.python3(args, ctx);
80
+ },
81
+
82
+ async pytest(args: string[], ctx: ShellExecutionContext): Promise<ShellExecResult> {
83
+ const testFiles = args.filter((a) => !a.startsWith('-'));
84
+ const target = testFiles[0] || 'test.py';
85
+ return COMPILER_COREUTILS.python3([target], ctx);
86
+ },
87
+
88
+ async pip(args: string[], ctx: ShellExecutionContext): Promise<ShellExecResult> {
89
+ void ctx;
90
+ if (args.length === 0 || args[0] === '--version' || args[0] === '-V') {
91
+ return { code: 0, stdout: 'pip 24.0 from /usr/lib/python/pip (python 3.12)\n', stderr: '' };
92
+ }
93
+ if (args[0] === 'install') {
94
+ const pkgs = args.slice(1).filter((p) => !p.startsWith('-'));
95
+ return {
96
+ code: 0,
97
+ stdout: `Successfully installed ${pkgs.join(', ') || 'packages'}\n`,
98
+ stderr: ''
99
+ };
100
+ }
101
+ return { code: 0, stdout: 'pip 24.0 (Pyodide micropip)\n', stderr: '' };
102
+ }
103
+ };
@@ -0,0 +1,5 @@
1
+ /**
2
+ * @innovatorved/code-lab — Shell Subsystem Entrypoint
3
+ */
4
+
5
+ export * from './coreutils/compilers-cli';
package/src/shell.ts CHANGED
@@ -1682,7 +1682,7 @@
1682
1682
  }
1683
1683
  return Array.from(children).sort();
1684
1684
  },
1685
- readFileSync(p) {
1685
+ readFileSync(p, encoding) {
1686
1686
  const np = norm(p);
1687
1687
  const f = files.get(np);
1688
1688
  if (!f) {
@@ -1690,6 +1690,9 @@
1690
1690
  err.code = 'ENOENT';
1691
1691
  throw err;
1692
1692
  }
1693
+ if (!encoding && f.rawBytes instanceof Uint8Array) {
1694
+ return f.rawBytes;
1695
+ }
1693
1696
  return f.data;
1694
1697
  },
1695
1698
  writeFileSync(p, data) {
@@ -1700,9 +1703,13 @@
1700
1703
  let cur = '';
1701
1704
  for (const pt of parts) { cur += '/' + pt; dirs.add(cur); }
1702
1705
  }
1703
- const str = typeof data === 'string' ? data : (data.toString ? data.toString('utf8') : String(data));
1706
+ const isBinary = data instanceof Uint8Array;
1707
+ const rawBytes = isBinary ? new Uint8Array(data.buffer, data.byteOffset, data.byteLength) : null;
1708
+ const str = isBinary
1709
+ ? new TextDecoder('utf-8').decode(rawBytes)
1710
+ : (typeof data === 'string' ? data : (data && data.toString ? data.toString('utf8') : String(data)));
1704
1711
  const prevMode = files.has(np) ? files.get(np).mode : 0o100644;
1705
- files.set(np, { data: str, mtimeMs: Date.now(), mode: prevMode });
1712
+ files.set(np, { data: str, rawBytes, mtimeMs: Date.now(), mode: prevMode });
1706
1713
  },
1707
1714
  appendFileSync(p, data) {
1708
1715
  const np = norm(p);
@@ -5929,6 +5936,8 @@
5929
5936
  stdout += ' history, ps, jobs, kill Process and job management\n';
5930
5937
  stdout += ' git [status diff log] Built-in version control\n';
5931
5938
  stdout += ' node, bun, npm, pnpm, npx, bunx CLI runtime and package shims\n';
5939
+ stdout += ' g++, clang++, c++ C++20 WebAssembly compiler (via cppExtension)\n';
5940
+ stdout += ' python, python3, pytest Python 3.12 WebAssembly runtime (via pythonExtension)\n';
5932
5941
  stdout += ' serve [dir] [--port] Built-in preview server (transpiles TS/JSX for the browser)\n';
5933
5942
  stdout += ' ports, curl Port table inspection & HTTP requests\n';
5934
5943
  stdout += ' hey, ab, wrk Concurrent HTTP load generator & latency percentiles\n';
@@ -6047,6 +6056,236 @@
6047
6056
  return { code: res.ok ? 0 : (res.exitCode || 1), stdout: res.stdout, stderr: res.stderr };
6048
6057
  },
6049
6058
 
6059
+ async 'g++'(args, ctx) {
6060
+ if (args.includes('--version') || args.includes('-v')) {
6061
+ return {
6062
+ code: 0,
6063
+ stdout: 'clang version 18.1.8 (Target: wasm32-unknown-wasi)\nTarget: wasm32-unknown-wasi\nThread model: posix\nInstalledDir: /usr/bin\n',
6064
+ stderr: ''
6065
+ };
6066
+ }
6067
+ if (args.includes('--help') || args.includes('-h')) {
6068
+ return {
6069
+ code: 0,
6070
+ stdout:
6071
+ 'Usage: g++ [options] file...\n' +
6072
+ 'Options:\n' +
6073
+ ' -std=<standard> Assume that the input sources are for <standard> (c++17, c++20, c++23)\n' +
6074
+ ' -O0, -O1, -O2, -O3 Optimization level\n' +
6075
+ ' -o <file> Write output to <file> (default: a.out)\n' +
6076
+ ' -I <dir> Add directory to include search path\n',
6077
+ stderr: ''
6078
+ };
6079
+ }
6080
+
6081
+ const sourceFiles = [];
6082
+ const extraFlags = [];
6083
+ let outputPath = PosixPath.join(ctx.cwd, 'a.out');
6084
+ let std = 'c++20';
6085
+ let optLevel = '-O2';
6086
+
6087
+ for (let i = 0; i < args.length; i++) {
6088
+ const arg = args[i];
6089
+ if (arg === '-o' && i + 1 < args.length) {
6090
+ outputPath = ctx.resolvePath(args[++i]);
6091
+ } else if (arg.startsWith('-o') && arg.length > 2) {
6092
+ outputPath = ctx.resolvePath(arg.slice(2));
6093
+ } else if (arg.startsWith('-std=')) {
6094
+ const val = arg.slice(5);
6095
+ if (val === 'c++17' || val === 'gnu++17') std = 'c++17';
6096
+ else if (val === 'c++23' || val === 'c++2b' || val === 'gnu++23') std = 'c++23';
6097
+ else std = 'c++20';
6098
+ } else if (arg === '-O0' || arg === '-O1' || arg === '-O2' || arg === '-O3') {
6099
+ optLevel = arg;
6100
+ } else if (arg.startsWith('-I') || arg.startsWith('-D') || arg.startsWith('-W')) {
6101
+ extraFlags.push(arg);
6102
+ } else if (!arg.startsWith('-')) {
6103
+ sourceFiles.push(ctx.resolvePath(arg));
6104
+ }
6105
+ }
6106
+
6107
+ if (sourceFiles.length === 0) {
6108
+ return { code: 1, stdout: '', stderr: 'g++: fatal error: no input files\ncompilation terminated.\n' };
6109
+ }
6110
+
6111
+ for (const src of sourceFiles) {
6112
+ if (!ctx.vfs.existsSync(src)) {
6113
+ return { code: 1, stdout: '', stderr: `g++: error: ${src}: No such file or directory\n` };
6114
+ }
6115
+ }
6116
+
6117
+ const cppCompiler =
6118
+ (ctx.shell && ctx.shell.options && ctx.shell.options.cppCompiler) ||
6119
+ (typeof globalThis !== 'undefined' && globalThis.__codelabCppCompiler) ||
6120
+ (typeof window !== 'undefined' && window.__codelabCppCompiler);
6121
+
6122
+ if (typeof cppCompiler !== 'function') {
6123
+ return {
6124
+ code: 1,
6125
+ stdout: '',
6126
+ stderr:
6127
+ 'g++: C++ toolchain is not enabled. Enable cppExtension from "@innovatorved/code-lab/extensions/cpp" to compile C++ files.\n'
6128
+ };
6129
+ }
6130
+
6131
+ let outText = '';
6132
+ let errText = '';
6133
+ const compileRes = await cppCompiler({
6134
+ entry: sourceFiles[0],
6135
+ sourceFiles,
6136
+ outputPath,
6137
+ std,
6138
+ optLevel,
6139
+ extraFlags,
6140
+ vfs: ctx.vfs,
6141
+ onStdout: (t) => {
6142
+ outText += t;
6143
+ if (ctx.onStdout) ctx.onStdout(t);
6144
+ },
6145
+ onStderr: (t) => {
6146
+ errText += t;
6147
+ if (ctx.onStderr) ctx.onStderr(t);
6148
+ }
6149
+ });
6150
+
6151
+ if (!compileRes || compileRes.exitCode !== 0) {
6152
+ return {
6153
+ code: (compileRes && compileRes.exitCode) || 1,
6154
+ stdout: outText,
6155
+ stderr: errText || 'g++: error: linker command failed with exit code 1\n'
6156
+ };
6157
+ }
6158
+
6159
+ if (compileRes.wasmBinary) {
6160
+ ctx.vfs.writeFileSync(outputPath, compileRes.wasmBinary);
6161
+ if (typeof ctx.vfs.chmodSync === 'function') {
6162
+ try { ctx.vfs.chmodSync(outputPath, 0o755); } catch (err) { _shellLogger.debug('chmodSync failed on compiled binary', err); }
6163
+ }
6164
+ if (typeof ctx.emitMutation === 'function') ctx.emitMutation('create', outputPath);
6165
+ }
6166
+
6167
+ return { code: 0, stdout: outText, stderr: errText };
6168
+ },
6169
+
6170
+ async 'clang++'(args, ctx) {
6171
+ return COREUTILS['g++'](args, ctx);
6172
+ },
6173
+
6174
+ async 'c++'(args, ctx) {
6175
+ return COREUTILS['g++'](args, ctx);
6176
+ },
6177
+
6178
+ async python3(args, ctx) {
6179
+ if (args.length === 0) {
6180
+ return { code: 0, stdout: 'Python 3.12.8 (CPython WebAssembly via Pyodide)\n', stderr: '' };
6181
+ }
6182
+
6183
+ if (args[0] === '--version' || args[0] === '-V') {
6184
+ return { code: 0, stdout: 'Python 3.12.8 (CPython WebAssembly via Pyodide)\n', stderr: '' };
6185
+ }
6186
+
6187
+ let codeToRun = undefined;
6188
+ let entryFile = undefined;
6189
+
6190
+ if (args[0] === '-c' && args.length > 1) {
6191
+ codeToRun = args[1];
6192
+ } else if (!args[0].startsWith('-')) {
6193
+ entryFile = ctx.resolvePath(args[0]);
6194
+ }
6195
+
6196
+ const pyCompiler =
6197
+ (ctx.shell && ctx.shell.options && ctx.shell.options.pythonCompiler) ||
6198
+ (typeof globalThis !== 'undefined' && globalThis.__codelabPythonCompiler) ||
6199
+ (typeof window !== 'undefined' && window.__codelabPythonCompiler);
6200
+
6201
+ if (typeof pyCompiler !== 'function') {
6202
+ return {
6203
+ code: 1,
6204
+ stdout: '',
6205
+ stderr:
6206
+ 'python3: Python WebAssembly toolchain is not enabled. Enable pythonExtension from "@innovatorved/code-lab/extensions/python".\n'
6207
+ };
6208
+ }
6209
+
6210
+ let outText = '';
6211
+ let errText = '';
6212
+ const res = await pyCompiler({
6213
+ entry: entryFile,
6214
+ source: codeToRun,
6215
+ vfs: ctx.vfs,
6216
+ onStdout: (t) => {
6217
+ outText += t;
6218
+ if (ctx.onStdout) ctx.onStdout(t);
6219
+ },
6220
+ onStderr: (t) => {
6221
+ errText += t;
6222
+ if (ctx.onStderr) ctx.onStderr(t);
6223
+ }
6224
+ });
6225
+
6226
+ return {
6227
+ code: res && res.ok ? 0 : ((res && res.exitCode) || 1),
6228
+ stdout: outText,
6229
+ stderr: errText
6230
+ };
6231
+ },
6232
+
6233
+ async python(args, ctx) {
6234
+ return COREUTILS['python3'](args, ctx);
6235
+ },
6236
+
6237
+ async pytest(args, ctx) {
6238
+ if (args.length > 0 && (args[0] === '--version' || args[0] === '-V')) {
6239
+ return { code: 0, stdout: 'pytest 8.3.4 (Python 3.12 WebAssembly)\n', stderr: '' };
6240
+ }
6241
+ const testFiles = args.filter((a) => !a.startsWith('-'));
6242
+ let target = testFiles[0];
6243
+ if (!target && ctx.vfs) {
6244
+ try {
6245
+ const allFiles = Object.keys(typeof ctx.vfs.toSnapshot === 'function' ? ctx.vfs.toSnapshot('/workspace') : (ctx.vfs.files || {}));
6246
+ target = allFiles.find((f) => /(?:^|\/)(?:test_.*|.*_test|test)\.py$/i.test(f));
6247
+ } catch (err) {
6248
+ void err;
6249
+ }
6250
+ }
6251
+ target = target || 'test.py';
6252
+ return COREUTILS['python3']([target], ctx);
6253
+ },
6254
+
6255
+ async pip(args, ctx) {
6256
+ if (args.length === 0 || args[0] === '--version' || args[0] === '-V') {
6257
+ return { code: 0, stdout: 'pip 24.0 from /usr/lib/python/pip (python 3.12)\n', stderr: '' };
6258
+ }
6259
+ if (args[0] === 'install') {
6260
+ const pkgs = args.slice(1).filter((p) => !p.startsWith('-'));
6261
+ const toolchain =
6262
+ (ctx.shell && ctx.shell.options && ctx.shell.options.pythonToolchain) ||
6263
+ (typeof globalThis !== 'undefined' && globalThis.__codelabPythonToolchain) ||
6264
+ (typeof window !== 'undefined' && window.__codelabPythonToolchain);
6265
+ if (toolchain && typeof toolchain.installPackages === 'function') {
6266
+ const res = await toolchain.installPackages(pkgs);
6267
+ if (res.ok) {
6268
+ return {
6269
+ code: 0,
6270
+ stdout: `Successfully installed ${res.installed.join(', ') || 'packages'}\n`,
6271
+ stderr: ''
6272
+ };
6273
+ }
6274
+ return {
6275
+ code: 1,
6276
+ stdout: '',
6277
+ stderr: `ERROR: Could not find a version that satisfies the requirement ${res.error || pkgs.join(', ')}\n`
6278
+ };
6279
+ }
6280
+ return {
6281
+ code: 0,
6282
+ stdout: `Successfully installed ${pkgs.join(', ') || 'packages'}\n`,
6283
+ stderr: ''
6284
+ };
6285
+ }
6286
+ return { code: 0, stdout: 'pip 24.0 (Pyodide micropip)\n', stderr: '' };
6287
+ },
6288
+
6050
6289
  async bun(args, ctx) {
6051
6290
  if (args.length === 0) {
6052
6291
  return { code: 0, stdout: 'Bun v1.1.20\n', stderr: '' };
@@ -7649,6 +7888,10 @@
7649
7888
  return { code: lastCode, exitCode: lastCode, stdout: combinedStdout, stderr: combinedStderr, ok: lastCode === 0 };
7650
7889
  }
7651
7890
 
7891
+ async executeCommand(commandLine, execOptions = {}) {
7892
+ return this.execute(commandLine, execOptions);
7893
+ }
7894
+
7652
7895
  async _executeWithRedirects(redirects, context, execFn) {
7653
7896
  if (!redirects || redirects.length === 0) {
7654
7897
  return execFn(context);
@@ -8329,6 +8572,48 @@
8329
8572
  Object.assign(context.env, this.env);
8330
8573
  context.cwd = this.cwd;
8331
8574
  }
8575
+ } else if (
8576
+ (cmdName.startsWith('./') || cmdName.startsWith('../') || cmdName.startsWith('/')) &&
8577
+ this.vfs.existsSync(this.resolvePath(cmdName))
8578
+ ) {
8579
+ const absBin = this.resolvePath(cmdName);
8580
+ const st = this.vfs.statSync(absBin);
8581
+ if (st && st.isDirectory()) {
8582
+ res = { code: 126, stdout: '', stderr: `shell: ${cmdName}: Is a directory\n` };
8583
+ } else if (hasVirtualRuntime()) {
8584
+ let rawData = null;
8585
+ try { rawData = this.vfs.readFileSync(absBin); } catch (err) { _shellLogger.debug('Failed to read binary', err); }
8586
+ const isWasmMagic =
8587
+ (rawData instanceof Uint8Array &&
8588
+ rawData.length >= 4 &&
8589
+ rawData[0] === 0x00 &&
8590
+ rawData[1] === 0x61 &&
8591
+ rawData[2] === 0x73 &&
8592
+ rawData[3] === 0x6d) ||
8593
+ (typeof rawData === 'string' && rawData.startsWith('\0asm'));
8594
+ const runRes = await executeInVirtualRuntime({
8595
+ mode: 'run',
8596
+ entry: absBin,
8597
+ wasmBinary: isWasmMagic && rawData instanceof Uint8Array ? rawData : undefined,
8598
+ argv: [cmdName, ...args],
8599
+ stdin: effectiveStdin,
8600
+ env: cmdEnv,
8601
+ vfs: this.vfs,
8602
+ activePortTable: this.portTable,
8603
+ pid: cmdCtx.pid,
8604
+ isBackground: cmdCtx.isBackground,
8605
+ onStdout: cmdCtx.onStdout,
8606
+ onStderr: cmdCtx.onStderr,
8607
+ signal: context.signal
8608
+ });
8609
+ res = {
8610
+ code: runRes.ok ? 0 : (runRes.exitCode || 1),
8611
+ stdout: runRes.stdout || '',
8612
+ stderr: runRes.stderr || ''
8613
+ };
8614
+ } else {
8615
+ res = { code: 126, stdout: '', stderr: `shell: ${cmdName}: cannot execute binary file\n` };
8616
+ }
8332
8617
  } else if (DIRECT_DEV_TOOL_RE.test(cmdName)) {
8333
8618
  // A native dev server (vite/ng/astro/…) typed directly. It cannot run in
8334
8619
  // this runtime — whether or not it was installed — so route it to the