@innovatorved/code-lab 0.1.13 → 0.2.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.
@@ -0,0 +1,1081 @@
1
+ import { CppExtensionOptions, CppExtensionOptionsSchema, CppToolchainProgress } from '../schemas';
2
+
3
+ /**
4
+ * Built-in competitive programming & DSA headers seeded into `/usr/include`
5
+ * inside the VirtualFS alongside the WASI sysroot.
6
+ */
7
+ export const BUILTIN_CPP_HEADERS: Record<string, string> = {
8
+ '/usr/include/bits/stdc++.h': `// CodeLab <bits/stdc++.h> — Competitive Programming & DSA Umbrella Header
9
+ #pragma once
10
+ #include <iostream>
11
+ #include <iomanip>
12
+ #include <sstream>
13
+ #include <fstream>
14
+ #include <string>
15
+ #include <string_view>
16
+ #include <vector>
17
+ #include <deque>
18
+ #include <list>
19
+ #include <forward_list>
20
+ #include <array>
21
+ #include <set>
22
+ #include <unordered_set>
23
+ #include <map>
24
+ #include <unordered_map>
25
+ #include <stack>
26
+ #include <queue>
27
+ #include <bitset>
28
+ #include <algorithm>
29
+ #include <numeric>
30
+ #include <iterator>
31
+ #include <functional>
32
+ #include <utility>
33
+ #include <tuple>
34
+ #include <optional>
35
+ #include <variant>
36
+ #include <any>
37
+ #include <memory>
38
+ #include <cmath>
39
+ #include <cstdlib>
40
+ #include <cstdio>
41
+ #include <cstring>
42
+ #include <climits>
43
+ #include <cfloat>
44
+ #include <cstdint>
45
+ #include <cassert>
46
+ #include <chrono>
47
+ #include <random>
48
+ #include <complex>
49
+ #include <exception>
50
+ #include <stdexcept>
51
+ #include <type_traits>
52
+ #include <limits>
53
+ `,
54
+
55
+ '/usr/include/codelab/dsa.hpp': `// CodeLab <codelab/dsa.hpp> — Data Structures & Algorithms Utilities
56
+ #pragma once
57
+ #include <iostream>
58
+ #include <vector>
59
+ #include <queue>
60
+ #include <string>
61
+ #include <sstream>
62
+ #include <climits>
63
+
64
+ namespace codelab {
65
+
66
+ struct ListNode {
67
+ int val;
68
+ ListNode* next;
69
+ ListNode() : val(0), next(nullptr) {}
70
+ explicit ListNode(int x) : val(x), next(nullptr) {}
71
+ ListNode(int x, ListNode* n) : val(x), next(n) {}
72
+ };
73
+
74
+ struct TreeNode {
75
+ int val;
76
+ TreeNode* left;
77
+ TreeNode* right;
78
+ TreeNode() : val(0), left(nullptr), right(nullptr) {}
79
+ explicit TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
80
+ TreeNode(int x, TreeNode* l, TreeNode* r) : val(x), left(l), right(r) {}
81
+ };
82
+
83
+ inline ListNode* buildLinkedList(const std::vector<int>& values) {
84
+ ListNode dummy(0);
85
+ ListNode* tail = &dummy;
86
+ for (int v : values) {
87
+ tail->next = new ListNode(v);
88
+ tail = tail->next;
89
+ }
90
+ return dummy.next;
91
+ }
92
+
93
+ inline std::vector<int> linkedListToVector(const ListNode* head) {
94
+ std::vector<int> out;
95
+ while (head != nullptr) {
96
+ out.push_back(head->val);
97
+ head = head->next;
98
+ }
99
+ return out;
100
+ }
101
+
102
+ inline TreeNode* buildBinaryTree(const std::vector<int>& values, int nullSentinel = INT_MIN) {
103
+ if (values.empty() || values[0] == nullSentinel) return nullptr;
104
+ TreeNode* root = new TreeNode(values[0]);
105
+ std::queue<TreeNode*> q;
106
+ q.push(root);
107
+ size_t i = 1;
108
+ while (!q.empty() && i < values.size()) {
109
+ TreeNode* curr = q.front();
110
+ q.pop();
111
+ if (i < values.size() && values[i] != nullSentinel) {
112
+ curr->left = new TreeNode(values[i]);
113
+ q.push(curr->left);
114
+ }
115
+ i++;
116
+ if (i < values.size() && values[i] != nullSentinel) {
117
+ curr->right = new TreeNode(values[i]);
118
+ q.push(curr->right);
119
+ }
120
+ i++;
121
+ }
122
+ return root;
123
+ }
124
+
125
+ template <typename T>
126
+ inline std::string vectorToString(const std::vector<T>& vec) {
127
+ std::ostringstream oss;
128
+ oss << "[";
129
+ for (size_t i = 0; i < vec.size(); ++i) {
130
+ if (i > 0) oss << ", ";
131
+ oss << vec[i];
132
+ }
133
+ oss << "]";
134
+ return oss.str();
135
+ }
136
+
137
+ template <typename T>
138
+ inline void printVector(const std::vector<T>& vec) {
139
+ std::cout << vectorToString(vec) << "\\n";
140
+ }
141
+
142
+ } // namespace codelab
143
+
144
+ using codelab::ListNode;
145
+ using codelab::TreeNode;
146
+ using codelab::buildLinkedList;
147
+ using codelab::linkedListToVector;
148
+ using codelab::buildBinaryTree;
149
+ using codelab::vectorToString;
150
+ using codelab::printVector;
151
+ `,
152
+
153
+ '/usr/include/codelab/test.hpp': `// CodeLab <codelab/test.hpp> — Zero-Overhead C++ Test Runner for CodeLab Test Suite & Guided Lab
154
+ #pragma once
155
+ #include <iostream>
156
+ #include <sstream>
157
+ #include <string>
158
+ #include <vector>
159
+ #include <functional>
160
+ #include <chrono>
161
+ #include <stdexcept>
162
+
163
+ namespace codelab {
164
+ namespace testing {
165
+
166
+ struct AssertionFailure : public std::exception {
167
+ std::string message;
168
+ std::string actual;
169
+ std::string expected;
170
+ std::string op;
171
+ AssertionFailure(std::string m, std::string a = "", std::string e = "", std::string o = "")
172
+ : message(std::move(m)), actual(std::move(a)), expected(std::move(e)), op(std::move(o)) {}
173
+ const char* what() const noexcept override { return message.c_str(); }
174
+ };
175
+
176
+ inline std::string escapeJson(const std::string& s) {
177
+ std::ostringstream o;
178
+ for (char c : s) {
179
+ switch (c) {
180
+ case '"': o << "\\\\\\""; break;
181
+ case '\\\\': o << "\\\\\\\\"; break;
182
+ case '\\b': o << "\\\\b"; break;
183
+ case '\\f': o << "\\\\f"; break;
184
+ case '\\n': o << "\\\\n"; break;
185
+ case '\\r': o << "\\\\r"; break;
186
+ case '\\t': o << "\\\\t"; break;
187
+ default: o << c; break;
188
+ }
189
+ }
190
+ return o.str();
191
+ }
192
+
193
+ template <typename T>
194
+ inline std::string formatVal(const T& val) {
195
+ std::ostringstream oss;
196
+ oss << val;
197
+ return oss.str();
198
+ }
199
+
200
+ template <typename T>
201
+ inline std::string formatVal(const std::vector<T>& vec) {
202
+ std::ostringstream oss;
203
+ oss << "[";
204
+ for (size_t i = 0; i < vec.size(); ++i) {
205
+ if (i > 0) oss << ", ";
206
+ oss << formatVal(vec[i]);
207
+ }
208
+ oss << "]";
209
+ return oss.str();
210
+ }
211
+
212
+ inline std::vector<std::string>& currentSuiteStack() {
213
+ static std::vector<std::string> stack;
214
+ return stack;
215
+ }
216
+
217
+ inline int& failedCount() {
218
+ static int count = 0;
219
+ return count;
220
+ }
221
+
222
+ inline void runTest(const std::string& name, const std::function<void()>& fn) {
223
+ std::string fullName = name;
224
+ const auto& stack = currentSuiteStack();
225
+ if (!stack.empty()) {
226
+ std::ostringstream oss;
227
+ for (const auto& s : stack) oss << s << " > ";
228
+ oss << name;
229
+ fullName = oss.str();
230
+ }
231
+ auto t0 = std::chrono::steady_clock::now();
232
+ try {
233
+ fn();
234
+ auto t1 = std::chrono::steady_clock::now();
235
+ double ms = std::chrono::duration<double, std::milli>(t1 - t0).count();
236
+ std::cout << "__CODELAB_TEST__:{\\"name\\":\\"" << escapeJson(fullName)
237
+ << "\\",\\"passed\\":true,\\"durationMs\\":" << ms << "}\\n";
238
+ } catch (const AssertionFailure& af) {
239
+ failedCount()++;
240
+ auto t1 = std::chrono::steady_clock::now();
241
+ double ms = std::chrono::duration<double, std::milli>(t1 - t0).count();
242
+ std::cout << "__CODELAB_TEST__:{\\"name\\":\\"" << escapeJson(fullName)
243
+ << "\\",\\"passed\\":false,\\"durationMs\\":" << ms
244
+ << ",\\"error\\":{\\"message\\":\\"" << escapeJson(af.message)
245
+ << "\\",\\"actual\\":\\"" << escapeJson(af.actual)
246
+ << "\\",\\"expected\\":\\"" << escapeJson(af.expected)
247
+ << "\\",\\"operator\\":\\"" << escapeJson(af.op) << "\\"}}\\n";
248
+ } catch (const std::exception& ex) {
249
+ failedCount()++;
250
+ auto t1 = std::chrono::steady_clock::now();
251
+ double ms = std::chrono::duration<double, std::milli>(t1 - t0).count();
252
+ std::cout << "__CODELAB_TEST__:{\\"name\\":\\"" << escapeJson(fullName)
253
+ << "\\",\\"passed\\":false,\\"durationMs\\":" << ms
254
+ << ",\\"error\\":{\\"message\\":\\"" << escapeJson(ex.what()) << "\\"}}\\n";
255
+ }
256
+ }
257
+
258
+ inline void runSuite(const std::string& suiteName, const std::function<void()>& fn) {
259
+ currentSuiteStack().push_back(suiteName);
260
+ try {
261
+ fn();
262
+ } catch (...) {
263
+ currentSuiteStack().pop_back();
264
+ throw;
265
+ }
266
+ currentSuiteStack().pop_back();
267
+ }
268
+
269
+ template <typename A, typename B>
270
+ inline void assertEq(const A& actual, const B& expected, const char* exprA, const char* exprB, int line) {
271
+ if (!(actual == expected)) {
272
+ std::string aStr = formatVal(actual);
273
+ std::string eStr = formatVal(expected);
274
+ std::ostringstream msg;
275
+ msg << "Line " << line << ": Expected " << exprA << " == " << exprB << " (got " << aStr << ", expected " << eStr << ")";
276
+ throw AssertionFailure(msg.str(), aStr, eStr, "==");
277
+ }
278
+ }
279
+
280
+ template <typename A, typename B>
281
+ inline void assertNe(const A& actual, const B& expected, const char* exprA, const char* exprB, int line) {
282
+ if (!(actual != expected)) {
283
+ std::string aStr = formatVal(actual);
284
+ std::string eStr = formatVal(expected);
285
+ std::ostringstream msg;
286
+ msg << "Line " << line << ": Expected " << exprA << " != " << exprB << " (both were " << aStr << ")";
287
+ throw AssertionFailure(msg.str(), aStr, eStr, "!=");
288
+ }
289
+ }
290
+
291
+ inline void assertBool(bool cond, bool expected, const char* expr, int line) {
292
+ if (cond != expected) {
293
+ std::ostringstream msg;
294
+ msg << "Line " << line << ": Expected " << expr << " to be " << (expected ? "true" : "false");
295
+ throw AssertionFailure(msg.str(), cond ? "true" : "false", expected ? "true" : "false", "bool");
296
+ }
297
+ }
298
+
299
+ } // namespace testing
300
+ } // namespace codelab
301
+
302
+ #define DESCRIBE(name, body) ::codelab::testing::runSuite((name), [&]() body)
303
+ #define TEST(name, body) ::codelab::testing::runTest((name), [&]() body)
304
+ #define IT(name, body) ::codelab::testing::runTest((name), [&]() body)
305
+ #define ASSERT_EQ(actual, expected) ::codelab::testing::assertEq((actual), (expected), #actual, #expected, __LINE__)
306
+ #define EXPECT_EQ(actual, expected) ::codelab::testing::assertEq((actual), (expected), #actual, #expected, __LINE__)
307
+ #define ASSERT_NE(actual, expected) ::codelab::testing::assertNe((actual), (expected), #actual, #expected, __LINE__)
308
+ #define ASSERT_TRUE(cond) ::codelab::testing::assertBool(static_cast<bool>(cond), true, #cond, __LINE__)
309
+ #define ASSERT_FALSE(cond) ::codelab::testing::assertBool(static_cast<bool>(cond), false, #cond, __LINE__)
310
+ #define CODELAB_TEST_EXIT_CODE() (::codelab::testing::failedCount() > 0 ? 1 : 0)
311
+ `
312
+ };
313
+
314
+ const IDB_NAME = 'codelab_cpp_toolchain_v1';
315
+ const IDB_STORE = 'assets';
316
+ const memoryAssetCache = new Map<string, Uint8Array>();
317
+
318
+ function openToolchainIdb(): Promise<IDBDatabase | null> {
319
+ if (typeof indexedDB === 'undefined') return Promise.resolve(null);
320
+ return new Promise((resolve) => {
321
+ try {
322
+ const req = indexedDB.open(IDB_NAME, 1);
323
+ req.onupgradeneeded = () => {
324
+ const db = req.result;
325
+ if (!db.objectStoreNames.contains(IDB_STORE)) {
326
+ db.createObjectStore(IDB_STORE);
327
+ }
328
+ };
329
+ req.onsuccess = () => resolve(req.result);
330
+ req.onerror = () => resolve(null);
331
+ } catch (err) {
332
+ if (err) resolve(null);
333
+ }
334
+ });
335
+ }
336
+
337
+ async function getCachedAsset(key: string): Promise<Uint8Array | null> {
338
+ const mem = memoryAssetCache.get(key);
339
+ if (mem) return mem;
340
+ const db = await openToolchainIdb();
341
+ if (!db) return null;
342
+ return new Promise((resolve) => {
343
+ try {
344
+ const tx = db.transaction(IDB_STORE, 'readonly');
345
+ const store = tx.objectStore(IDB_STORE);
346
+ const req = store.get(key);
347
+ req.onsuccess = () => {
348
+ const val = req.result;
349
+ if (val instanceof Uint8Array) {
350
+ memoryAssetCache.set(key, val);
351
+ resolve(val);
352
+ } else if (val instanceof ArrayBuffer) {
353
+ const arr = new Uint8Array(val);
354
+ memoryAssetCache.set(key, arr);
355
+ resolve(arr);
356
+ } else {
357
+ resolve(null);
358
+ }
359
+ };
360
+ req.onerror = () => resolve(null);
361
+ } catch (err) {
362
+ if (err) resolve(null);
363
+ }
364
+ });
365
+ }
366
+
367
+ async function setCachedAsset(key: string, data: Uint8Array): Promise<void> {
368
+ memoryAssetCache.set(key, data);
369
+ const db = await openToolchainIdb();
370
+ if (!db) return;
371
+ return new Promise((resolve) => {
372
+ try {
373
+ const tx = db.transaction(IDB_STORE, 'readwrite');
374
+ const store = tx.objectStore(IDB_STORE);
375
+ store.put(data, key);
376
+ tx.oncomplete = () => resolve();
377
+ tx.onerror = () => resolve();
378
+ } catch (err) {
379
+ if (err) resolve();
380
+ }
381
+ });
382
+ }
383
+
384
+ /**
385
+ * Extracts a POSIX UStar `.tar` archive into a `VirtualFS` instance.
386
+ */
387
+ export function extractTarToVfs(tarBytes: Uint8Array, vfs: any, baseDir = '/'): string[] {
388
+ const extractedPaths: string[] = [];
389
+ const decoder = new TextDecoder('utf-8');
390
+ let offset = 0;
391
+
392
+ const readString = (start: number, length: number): string => {
393
+ let end = start;
394
+ const max = Math.min(tarBytes.length, start + length);
395
+ while (end < max && tarBytes[end] !== 0) end++;
396
+ return decoder.decode(tarBytes.subarray(start, end)).trim();
397
+ };
398
+
399
+ while (offset + 512 <= tarBytes.length) {
400
+ const name = readString(offset, 100);
401
+ if (!name) {
402
+ offset += 512;
403
+ continue;
404
+ }
405
+ const sizeOctal = readString(offset + 124, 12);
406
+ const size = parseInt(sizeOctal || '0', 8) || 0;
407
+ const typeFlag = tarBytes[offset + 156];
408
+ const prefix = readString(offset + 345, 155);
409
+ const fullName = prefix ? `${prefix}/${name}` : name;
410
+ const cleanRel = fullName.replace(/^\.?\/+/, '');
411
+ const targetPath = baseDir === '/' ? `/${cleanRel}` : `${baseDir.replace(/\/+$/, '')}/${cleanRel}`;
412
+
413
+ const dataStart = offset + 512;
414
+ const dataEnd = dataStart + size;
415
+
416
+ if (cleanRel) {
417
+ if (typeFlag === 53 || fullName.endsWith('/')) {
418
+ // Directory ('5')
419
+ if (!vfs.existsSync(targetPath)) {
420
+ vfs.mkdirSync(targetPath, { recursive: true });
421
+ }
422
+ } else if (typeFlag === 0 || typeFlag === 48) {
423
+ // Regular file ('0' or '\0')
424
+ const parentDir = targetPath.slice(0, targetPath.lastIndexOf('/')) || '/';
425
+ if (!vfs.existsSync(parentDir)) {
426
+ vfs.mkdirSync(parentDir, { recursive: true });
427
+ }
428
+ const fileData = tarBytes.slice(dataStart, dataEnd);
429
+ vfs.writeFileSync(targetPath, fileData);
430
+ extractedPaths.push(targetPath);
431
+ }
432
+ }
433
+
434
+ const blocks = Math.ceil(size / 512);
435
+ offset = dataStart + blocks * 512;
436
+ }
437
+
438
+ return extractedPaths;
439
+ }
440
+
441
+ /**
442
+ * Creates a POSIX UStar `.tar` archive from a map of file paths to contents.
443
+ * Useful for packaging custom sysroot headers/libraries or testing TAR extraction.
444
+ */
445
+ export function createTarArchive(files: Record<string, string | Uint8Array>): Uint8Array {
446
+ const encoder = new TextEncoder();
447
+ const chunks: Uint8Array[] = [];
448
+
449
+ for (const [rawPath, content] of Object.entries(files)) {
450
+ const cleanPath = rawPath.replace(/^\/+/, '');
451
+ const data = typeof content === 'string' ? encoder.encode(content) : content;
452
+ const header = new Uint8Array(512);
453
+
454
+ const writeField = (str: string, offset: number, maxLen: number) => {
455
+ const bytes = encoder.encode(str);
456
+ header.set(bytes.subarray(0, Math.min(bytes.length, maxLen)), offset);
457
+ };
458
+
459
+ writeField(cleanPath, 0, 100);
460
+ writeField('0000644\0', 100, 8);
461
+ writeField('0000000\0', 108, 8);
462
+ writeField('0000000\0', 116, 8);
463
+ writeField(data.byteLength.toString(8).padStart(11, '0') + '\0', 124, 12);
464
+ writeField(Math.floor(Date.now() / 1000).toString(8).padStart(11, '0') + '\0', 136, 12);
465
+ // Checksum placeholder (8 spaces)
466
+ for (let i = 148; i < 156; i++) header[i] = 32;
467
+ header[156] = 48; // '0' regular file
468
+ writeField('ustar\0', 257, 6);
469
+ writeField('00', 263, 2);
470
+
471
+ let chksum = 0;
472
+ for (let i = 0; i < 512; i++) chksum += header[i];
473
+ writeField(chksum.toString(8).padStart(6, '0') + '\0 ', 148, 8);
474
+
475
+ chunks.push(header);
476
+ chunks.push(data);
477
+ const remainder = data.byteLength % 512;
478
+ if (remainder !== 0) {
479
+ chunks.push(new Uint8Array(512 - remainder));
480
+ }
481
+ }
482
+
483
+ // Two 512-byte zero blocks mark end-of-archive
484
+ chunks.push(new Uint8Array(1024));
485
+
486
+ const totalLen = chunks.reduce((acc, c) => acc + c.byteLength, 0);
487
+ const out = new Uint8Array(totalLen);
488
+ let pos = 0;
489
+ for (const c of chunks) {
490
+ out.set(c, pos);
491
+ pos += c.byteLength;
492
+ }
493
+ return out;
494
+ }
495
+
496
+ /**
497
+ * Seeds built-in C++ headers (`<bits/stdc++.h>`, `<codelab/dsa.hpp>`, `<codelab/test.hpp>`)
498
+ * and any user-provided extra headers into a VirtualFS instance.
499
+ */
500
+ export function seedCppHeadersIntoVfs(vfs: any, extraHeaders?: Record<string, string>) {
501
+ if (!vfs) return;
502
+ const allHeaders: Record<string, string> = {
503
+ ...BUILTIN_CPP_HEADERS,
504
+ ...(extraHeaders || {})
505
+ };
506
+ for (const [hPath, content] of Object.entries(allHeaders)) {
507
+ const absPath = hPath.startsWith('/') ? hPath : `/usr/include/${hPath}`;
508
+ const dir = absPath.slice(0, absPath.lastIndexOf('/')) || '/';
509
+ if (!vfs.existsSync(dir)) {
510
+ vfs.mkdirSync(dir, { recursive: true });
511
+ }
512
+ vfs.writeFileSync(absPath, content);
513
+ }
514
+ if (!vfs.existsSync('/tmp')) {
515
+ vfs.mkdirSync('/tmp', { recursive: true });
516
+ }
517
+ if (!vfs.existsSync('/usr/lib/wasm32-wasi')) {
518
+ vfs.mkdirSync('/usr/lib/wasm32-wasi', { recursive: true });
519
+ }
520
+ }
521
+
522
+ export interface CppCompileRequest {
523
+ entry?: string;
524
+ sourceFiles?: string[];
525
+ outputPath?: string;
526
+ std?: 'c++17' | 'c++20' | 'c++23';
527
+ optLevel?: '-O0' | '-O1' | '-O2' | '-O3';
528
+ extraFlags?: string[];
529
+ vfs: any;
530
+ onStdout?: (text: string) => void;
531
+ onStderr?: (text: string) => void;
532
+ }
533
+
534
+ export interface CppCompileResult {
535
+ ok: boolean;
536
+ exitCode: number;
537
+ wasmBinary: Uint8Array | null;
538
+ outputPath: string;
539
+ stdout: string;
540
+ stderr: string;
541
+ }
542
+
543
+ export const DEFAULT_CPP_CDN_BASE_URL = 'https://cdn.jsdelivr.net/npm/@yowasp/clang';
544
+ export type CppCompileOptions = CppCompileRequest;
545
+ export type CppCompilerAdapter = CppToolchainManager;
546
+
547
+ export interface ExtendedCppExtensionOptions extends Partial<CppExtensionOptions> {
548
+ /**
549
+ * Pre-loaded `clang.wasm` binary (optional; bypasses network download).
550
+ */
551
+ clangWasm?: Uint8Array;
552
+ /**
553
+ * Pre-loaded `lld.wasm` binary (optional; bypasses network download).
554
+ */
555
+ lldWasm?: Uint8Array;
556
+ /**
557
+ * Pre-loaded `sysroot.tar` archive (optional; bypasses network download).
558
+ */
559
+ sysrootTar?: Uint8Array;
560
+ /**
561
+ * Optional custom compilation hook `(req: CppCompileRequest) => Promise<CppCompileResult>`.
562
+ */
563
+ compilerHook?: (req: CppCompileRequest) => Promise<CppCompileResult>;
564
+ /**
565
+ * Immediately switch the active workbench language to 'cpp'.
566
+ */
567
+ activate?: boolean;
568
+ }
569
+
570
+ /**
571
+ * Manages downloading, IndexedDB caching (`codelab_cpp_toolchain_v1`), sysroot extraction,
572
+ * and 2-stage WASI Clang + LLD compilation (`clang.wasm` -> `lld.wasm` -> `.wasm` binary).
573
+ */
574
+ export class CppToolchainManager {
575
+ options: CppExtensionOptions & ExtendedCppExtensionOptions;
576
+ clangWasm: Uint8Array | null = null;
577
+ lldWasm: Uint8Array | null = null;
578
+ sysrootTar: Uint8Array | null = null;
579
+ private _loadingPromise: Promise<void> | null = null;
580
+
581
+ constructor(options: ExtendedCppExtensionOptions = {}) {
582
+ const parsed = CppExtensionOptionsSchema.parse(options);
583
+ this.options = { ...parsed, ...options };
584
+ if (options.clangWasm) this.clangWasm = options.clangWasm;
585
+ if (options.lldWasm) this.lldWasm = options.lldWasm;
586
+ if (options.sysrootTar) this.sysrootTar = options.sysrootTar;
587
+ }
588
+
589
+ private _emitProgress(progress: CppToolchainProgress) {
590
+ if (typeof this.options.onProgress === 'function') {
591
+ this.options.onProgress(progress);
592
+ }
593
+ }
594
+
595
+ private async _fetchAssetWithProgress(
596
+ url: string,
597
+ cacheKey: string,
598
+ label: string
599
+ ): Promise<Uint8Array> {
600
+ if (this.options.cacheInIndexedDB !== false) {
601
+ const cached = await getCachedAsset(cacheKey);
602
+ if (cached) {
603
+ this._emitProgress({
604
+ stage: 'caching',
605
+ loadedBytes: cached.byteLength,
606
+ totalBytes: cached.byteLength,
607
+ percent: 100,
608
+ message: `Loaded ${label} from IndexedDB cache`
609
+ });
610
+ return cached;
611
+ }
612
+ }
613
+
614
+ if (typeof fetch !== 'function') {
615
+ throw new Error(`Cannot download ${label}: global fetch is unavailable.`);
616
+ }
617
+
618
+ const res = await fetch(url);
619
+ if (!res.ok) {
620
+ throw new Error(`Failed to download ${label} from ${url} (HTTP ${res.status})`);
621
+ }
622
+
623
+ const totalBytes = Number(res.headers.get('content-length') || 0) || 12 * 1024 * 1024;
624
+ let data: Uint8Array;
625
+
626
+ if (res.body && typeof res.body.getReader === 'function') {
627
+ const reader = res.body.getReader();
628
+ const chunks: Uint8Array[] = [];
629
+ let loadedBytes = 0;
630
+
631
+ while (true) {
632
+ const { done, value } = await reader.read();
633
+ if (done) break;
634
+ if (value) {
635
+ chunks.push(value);
636
+ loadedBytes += value.byteLength;
637
+ const percent = Math.min(99, Math.round((loadedBytes / Math.max(totalBytes, loadedBytes)) * 100));
638
+ this._emitProgress({
639
+ stage: 'downloading',
640
+ loadedBytes,
641
+ totalBytes: Math.max(totalBytes, loadedBytes),
642
+ percent,
643
+ message: `Downloading ${label} (${(loadedBytes / (1024 * 1024)).toFixed(1)} MB)...`
644
+ });
645
+ }
646
+ }
647
+
648
+ data = new Uint8Array(loadedBytes);
649
+ let offset = 0;
650
+ for (const chunk of chunks) {
651
+ data.set(chunk, offset);
652
+ offset += chunk.byteLength;
653
+ }
654
+ } else {
655
+ const buf = await res.arrayBuffer();
656
+ data = new Uint8Array(buf);
657
+ }
658
+
659
+ if (this.options.cacheInIndexedDB !== false) {
660
+ await setCachedAsset(cacheKey, data);
661
+ }
662
+
663
+ return data;
664
+ }
665
+
666
+ async ensureLoaded(): Promise<void> {
667
+ if (this.clangWasm && this.lldWasm && this.sysrootTar) {
668
+ return;
669
+ }
670
+ if (this._loadingPromise) {
671
+ return this._loadingPromise;
672
+ }
673
+
674
+ this._loadingPromise = (async () => {
675
+ try {
676
+ const base = (this.options.toolchainUrl || 'https://cdn.jsdelivr.net/npm/@yowasp/clang').replace(/\/+$/, '');
677
+ const clangUrl = this.options.clangUrl || `${base}/clang.wasm`;
678
+ const lldUrl = this.options.lldUrl || `${base}/lld.wasm`;
679
+ const sysrootUrl = this.options.sysrootUrl || `${base}/sysroot.tar`;
680
+
681
+ if (!this.sysrootTar) {
682
+ this.sysrootTar = await this._fetchAssetWithProgress(
683
+ sysrootUrl,
684
+ `sysroot:${sysrootUrl}`,
685
+ 'WASI C++20 Sysroot (libc + libc++)'
686
+ );
687
+ }
688
+ if (!this.clangWasm) {
689
+ this.clangWasm = await this._fetchAssetWithProgress(
690
+ clangUrl,
691
+ `clang:${clangUrl}`,
692
+ 'Clang C++20 WebAssembly Compiler (clang.wasm)'
693
+ );
694
+ }
695
+ if (!this.lldWasm) {
696
+ this.lldWasm = await this._fetchAssetWithProgress(
697
+ lldUrl,
698
+ `lld:${lldUrl}`,
699
+ 'LLD WebAssembly Linker (lld.wasm)'
700
+ );
701
+ }
702
+
703
+ this._emitProgress({
704
+ stage: 'ready',
705
+ loadedBytes:
706
+ (this.clangWasm?.byteLength || 0) +
707
+ (this.lldWasm?.byteLength || 0) +
708
+ (this.sysrootTar?.byteLength || 0),
709
+ totalBytes:
710
+ (this.clangWasm?.byteLength || 0) +
711
+ (this.lldWasm?.byteLength || 0) +
712
+ (this.sysrootTar?.byteLength || 0),
713
+ percent: 100,
714
+ message: 'C++20 WebAssembly Toolchain Ready'
715
+ });
716
+ } finally {
717
+ this._loadingPromise = null;
718
+ }
719
+ })();
720
+
721
+ return this._loadingPromise;
722
+ }
723
+
724
+ prepareVfs(vfs: any): void {
725
+ if (!vfs) return;
726
+ if (this.sysrootTar && !vfs.existsSync('/usr/include/.sysroot_extracted')) {
727
+ extractTarToVfs(this.sysrootTar, vfs, '/');
728
+ if (!vfs.existsSync('/usr/include')) {
729
+ vfs.mkdirSync('/usr/include', { recursive: true });
730
+ }
731
+ vfs.writeFileSync('/usr/include/.sysroot_extracted', '1');
732
+ }
733
+ seedCppHeadersIntoVfs(vfs, this.options.extraHeaders);
734
+ }
735
+
736
+ async compile(req: CppCompileRequest): Promise<CppCompileResult> {
737
+ const vfs = req.vfs;
738
+ const outputPath = req.outputPath || '/workspace/a.out';
739
+ const std = req.std || this.options.std || 'c++20';
740
+ const optLevel = req.optLevel || this.options.optLevel || '-O2';
741
+
742
+ const rawSources =
743
+ req.sourceFiles && req.sourceFiles.length > 0
744
+ ? req.sourceFiles
745
+ : req.entry
746
+ ? [req.entry]
747
+ : ['/workspace/src/main.cpp'];
748
+
749
+ const sourceFiles = rawSources.map((s) => (s.startsWith('/') ? s : `/workspace/${s.replace(/^\/+/, '')}`));
750
+
751
+ for (const src of sourceFiles) {
752
+ if (!vfs.existsSync(src)) {
753
+ const msg = `clang++: error: no such file or directory: '${src}'\n`;
754
+ if (req.onStderr) req.onStderr(msg);
755
+ return { ok: false, exitCode: 1, wasmBinary: null, outputPath, stdout: '', stderr: msg };
756
+ }
757
+ }
758
+
759
+ seedCppHeadersIntoVfs(vfs, this.options.extraHeaders);
760
+
761
+ if (typeof this.options.compilerHook === 'function') {
762
+ return this.options.compilerHook({
763
+ ...req,
764
+ sourceFiles,
765
+ outputPath,
766
+ std,
767
+ optLevel
768
+ });
769
+ }
770
+
771
+ await this.ensureLoaded();
772
+ this.prepareVfs(vfs);
773
+
774
+ const runtime =
775
+ (typeof globalThis !== 'undefined' && (globalThis as any).CodeLabRuntime) ||
776
+ (typeof window !== 'undefined' && (window as any).CodeLabRuntime);
777
+
778
+ if (!runtime || typeof runtime.executeWasiModule !== 'function') {
779
+ throw new Error('CodeLabRuntime.executeWasiModule is unavailable.');
780
+ }
781
+
782
+ let stdoutAcc = '';
783
+ let stderrAcc = '';
784
+ const handleOut = (t: string) => {
785
+ stdoutAcc += t;
786
+ if (req.onStdout) req.onStdout(t);
787
+ };
788
+ const handleErr = (t: string) => {
789
+ stderrAcc += t;
790
+ if (req.onStderr) req.onStderr(t);
791
+ };
792
+
793
+ this._emitProgress({
794
+ stage: 'compiling',
795
+ loadedBytes: 100,
796
+ totalBytes: 100,
797
+ percent: 100,
798
+ message: `Compiling ${sourceFiles.map((s) => s.split('/').pop()).join(', ')} with Clang (${std}, ${optLevel})...`
799
+ });
800
+
801
+ const objectFiles: string[] = [];
802
+ for (let i = 0; i < sourceFiles.length; i++) {
803
+ const srcPath = sourceFiles[i];
804
+ const objPath = `/tmp/obj_${i}.o`;
805
+ objectFiles.push(objPath);
806
+
807
+ const clangArgs = [
808
+ 'clang++',
809
+ '-cc1',
810
+ '-triple',
811
+ 'wasm32-unknown-wasi',
812
+ '-emit-obj',
813
+ `-std=${std}`,
814
+ optLevel,
815
+ '-isysroot',
816
+ '/usr',
817
+ '-internal-isystem',
818
+ '/usr/include/c++/v1',
819
+ '-internal-isystem',
820
+ '/usr/include',
821
+ '-I',
822
+ '/usr/include',
823
+ '-I',
824
+ '/workspace',
825
+ '-I',
826
+ '/workspace/src',
827
+ ...(req.extraFlags || []),
828
+ '-o',
829
+ objPath,
830
+ srcPath
831
+ ];
832
+
833
+ const compileStep = await runtime.executeWasiModule(this.clangWasm, {
834
+ vfs,
835
+ args: clangArgs,
836
+ env: { PATH: '/usr/bin:/bin', TMPDIR: '/tmp' },
837
+ onStdout: handleOut,
838
+ onStderr: handleErr
839
+ });
840
+
841
+ if (compileStep.exitCode !== 0) {
842
+ return {
843
+ ok: false,
844
+ exitCode: compileStep.exitCode,
845
+ wasmBinary: null,
846
+ outputPath,
847
+ stdout: stdoutAcc,
848
+ stderr: stderrAcc
849
+ };
850
+ }
851
+ }
852
+
853
+ this._emitProgress({
854
+ stage: 'linking',
855
+ loadedBytes: 100,
856
+ totalBytes: 100,
857
+ percent: 100,
858
+ message: `Linking ${outputPath.split('/').pop()} with wasm-ld...`
859
+ });
860
+
861
+ const crt1Path = '/usr/lib/wasm32-wasi/crt1.o';
862
+ const hasCrt1 = vfs.existsSync(crt1Path);
863
+ const lldArgs = [
864
+ 'wasm-ld',
865
+ '--no-threads',
866
+ '--export-dynamic',
867
+ '-L/usr/lib/wasm32-wasi',
868
+ ...(hasCrt1 ? [crt1Path] : []),
869
+ ...objectFiles,
870
+ '-lc++',
871
+ '-lc++abi',
872
+ '-lc',
873
+ '-o',
874
+ outputPath
875
+ ];
876
+
877
+ const linkStep = await runtime.executeWasiModule(this.lldWasm, {
878
+ vfs,
879
+ args: lldArgs,
880
+ env: { PATH: '/usr/bin:/bin', TMPDIR: '/tmp' },
881
+ onStdout: handleOut,
882
+ onStderr: handleErr
883
+ });
884
+
885
+ if (linkStep.exitCode !== 0 || !vfs.existsSync(outputPath)) {
886
+ return {
887
+ ok: false,
888
+ exitCode: linkStep.exitCode || 1,
889
+ wasmBinary: null,
890
+ outputPath,
891
+ stdout: stdoutAcc,
892
+ stderr: stderrAcc || 'wasm-ld: error: failed to produce output binary\n'
893
+ };
894
+ }
895
+
896
+ const wasmBuf = vfs.readFileSync(outputPath);
897
+ const wasmBinary =
898
+ wasmBuf instanceof Uint8Array ? new Uint8Array(wasmBuf.buffer, wasmBuf.byteOffset, wasmBuf.byteLength) : new Uint8Array(wasmBuf);
899
+
900
+ this._emitProgress({
901
+ stage: 'ready',
902
+ loadedBytes: 100,
903
+ totalBytes: 100,
904
+ percent: 100,
905
+ message: 'C++20 WebAssembly Toolchain Ready'
906
+ });
907
+
908
+ return {
909
+ ok: true,
910
+ exitCode: 0,
911
+ wasmBinary,
912
+ outputPath,
913
+ stdout: stdoutAcc,
914
+ stderr: stderrAcc
915
+ };
916
+ }
917
+ }
918
+
919
+ /**
920
+ * Parses POSIX shell arguments for `g++` / `clang++` / `c++` commands.
921
+ */
922
+ export function parseCppCompilerFlags(args: string[], cwd = '/workspace') {
923
+ const sourceFiles: string[] = [];
924
+ const extraFlags: string[] = [];
925
+ let outputPath = `${cwd.replace(/\/+$/, '')}/a.out`;
926
+ let std: 'c++17' | 'c++20' | 'c++23' | undefined;
927
+ let optLevel: '-O0' | '-O1' | '-O2' | '-O3' | undefined;
928
+ let showVersion = false;
929
+ let showHelp = false;
930
+
931
+ for (let i = 0; i < args.length; i++) {
932
+ const arg = args[i];
933
+ if (arg === '--version' || arg === '-v') {
934
+ showVersion = true;
935
+ } else if (arg === '--help' || arg === '-h') {
936
+ showHelp = true;
937
+ } else if (arg === '-o' && i + 1 < args.length) {
938
+ const next = args[++i];
939
+ outputPath = next.startsWith('/') ? next : `${cwd.replace(/\/+$/, '')}/${next.replace(/^\.\//, '')}`;
940
+ } else if (arg.startsWith('-o') && arg.length > 2) {
941
+ const next = arg.slice(2);
942
+ outputPath = next.startsWith('/') ? next : `${cwd.replace(/\/+$/, '')}/${next.replace(/^\.\//, '')}`;
943
+ } else if (arg.startsWith('-std=')) {
944
+ const val = arg.slice(5);
945
+ if (val === 'c++17' || val === 'c++20' || val === 'c++23') {
946
+ std = val;
947
+ } else if (val === 'c++2a' || val === 'gnu++20') {
948
+ std = 'c++20';
949
+ } else if (val === 'c++2b' || val === 'gnu++23') {
950
+ std = 'c++23';
951
+ } else if (val === 'gnu++17') {
952
+ std = 'c++17';
953
+ }
954
+ } else if (arg === '-O0' || arg === '-O1' || arg === '-O2' || arg === '-O3') {
955
+ optLevel = arg;
956
+ } else if (arg.startsWith('-I') || arg.startsWith('-D') || arg.startsWith('-W')) {
957
+ extraFlags.push(arg);
958
+ } else if (!arg.startsWith('-')) {
959
+ const resolved = arg.startsWith('/') ? arg : `${cwd.replace(/\/+$/, '')}/${arg.replace(/^\.\//, '')}`;
960
+ sourceFiles.push(resolved);
961
+ }
962
+ }
963
+
964
+ return { sourceFiles, outputPath, std, optLevel, extraFlags, showVersion, showHelp };
965
+ }
966
+
967
+ /**
968
+ * Registers the C++20 WebAssembly compiler toolchain on the global runtime and workbench.
969
+ */
970
+ export function registerCppCompilerOnRuntime(toolchain: CppToolchainManager) {
971
+ const compilerFn = async (req: any) => {
972
+ const res = await toolchain.compile({
973
+ entry: req.entry,
974
+ sourceFiles: req.sourceFiles,
975
+ outputPath: req.outputPath || '/workspace/a.out',
976
+ std: req.std,
977
+ optLevel: req.optLevel,
978
+ extraFlags: req.extraFlags,
979
+ vfs: req.vfs,
980
+ onStdout: req.onStdout,
981
+ onStderr: req.onStderr
982
+ });
983
+ return {
984
+ ok: res.ok,
985
+ exitCode: res.exitCode,
986
+ wasmBinary: res.wasmBinary,
987
+ outputPath: res.outputPath
988
+ };
989
+ };
990
+
991
+ if (typeof globalThis !== 'undefined') {
992
+ (globalThis as any).__codelabCppCompiler = compilerFn;
993
+ (globalThis as any).__codelabCppToolchain = toolchain;
994
+ }
995
+ if (typeof window !== 'undefined') {
996
+ (window as any).__codelabCppCompiler = compilerFn;
997
+ (window as any).__codelabCppToolchain = toolchain;
998
+ }
999
+ return compilerFn;
1000
+ }
1001
+
1002
+ /**
1003
+ * Real C++20 in WebAssembly Extension for CodeLab (`@innovatorved/code-lab/extensions/cpp`).
1004
+ *
1005
+ * Enables:
1006
+ * - Real Clang/LLVM + LLD + WASI C++20 compilation in WebAssembly (~35 MB downloaded on demand & cached in IndexedDB)
1007
+ * - `<bits/stdc++.h>`, `<codelab/dsa.hpp>`, and `<codelab/test.hpp>` headers in VirtualFS
1008
+ * - `JS | TS | C++` language switcher in the CodeLab workbench
1009
+ * - `g++`, `clang++`, `c++`, and `./a.out` binary execution in the POSIX shell
1010
+ * - Guided Lab `cppStarterFiles`, `cppSolutionFiles`, and `cppFiles` curriculum support
1011
+ */
1012
+ export function cppExtension(workbench: any, options: ExtendedCppExtensionOptions = {}) {
1013
+ const toolchain = new CppToolchainManager(options);
1014
+ const compilerFn = registerCppCompilerOnRuntime(toolchain);
1015
+
1016
+ if (!workbench) return toolchain;
1017
+
1018
+ workbench.cppToolchain = toolchain;
1019
+ workbench.cppCompiler = compilerFn;
1020
+ workbench.cppOptions = toolchain.options;
1021
+
1022
+ if (!workbench.enabledLanguages || !(workbench.enabledLanguages instanceof Set)) {
1023
+ workbench.enabledLanguages = new Set(['js', 'cpp']);
1024
+ } else {
1025
+ workbench.enabledLanguages.add('cpp');
1026
+ }
1027
+
1028
+ if (options.files && typeof options.files === 'object') {
1029
+ workbench.cppFiles = { ...(workbench.cppFiles || {}), ...options.files };
1030
+ if (workbench.guidedConfig) {
1031
+ workbench.guidedConfig.cppFiles = { ...(workbench.guidedConfig.cppFiles || {}), ...options.files };
1032
+ }
1033
+ }
1034
+ if (options.starterFiles && typeof options.starterFiles === 'object') {
1035
+ if (!workbench.guidedConfig) workbench.guidedConfig = {};
1036
+ workbench.guidedConfig.cppStarterFiles = {
1037
+ ...(workbench.guidedConfig.cppStarterFiles || {}),
1038
+ ...options.starterFiles
1039
+ };
1040
+ }
1041
+ if (options.solutionFiles && typeof options.solutionFiles === 'object') {
1042
+ if (!workbench.guidedConfig) workbench.guidedConfig = {};
1043
+ workbench.guidedConfig.cppSolutionFiles = {
1044
+ ...(workbench.guidedConfig.cppSolutionFiles || {}),
1045
+ ...options.solutionFiles
1046
+ };
1047
+ }
1048
+
1049
+ if (workbench.vfs) {
1050
+ seedCppHeadersIntoVfs(workbench.vfs, toolchain.options.extraHeaders);
1051
+ }
1052
+
1053
+ workbench.hasMultipleLanguages = workbench.enabledLanguages.size > 1;
1054
+
1055
+ if (options.preload) {
1056
+ toolchain.ensureLoaded().catch((err) => {
1057
+ if (typeof workbench._appendTerminalOutput === 'function') {
1058
+ workbench._appendTerminalOutput('stderr', `[C++ Toolchain preload warning]: ${err.message || err}\n`);
1059
+ }
1060
+ });
1061
+ }
1062
+
1063
+ if (options.activate && typeof workbench.setLanguage === 'function') {
1064
+ workbench.setLanguage('cpp');
1065
+ } else if (typeof workbench._renderShell === 'function' && workbench.container) {
1066
+ workbench._renderShell();
1067
+ if (typeof workbench._bindEvents === 'function') workbench._bindEvents();
1068
+ if (typeof workbench._renderFileLists === 'function') workbench._renderFileLists();
1069
+ }
1070
+
1071
+ return workbench;
1072
+ }
1073
+
1074
+ export function createCppExtension(options: ExtendedCppExtensionOptions = {}) {
1075
+ const plugin = (workbench: any) => cppExtension(workbench, options);
1076
+ plugin.extensionName = 'cpp';
1077
+ plugin.languageId = 'cpp' as const;
1078
+ return plugin;
1079
+ }
1080
+
1081
+ export default cppExtension;