@innovatorved/code-lab 0.3.1 → 0.3.2

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 (48) hide show
  1. package/ARCHITECTURE.md +4 -2
  2. package/CHANGELOG.md +25 -0
  3. package/README.md +15 -5
  4. package/dist/code-lab.css +52 -2
  5. package/dist/code-lab.d.ts +1 -1
  6. package/dist/code-lab.esm.js +1247 -377
  7. package/dist/code-lab.js +1246 -376
  8. package/dist/diagnostics.d.ts +5 -0
  9. package/dist/extensions/cpp.esm.js +51 -9
  10. package/dist/extensions/cpp.js +51 -9
  11. package/dist/extensions/python.esm.js +116 -103
  12. package/dist/extensions/python.js +116 -103
  13. package/dist/index.d.ts +1 -1
  14. package/dist/preview-sw.js +34 -17
  15. package/dist/runtime.esm.js +38 -31
  16. package/dist/runtime.js +38 -31
  17. package/dist/schemas.d.ts +1 -1
  18. package/dist/scm.d.ts +13 -2
  19. package/dist/search.d.ts +5 -1
  20. package/dist/shell.esm.js +72 -16
  21. package/dist/shell.js +72 -16
  22. package/dist/terminal.esm.js +183 -54
  23. package/dist/terminal.js +183 -54
  24. package/dist/workbench/index.d.ts +1 -1
  25. package/dist/workbench/styles.d.ts +1 -1
  26. package/dist/zip.d.ts +4 -3
  27. package/package.json +1 -1
  28. package/src/code-lab.css +52 -2
  29. package/src/csp.ts +7 -10
  30. package/src/diagnostics.ts +42 -3
  31. package/src/extensions/cpp.ts +47 -9
  32. package/src/extensions/python.ts +128 -116
  33. package/src/index.ts +1 -1
  34. package/src/preview-sw.js +25 -5
  35. package/src/runtime.ts +36 -29
  36. package/src/schemas.ts +1 -1
  37. package/src/scm.ts +106 -19
  38. package/src/search.ts +71 -27
  39. package/src/shell.ts +70 -14
  40. package/src/terminal.ts +181 -52
  41. package/src/workbench/diff-editor.ts +41 -13
  42. package/src/workbench/drawer.ts +17 -4
  43. package/src/workbench/guided-pane.ts +12 -2
  44. package/src/workbench/share.ts +37 -8
  45. package/src/workbench/styles.ts +2 -1
  46. package/src/workbench/toolbar.ts +15 -4
  47. package/src/workbench.ts +482 -79
  48. package/src/zip.ts +29 -7
package/dist/code-lab.js CHANGED
@@ -1,11 +1,11 @@
1
1
  /**
2
2
  * ============================================================
3
- * @innovatorved/code-lab v0.3.1 — Standalone Browser Code IDE & Virtual Runtime
3
+ * @innovatorved/code-lab v0.3.2 — Standalone Browser Code IDE & Virtual Runtime
4
4
  * ============================================================
5
5
  * Features:
6
6
  * - Sandboxed Web Worker Execution Engine with Multi-Instance Isolation & Watchdog Timer
7
7
  * - First-Class Node.js and Bun Runtimes (Bun.serve, bun:test, bun:sqlite, Bun.*)
8
- * - Full POSIX Shell AST & 55+ UNIX Coreutils (pipes, redirects, globs, env vars, git & git clone)
8
+ * - Full POSIX Shell AST & 71 UNIX Coreutils (pipes, redirects, globs, env vars, git & git clone)
9
9
  * - Interactive PTY Terminal Emulator with inline prompt, Tab completion & ANSI colors
10
10
  * - Persistent HTTP/TCP Servers, CLI curl & Live Port/HTTP Preview
11
11
  * - Modular VS Code Workbench: File Tree, Tabs, Command Palette, Diff Viewer
@@ -163,7 +163,12 @@ var CodeLabCsp = (() => {
163
163
  directive("worker-src", [self, "blob:"].concat(sourcesFor(mode, allow, "workerSrc"))),
164
164
  directive("frame-src", withData("frameSrc")),
165
165
  directive("form-action", [self]),
166
- directive("frame-ancestors", [options.frameAncestors || "'self'"])
166
+ directive("frame-ancestors", (() => {
167
+ const rawFa = typeof options.frameAncestors === "string" ? options.frameAncestors.trim() : "";
168
+ if (!rawFa) return ["'self'"];
169
+ const tokens = cleanSources(rawFa.split(/\s+/));
170
+ return tokens.length > 0 ? tokens : ["'self'"];
171
+ })())
167
172
  ].join("; ");
168
173
  }
169
174
  function describePreviewNetwork(config) {
@@ -201,15 +206,6 @@ var CodeLabCsp = (() => {
201
206
  };
202
207
  }
203
208
  function shim(name) {
204
- var blocked = false;
205
- try {
206
- var existing = window[name];
207
- if (existing) { existing.getItem('__codelab_probe__'); return; }
208
- } catch (err) {
209
- // Expected on an opaque origin: the accessor itself throws.
210
- blocked = Boolean(err);
211
- }
212
- void blocked;
213
209
  try {
214
210
  Object.defineProperty(window, name, { configurable: true, value: memoryStorage() });
215
211
  } catch (err) {
@@ -369,6 +365,7 @@ var CodeLabCsp = (() => {
369
365
  }
370
366
 
371
367
  window.addEventListener('message', function (event) {
368
+ if (event && event.source && event.source !== window.parent) return;
372
369
  var data = event && event.data;
373
370
  if (!data || typeof data !== 'object') return;
374
371
  if (data.type === 'codelab:preview-fetch-res' && data.reqId) {
@@ -772,6 +769,13 @@ var CodeLabZip = (() => {
772
769
  }
773
770
  return (crc ^ 4294967295) >>> 0;
774
771
  }
772
+ var DANGEROUS_PATH_SEGMENTS = /* @__PURE__ */ new Set([
773
+ "__proto__",
774
+ "constructor",
775
+ "prototype"
776
+ ]);
777
+ var MAX_ZIP_ENTRIES = 1e4;
778
+ var MAX_ZIP_UNCOMPRESSED_BYTES = 100 * 1024 * 1024;
775
779
  function sanitizeZipPath(rawPath) {
776
780
  const normalized = String(rawPath || "").replace(/\\/g, "/").replace(/^[A-Za-z]:/, "");
777
781
  const parts = normalized.split("/");
@@ -779,6 +783,9 @@ var CodeLabZip = (() => {
779
783
  for (const part of parts) {
780
784
  const trimmed = part.trim();
781
785
  if (!trimmed || trimmed === ".") continue;
786
+ if (DANGEROUS_PATH_SEGMENTS.has(trimmed)) {
787
+ return "";
788
+ }
782
789
  if (trimmed === "..") {
783
790
  if (safeParts.length > 0) {
784
791
  safeParts.pop();
@@ -805,7 +812,7 @@ var CodeLabZip = (() => {
805
812
  function readUInt32LE(buf, offset) {
806
813
  return (buf[offset] | buf[offset + 1] << 8 | buf[offset + 2] << 16 | buf[offset + 3] << 24) >>> 0;
807
814
  }
808
- async function createZip(files) {
815
+ function createZip(files) {
809
816
  const entries = [];
810
817
  let localSectionSize = 0;
811
818
  let centralDirSize = 0;
@@ -880,7 +887,7 @@ var CodeLabZip = (() => {
880
887
  writeUInt16LE(out, cursor + 20, 0);
881
888
  return out;
882
889
  }
883
- async function extractZip(data) {
890
+ function extractZip(data) {
884
891
  const bytes = toUint8Array(data);
885
892
  if (bytes.length < 22) {
886
893
  throw new Error("Invalid or truncated ZIP archive: buffer shorter than minimum 22-byte EOCD record");
@@ -897,13 +904,17 @@ var CodeLabZip = (() => {
897
904
  throw new Error("Invalid ZIP archive: End of Central Directory (PK\\x05\\x06) signature not found");
898
905
  }
899
906
  const totalEntries = readUInt16LE(bytes, eocdOffset + 10);
907
+ if (totalEntries > MAX_ZIP_ENTRIES) {
908
+ throw new Error(`ZIP archive exceeds maximum allowed entry count (${MAX_ZIP_ENTRIES})`);
909
+ }
900
910
  const centralDirSize = readUInt32LE(bytes, eocdOffset + 12);
901
911
  const centralDirOffset = readUInt32LE(bytes, eocdOffset + 16);
902
912
  if (centralDirOffset + centralDirSize > bytes.length) {
903
913
  throw new Error("Corrupted ZIP archive: Central Directory extends past end of buffer");
904
914
  }
905
- const result = {};
915
+ const result = /* @__PURE__ */ Object.create(null);
906
916
  let cdCursor = centralDirOffset;
917
+ let totalExtractedBytes = 0;
907
918
  for (let i = 0; i < totalEntries; i++) {
908
919
  if (cdCursor + 46 > bytes.length) {
909
920
  throw new Error("Corrupted ZIP archive: truncated Central Directory header");
@@ -943,6 +954,10 @@ var CodeLabZip = (() => {
943
954
  if (dataEnd > bytes.length) {
944
955
  throw new Error(`Corrupted ZIP archive: file data truncated for ${safeName}`);
945
956
  }
957
+ totalExtractedBytes += compressedSize;
958
+ if (totalExtractedBytes > MAX_ZIP_UNCOMPRESSED_BYTES) {
959
+ throw new Error(`ZIP archive exceeds maximum uncompressed size limit (${MAX_ZIP_UNCOMPRESSED_BYTES} bytes)`);
960
+ }
946
961
  const rawFileBytes = bytes.subarray(dataStart, dataEnd);
947
962
  if (compressionMethod !== 0) {
948
963
  throw new Error(`Unsupported ZIP compression method ${compressionMethod} for ${safeName} (only Store=0 is supported)`);
@@ -955,7 +970,7 @@ var CodeLabZip = (() => {
955
970
  }
956
971
  result[safeName] = textDecoder.decode(rawFileBytes);
957
972
  }
958
- return result;
973
+ return { ...result };
959
974
  }
960
975
  var zip_default = {
961
976
  createZip,
@@ -1333,8 +1348,14 @@ var CodeLabSearch = (() => {
1333
1348
  }
1334
1349
  function matchesGlob(filePath, pattern) {
1335
1350
  if (!pattern || pattern === "*" || pattern === "**") return true;
1351
+ if (pattern.includes(",")) {
1352
+ const subPatterns = pattern.split(",").map((s) => s.trim()).filter(Boolean);
1353
+ if (subPatterns.length > 1) {
1354
+ return subPatterns.some((sub) => matchesGlob(filePath, sub));
1355
+ }
1356
+ }
1336
1357
  const normPath = normalizeSearchPath(filePath);
1337
- const normPattern = normalizeSearchPath(pattern);
1358
+ const normPattern = normalizeSearchPath(pattern.trim());
1338
1359
  if (normPattern === normPath) return true;
1339
1360
  if (!normPattern.includes("*") && !normPattern.includes("?")) {
1340
1361
  return normPath.includes(normPattern) || normPath.endsWith(normPattern);
@@ -1345,10 +1366,12 @@ var CodeLabSearch = (() => {
1345
1366
  const c = normPattern[i];
1346
1367
  if (c === "*") {
1347
1368
  if (normPattern[i + 1] === "*") {
1348
- regexStr += ".*";
1349
1369
  i += 2;
1350
1370
  if (normPattern[i] === "/") {
1371
+ regexStr += "(?:.*/)?";
1351
1372
  i++;
1373
+ } else {
1374
+ regexStr += ".*";
1352
1375
  }
1353
1376
  continue;
1354
1377
  } else {
@@ -1372,7 +1395,12 @@ var CodeLabSearch = (() => {
1372
1395
  regexStr += "$";
1373
1396
  try {
1374
1397
  const re = new RegExp(regexStr);
1375
- return re.test(normPath);
1398
+ if (re.test(normPath)) return true;
1399
+ if (!normPattern.includes("/")) {
1400
+ const baseName = normPath.split("/").pop() || normPath;
1401
+ if (re.test(baseName)) return true;
1402
+ }
1403
+ return false;
1376
1404
  } catch (err) {
1377
1405
  return normPath.includes(normPattern.replace(/[*?]/g, ""));
1378
1406
  }
@@ -1485,7 +1513,7 @@ var CodeLabSearch = (() => {
1485
1513
  }
1486
1514
  function replaceInFiles(files, arg2, arg3, arg4) {
1487
1515
  let query = "";
1488
- const replacement = typeof arg3 === "string" ? arg3 : "";
1516
+ let replacement = typeof arg3 === "string" ? arg3 : "";
1489
1517
  let opts = {};
1490
1518
  let targetFiles = void 0;
1491
1519
  if (typeof arg2 === "string") {
@@ -1499,6 +1527,9 @@ var CodeLabSearch = (() => {
1499
1527
  } else if (arg2 && typeof arg2 === "object") {
1500
1528
  opts = arg2;
1501
1529
  query = opts.query || "";
1530
+ if (typeof arg3 !== "string" && typeof opts.replacement === "string") {
1531
+ replacement = opts.replacement;
1532
+ }
1502
1533
  if (Array.isArray(arg4)) {
1503
1534
  targetFiles = arg4;
1504
1535
  } else {
@@ -1506,10 +1537,13 @@ var CodeLabSearch = (() => {
1506
1537
  }
1507
1538
  }
1508
1539
  if (!query) {
1540
+ const copy = { ...files };
1509
1541
  return {
1510
- updatedFiles: { ...files },
1542
+ updatedFiles: copy,
1543
+ files: copy,
1511
1544
  replacedCount: 0,
1512
- filesAffected: []
1545
+ filesAffected: [],
1546
+ filesModified: 0
1513
1547
  };
1514
1548
  }
1515
1549
  const isCaseSensitive = Boolean(opts.caseSensitive);
@@ -1525,10 +1559,13 @@ var CodeLabSearch = (() => {
1525
1559
  try {
1526
1560
  regex = new RegExp(patternStr, isCaseSensitive ? "g" : "gi");
1527
1561
  } catch (err) {
1562
+ const copy = { ...files };
1528
1563
  return {
1529
- updatedFiles: { ...files },
1564
+ updatedFiles: copy,
1565
+ files: copy,
1530
1566
  replacedCount: 0,
1531
- filesAffected: []
1567
+ filesAffected: [],
1568
+ filesModified: 0
1532
1569
  };
1533
1570
  }
1534
1571
  const updatedFiles = { ...files };
@@ -1538,35 +1575,47 @@ var CodeLabSearch = (() => {
1538
1575
  if (targetFiles && !targetFiles.includes(filePath)) continue;
1539
1576
  if (includeFilter && !checkFilter(filePath, includeFilter)) continue;
1540
1577
  if (excludeFilter && checkFilter(filePath, excludeFilter)) continue;
1541
- regex.lastIndex = 0;
1578
+ const lines = content.split("\n");
1542
1579
  let countInFile = 0;
1543
- let m;
1544
- while ((m = regex.exec(content)) !== null) {
1545
- countInFile++;
1546
- if (m[0].length === 0) {
1547
- regex.lastIndex++;
1548
- if (regex.lastIndex > content.length) {
1549
- break;
1580
+ const newLines = [];
1581
+ for (let lineIdx = 0; lineIdx < lines.length; lineIdx++) {
1582
+ const lineText = lines[lineIdx];
1583
+ regex.lastIndex = 0;
1584
+ let lineMatches = 0;
1585
+ let m;
1586
+ while ((m = regex.exec(lineText)) !== null) {
1587
+ lineMatches++;
1588
+ if (m[0].length === 0) {
1589
+ regex.lastIndex++;
1590
+ if (regex.lastIndex > lineText.length) {
1591
+ break;
1592
+ }
1550
1593
  }
1551
1594
  }
1552
- }
1553
- if (countInFile > 0) {
1554
- regex.lastIndex = 0;
1555
- let newContent;
1556
- if (isRegex) {
1557
- newContent = content.replace(regex, replacement);
1595
+ if (lineMatches > 0) {
1596
+ countInFile += lineMatches;
1597
+ regex.lastIndex = 0;
1598
+ if (isRegex) {
1599
+ newLines.push(lineText.replace(regex, replacement));
1600
+ } else {
1601
+ newLines.push(lineText.replace(regex, () => replacement));
1602
+ }
1558
1603
  } else {
1559
- newContent = content.replace(regex, () => replacement);
1604
+ newLines.push(lineText);
1560
1605
  }
1561
- updatedFiles[filePath] = newContent;
1606
+ }
1607
+ if (countInFile > 0) {
1608
+ updatedFiles[filePath] = newLines.join("\n");
1562
1609
  filesAffected.push(filePath);
1563
1610
  replacedCount += countInFile;
1564
1611
  }
1565
1612
  }
1566
1613
  return {
1567
1614
  updatedFiles,
1615
+ files: updatedFiles,
1568
1616
  replacedCount,
1569
- filesAffected
1617
+ filesAffected,
1618
+ filesModified: filesAffected.length
1570
1619
  };
1571
1620
  }
1572
1621
  return __toCommonJS(search_exports);
@@ -1601,9 +1650,11 @@ var CodeLabDiagnostics = (() => {
1601
1650
  var DiagnosticsStore = class {
1602
1651
  items = /* @__PURE__ */ new Map();
1603
1652
  listeners = /* @__PURE__ */ new Set();
1604
- add(item) {
1605
- if (!item || typeof item.id !== "string" || !item.id) return;
1606
- const normalized = {
1653
+ batchDepth = 0;
1654
+ batchDirty = false;
1655
+ normalizeItem(item) {
1656
+ if (!item || typeof item.id !== "string" || !item.id) return null;
1657
+ return {
1607
1658
  ...item,
1608
1659
  file: String(item.file || ""),
1609
1660
  line: typeof item.line === "number" && item.line > 0 ? Math.floor(item.line) : 1,
@@ -1611,9 +1662,39 @@ var CodeLabDiagnostics = (() => {
1611
1662
  message: String(item.message || ""),
1612
1663
  severity: item.severity || "error"
1613
1664
  };
1665
+ }
1666
+ add(item) {
1667
+ const normalized = this.normalizeItem(item);
1668
+ if (!normalized) return;
1614
1669
  this.items.set(normalized.id, normalized);
1615
1670
  this.notify();
1616
1671
  }
1672
+ setMany(items, clearSource) {
1673
+ this.batch(() => {
1674
+ if (clearSource !== void 0) {
1675
+ this.clear(clearSource);
1676
+ }
1677
+ for (const item of items) {
1678
+ const normalized = this.normalizeItem(item);
1679
+ if (normalized) {
1680
+ this.items.set(normalized.id, normalized);
1681
+ this.batchDirty = true;
1682
+ }
1683
+ }
1684
+ });
1685
+ }
1686
+ batch(fn) {
1687
+ this.batchDepth++;
1688
+ try {
1689
+ fn();
1690
+ } finally {
1691
+ this.batchDepth--;
1692
+ if (this.batchDepth === 0 && this.batchDirty) {
1693
+ this.batchDirty = false;
1694
+ this.notify();
1695
+ }
1696
+ }
1697
+ }
1617
1698
  remove(id) {
1618
1699
  if (this.items.delete(id)) {
1619
1700
  this.notify();
@@ -1655,6 +1736,10 @@ var CodeLabDiagnostics = (() => {
1655
1736
  };
1656
1737
  }
1657
1738
  notify() {
1739
+ if (this.batchDepth > 0) {
1740
+ this.batchDirty = true;
1741
+ return;
1742
+ }
1658
1743
  if (this.listeners.size === 0) return;
1659
1744
  const snapshot = this.getAll();
1660
1745
  for (const listener of this.listeners) {
@@ -1738,10 +1823,28 @@ var CodeLabScm = (() => {
1738
1823
  ]
1739
1824
  };
1740
1825
  }
1741
- function computeGitStatus(vfsFiles, _repoRoot = "/workspace", gitState) {
1742
- const state = gitState || createGitState({});
1743
- const headFiles = state.headFiles || {};
1744
- const currentStaged = state.staged instanceof Map ? state.staged : /* @__PURE__ */ new Map();
1826
+ function computeGitStatus(arg1, arg2 = "/workspace", gitState) {
1827
+ let vfsFiles;
1828
+ let state;
1829
+ if (arg1 && typeof arg1 === "object" && ("headFiles" in arg1 || "headSnapshot" in arg1 || "staged" in arg1 || "commits" in arg1)) {
1830
+ state = arg1;
1831
+ vfsFiles = arg2 && typeof arg2 === "object" ? arg2 : {};
1832
+ } else {
1833
+ vfsFiles = arg1 && typeof arg1 === "object" ? arg1 : {};
1834
+ state = gitState || createGitState({});
1835
+ }
1836
+ const headFiles = state.headFiles || state.headSnapshot || {};
1837
+ const currentStaged = /* @__PURE__ */ new Map();
1838
+ if (state.staged instanceof Map) {
1839
+ for (const [k, v] of state.staged.entries()) {
1840
+ currentStaged.set(k, v);
1841
+ }
1842
+ } else if (state.staged instanceof Set) {
1843
+ for (const k of state.staged.values()) {
1844
+ const existsInVfs = Object.prototype.hasOwnProperty.call(vfsFiles, k);
1845
+ currentStaged.set(k, existsInVfs ? vfsFiles[k] : null);
1846
+ }
1847
+ }
1745
1848
  const untracked = [];
1746
1849
  const modified = [];
1747
1850
  const deleted = [];
@@ -1749,12 +1852,14 @@ var CodeLabScm = (() => {
1749
1852
  for (const [filePath, stagedContent] of currentStaged.entries()) {
1750
1853
  const inHead = Object.prototype.hasOwnProperty.call(headFiles, filePath);
1751
1854
  if (stagedContent === null) {
1752
- staged.push({
1753
- path: filePath,
1754
- status: "deleted",
1755
- staged: true,
1756
- oldContent: headFiles[filePath]
1757
- });
1855
+ if (inHead) {
1856
+ staged.push({
1857
+ path: filePath,
1858
+ status: "deleted",
1859
+ staged: true,
1860
+ oldContent: headFiles[filePath]
1861
+ });
1862
+ }
1758
1863
  } else {
1759
1864
  staged.push({
1760
1865
  path: filePath,
@@ -1807,6 +1912,36 @@ var CodeLabScm = (() => {
1807
1912
  }
1808
1913
  }
1809
1914
  const unstaged = [...modified, ...deleted];
1915
+ const entries = [
1916
+ ...staged.map((s) => ({
1917
+ path: s.path,
1918
+ status: s.status,
1919
+ staged: true,
1920
+ index: s.status === "added" ? "A" : s.status === "deleted" ? "D" : "M",
1921
+ worktree: " "
1922
+ })),
1923
+ ...modified.map((m) => ({
1924
+ path: m.path,
1925
+ status: m.status,
1926
+ staged: false,
1927
+ index: " ",
1928
+ worktree: "M"
1929
+ })),
1930
+ ...deleted.map((d) => ({
1931
+ path: d.path,
1932
+ status: d.status,
1933
+ staged: false,
1934
+ index: " ",
1935
+ worktree: "D"
1936
+ })),
1937
+ ...untracked.map((u) => ({
1938
+ path: u.path,
1939
+ status: u.status,
1940
+ staged: false,
1941
+ index: "?",
1942
+ worktree: "?"
1943
+ }))
1944
+ ];
1810
1945
  const isClean = untracked.length === 0 && modified.length === 0 && deleted.length === 0 && staged.length === 0;
1811
1946
  return {
1812
1947
  branch: state.branch || "main",
@@ -1816,6 +1951,7 @@ var CodeLabScm = (() => {
1816
1951
  deleted,
1817
1952
  staged,
1818
1953
  unstaged,
1954
+ entries,
1819
1955
  hasChanges: !isClean,
1820
1956
  isClean
1821
1957
  };
@@ -1825,11 +1961,20 @@ var CodeLabScm = (() => {
1825
1961
  if (!(gitState.staged instanceof Map)) {
1826
1962
  gitState.staged = /* @__PURE__ */ new Map();
1827
1963
  }
1828
- gitState.staged.set(relativePath, currentContent === void 0 ? null : currentContent);
1964
+ const normalizedContent = currentContent === void 0 ? null : currentContent;
1965
+ const headFiles = gitState.headFiles || gitState.headSnapshot || {};
1966
+ if (normalizedContent === null && !Object.prototype.hasOwnProperty.call(headFiles, relativePath) && !gitState.staged.has(relativePath)) {
1967
+ return;
1968
+ }
1969
+ gitState.staged.set(relativePath, normalizedContent);
1829
1970
  }
1830
1971
  function unstageFile(gitState, relativePath) {
1831
- if (!gitState || !(gitState.staged instanceof Map)) return;
1832
- gitState.staged.delete(relativePath);
1972
+ if (!gitState) return;
1973
+ if (gitState.staged instanceof Map) {
1974
+ gitState.staged.delete(relativePath);
1975
+ } else if (gitState.staged instanceof Set) {
1976
+ gitState.staged.delete(relativePath);
1977
+ }
1833
1978
  }
1834
1979
  function commitChanges(gitState, message) {
1835
1980
  const trimmed = typeof message === "string" ? message.trim() : "";
@@ -1839,8 +1984,10 @@ var CodeLabScm = (() => {
1839
1984
  if (!gitState || !(gitState.staged instanceof Map) || gitState.staged.size === 0) {
1840
1985
  throw new Error("Nothing to commit (staging area is empty)");
1841
1986
  }
1842
- const newHeadFiles = { ...gitState.headFiles || {} };
1987
+ const newHeadFiles = { ...gitState.headFiles || gitState.headSnapshot || {} };
1988
+ const diffSummaryParts = [];
1843
1989
  for (const [filePath, content] of gitState.staged.entries()) {
1990
+ diffSummaryParts.push(`${filePath}:${content === null ? "<DEL>" : content}`);
1844
1991
  if (content === null) {
1845
1992
  delete newHeadFiles[filePath];
1846
1993
  } else {
@@ -1848,19 +1995,22 @@ var CodeLabScm = (() => {
1848
1995
  }
1849
1996
  }
1850
1997
  const timestamp = Date.now();
1851
- const hash = computeShortCommitHash(`${gitState.headCommit}:${trimmed}:${timestamp}`);
1998
+ const commitSeq = Array.isArray(gitState.commits) ? gitState.commits.length : 0;
1999
+ const hash = computeShortCommitHash(
2000
+ `${gitState.headCommit}:${trimmed}:${timestamp}:${commitSeq}:${diffSummaryParts.join("|")}`
2001
+ );
1852
2002
  const commit = {
1853
2003
  hash,
1854
2004
  message: trimmed,
1855
2005
  timestamp,
1856
- files: newHeadFiles
2006
+ files: { ...newHeadFiles }
1857
2007
  };
1858
2008
  if (!Array.isArray(gitState.commits)) {
1859
2009
  gitState.commits = [];
1860
2010
  }
1861
2011
  gitState.commits.push(commit);
1862
2012
  gitState.headCommit = hash;
1863
- gitState.headFiles = newHeadFiles;
2013
+ gitState.headFiles = { ...newHeadFiles };
1864
2014
  gitState.staged.clear();
1865
2015
  return hash;
1866
2016
  }
@@ -2004,7 +2154,8 @@ var CodeLabWorkbenchComponents = (() => {
2004
2154
  padding: 4px 0;
2005
2155
  display: none;
2006
2156
  }
2007
- .codelab-split-menu.open {
2157
+ .codelab-split-menu.open,
2158
+ .codelab-split-menu.active {
2008
2159
  display: block;
2009
2160
  }
2010
2161
  .codelab-split-menu__item {
@@ -2174,6 +2325,9 @@ var CodeLabWorkbenchComponents = (() => {
2174
2325
  renderLanguageSwitcherHtml: () => renderLanguageSwitcherHtml,
2175
2326
  renderToolbarHtml: () => renderToolbarHtml
2176
2327
  });
2328
+ function escapeHtml(str) {
2329
+ return String(str ?? "").replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;").replace(/"/g, "&quot;").replace(/'/g, "&#39;");
2330
+ }
2177
2331
  function renderLanguageSwitcherHtml(workbench) {
2178
2332
  const enabled = workbench.enabledLanguages || /* @__PURE__ */ new Set(["js"]);
2179
2333
  const showTs = enabled.has("ts");
@@ -2195,7 +2349,9 @@ var CodeLabWorkbenchComponents = (() => {
2195
2349
  function renderToolbarHtml(opts) {
2196
2350
  const { workbench, title, backLabel, hasGuidedLab, mode, activeFile, hasWebContent, activeServerCount } = opts;
2197
2351
  const isGuided = Boolean(hasGuidedLab && mode === "guided");
2198
- const brandLabel = title || "code-lab";
2352
+ const brandLabel = escapeHtml(title || "code-lab");
2353
+ const safeBackLabel = escapeHtml(backLabel);
2354
+ const safeActiveFile = escapeHtml(activeFile || "active");
2199
2355
  const testFileExists = Boolean(
2200
2356
  workbench._findEntryFile && workbench._findEntryFile("test") !== null
2201
2357
  );
@@ -2203,9 +2359,9 @@ var CodeLabWorkbenchComponents = (() => {
2203
2359
  <div class="codelab-topbar codelab-toolbar">
2204
2360
  <div class="codelab-topbar__left">
2205
2361
  ${workbench.onClose ? `
2206
- <button type="button" class="codelab-btn codelab-btn--back" data-cl-action="close-lab" title="${backLabel}">
2362
+ <button type="button" class="codelab-btn codelab-btn--back" data-cl-action="close-lab" title="${safeBackLabel}">
2207
2363
  ${CL_ICONS.arrowLeft}
2208
- <span>${backLabel}</span>
2364
+ <span>${safeBackLabel}</span>
2209
2365
  </button>
2210
2366
  ` : ""}
2211
2367
  <span class="codelab-brand ${workbench.onClose ? "codelab-brand--with-back" : ""}" title="${brandLabel}">
@@ -2269,7 +2425,7 @@ var CodeLabWorkbenchComponents = (() => {
2269
2425
  <span>\u25B6 Run Entry / Demo</span> <kbd style="opacity:0.6">\u2318\u21B5</kbd>
2270
2426
  </button>
2271
2427
  <button type="button" class="codelab-split-menu__item" data-cl-action="run-active-file">
2272
- <span>\u25B6 Run Active File (${activeFile || "active"})</span> <kbd style="opacity:0.6">\u21E7\u2318\u21B5</kbd>
2428
+ <span>\u25B6 Run Active File (${safeActiveFile})</span> <kbd style="opacity:0.6">\u21E7\u2318\u21B5</kbd>
2273
2429
  </button>
2274
2430
  ${testFileExists ? `
2275
2431
  <button type="button" class="codelab-split-menu__item" data-cl-action="run-tests">
@@ -2329,6 +2485,9 @@ var CodeLabWorkbenchComponents = (() => {
2329
2485
  renderProblemsPanelHtml: () => renderProblemsPanelHtml,
2330
2486
  renderStdinPanelHtml: () => renderStdinPanelHtml
2331
2487
  });
2488
+ function escapeHtml2(str) {
2489
+ return String(str ?? "").replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;").replace(/"/g, "&quot;").replace(/'/g, "&#39;");
2490
+ }
2332
2491
  function formatTelemetryHud(durationMs, memoryBytes, lang) {
2333
2492
  if (durationMs === null && memoryBytes === null) return "";
2334
2493
  const timeStr = durationMs !== null ? durationMs < 1e3 ? `${durationMs.toFixed(1)} ms` : `${(durationMs / 1e3).toFixed(2)} s` : "";
@@ -2421,11 +2580,15 @@ var CodeLabWorkbenchComponents = (() => {
2421
2580
  ${items.map((item) => {
2422
2581
  const icon = item.severity === "error" ? "\u2717" : item.severity === "warning" ? "\u26A0" : "\u2139";
2423
2582
  const cls = item.severity === "error" ? "codelab-problem-item--error" : item.severity === "warning" ? "codelab-problem-item--warning" : "codelab-problem-item--info";
2583
+ const safeFile = escapeHtml2(item.file);
2584
+ const safeMsg = escapeHtml2(item.message);
2585
+ const safeLine = Number(item.line) || 1;
2586
+ const safeCol = Number(item.col) || 1;
2424
2587
  return `
2425
- <div class="codelab-problem-item ${cls}" data-cl-problem-file="${item.file}" data-cl-problem-line="${item.line}" data-cl-problem-col="${item.col || 1}">
2588
+ <div class="codelab-problem-item ${cls}" data-cl-problem-file="${safeFile}" data-cl-problem-line="${safeLine}" data-cl-problem-col="${safeCol}">
2426
2589
  <span style="font-weight:bold;">${icon}</span>
2427
- <span>${item.message}</span>
2428
- <span class="codelab-problem-item__location">${item.file}:${item.line}:${item.col || 1}</span>
2590
+ <span>${safeMsg}</span>
2591
+ <span class="codelab-problem-item__location">${safeFile}:${safeLine}:${safeCol}</span>
2429
2592
  </div>
2430
2593
  `;
2431
2594
  }).join("")}
@@ -2433,7 +2596,7 @@ var CodeLabWorkbenchComponents = (() => {
2433
2596
  `;
2434
2597
  }
2435
2598
  function renderStdinPanelHtml(workbench) {
2436
- const val = workbench.customStdin || "";
2599
+ const val = escapeHtml2(workbench.customStdin || "");
2437
2600
  return `
2438
2601
  <div class="codelab-stdin-panel">
2439
2602
  <div class="codelab-stdin-panel__header">
@@ -2451,6 +2614,9 @@ var CodeLabWorkbenchComponents = (() => {
2451
2614
  CodeLabDiffEditorManager: () => CodeLabDiffEditorManager,
2452
2615
  computeSimpleDiff: () => computeSimpleDiff
2453
2616
  });
2617
+ function escapeHtml3(str) {
2618
+ return String(str ?? "").replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;").replace(/"/g, "&quot;").replace(/'/g, "&#39;");
2619
+ }
2454
2620
  function computeSimpleDiff(oldText, newText) {
2455
2621
  const oldLines = String(oldText || "").split("\n");
2456
2622
  const newLines = String(newText || "").split("\n");
@@ -2536,11 +2702,24 @@ var CodeLabWorkbenchComponents = (() => {
2536
2702
  diffContainer.style.display = "flex";
2537
2703
  if (editorHost) editorHost.style.display = "none";
2538
2704
  if (fallbackTextarea) fallbackTextarea.style.display = "none";
2705
+ if (this.diffEditor) {
2706
+ this.diffEditor.dispose();
2707
+ this.diffEditor = null;
2708
+ }
2709
+ if (this.originalModel) {
2710
+ this.originalModel.dispose();
2711
+ this.originalModel = null;
2712
+ }
2713
+ if (this.modifiedModel) {
2714
+ this.modifiedModel.dispose();
2715
+ this.modifiedModel = null;
2716
+ }
2717
+ const safeFile = escapeHtml3(file);
2539
2718
  diffContainer.innerHTML = `
2540
2719
  <div class="codelab-diff-toolbar">
2541
2720
  <span style="font-weight:600;display:inline-flex;align-items:center;gap:6px;">
2542
2721
  ${CL_ICONS.diff}
2543
- <span>Diff: <code>${file}</code> (${isStarter ? "Current vs Starter" : "Current vs Solution"})</span>
2722
+ <span>Diff: <code>${safeFile}</code> (${isStarter ? "Current vs Starter" : "Current vs Solution"})</span>
2544
2723
  </span>
2545
2724
  <div class="codelab-segmented" style="margin-left:16px;">
2546
2725
  <button type="button" class="codelab-segmented__btn ${target === "starter" ? "active" : ""}" id="cl-diff-toggle-starter">Starter</button>
@@ -2555,16 +2734,14 @@ var CodeLabWorkbenchComponents = (() => {
2555
2734
  <div class="codelab-diff-host" id="cl-diff-editor-slot"></div>
2556
2735
  `;
2557
2736
  const slot = diffContainer.querySelector("#cl-diff-editor-slot");
2558
- if (!this.diffEditor) {
2559
- this.diffEditor = monaco.editor.createDiffEditor(slot, {
2560
- readOnly: false,
2561
- originalEditable: false,
2562
- theme: this.workbench.theme === "light" ? "vs" : "vs-dark",
2563
- renderSideBySide: true,
2564
- automaticLayout: true,
2565
- minimap: { enabled: false }
2566
- });
2567
- }
2737
+ this.diffEditor = monaco.editor.createDiffEditor(slot, {
2738
+ readOnly: false,
2739
+ originalEditable: false,
2740
+ theme: this.workbench.theme === "light" ? "vs" : "vs-dark",
2741
+ renderSideBySide: true,
2742
+ automaticLayout: true,
2743
+ minimap: { enabled: false }
2744
+ });
2568
2745
  const lang = file.endsWith(".ts") ? "typescript" : file.endsWith(".cpp") ? "cpp" : file.endsWith(".py") ? "python" : "javascript";
2569
2746
  this.originalModel = monaco.editor.createModel(refCode, lang);
2570
2747
  this.modifiedModel = monaco.editor.createModel(currentCode, lang);
@@ -2586,13 +2763,20 @@ var CodeLabWorkbenchComponents = (() => {
2586
2763
  this.openInlineDiff(file, "solution");
2587
2764
  });
2588
2765
  diffContainer.querySelector("#cl-diff-revert-btn")?.addEventListener("click", () => {
2589
- const starterCode = this.workbench.starterFiles && this.workbench.starterFiles[file] || "";
2766
+ const starterMap = this.workbench.starterFiles || (typeof this.workbench._getBaseFilesForModeAndLang === "function" ? this.workbench._getBaseFilesForModeAndLang("guided", this.workbench.lang) : {});
2767
+ const starterCode = starterMap && starterMap[file] || "";
2590
2768
  this.workbench.files[file] = starterCode;
2591
2769
  this.closeInlineDiff();
2592
2770
  this.workbench.openFile(file);
2593
2771
  });
2594
2772
  diffContainer.querySelector("#cl-diff-apply-btn")?.addEventListener("click", () => {
2595
- const solutionCode = this.workbench.solutionFiles && this.workbench.solutionFiles[file] || "";
2773
+ if (typeof this.workbench.applyReferenceSolution === "function") {
2774
+ this.closeInlineDiff();
2775
+ this.workbench.applyReferenceSolution();
2776
+ return;
2777
+ }
2778
+ const solutionMap = this.workbench.solutionFiles || (typeof this.workbench._getBaseFilesForModeAndLang === "function" ? this.workbench._getBaseFilesForModeAndLang("sandbox", this.workbench.lang) : {});
2779
+ const solutionCode = solutionMap && solutionMap[file] || "";
2596
2780
  this.workbench.files[file] = solutionCode;
2597
2781
  this.closeInlineDiff();
2598
2782
  this.workbench.openFile(file);
@@ -2807,21 +2991,53 @@ var CodeLabWorkbenchComponents = (() => {
2807
2991
  }
2808
2992
  return bufferToBase64Url(rawBytes);
2809
2993
  }
2994
+ var MAX_DECOMPRESSED_SNAPSHOT_BYTES = 5 * 1024 * 1024;
2810
2995
  async function decompressWorkspaceSnapshot(encoded) {
2811
2996
  if (!encoded || typeof encoded !== "string") return null;
2812
2997
  try {
2813
2998
  const bytes = base64UrlToBuffer(encoded);
2999
+ if (bytes.byteLength > MAX_DECOMPRESSED_SNAPSHOT_BYTES) {
3000
+ throw new Error("Snapshot payload exceeds maximum allowed size");
3001
+ }
2814
3002
  if (typeof DecompressionStream !== "undefined") {
2815
3003
  try {
2816
3004
  const ds = new DecompressionStream("deflate-raw");
2817
3005
  const writer = ds.writable.getWriter();
2818
- writer.write(bytes);
2819
- writer.close();
2820
- const response = new Response(ds.readable);
2821
- const decompressed = await response.arrayBuffer();
3006
+ const writeInput = new Uint8Array(bytes.byteLength);
3007
+ writeInput.set(bytes);
3008
+ writer.write(writeInput).catch(() => {
3009
+ });
3010
+ writer.close().catch(() => {
3011
+ });
3012
+ const reader = ds.readable.getReader();
3013
+ const chunks = [];
3014
+ let totalLength = 0;
3015
+ while (true) {
3016
+ const step = await reader.read();
3017
+ if (step.done) break;
3018
+ const chunk = step.value;
3019
+ if (chunk) {
3020
+ totalLength += chunk.byteLength;
3021
+ if (totalLength > MAX_DECOMPRESSED_SNAPSHOT_BYTES) {
3022
+ await reader.cancel().catch(() => {
3023
+ });
3024
+ throw new Error("Decompressed snapshot exceeds 5 MB safety limit");
3025
+ }
3026
+ chunks.push(chunk);
3027
+ }
3028
+ }
3029
+ const decompressed = new Uint8Array(totalLength);
3030
+ let offset = 0;
3031
+ for (const chunk of chunks) {
3032
+ decompressed.set(chunk, offset);
3033
+ offset += chunk.byteLength;
3034
+ }
2822
3035
  const text = new TextDecoder().decode(decompressed);
2823
3036
  return JSON.parse(text);
2824
3037
  } catch (err) {
3038
+ if (err instanceof Error && err.message.includes("safety limit")) {
3039
+ throw err;
3040
+ }
2825
3041
  const rawText2 = new TextDecoder().decode(bytes);
2826
3042
  return JSON.parse(rawText2);
2827
3043
  }
@@ -2915,6 +3131,9 @@ var CodeLabWorkbenchComponents = (() => {
2915
3131
  __export(guided_pane_exports, {
2916
3132
  renderStepPillsHtml: () => renderStepPillsHtml
2917
3133
  });
3134
+ function escapeHtml4(str) {
3135
+ return String(str ?? "").replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;").replace(/"/g, "&quot;").replace(/'/g, "&#39;");
3136
+ }
2918
3137
  function renderStepPillsHtml(steps, activeIndex, completedStepIds) {
2919
3138
  if (!steps || steps.length === 0) return "";
2920
3139
  return `
@@ -2923,10 +3142,11 @@ var CodeLabWorkbenchComponents = (() => {
2923
3142
  const isPassed = completedStepIds.has(step.id);
2924
3143
  const isActive = idx === activeIndex;
2925
3144
  const cls = `codelab-step-pill ${isActive ? "active" : ""} ${isPassed ? "passed" : ""}`;
3145
+ const safeTitle = escapeHtml4(step.title);
2926
3146
  return `
2927
- <button type="button" role="tab" aria-selected="${isActive}" class="${cls}" data-cl-step="${idx}" title="Step ${idx + 1}: ${step.title}">
3147
+ <button type="button" role="tab" aria-selected="${isActive}" class="${cls}" data-cl-step="${idx}" title="Step ${idx + 1}: ${safeTitle}">
2928
3148
  <span class="codelab-step-pill__num">${isPassed ? CL_ICONS.check : idx + 1}</span>
2929
- <span class="codelab-step-pill__label">${step.title}</span>
3149
+ <span class="codelab-step-pill__label">${safeTitle}</span>
2930
3150
  </button>
2931
3151
  `;
2932
3152
  }).join("")}
@@ -3976,22 +4196,40 @@ function __initVirtualRuntime(rootScope) {
3976
4196
  // =========================================================================
3977
4197
  // 5. VIRTUAL IN-MEMORY POSIX FILESYSTEM (node:fs)
3978
4198
  // =========================================================================
3979
- function createVirtualFs(initialFiles = {}) {
4199
+ function createVirtualFs(initialFiles = {}, vfsOptions = {}) {
3980
4200
  const dirs = new Set(['/', '/tmp', '/workspace', '/home', '/home/user']);
3981
4201
  const files = new Map(); // normalizedPath -> { data: Uint8Array, mtimeMs, ctimeMs, ino }
3982
4202
  const deletedInspectorCache = new Map(); // normalizedPath -> { data: Uint8Array, mtimeMs, deletedAtMs }
4203
+ const MAX_DELETED_CACHE_ENTRIES = 50;
4204
+ const MAX_DELETED_CACHE_FILE_BYTES = 65536;
4205
+ const customCwdGetter = typeof vfsOptions === 'function'
4206
+ ? vfsOptions
4207
+ : (vfsOptions && typeof vfsOptions.cwdGetter === 'function' ? vfsOptions.cwdGetter : null);
3983
4208
  const fdTable = new Map(); // fd -> { inode, path, flags, pos, isDirectory }
3984
4209
  let nextFd = 10;
3985
4210
  let nextIno = 100;
3986
4211
  let mkdtempCounter = 1;
3987
4212
 
4213
+ function recordDeletedForInspector(p, data, mtimeMs) {
4214
+ if (!data || data.byteLength <= 0 || data.byteLength > MAX_DELETED_CACHE_FILE_BYTES) return;
4215
+ if (deletedInspectorCache.has(p)) {
4216
+ deletedInspectorCache.delete(p);
4217
+ } else if (deletedInspectorCache.size >= MAX_DELETED_CACHE_ENTRIES) {
4218
+ const oldestKey = deletedInspectorCache.keys().next().value;
4219
+ if (oldestKey !== undefined) deletedInspectorCache.delete(oldestKey);
4220
+ }
4221
+ deletedInspectorCache.set(p, { data: data.slice(), mtimeMs, deletedAtMs: Date.now() });
4222
+ }
4223
+
3988
4224
  function normPath(p) {
3989
4225
  if (typeof p !== 'string' || !p) {
3990
4226
  const err = new TypeError('path must be a non-empty string');
3991
4227
  err.code = 'ERR_INVALID_ARG_TYPE';
3992
4228
  throw err;
3993
4229
  }
3994
- const baseCwd = typeof _activeCwdGetter === 'function' ? _activeCwdGetter() : '/workspace';
4230
+ const baseCwd = typeof customCwdGetter === 'function'
4231
+ ? customCwdGetter()
4232
+ : (typeof _activeCwdGetter === 'function' ? _activeCwdGetter() : '/workspace');
3995
4233
  const abs = p.startsWith('/') ? VirtualPath.normalize(p) : VirtualPath.resolve(baseCwd, p);
3996
4234
  return abs.length > 1 && abs.endsWith('/') ? abs.slice(0, -1) : abs;
3997
4235
  }
@@ -4042,9 +4280,13 @@ function __initVirtualRuntime(rootScope) {
4042
4280
  for (const [relPath, content] of Object.entries(initialFiles)) {
4043
4281
  const cleanRel = relPath.startsWith('/') ? relPath.slice(1) : relPath;
4044
4282
  const isSystemPath = /^\/(workspace|usr|tmp|lib|include|etc|bin|dev)(\/|$)/.test(relPath);
4045
- const fullPath = isSystemPath
4283
+ let fullPath = isSystemPath
4046
4284
  ? normPath(relPath)
4047
4285
  : normPath(`/workspace/${cleanRel}`);
4286
+ if (!isSystemPath && fullPath !== '/workspace' && !fullPath.startsWith('/workspace/')) {
4287
+ const safeSub = cleanRel.split('/').filter((seg) => seg && seg !== '.' && seg !== '..').join('/');
4288
+ fullPath = normPath(`/workspace/${safeSub || 'file'}`);
4289
+ }
4048
4290
  ensureParentDirs(fullPath);
4049
4291
  const bytes = typeof content === 'string' ? utf8Encode(content) : new Uint8Array(content);
4050
4292
  files.set(fullPath, {
@@ -4224,13 +4466,6 @@ function __initVirtualRuntime(rootScope) {
4224
4466
  fsyncSync(fd) {
4225
4467
  const entry = fdTable.get(fd);
4226
4468
  if (!entry) throw fsError('EBADF', 'fsync', String(fd), 'bad file descriptor');
4227
- if (!entry.isDirectory && entry.inode) {
4228
- deletedInspectorCache.set(entry.path, {
4229
- data: entry.inode.data.slice(),
4230
- mtimeMs: entry.inode.mtimeMs,
4231
- deletedAtMs: null
4232
- });
4233
- }
4234
4469
  },
4235
4470
 
4236
4471
  fdatasyncSync(fd) {
@@ -4271,12 +4506,6 @@ function __initVirtualRuntime(rootScope) {
4271
4506
  inode.mtimeMs = Date.now();
4272
4507
  entry.pos = writePos + chunk.byteLength;
4273
4508
 
4274
- deletedInspectorCache.set(entry.path, {
4275
- data: inode.data.slice(),
4276
- mtimeMs: inode.mtimeMs,
4277
- deletedAtMs: null
4278
- });
4279
-
4280
4509
  return chunk.byteLength;
4281
4510
  },
4282
4511
 
@@ -4328,7 +4557,7 @@ function __initVirtualRuntime(rootScope) {
4328
4557
  inode.mode = 0o100000 | (Number(opts.mode) & 0o777);
4329
4558
  }
4330
4559
  }
4331
- deletedInspectorCache.set(np, { data: bytes.slice(), mtimeMs: inode.mtimeMs, deletedAtMs: null });
4560
+ deletedInspectorCache.delete(np);
4332
4561
  },
4333
4562
 
4334
4563
  chmodSync(p, mode) {
@@ -4357,7 +4586,7 @@ function __initVirtualRuntime(rootScope) {
4357
4586
  combined.set(chunk, inode.data.byteLength);
4358
4587
  inode.data = combined;
4359
4588
  inode.mtimeMs = Date.now();
4360
- deletedInspectorCache.set(np, { data: combined.slice(), mtimeMs: inode.mtimeMs, deletedAtMs: null });
4589
+ deletedInspectorCache.delete(np);
4361
4590
  },
4362
4591
 
4363
4592
  truncateSync(p, len = 0) {
@@ -4373,7 +4602,6 @@ function __initVirtualRuntime(rootScope) {
4373
4602
  inode.data = grown;
4374
4603
  }
4375
4604
  inode.mtimeMs = Date.now();
4376
- deletedInspectorCache.set(np, { data: inode.data.slice(), mtimeMs: inode.mtimeMs, deletedAtMs: null });
4377
4605
  },
4378
4606
 
4379
4607
  renameSync(oldP, newP) {
@@ -4434,16 +4662,14 @@ function __initVirtualRuntime(rootScope) {
4434
4662
  if (fdEntry.path === src) fdEntry.path = dst;
4435
4663
  }
4436
4664
  deletedInspectorCache.delete(src);
4437
- deletedInspectorCache.set(dst, { data: inode.data.slice(), mtimeMs: inode.mtimeMs, deletedAtMs: null });
4665
+ deletedInspectorCache.delete(dst);
4438
4666
  },
4439
4667
 
4440
4668
  unlinkSync(p) {
4441
4669
  const np = normPath(p);
4442
4670
  const inode = files.get(np);
4443
4671
  if (!inode) throw fsError('ENOENT', 'unlink', p, 'no such file or directory');
4444
- if (inode.data.byteLength > 0) {
4445
- deletedInspectorCache.set(np, { data: inode.data.slice(), mtimeMs: inode.mtimeMs, deletedAtMs: Date.now() });
4446
- }
4672
+ recordDeletedForInspector(np, inode.data, inode.mtimeMs);
4447
4673
  files.delete(np);
4448
4674
  },
4449
4675
 
@@ -4460,9 +4686,7 @@ function __initVirtualRuntime(rootScope) {
4460
4686
  for (const [fPath, inode] of Array.from(files.entries())) {
4461
4687
  if (fPath.startsWith(prefix)) {
4462
4688
  if (!recursive) throw fsError('ENOTEMPTY', 'rm', p, 'directory not empty');
4463
- if (inode.data.byteLength > 0) {
4464
- deletedInspectorCache.set(fPath, { data: inode.data.slice(), mtimeMs: inode.mtimeMs, deletedAtMs: Date.now() });
4465
- }
4689
+ recordDeletedForInspector(fPath, inode.data, inode.mtimeMs);
4466
4690
  files.delete(fPath);
4467
4691
  }
4468
4692
  }
@@ -6036,6 +6260,7 @@ function __initVirtualRuntime(rootScope) {
6036
6260
  responseHeaders: {},
6037
6261
  _t0: performance.now()
6038
6262
  };
6263
+ if (httpTrace.length >= 500) httpTrace.shift();
6039
6264
  httpTrace.push(traceEntry);
6040
6265
  this._traceEntry = traceEntry;
6041
6266
 
@@ -7027,6 +7252,7 @@ function __initVirtualRuntime(rootScope) {
7027
7252
  this._peer = serverSocket;
7028
7253
  this.connecting = false;
7029
7254
 
7255
+ if (sharedTrace.length >= 500) sharedTrace.shift();
7030
7256
  sharedTrace.push({
7031
7257
  protocol: 'TCP',
7032
7258
  event: 'connect',
@@ -9319,7 +9545,10 @@ function __initVirtualRuntime(rootScope) {
9319
9545
  const activePortTable = optPortTable || portTable || _defaultPortTable;
9320
9546
  resourceTracker.pid = pid;
9321
9547
 
9322
- const vfs = optVfs || createVirtualFs(files);
9548
+ let currentCwd = '/workspace';
9549
+ _activeCwdGetter = () => currentCwd;
9550
+
9551
+ const vfs = optVfs || createVirtualFs(files, { cwdGetter: () => currentCwd });
9323
9552
  if (optVfs && files && typeof files === 'object') {
9324
9553
  for (const [fPath, content] of Object.entries(files)) {
9325
9554
  const abs = fPath.startsWith('/') ? fPath : '/workspace/' + fPath;
@@ -9713,8 +9942,6 @@ function __initVirtualRuntime(rootScope) {
9713
9942
  hrtimeFn.bigint = () => BigInt(Math.round(performance.now() * 1e6));
9714
9943
 
9715
9944
  let syncExecDepth = 0;
9716
- let currentCwd = '/workspace';
9717
- _activeCwdGetter = () => currentCwd;
9718
9945
 
9719
9946
  const sandboxProcess = Object.assign(new EventEmitter(), {
9720
9947
  env: { NODE_ENV: 'development', PATH: '/usr/local/bin:/usr/bin:/bin', HOME: '/home/user' },
@@ -15625,6 +15852,13 @@ if (typeof module !== 'undefined' && module.exports) {
15625
15852
  return out;
15626
15853
  }
15627
15854
 
15855
+ function quoteShellArg(arg) {
15856
+ const s = String(arg ?? '');
15857
+ if (s.length === 0) return "''";
15858
+ if (!/[\s"'\\$&|;<>()`!*?~#]/.test(s)) return s;
15859
+ return "'" + s.replace(/'/g, "'\\''") + "'";
15860
+ }
15861
+
15628
15862
  async function runPackageScript(scriptName, scriptArgs, ctx) {
15629
15863
  const { data: pkgData } = readPackageJson(ctx.vfs, ctx.cwd);
15630
15864
  if (!pkgData.scripts || !pkgData.scripts[scriptName]) {
@@ -15632,7 +15866,7 @@ if (typeof module !== 'undefined' && module.exports) {
15632
15866
  }
15633
15867
  let cmd = pkgData.scripts[scriptName];
15634
15868
  if (scriptArgs && scriptArgs.length > 0) {
15635
- cmd += ' ' + scriptArgs.join(' ');
15869
+ cmd += ' ' + scriptArgs.map(quoteShellArg).join(' ');
15636
15870
  }
15637
15871
  const fallback = tryDevScriptFallback(scriptName, cmd, ctx);
15638
15872
  if (fallback) return fallback;
@@ -15885,6 +16119,11 @@ if (typeof module !== 'undefined' && module.exports) {
15885
16119
  const isFile = (p) => exists(p) && !isDir(p);
15886
16120
  const readText = (p) => { try { return ctx.vfs.readFileSync(p, 'utf8'); } catch (_) { return null; } };
15887
16121
 
16122
+ const isWithinRoot = (p) => {
16123
+ const rootPrefix = rootDir === '/' ? '/' : rootDir + '/';
16124
+ return p === rootDir || p.startsWith(rootPrefix);
16125
+ };
16126
+
15888
16127
  const resolveLocalTarget = (baseDir, rawSpec) => {
15889
16128
  if (!rawSpec || typeof rawSpec !== 'string') return null;
15890
16129
  const clean = rawSpec.split(/[?#]/)[0].trim();
@@ -15892,6 +16131,7 @@ if (typeof module !== 'undefined' && module.exports) {
15892
16131
  const candidateBase = clean.startsWith('/')
15893
16132
  ? PosixPath.join(rootDir, clean.replace(/^\/+/, ''))
15894
16133
  : PosixPath.join(baseDir, clean);
16134
+ if (!isWithinRoot(candidateBase)) return null;
15895
16135
  if (isFile(candidateBase)) return candidateBase;
15896
16136
  const cands = [
15897
16137
  candidateBase + '.tsx', candidateBase + '.ts', candidateBase + '.jsx', candidateBase + '.js',
@@ -15900,7 +16140,7 @@ if (typeof module !== 'undefined' && module.exports) {
15900
16140
  PosixPath.join(candidateBase, 'index.jsx'), PosixPath.join(candidateBase, 'index.js')
15901
16141
  ];
15902
16142
  for (const c of cands) {
15903
- if (isFile(c)) return c;
16143
+ if (isWithinRoot(c) && isFile(c)) return c;
15904
16144
  }
15905
16145
  return null;
15906
16146
  };
@@ -16029,7 +16269,7 @@ if (typeof module !== 'undefined' && module.exports) {
16029
16269
  if (/@import\s+['"]tailwindcss['"]/i.test(cssContent)) {
16030
16270
  needsTailwindBrowser = true;
16031
16271
  }
16032
- const resolvedCss = inlineLocalCssImports(cssContent, PosixPath.dirname(cssTarget));
16272
+ const resolvedCss = inlineLocalCssImports(cssContent, PosixPath.dirname(cssTarget)).replace(/<\/style/gi, '<\\/style');
16033
16273
  return `<style data-codelab-href="${hrefMatch[1].replace(/"/g, '&quot;')}">\n${resolvedCss}\n</style>`;
16034
16274
  });
16035
16275
 
@@ -16041,7 +16281,7 @@ if (typeof module !== 'undefined' && module.exports) {
16041
16281
  if (!scriptTarget || !isPreviewScriptPath(scriptTarget)) return fullTag;
16042
16282
  const rawScript = readText(scriptTarget);
16043
16283
  if (rawScript === null) return fullTag;
16044
- const compiled = transpileAndRewriteLocalImports(rawScript, scriptTarget);
16284
+ const compiled = transpileAndRewriteLocalImports(rawScript, scriptTarget).replace(/<\/script/gi, '<\\/script');
16045
16285
  const isMod = /\btype\s*=\s*["']module["']/i.test(attrs) || /\.(?:tsx|ts|jsx|mjs)$/i.test(scriptTarget) || /^\s*(?:import|export)\b/m.test(rawScript);
16046
16286
  const typeAttr = isMod ? ' type="module"' : '';
16047
16287
  return `<script${typeAttr} data-codelab-src="${srcMatch[1].replace(/"/g, '&quot;')}">\n${compiled}\n</script>`;
@@ -16064,6 +16304,12 @@ if (typeof module !== 'undefined' && module.exports) {
16064
16304
  try { pathname = decodeURIComponent(new URL(request.url).pathname); } catch (err) { _shellLogger.debug('Preview URL decode failed.', err); }
16065
16305
  const rel = pathname.replace(/^\/+/, '');
16066
16306
  let target = PosixPath.join(rootDir, rel);
16307
+ if (!isWithinRoot(target)) {
16308
+ return new Response(
16309
+ '<!doctype html><meta charset="utf-8"><title>403</title><h1>403 Forbidden</h1>',
16310
+ { status: 403, headers: { 'content-type': 'text/html; charset=utf-8' } }
16311
+ );
16312
+ }
16067
16313
  const hasExt = /\.[A-Za-z0-9]+$/.test(rel);
16068
16314
 
16069
16315
  if (!rel || pathname.endsWith('/') || isDir(target)) {
@@ -16088,8 +16334,13 @@ if (typeof module !== 'undefined' && module.exports) {
16088
16334
  target = (!exists(rootIdx) && exists(pubIdx)) ? pubIdx : rootIdx; // SPA fallback
16089
16335
  }
16090
16336
  if (!exists(target)) {
16337
+ const safePath = String(pathname)
16338
+ .replace(/&/g, '&amp;')
16339
+ .replace(/</g, '&lt;')
16340
+ .replace(/>/g, '&gt;')
16341
+ .replace(/"/g, '&quot;');
16091
16342
  return new Response(
16092
- `<!doctype html><meta charset="utf-8"><title>404</title><h1>404 Not Found</h1><p>${pathname}</p>`,
16343
+ `<!doctype html><meta charset="utf-8"><title>404</title><h1>404 Not Found</h1><p>${safePath}</p>`,
16093
16344
  { status: 404, headers: { 'content-type': 'text/html; charset=utf-8' } }
16094
16345
  );
16095
16346
  }
@@ -18240,13 +18491,17 @@ if (typeof module !== 'undefined' && module.exports) {
18240
18491
 
18241
18492
  const count = Math.max(1, result.filesWritten);
18242
18493
  const kb = Math.max(0.1, result.totalBytes / 1024).toFixed(1);
18494
+ if (!enumeratedEmitted) {
18495
+ streamLine(`remote: Enumerating objects: ${count}, done.\n`);
18496
+ streamLine(`remote: Counting objects: 100% (${count}/${count}), done.\n`);
18497
+ }
18243
18498
  streamLine(`Receiving objects: 100% (${count}/${count}), ${kb} KiB, done.\n`);
18244
18499
  const stdout =
18245
18500
  `Cloning into '${dirDisplayName}'...\n` +
18246
18501
  `remote: Enumerating objects: ${count}, done.\n` +
18247
18502
  `remote: Counting objects: 100% (${count}/${count}), done.\n` +
18248
18503
  `Receiving objects: 100% (${count}/${count}), ${kb} KiB, done.\n`;
18249
- return { code: 0, stdout, stderr: '' };
18504
+ return { code: 0, stdout, stderr: '', alreadyStreamed: canStream };
18250
18505
  } catch (err) {
18251
18506
  if (ctx.signal && ctx.signal.aborted) {
18252
18507
  return { code: 130, stdout: '', stderr: '', aborted: true };
@@ -19309,7 +19564,8 @@ if (typeof module !== 'undefined' && module.exports) {
19309
19564
  if (ctx.vfs.existsSync(binPath)) {
19310
19565
  return await ctx.commands.node([binPath, ...cmdArgs], ctx);
19311
19566
  }
19312
- return await ctx.shell.execute(cmd + (cmdArgs.length ? ' ' + cmdArgs.join(' ') : ''));
19567
+ const cmdStr = [cmd, ...cmdArgs].map(quoteShellArg).join(' ');
19568
+ return await ctx.shell.execute(cmdStr, { cwd: ctx.cwd, env: ctx.env, signal: ctx.signal });
19313
19569
  },
19314
19570
 
19315
19571
  async bunx(args, ctx) {
@@ -19380,7 +19636,8 @@ if (typeof module !== 'undefined' && module.exports) {
19380
19636
  if (!cmd) return { code: 1, stdout: '', stderr: 'pnpm: exec requires a command\n' };
19381
19637
  const binPath = PosixPath.join('/workspace/node_modules/.bin', cmd);
19382
19638
  if (ctx.vfs.existsSync(binPath)) return await ctx.commands.node([binPath, ...args.slice(2)], ctx);
19383
- return await ctx.shell.execute([cmd, ...args.slice(2)].join(' '));
19639
+ const cmdStr = [cmd, ...args.slice(2)].map(quoteShellArg).join(' ');
19640
+ return await ctx.shell.execute(cmdStr, { cwd: ctx.cwd, env: ctx.env, signal: ctx.signal });
19384
19641
  }
19385
19642
 
19386
19643
  if (sub === 'dlx') {
@@ -20563,18 +20820,27 @@ if (typeof module !== 'undefined' && module.exports) {
20563
20820
  if (item.background) {
20564
20821
  const pid = this.nextPid++;
20565
20822
  const jobId = this.nextJobId++;
20823
+ const jobAbortCtrl = typeof AbortController !== 'undefined' ? new AbortController() : null;
20566
20824
  const job = {
20567
20825
  id: jobId,
20568
20826
  pid,
20569
20827
  command: trimmed,
20570
20828
  status: 'Running',
20571
- startTime: Date.now()
20829
+ startTime: Date.now(),
20830
+ abort: () => { if (jobAbortCtrl) jobAbortCtrl.abort(); }
20572
20831
  };
20573
20832
  this.jobs.set(jobId, job);
20574
20833
  if (typeof this.options.onJobStart === 'function') this.options.onJobStart(job);
20575
20834
 
20576
- // Run in background promise
20577
- this._executeAstNode(item.node, { ...execOptions, env: Object.assign({}, this.env, currentEnv), cwd: this.cwd, pid, isBackground: true })
20835
+ // Run in background promise with its own independent AbortSignal
20836
+ this._executeAstNode(item.node, {
20837
+ ...execOptions,
20838
+ signal: jobAbortCtrl ? jobAbortCtrl.signal : undefined,
20839
+ env: Object.assign({}, this.env, currentEnv),
20840
+ cwd: this.cwd,
20841
+ pid,
20842
+ isBackground: true
20843
+ })
20578
20844
  .then(res => {
20579
20845
  if (job.status !== 'Terminated') {
20580
20846
  job.status = 'Done';
@@ -20728,17 +20994,24 @@ if (typeof module !== 'undefined' && module.exports) {
20728
20994
  if (item.background) {
20729
20995
  const pid = this.nextPid++;
20730
20996
  const jobId = this.nextJobId++;
20997
+ const jobAbortCtrl = typeof AbortController !== 'undefined' ? new AbortController() : null;
20731
20998
  const job = {
20732
20999
  id: jobId,
20733
21000
  pid,
20734
21001
  command: 'background',
20735
21002
  status: 'Running',
20736
- startTime: Date.now()
21003
+ startTime: Date.now(),
21004
+ abort: () => { if (jobAbortCtrl) jobAbortCtrl.abort(); }
20737
21005
  };
20738
21006
  this.jobs.set(jobId, job);
20739
21007
  if (typeof this.options.onJobStart === 'function') this.options.onJobStart(job);
20740
21008
 
20741
- this._executeAstNode(item.node, { ...context, pid, isBackground: true })
21009
+ this._executeAstNode(item.node, {
21010
+ ...context,
21011
+ signal: jobAbortCtrl ? jobAbortCtrl.signal : undefined,
21012
+ pid,
21013
+ isBackground: true
21014
+ })
20742
21015
  .then(res => {
20743
21016
  if (job.status !== 'Terminated') {
20744
21017
  job.status = 'Done';
@@ -20854,7 +21127,11 @@ if (typeof module !== 'undefined' && module.exports) {
20854
21127
  wordItems.push(...(innerCtx.positionalArgs || []));
20855
21128
  }
20856
21129
 
21130
+ let loopIter = 0;
20857
21131
  for (const val of wordItems) {
21132
+ if (++loopIter % 250 === 0 && typeof setTimeout === 'function') {
21133
+ await new Promise((r) => setTimeout(r, 0));
21134
+ }
20858
21135
  if (innerCtx.signal && innerCtx.signal.aborted) {
20859
21136
  return { code: 130, stdout: combinedStdout, stderr: combinedStderr, aborted: true };
20860
21137
  }
@@ -20899,7 +21176,11 @@ if (typeof module !== 'undefined' && module.exports) {
20899
21176
  let combinedStderr = '';
20900
21177
  let lastCode = 0;
20901
21178
 
21179
+ let loopIter = 0;
20902
21180
  while (true) {
21181
+ if (++loopIter % 250 === 0 && typeof setTimeout === 'function') {
21182
+ await new Promise((r) => setTimeout(r, 0));
21183
+ }
20903
21184
  if (innerCtx.signal && innerCtx.signal.aborted) {
20904
21185
  return { code: 130, stdout: combinedStdout, stderr: combinedStderr, aborted: true };
20905
21186
  }
@@ -21366,7 +21647,9 @@ if (typeof module !== 'undefined' && module.exports) {
21366
21647
 
21367
21648
  // Route any remaining unstreamed output
21368
21649
  if (res.stdout) {
21369
- if (streamedStdoutBytes > 0) {
21650
+ if (res.alreadyStreamed) {
21651
+ stdoutOut = res.stdout;
21652
+ } else if (streamedStdoutBytes > 0) {
21370
21653
  if (res.stdout.length > streamedStdoutBytes) {
21371
21654
  routeOutput(fd1, res.stdout.slice(streamedStdoutBytes), true);
21372
21655
  }
@@ -21727,6 +22010,14 @@ if (typeof module !== 'undefined' && module.exports) {
21727
22010
 
21728
22011
  const parseAnsiToHtml = ansiToHtml;
21729
22012
 
22013
+ const MAX_SCROLLBACK = 2000;
22014
+ const VALID_LOG_TYPES = new Set(['stdout', 'stderr', 'system', 'info', 'warn', 'error', 'success']);
22015
+
22016
+ function sanitizeLogType(type) {
22017
+ const t = String(type || 'stdout').trim();
22018
+ return VALID_LOG_TYPES.has(t) ? t : 'stdout';
22019
+ }
22020
+
21730
22021
  class PTYTerminalEngine {
21731
22022
  constructor(container, options = {}) {
21732
22023
  if (
@@ -21741,6 +22032,9 @@ if (typeof module !== 'undefined' && module.exports) {
21741
22032
  }
21742
22033
  this.container = container || null;
21743
22034
  this.options = options || {};
22035
+ this.maxScrollback = typeof this.options.maxScrollback === 'number' && this.options.maxScrollback > 0
22036
+ ? this.options.maxScrollback
22037
+ : MAX_SCROLLBACK;
21744
22038
  this.logs = Array.isArray(this.options.logs) ? this.options.logs : [];
21745
22039
  this.cwd = this.options.cwd || '/workspace';
21746
22040
  this.replMode = Boolean(this.options.replMode);
@@ -21754,6 +22048,7 @@ if (typeof module !== 'undefined' && module.exports) {
21754
22048
  this.searchQuery = '';
21755
22049
  this.searchMatchIdx = -1;
21756
22050
  this._readLineQueue = [];
22051
+ this.isBusy = false;
21757
22052
  this.onCommand = typeof this.options.onCommand === 'function' ? this.options.onCommand : null;
21758
22053
  this.getCompletions = typeof this.options.getCompletions === 'function' ? this.options.getCompletions : null;
21759
22054
  this.onKey = typeof this.options.onKey === 'function' ? this.options.onKey : null;
@@ -21904,13 +22199,40 @@ if (typeof module !== 'undefined' && module.exports) {
21904
22199
  this.writeStreamChunk(String(data) + '\n', type);
21905
22200
  }
21906
22201
 
22202
+ isCommandRunning() {
22203
+ return Boolean(this.isBusy && (!this._readLineQueue || this._readLineQueue.length === 0));
22204
+ }
22205
+
22206
+ _pushLog(entry) {
22207
+ const normalized = {
22208
+ type: sanitizeLogType(entry && entry.type),
22209
+ text: String(entry && entry.text != null ? entry.text : '')
22210
+ };
22211
+ this.logs.push(normalized);
22212
+ if (this.logs.length > this.maxScrollback) {
22213
+ const excess = this.logs.length - this.maxScrollback;
22214
+ this.logs.splice(0, excess);
22215
+ if (this._targetLineIdx >= 0) {
22216
+ this._targetLineIdx = Math.max(0, this._targetLineIdx - excess);
22217
+ }
22218
+ if (this.container && typeof this.container.querySelector === 'function') {
22219
+ const logEl = this.container.querySelector('#cl-terminal-log');
22220
+ if (logEl && logEl.children && logEl.children.length > this.maxScrollback) {
22221
+ while (logEl.children.length > this.maxScrollback && typeof logEl.removeChild === 'function' && logEl.firstChild) {
22222
+ logEl.removeChild(logEl.firstChild);
22223
+ }
22224
+ }
22225
+ }
22226
+ }
22227
+ return normalized;
22228
+ }
22229
+
21907
22230
  _getActiveLine(type) {
21908
22231
  if (this._targetLineIdx >= 0 && this._targetLineIdx < this.logs.length) {
21909
22232
  return this.logs[this._targetLineIdx];
21910
22233
  }
21911
22234
  if (this._activeLineCommitted || this.logs.length === 0) {
21912
- const newLine = { text: '', type };
21913
- this.logs.push(newLine);
22235
+ const newLine = this._pushLog({ text: '', type });
21914
22236
  this._activeLineCommitted = false;
21915
22237
  this._cursorCol = 0;
21916
22238
  this._targetLineIdx = this.logs.length - 1;
@@ -21927,7 +22249,7 @@ if (typeof module !== 'undefined' && module.exports) {
21927
22249
  const logEl = this.container.querySelector('#cl-terminal-log');
21928
22250
  if (!logEl) return;
21929
22251
  const lineEl = document.createElement('div');
21930
- lineEl.className = 'codelab-log-line ' + (line.type || 'stdout');
22252
+ lineEl.className = 'codelab-log-line ' + sanitizeLogType(line.type);
21931
22253
  lineEl.innerHTML = ansiToHtml(line.text);
21932
22254
  logEl.appendChild(lineEl);
21933
22255
  this._activeLineEl = lineEl;
@@ -21950,7 +22272,7 @@ if (typeof module !== 'undefined' && module.exports) {
21950
22272
  }
21951
22273
  }
21952
22274
  if (lineEl) {
21953
- lineEl.className = 'codelab-log-line ' + (line.type || 'stdout');
22275
+ lineEl.className = 'codelab-log-line ' + sanitizeLogType(line.type);
21954
22276
  lineEl.innerHTML = ansiToHtml(line.text);
21955
22277
  }
21956
22278
  }
@@ -21989,17 +22311,29 @@ if (typeof module !== 'undefined' && module.exports) {
21989
22311
  return [...this.history];
21990
22312
  }
21991
22313
 
21992
- readLine(promptText = '') {
21993
- const prevPrompt = this.promptOverride;
21994
- if (promptText) {
21995
- this.setPrompt(promptText);
22314
+ _activateNextReadLine() {
22315
+ if (!this._readLineQueue || this._readLineQueue.length === 0) return;
22316
+ const head = this._readLineQueue[0];
22317
+ if (head && typeof head === 'object' && !head._activated) {
22318
+ head._activated = true;
22319
+ head.prevPrompt = this.promptOverride;
22320
+ if (head.promptText) {
22321
+ this.promptOverride = head.promptText;
22322
+ }
21996
22323
  }
22324
+ }
22325
+
22326
+ readLine(promptText = '') {
21997
22327
  return new Promise((resolve) => {
21998
- this._readLineQueue.push((line) => {
21999
- this.promptOverride = prevPrompt;
22000
- this.updateActiveLine();
22001
- resolve(line);
22002
- });
22328
+ const item = {
22329
+ promptText: String(promptText || ''),
22330
+ prevPrompt: null,
22331
+ _activated: false,
22332
+ resolve
22333
+ };
22334
+ this._readLineQueue.push(item);
22335
+ this._activateNextReadLine();
22336
+ this.updateActiveLine();
22003
22337
  });
22004
22338
  }
22005
22339
 
@@ -22069,6 +22403,10 @@ if (typeof module !== 'undefined' && module.exports) {
22069
22403
  if (input) {
22070
22404
  this._addListener(input, 'keydown', (e) => this.handleKeyDown(e));
22071
22405
  this._addListener(input, 'input', () => {
22406
+ if (this.isCommandRunning()) {
22407
+ input.value = '';
22408
+ return;
22409
+ }
22072
22410
  if (input.value !== this.buffer) {
22073
22411
  this.buffer = input.value;
22074
22412
  this.cursor = typeof input.selectionStart === 'number' ? input.selectionStart : this.buffer.length;
@@ -22110,6 +22448,35 @@ if (typeof module !== 'undefined' && module.exports) {
22110
22448
  const key = e.key;
22111
22449
  const isCtrl = Boolean(e.ctrlKey || e.metaKey);
22112
22450
 
22451
+ if (isCtrl && (key === 'l' || key === 'L')) {
22452
+ if (e.preventDefault) e.preventDefault();
22453
+ this.clear();
22454
+ return;
22455
+ }
22456
+
22457
+ if (isCtrl && (key === 'c' || key === 'C')) {
22458
+ if (e.preventDefault) e.preventDefault();
22459
+ const wasBusy = this.isBusy;
22460
+ this.isBusy = false;
22461
+ this._pushLog({ type: 'system', text: wasBusy ? '^C' : `${this.getPrompt()}${this.buffer}^C` });
22462
+ this.buffer = '';
22463
+ this.cursor = 0;
22464
+ this.historyIdx = -1;
22465
+ if (this.replMode) {
22466
+ this.replMode = false;
22467
+ }
22468
+ if (this.onInterrupt) {
22469
+ try { this.onInterrupt(); } catch (err) { _terminalLogger.warn('Terminal onInterrupt callback threw.', err); }
22470
+ }
22471
+ this.render();
22472
+ return;
22473
+ }
22474
+
22475
+ if (this.isCommandRunning()) {
22476
+ if (e.preventDefault) e.preventDefault();
22477
+ return;
22478
+ }
22479
+
22113
22480
  if (isCtrl && (key === 'r' || key === 'R')) {
22114
22481
  if (e.preventDefault) e.preventDefault();
22115
22482
  if (!this.searchMode) {
@@ -22241,33 +22608,11 @@ if (typeof module !== 'undefined' && module.exports) {
22241
22608
  return;
22242
22609
  }
22243
22610
 
22244
- if (isCtrl && (key === 'l' || key === 'L')) {
22245
- if (e.preventDefault) e.preventDefault();
22246
- this.clear();
22247
- return;
22248
- }
22249
-
22250
- if (isCtrl && (key === 'c' || key === 'C')) {
22251
- if (e.preventDefault) e.preventDefault();
22252
- this.logs.push({ type: 'system', text: `${this.getPrompt()}${this.buffer}^C` });
22253
- this.buffer = '';
22254
- this.cursor = 0;
22255
- this.historyIdx = -1;
22256
- if (this.replMode) {
22257
- this.replMode = false;
22258
- }
22259
- if (this.onInterrupt) {
22260
- try { this.onInterrupt(); } catch (err) { _terminalLogger.warn('Terminal onInterrupt callback threw.', err); }
22261
- }
22262
- this.render();
22263
- return;
22264
- }
22265
-
22266
22611
  if (isCtrl && (key === 'd' || key === 'D')) {
22267
22612
  if (this.buffer === '') {
22268
22613
  if (e.preventDefault) e.preventDefault();
22269
22614
  if (this.replMode) {
22270
- this.logs.push({ type: 'system', text: `${this.getPrompt()}.exit` });
22615
+ this._pushLog({ type: 'system', text: `${this.getPrompt()}.exit` });
22271
22616
  this.replMode = false;
22272
22617
  this.render();
22273
22618
  return;
@@ -22361,14 +22706,41 @@ if (typeof module !== 'undefined' && module.exports) {
22361
22706
  }
22362
22707
 
22363
22708
  // Print candidate matches
22364
- this.logs.push({ type: 'system', text: `${this.getPrompt()}${this.buffer}` });
22365
- this.logs.push({ type: 'stdout', text: matches.join(' ') });
22709
+ this._pushLog({ type: 'system', text: `${this.getPrompt()}${this.buffer}` });
22710
+ this._pushLog({ type: 'stdout', text: matches.join(' ') });
22366
22711
  this.render();
22367
22712
  }
22368
22713
  }
22369
22714
 
22370
22715
  submitLine() {
22716
+ if (this._readLineQueue && this._readLineQueue.length > 0) {
22717
+ const line = this.buffer;
22718
+ this.buffer = '';
22719
+ this.cursor = 0;
22720
+ this.historyIdx = -1;
22721
+ this.searchMode = false;
22722
+ this.searchQuery = '';
22723
+ this.searchMatchIdx = -1;
22724
+
22725
+ const entry = this._readLineQueue.shift();
22726
+ if (typeof entry === 'function') {
22727
+ this.updateActiveLine();
22728
+ entry(line);
22729
+ } else if (entry && typeof entry.resolve === 'function') {
22730
+ this.promptOverride = entry.prevPrompt;
22731
+ this._activateNextReadLine();
22732
+ this.updateActiveLine();
22733
+ entry.resolve(line);
22734
+ }
22735
+ return;
22736
+ }
22737
+
22738
+ if (this.isBusy) {
22739
+ return;
22740
+ }
22741
+
22371
22742
  const line = this.buffer;
22743
+ const promptSnap = this.getPrompt();
22372
22744
  this.buffer = '';
22373
22745
  this.cursor = 0;
22374
22746
  this.historyIdx = -1;
@@ -22376,22 +22748,49 @@ if (typeof module !== 'undefined' && module.exports) {
22376
22748
  this.searchQuery = '';
22377
22749
  this.searchMatchIdx = -1;
22378
22750
 
22751
+ const echoed = this._pushLog({ type: 'system', text: `${promptSnap}${line}` });
22752
+ this._activeLineCommitted = true;
22753
+ this._cursorCol = 0;
22754
+ this._targetLineIdx = -1;
22755
+ this._needsRewrite = false;
22756
+ this._appendDomLine(echoed);
22757
+ this._activeLineEl = null;
22758
+
22379
22759
  if (line.trim()) {
22380
22760
  if (this.history[this.history.length - 1] !== line.trim()) {
22381
22761
  this.history.push(line.trim());
22382
22762
  }
22383
22763
  }
22384
22764
 
22385
- if (this._readLineQueue && this._readLineQueue.length > 0) {
22386
- const resolver = this._readLineQueue.shift();
22765
+ if (!this.onCommand) {
22387
22766
  this.updateActiveLine();
22388
- resolver(line);
22389
22767
  return;
22390
22768
  }
22391
22769
 
22770
+ this.isBusy = true;
22392
22771
  this.updateActiveLine();
22393
- if (this.onCommand) {
22394
- this.onCommand(line);
22772
+
22773
+ let cmdResult;
22774
+ try {
22775
+ cmdResult = this.onCommand(line);
22776
+ } catch (err) {
22777
+ this.isBusy = false;
22778
+ this.updateActiveLine();
22779
+ throw err;
22780
+ }
22781
+
22782
+ if (cmdResult && typeof cmdResult.then === 'function') {
22783
+ Promise.resolve(cmdResult)
22784
+ .catch((err) => {
22785
+ _terminalLogger.debug('Terminal onCommand promise rejected.', err);
22786
+ })
22787
+ .finally(() => {
22788
+ this.isBusy = false;
22789
+ this.updateActiveLine();
22790
+ });
22791
+ } else {
22792
+ this.isBusy = false;
22793
+ this.updateActiveLine();
22395
22794
  }
22396
22795
  }
22397
22796
 
@@ -22404,6 +22803,16 @@ if (typeof module !== 'undefined' && module.exports) {
22404
22803
  const lineEl = this.container.querySelector('#cl-pty-active-line');
22405
22804
  if (!lineEl) return;
22406
22805
 
22806
+ if (this.isCommandRunning()) {
22807
+ if (typeof lineEl.setAttribute === 'function') lineEl.setAttribute('data-busy', 'true');
22808
+ if (lineEl.style) lineEl.style.display = 'none';
22809
+ lineEl.innerHTML = `<span class="codelab-pty__prompt"></span><span class="codelab-pty__before"></span><span class="codelab-pty__cursor"></span><span class="codelab-pty__after"></span>`;
22810
+ return;
22811
+ }
22812
+
22813
+ if (typeof lineEl.removeAttribute === 'function') lineEl.removeAttribute('data-busy');
22814
+ if (lineEl.style) lineEl.style.display = '';
22815
+
22407
22816
  const prompt = this.searchMode
22408
22817
  ? `(reverse-i-search)\`${this.searchQuery}\`: `
22409
22818
  : this.getPrompt();
@@ -22424,21 +22833,24 @@ if (typeof module !== 'undefined' && module.exports) {
22424
22833
  );
22425
22834
 
22426
22835
  const logsHtml = this.logs
22427
- .map(item => `<div class="codelab-log-line ${escapeHtml(item.type || '')}">${ansiToHtml(item.text)}</div>`)
22836
+ .map(item => `<div class="codelab-log-line ${sanitizeLogType(item.type)}">${ansiToHtml(item.text)}</div>`)
22428
22837
  .join('');
22429
22838
 
22430
- const prompt = this.searchMode
22431
- ? `(reverse-i-search)\`${this.searchQuery}\`: `
22432
- : this.getPrompt();
22433
- const before = this.buffer.slice(0, this.cursor);
22434
- const cursorChar = this.cursor < this.buffer.length ? this.buffer[this.cursor] : ' ';
22435
- const after = this.cursor < this.buffer.length ? this.buffer.slice(this.cursor + 1) : '';
22839
+ const busy = this.isCommandRunning();
22840
+ const prompt = busy
22841
+ ? ''
22842
+ : (this.searchMode ? `(reverse-i-search)\`${this.searchQuery}\`: ` : this.getPrompt());
22843
+ const before = busy ? '' : this.buffer.slice(0, this.cursor);
22844
+ const cursorChar = busy ? '' : (this.cursor < this.buffer.length ? this.buffer[this.cursor] : ' ');
22845
+ const after = busy ? '' : (this.cursor < this.buffer.length ? this.buffer.slice(this.cursor + 1) : '');
22846
+ const busyAttr = busy ? ' data-busy="true" style="display:none;"' : '';
22847
+ const cursorClass = busy ? 'codelab-pty__cursor' : 'codelab-pty__cursor blink';
22436
22848
 
22437
22849
  this.container.innerHTML = `
22438
22850
  <div class="codelab-terminal" id="cl-terminal-surface" tabindex="0">
22439
22851
  <div class="codelab-terminal__log" id="cl-terminal-log">${logsHtml}</div>
22440
- <div class="codelab-pty__active-line" id="cl-pty-active-line">
22441
- <span class="codelab-pty__prompt">${escapeHtml(prompt)}</span><span class="codelab-pty__before">${escapeHtml(before)}</span><span class="codelab-pty__cursor blink">${escapeHtml(cursorChar)}</span><span class="codelab-pty__after">${escapeHtml(after)}</span>
22852
+ <div class="codelab-pty__active-line" id="cl-pty-active-line"${busyAttr}>
22853
+ <span class="codelab-pty__prompt">${escapeHtml(prompt)}</span><span class="codelab-pty__before">${escapeHtml(before)}</span><span class="${cursorClass}">${escapeHtml(cursorChar)}</span><span class="codelab-pty__after">${escapeHtml(after)}</span>
22442
22854
  </div>
22443
22855
  <form class="codelab-repl" id="cl-repl-form" style="position:absolute;opacity:0;pointer-events:none;height:0;overflow:hidden;">
22444
22856
  <input type="text" class="codelab-repl__input" id="cl-repl-input" autocomplete="off" spellcheck="false" aria-label="Terminal command input" value="${escapeHtml(this.buffer)}">
@@ -22550,7 +22962,7 @@ if (typeof module !== 'undefined' && module.exports) {
22550
22962
 
22551
22963
  // The bundler rewrites this literal from package.json at build time. Keeping
22552
22964
  // the fallback in sync lets tests require src/workbench.js directly.
22553
- const CODELAB_VERSION = '0.3.1';
22965
+ const CODELAB_VERSION = '0.3.2';
22554
22966
 
22555
22967
  // Ambient TypeScript declarations for Node.js built-ins inside Monaco
22556
22968
  const NODE_AMBIENT_DTS = `
@@ -23125,11 +23537,16 @@ declare module 'bun:sqlite' {
23125
23537
  if (!str) return '';
23126
23538
  let text = String(str);
23127
23539
 
23128
- // Markdown Links: [label](url "title") or [label](url) — supports balanced parentheses in URLs
23129
- text = text.replace(/\[([^\]]+)\]\(([^()\s]+(?:\((?:[^()\s]+|\([^()\s]*\))*\)[^()\s]*)*)(?:\s+"([^"]*)")?\)/g, (_, label, url, title) => {
23540
+ // Markdown Links: [label](url "title") or [label](url) — stash anchors before emphasis regexes
23541
+ // so underscores/asterisks inside URLs or titles are not mangled, and use non-nested quantifiers.
23542
+ const inlineLinks = [];
23543
+ text = text.replace(/\[([^\]]+)\]\(([^\s()]+(?:\([^\s()]*\)[^\s()]*)*)(?:\s+"([^"]*)")?\)/g, (_, label, url, title) => {
23130
23544
  const cleanUrl = sanitizeUrl(url);
23131
23545
  const titleAttr = title ? raw(` title="${escapeHtml(title)}"`) : '';
23132
- return String(html`<a href="${cleanUrl}" class="codelab-link" target="_blank" rel="noopener noreferrer"${titleAttr}>${label}</a>`);
23546
+ const formattedLabel = renderInlineFormatting(label);
23547
+ const idx = inlineLinks.length;
23548
+ inlineLinks.push(String(html`<a href="${cleanUrl}" class="codelab-link" target="_blank" rel="noopener noreferrer"${titleAttr}>${raw(formattedLabel)}</a>`));
23549
+ return `\x00CLLINK${idx}\x00`;
23133
23550
  });
23134
23551
 
23135
23552
  // Strikethrough: ~~del~~
@@ -23147,6 +23564,10 @@ declare module 'bun:sqlite' {
23147
23564
  text = text.replace(/\*([^*\n]+)\*/g, '<em>$1</em>');
23148
23565
  text = text.replace(/(^|[\s(])_([^_]+)_(?=[\s).,!?:;]|$)/g, '$1<em>$2</em>');
23149
23566
 
23567
+ if (inlineLinks.length > 0) {
23568
+ text = text.replace(/\x00CLLINK(\d+)\x00/g, (_, i) => inlineLinks[Number(i)] || '');
23569
+ }
23570
+
23150
23571
  return text;
23151
23572
  }
23152
23573
 
@@ -23334,7 +23755,7 @@ declare module 'bun:sqlite' {
23334
23755
  const lang = (info || '').trim().split(/\s+/)[0] || '';
23335
23756
  const idx = codeBlocks.length;
23336
23757
  codeBlocks.push(renderCodeBlock(code || '', lang));
23337
- return `\n\n\x00CODEBLOCK_${idx}\x00\n\n`;
23758
+ return `\n\n\x00CLCODEBLOCK${idx}\x00\n\n`;
23338
23759
  });
23339
23760
 
23340
23761
  // Phase 2: Inline Code Span Extraction
@@ -23346,7 +23767,7 @@ declare module 'bun:sqlite' {
23346
23767
  }
23347
23768
  const idx = inlineCodes.length;
23348
23769
  inlineCodes.push(`<code class="codelab-inline-code">${escapeHtml(clean)}</code>`);
23349
- return `\x00INLINECODE_${idx}\x00`;
23770
+ return `\x00CLINLINECODE${idx}\x00`;
23350
23771
  });
23351
23772
 
23352
23773
  // Phase 2b: Autolinks are the only inline construct that uses angle
@@ -23359,7 +23780,7 @@ declare module 'bun:sqlite' {
23359
23780
  autolinks.push(
23360
23781
  `<a href="${escapeHtml(safe)}" class="codelab-link" target="_blank" rel="noopener noreferrer">${escapeHtml(url)}</a>`
23361
23782
  );
23362
- return `\x00AUTOLINK_${idx}\x00`;
23783
+ return `\x00CLAUTOLINK${idx}\x00`;
23363
23784
  });
23364
23785
 
23365
23786
  // Phase 2c: Neutralize all remaining raw HTML. Every tag needs a `<`, so
@@ -23394,7 +23815,7 @@ declare module 'bun:sqlite' {
23394
23815
  }
23395
23816
  const idx = calloutBlocks.length;
23396
23817
  calloutBlocks.push(blockHtml);
23397
- return `\n\n\x00CALLOUT_${idx}\x00\n\n`;
23818
+ return `\n\n\x00CLCALLOUT${idx}\x00\n\n`;
23398
23819
  });
23399
23820
 
23400
23821
  // Phase 4: GFM Tables with Column Alignments
@@ -23404,7 +23825,7 @@ declare module 'bun:sqlite' {
23404
23825
  if (rendered === tableText) return match;
23405
23826
  const idx = tableBlocks.length;
23406
23827
  tableBlocks.push(rendered);
23407
- return `\n\n\x00TABLE_${idx}\x00\n\n`;
23828
+ return `\n\n\x00CLTABLE${idx}\x00\n\n`;
23408
23829
  });
23409
23830
 
23410
23831
  // Phase 5: Task Lists & Nested Lists
@@ -23413,7 +23834,7 @@ declare module 'bun:sqlite' {
23413
23834
  text = text.replace(/(?:^[ ]*(?:[-*+]|\d+\.)[ ]+[^\n]*(?:\n[ ]*(?:[-*+]|\d+\.)[ ]+[^\n]*|\n[ ]{2,}[^\n]*)*)+/gm, (match) => {
23414
23835
  const idx = listBlocks.length;
23415
23836
  listBlocks.push(renderListBlock(match, taskCounter));
23416
- return `\n\n\x00LIST_${idx}\x00\n\n`;
23837
+ return `\n\n\x00CLLIST${idx}\x00\n\n`;
23417
23838
  });
23418
23839
 
23419
23840
  // Phase 6: Headings, Horizontal Rules, Paragraphs & Inline Spans
@@ -23435,18 +23856,18 @@ declare module 'bun:sqlite' {
23435
23856
  const trimmed = p.trim();
23436
23857
  if (!trimmed) return '';
23437
23858
  if (/^<(h[1-6]|hr|pre|div|blockquote|table|ul|ol)/i.test(trimmed)) return trimmed;
23438
- if (/^\x00(CODEBLOCK|CALLOUT|TABLE|LIST)_\d+\x00$/.test(trimmed)) return trimmed;
23859
+ if (/^\x00CL(CODEBLOCK|CALLOUT|TABLE|LIST)\d+\x00$/.test(trimmed)) return trimmed;
23439
23860
  return `<p>${renderInlineFormatting(trimmed).replace(/\n/g, '<br>')}</p>`;
23440
23861
  }).filter(Boolean).join('\n');
23441
23862
 
23442
23863
  // Phase 7: Placeholder Restoration (Reverse order)
23443
23864
  let finalHtml = paras
23444
- .replace(/\x00LIST_(\d+)\x00/g, (_, i) => listBlocks[Number(i)] || '')
23445
- .replace(/\x00TABLE_(\d+)\x00/g, (_, i) => tableBlocks[Number(i)] || '')
23446
- .replace(/\x00CALLOUT_(\d+)\x00/g, (_, i) => calloutBlocks[Number(i)] || '')
23447
- .replace(/\x00CODEBLOCK_(\d+)\x00/g, (_, i) => codeBlocks[Number(i)] || '')
23448
- .replace(/\x00INLINECODE_(\d+)\x00/g, (_, i) => inlineCodes[Number(i)] || '')
23449
- .replace(/\x00AUTOLINK_(\d+)\x00/g, (_, i) => autolinks[Number(i)] || '');
23865
+ .replace(/\x00CLLIST(\d+)\x00/g, (_, i) => listBlocks[Number(i)] || '')
23866
+ .replace(/\x00CLTABLE(\d+)\x00/g, (_, i) => tableBlocks[Number(i)] || '')
23867
+ .replace(/\x00CLCALLOUT(\d+)\x00/g, (_, i) => calloutBlocks[Number(i)] || '')
23868
+ .replace(/\x00CLCODEBLOCK(\d+)\x00/g, (_, i) => codeBlocks[Number(i)] || '')
23869
+ .replace(/\x00CLINLINECODE(\d+)\x00/g, (_, i) => inlineCodes[Number(i)] || '')
23870
+ .replace(/\x00CLAUTOLINK(\d+)\x00/g, (_, i) => autolinks[Number(i)] || '');
23450
23871
 
23451
23872
  return finalHtml;
23452
23873
  }
@@ -24449,9 +24870,18 @@ int main() {
24449
24870
  if (root.CodeLabStorage && typeof root.CodeLabStorage.createWorkspaceStorage === 'function') {
24450
24871
  try {
24451
24872
  if (!this._idbStorage) {
24452
- this._idbStorage = root.CodeLabStorage.createWorkspaceStorage({ keyPrefix: STORAGE_PREFIX });
24453
- }
24454
- if (this._idbStorage && typeof this._idbStorage.save === 'function') {
24873
+ this._idbStorage = root.CodeLabStorage.createWorkspaceStorage();
24874
+ }
24875
+ if (this._idbStorage && typeof this._idbStorage.saveProject === 'function') {
24876
+ Promise.resolve(this._idbStorage.saveProject({
24877
+ id: this.labId,
24878
+ name: this.title || this.labId,
24879
+ files: { ...(this.files || {}) },
24880
+ updatedAt: Date.now()
24881
+ })).catch((err) => {
24882
+ this.logger.debug('Async WorkspaceStorage saveProject skipped.', err);
24883
+ });
24884
+ } else if (this._idbStorage && typeof this._idbStorage.save === 'function') {
24455
24885
  Promise.resolve(this._idbStorage.save(this.labId, state)).catch((err) => {
24456
24886
  this.logger.debug('Async WorkspaceStorage save skipped.', err);
24457
24887
  });
@@ -24778,6 +25208,7 @@ int main() {
24778
25208
  this.container.querySelectorAll('[data-cl-action="run-code"], [data-cl-action="run-entry"], [data-cl-action="run-active-file"], [data-cl-action="run-demo"], [data-cl-action="run-tests"], [data-cl-action="verify-step"]').forEach(btn => {
24779
25209
  btn.disabled = this.isRunning;
24780
25210
  });
25211
+ this._updatePtyActiveLine();
24781
25212
  }
24782
25213
 
24783
25214
  _hasWebContent() {
@@ -24884,6 +25315,7 @@ int main() {
24884
25315
 
24885
25316
  let stdinTab = drawerTabs.querySelector('[data-cl-drawertab="stdin"]');
24886
25317
  if (!stdinTab) {
25318
+ const testTab = drawerTabs.querySelector('[data-cl-drawertab="tests"]');
24887
25319
  const afterTab = testTab || drawerTabs.querySelector('[data-cl-drawertab="problems"]') || drawerTabs.querySelector('[data-cl-drawertab="terminal"]');
24888
25320
  if (afterTab) {
24889
25321
  afterTab.insertAdjacentHTML('afterend', `
@@ -25132,6 +25564,8 @@ int main() {
25132
25564
  </div>
25133
25565
  <div class="codelab-hud-pill" id="cl-telemetry-hud" style="display:none;" title="Last Execution Telemetry"></div>
25134
25566
  <div style="display:flex;align-items:center;gap:6px;">
25567
+ <div class="codelab-terminal-sessions" id="cl-terminal-sessions"></div>
25568
+ <button type="button" class="codelab-btn codelab-btn--icon" id="cl-new-terminal-btn" data-cl-action="new-terminal-session" title="New Terminal Session" aria-label="New Terminal Session" style="padding:2px 6px;font-size:11px;">+</button>
25135
25569
  <button type="button" class="codelab-btn codelab-btn--icon codelab-btn--ctrl-c" id="cl-ctrl-c-btn" data-cl-action="interrupt" title="Send Ctrl+C — interrupt a running command" aria-label="Send Ctrl+C interrupt" style="padding:2px 8px;font-size:11px;font-family:var(--cl-font-mono);">Ctrl+C</button>
25136
25570
  <button type="button" class="codelab-btn codelab-btn--icon" data-cl-action="clear-terminal" title="Clear Output" style="padding:2px 6px;font-size:11px;">Clear</button>
25137
25571
  <button type="button" class="codelab-btn codelab-btn--icon" data-cl-action="toggle-drawer" title="Minimize/Expand Drawer" aria-label="Minimize or Expand Drawer" style="padding:2px 6px;font-size:11px;">${CL_ICONS.chevronsUpDown}</button>
@@ -26220,16 +26654,27 @@ int main() {
26220
26654
  ${problems.map(p => {
26221
26655
  const icon = p.severity === 'error' ? '✖' : (p.severity === 'warning' ? '⚠' : 'ℹ');
26222
26656
  const cls = p.severity === 'error' ? 'codelab-problem-item--error' : (p.severity === 'warning' ? 'codelab-problem-item--warning' : 'codelab-problem-item--info');
26657
+ const col = p.col || p.column || 1;
26223
26658
  return `
26224
- <div class="codelab-problem-item ${cls}" data-cl-problem-file="${escapeHtml(p.file || '')}" data-cl-problem-line="${p.line || 1}" data-cl-problem-col="${p.col || 1}" role="button" tabindex="0">
26659
+ <div class="codelab-problem-item ${cls}" data-cl-problem-file="${escapeHtml(p.file || '')}" data-cl-problem-line="${p.line || 1}" data-cl-problem-col="${col}" role="button" tabindex="0">
26225
26660
  <span class="codelab-problem-item__icon">${icon}</span>
26226
26661
  <span class="codelab-problem-item__msg">${escapeHtml(p.message || '')}</span>
26227
- <span class="codelab-problem-item__loc">${escapeHtml(p.file || '')}:${p.line || 1}:${p.col || 1}</span>
26662
+ <span class="codelab-problem-item__location codelab-problem-item__loc">${escapeHtml(p.file || '')}:${p.line || 1}:${col}</span>
26228
26663
  </div>
26229
26664
  `;
26230
26665
  }).join('')}
26231
26666
  </div>
26232
26667
  `;
26668
+ if (typeof bodyEl.querySelectorAll === 'function') {
26669
+ bodyEl.querySelectorAll('.codelab-problem-item').forEach((item) => {
26670
+ item.addEventListener('keydown', (e) => {
26671
+ if (e.key === 'Enter' || e.key === ' ') {
26672
+ e.preventDefault();
26673
+ item.click();
26674
+ }
26675
+ });
26676
+ });
26677
+ }
26233
26678
  return;
26234
26679
  }
26235
26680
 
@@ -26301,6 +26746,7 @@ int main() {
26301
26746
  }
26302
26747
 
26303
26748
  if (this.drawerTab === 'terminal') {
26749
+ this._renderTerminalSessionsBar();
26304
26750
  const logsHtml = this.terminalLogs
26305
26751
  .map(item => {
26306
26752
  const html = ansiToHtml ? ansiToHtml(item.text || '') : escapeHtml(item.text || '');
@@ -26309,7 +26755,13 @@ int main() {
26309
26755
  .join('');
26310
26756
  const cwdShort = (this.cwd || '/workspace').replace(/^\/workspace\/?/, '') || '~';
26311
26757
  const promptLabel = this.inRepl ? '> ' : `codelab:${cwdShort}$`;
26312
- bodyEl.innerHTML = `<div class="codelab-terminal" id="cl-terminal-surface" tabindex="0"><div class="codelab-terminal__log" id="cl-terminal-log">${logsHtml}</div><div class="codelab-pty__active-line" id="cl-pty-active-line"><span class="codelab-pty__prompt">${escapeHtml(promptLabel)} </span><span class="codelab-pty__before">${escapeHtml(this._ptyInputBeforeCursor || '')}</span><span class="codelab-pty__cursor blink">&#x2588;</span><span class="codelab-pty__after">${escapeHtml(this._ptyInputAfterCursor || '')}</span></div><form class="codelab-repl" id="cl-repl-form" style="position:absolute;width:1px;height:1px;overflow:hidden;opacity:0;"><span class="codelab-repl__prompt">${escapeHtml(promptLabel)}</span><input type="text" class="codelab-repl__input" id="cl-repl-input" placeholder="ls, pwd, cat file.js, node demo.js, node test.js, or JS/TS expression…" autocomplete="off" spellcheck="false" aria-label="REPL command input"></form></div>`;
26758
+ const busyAttr = this.isRunning ? ' data-busy="true" style="display:none;"' : '';
26759
+ const promptHtml = this.isRunning ? '' : `${escapeHtml(promptLabel)} `;
26760
+ const beforeHtml = this.isRunning ? '' : escapeHtml(this._ptyInputBeforeCursor || '');
26761
+ const afterHtml = this.isRunning ? '' : escapeHtml(this._ptyInputAfterCursor || '');
26762
+ const cursorClass = this.isRunning ? 'codelab-pty__cursor' : 'codelab-pty__cursor blink';
26763
+ const cursorCharHtml = this.isRunning ? '' : '&#x2588;';
26764
+ bodyEl.innerHTML = `<div class="codelab-terminal" id="cl-terminal-surface" tabindex="0"><div class="codelab-terminal__log" id="cl-terminal-log">${logsHtml}</div><div class="codelab-pty__active-line" id="cl-pty-active-line"${busyAttr}><span class="codelab-pty__prompt">${promptHtml}</span><span class="codelab-pty__before">${beforeHtml}</span><span class="${cursorClass}">${cursorCharHtml}</span><span class="codelab-pty__after">${afterHtml}</span></div><form class="codelab-repl" id="cl-repl-form" style="position:absolute;width:1px;height:1px;overflow:hidden;opacity:0;"><span class="codelab-repl__prompt">${escapeHtml(promptLabel)}</span><input type="text" class="codelab-repl__input" id="cl-repl-input" placeholder="ls, pwd, cat file.js, node demo.js, node test.js, or JS/TS expression…" autocomplete="off" spellcheck="false" aria-label="REPL command input"></form></div>`;
26313
26765
  bodyEl.scrollTop = bodyEl.scrollHeight;
26314
26766
  const termSurface = bodyEl.querySelector('#cl-terminal-surface');
26315
26767
  const input = bodyEl.querySelector('#cl-repl-input');
@@ -26321,15 +26773,43 @@ int main() {
26321
26773
  });
26322
26774
  }
26323
26775
  if (input) {
26324
- input.value = (this._ptyInputBeforeCursor || '') + (this._ptyInputAfterCursor || '');
26325
- input.addEventListener('input', () => {
26776
+ input.value = this.isRunning ? '' : ((this._ptyInputBeforeCursor || '') + (this._ptyInputAfterCursor || ''));
26777
+ const syncCaretFromInput = () => {
26778
+ if (this.isRunning) {
26779
+ input.value = '';
26780
+ return;
26781
+ }
26326
26782
  const val = input.value || '';
26327
26783
  const pos = (input.selectionStart !== undefined && input.selectionStart !== null) ? input.selectionStart : val.length;
26328
26784
  this._ptyInputBeforeCursor = val.slice(0, pos);
26329
26785
  this._ptyInputAfterCursor = val.slice(pos);
26330
26786
  this._updatePtyActiveLine();
26787
+ };
26788
+ input.addEventListener('input', syncCaretFromInput);
26789
+ input.addEventListener('click', syncCaretFromInput);
26790
+ input.addEventListener('keyup', e => {
26791
+ if (e.key === 'ArrowLeft' || e.key === 'ArrowRight' || e.key === 'Home' || e.key === 'End') {
26792
+ syncCaretFromInput();
26793
+ }
26331
26794
  });
26332
26795
  input.addEventListener('keydown', e => {
26796
+ if (e.ctrlKey && !e.metaKey && e.key.toLowerCase() === 'c') {
26797
+ e.preventDefault();
26798
+ this._handleInterrupt();
26799
+ return;
26800
+ }
26801
+ if (e.ctrlKey && !e.metaKey && e.key.toLowerCase() === 'l') {
26802
+ e.preventDefault();
26803
+ this._clearTerminalLogs();
26804
+ this._renderDrawerBody();
26805
+ const nextInput = this.container.querySelector('#cl-repl-input');
26806
+ if (nextInput && typeof nextInput.focus === 'function') nextInput.focus();
26807
+ return;
26808
+ }
26809
+ if (this.isRunning) {
26810
+ e.preventDefault();
26811
+ return;
26812
+ }
26333
26813
  if (e.key === 'Tab') {
26334
26814
  e.preventDefault();
26335
26815
  this._handlePtyTabCompletion(input);
@@ -26360,9 +26840,6 @@ int main() {
26360
26840
  this._ptyInputAfterCursor = '';
26361
26841
  this._updatePtyActiveLine();
26362
26842
  }
26363
- } else if (e.ctrlKey && !e.metaKey && e.key.toLowerCase() === 'c') {
26364
- e.preventDefault();
26365
- this._handleInterrupt();
26366
26843
  } else if (e.ctrlKey && !e.metaKey && e.key.toLowerCase() === 'd') {
26367
26844
  e.preventDefault();
26368
26845
  if (this.inRepl) {
@@ -26372,12 +26849,6 @@ int main() {
26372
26849
  const nextInput = this.container.querySelector('#cl-repl-input');
26373
26850
  if (nextInput && typeof nextInput.focus === 'function') nextInput.focus();
26374
26851
  }
26375
- } else if (e.ctrlKey && !e.metaKey && e.key.toLowerCase() === 'l') {
26376
- e.preventDefault();
26377
- this.terminalLogs = [];
26378
- this._renderDrawerBody();
26379
- const nextInput = this.container.querySelector('#cl-repl-input');
26380
- if (nextInput && typeof nextInput.focus === 'function') nextInput.focus();
26381
26852
  } else if (e.ctrlKey && e.key.toLowerCase() === 'u') {
26382
26853
  e.preventDefault();
26383
26854
  this._ptyInputBeforeCursor = '';
@@ -26408,6 +26879,7 @@ int main() {
26408
26879
  if (replForm) {
26409
26880
  replForm.addEventListener('submit', e => {
26410
26881
  e.preventDefault();
26882
+ if (this.isRunning) return;
26411
26883
  const rawCmd = (input && input.value !== undefined ? input.value : '') ||
26412
26884
  ((this._ptyInputBeforeCursor || '') + (this._ptyInputAfterCursor || ''));
26413
26885
  const cmd = rawCmd.trim();
@@ -26489,7 +26961,7 @@ int main() {
26489
26961
  if (chunk === null || chunk === undefined || chunk === '') return;
26490
26962
  const rawText = String(chunk);
26491
26963
 
26492
- if (this.ptyEngine && typeof this.ptyEngine.writeStreamChunk === 'function') {
26964
+ if (this.ptyEngine && this.ptyEngine.container && typeof this.ptyEngine.writeStreamChunk === 'function') {
26493
26965
  try {
26494
26966
  this.ptyEngine.writeStreamChunk(rawText, type);
26495
26967
  } catch (err) {
@@ -26530,6 +27002,14 @@ int main() {
26530
27002
  // A newline completes the current line: commit it to the log + DOM, then begin a fresh line.
26531
27003
  const commitActiveLine = () => {
26532
27004
  this.terminalLogs.push({ type: this._activeStreamType || type, text: this._activeStreamLine });
27005
+ if (this.terminalLogs.length > 2000) {
27006
+ this.terminalLogs.splice(0, this.terminalLogs.length - 2000);
27007
+ if (canPatchDom && termLogEl) {
27008
+ while (termLogEl.childElementCount > 2000 && termLogEl.firstElementChild) {
27009
+ termLogEl.removeChild(termLogEl.firstElementChild);
27010
+ }
27011
+ }
27012
+ }
26533
27013
  patchLineInDom(this._activeStreamLine);
26534
27014
  this._activeStreamLine = '';
26535
27015
  this._activeStreamEl = null;
@@ -26697,15 +27177,39 @@ int main() {
26697
27177
 
26698
27178
  _updatePtyActiveLine() {
26699
27179
  if (!this.container) return;
27180
+ const activeLine = this.container.querySelector('#cl-pty-active-line');
26700
27181
  const beforeEl = this.container.querySelector('.codelab-pty__before');
26701
27182
  const afterEl = this.container.querySelector('.codelab-pty__after');
26702
27183
  const promptEl = this.container.querySelector('.codelab-pty__prompt');
27184
+ const cursorEl = this.container.querySelector('.codelab-pty__cursor');
26703
27185
  const cwdShort = (this.cwd || '/workspace').replace(/^\/workspace\/?/, '') || '~';
26704
27186
  const promptLabel = this.inRepl ? '> ' : `codelab:${cwdShort}$`;
26705
27187
 
26706
- if (promptEl) promptEl.textContent = promptLabel + ' ';
26707
- if (beforeEl) beforeEl.textContent = this._ptyInputBeforeCursor || '';
26708
- if (afterEl) afterEl.textContent = this._ptyInputAfterCursor || '';
27188
+ if (this.isRunning) {
27189
+ if (activeLine) {
27190
+ activeLine.setAttribute('data-busy', 'true');
27191
+ if (activeLine.style) activeLine.style.display = 'none';
27192
+ }
27193
+ if (promptEl) promptEl.textContent = '';
27194
+ if (beforeEl) beforeEl.textContent = '';
27195
+ if (cursorEl) {
27196
+ cursorEl.textContent = '';
27197
+ if (cursorEl.classList) cursorEl.classList.remove('blink');
27198
+ }
27199
+ if (afterEl) afterEl.textContent = '';
27200
+ } else {
27201
+ if (activeLine) {
27202
+ activeLine.removeAttribute('data-busy');
27203
+ if (activeLine.style) activeLine.style.display = '';
27204
+ }
27205
+ if (promptEl) promptEl.textContent = promptLabel + ' ';
27206
+ if (beforeEl) beforeEl.textContent = this._ptyInputBeforeCursor || '';
27207
+ if (cursorEl) {
27208
+ if (!cursorEl.textContent) cursorEl.textContent = '\u2588';
27209
+ if (cursorEl.classList) cursorEl.classList.add('blink');
27210
+ }
27211
+ if (afterEl) afterEl.textContent = this._ptyInputAfterCursor || '';
27212
+ }
26709
27213
  }
26710
27214
 
26711
27215
  _handlePtyTabCompletion(input) {
@@ -27686,9 +28190,10 @@ int main() {
27686
28190
  _injectPreviewCsp(html, port) {
27687
28191
  if (typeof html !== 'string' || !html) return html;
27688
28192
 
28193
+ const csp = String(this._previewPolicy() || '').replace(/&/g, '&amp;').replace(/"/g, '&quot;').replace(/</g, '&lt;').replace(/>/g, '&gt;');
27689
28194
  const tags = [];
27690
28195
  if (!/<meta[^>]+http-equiv=["']?content-security-policy/i.test(html)) {
27691
- tags.push(`<meta http-equiv="Content-Security-Policy" content="${this._previewPolicy()}">`);
28196
+ tags.push(`<meta http-equiv="Content-Security-Policy" content="${csp}">`);
27692
28197
  }
27693
28198
  if (!/<base\b/i.test(html)) {
27694
28199
  tags.push(`<base href="/__preview/${Number(port) || 3000}/">`);
@@ -29254,21 +29759,29 @@ int main() {
29254
29759
  if (splitTrigger) {
29255
29760
  e.stopPropagation();
29256
29761
  const menu = this.container.querySelector('#cl-split-run-menu');
29257
- if (menu) menu.classList.toggle('active');
29762
+ if (menu) {
29763
+ const isOpen = !(menu.classList.contains('active') || menu.classList.contains('open'));
29764
+ menu.classList.toggle('active', isOpen);
29765
+ menu.classList.toggle('open', isOpen);
29766
+ }
29258
29767
  return;
29259
29768
  }
29260
29769
 
29261
29770
  const splitMenu = this.container.querySelector('#cl-split-run-menu');
29262
- if (splitMenu && splitMenu.classList.contains('active') && !e.target.closest('.codelab-btn-split')) {
29771
+ if (splitMenu && (splitMenu.classList.contains('active') || splitMenu.classList.contains('open')) && !e.target.closest('.codelab-btn-split')) {
29263
29772
  splitMenu.classList.remove('active');
29773
+ splitMenu.classList.remove('open');
29264
29774
  }
29265
29775
 
29266
- const problemItem = e.target.closest('[data-cl-problem-file]');
29776
+ const problemItem = e.target.closest('[data-cl-problem-file], [data-problem-file]');
29267
29777
  if (problemItem) {
29268
29778
  e.stopPropagation();
29269
- const pFile = problemItem.dataset.clProblemFile;
29270
- const pLine = Number(problemItem.dataset.clProblemLine || 1);
29271
- const pCol = Number(problemItem.dataset.clProblemCol || 1);
29779
+ const pFile = problemItem.dataset.clProblemFile || problemItem.dataset.problemFile;
29780
+ const pLine = Number(problemItem.dataset.clProblemLine || problemItem.dataset.problemLine || 1);
29781
+ const pCol = Number(problemItem.dataset.clProblemCol || problemItem.dataset.problemCol || 1);
29782
+ if (problemItem.closest('#cl-modal-slot')) {
29783
+ this.closeModal();
29784
+ }
29272
29785
  if (pFile) {
29273
29786
  this.openFile(pFile);
29274
29787
  if (this.editor && typeof this.editor.revealLineInCenter === 'function') {
@@ -29280,6 +29793,24 @@ int main() {
29280
29793
  return;
29281
29794
  }
29282
29795
 
29796
+ const searchMatch = e.target.closest('[data-cl-search-file]');
29797
+ if (searchMatch) {
29798
+ e.stopPropagation();
29799
+ const sFile = searchMatch.dataset.clSearchFile;
29800
+ const sLine = Number(searchMatch.dataset.clSearchLine || 1);
29801
+ const sCol = Number(searchMatch.dataset.clSearchCol || 1);
29802
+ this.closeModal();
29803
+ if (sFile) {
29804
+ this.openFile(sFile);
29805
+ if (this.editor && typeof this.editor.revealLineInCenter === 'function') {
29806
+ this.editor.revealLineInCenter(sLine);
29807
+ this.editor.setPosition({ lineNumber: sLine, column: sCol });
29808
+ this.editor.focus();
29809
+ }
29810
+ }
29811
+ return;
29812
+ }
29813
+
29283
29814
  const drawerTabBtn = e.target.closest('[data-cl-drawertab]');
29284
29815
  if (drawerTabBtn) {
29285
29816
  this.switchDrawerTab(drawerTabBtn.dataset.clDrawertab);
@@ -29288,8 +29819,9 @@ int main() {
29288
29819
 
29289
29820
  const actionBtn = e.target.closest('[data-cl-action], [data-action]');
29290
29821
  if (actionBtn) {
29291
- if (splitMenu && splitMenu.classList.contains('active')) {
29822
+ if (splitMenu && (splitMenu.classList.contains('active') || splitMenu.classList.contains('open'))) {
29292
29823
  splitMenu.classList.remove('active');
29824
+ splitMenu.classList.remove('open');
29293
29825
  }
29294
29826
  const action = actionBtn.dataset.clAction || actionBtn.dataset.action;
29295
29827
  if (action === 'run-code') this.runCode();
@@ -29392,9 +29924,49 @@ int main() {
29392
29924
  if (drawer) drawer.classList.toggle('is-minimized');
29393
29925
  if (this.editor) setTimeout(() => this.editor.layout(), 50);
29394
29926
  } else if (action === 'clear-terminal') {
29395
- this.terminalLogs = [];
29927
+ this._clearTerminalLogs();
29396
29928
  this.lastTestResults = [];
29397
29929
  this._renderDrawerBody();
29930
+ } else if (action === 'new-terminal-session') {
29931
+ this.createTerminalSession();
29932
+ if (this.drawerTab !== 'terminal') this.switchDrawerTab('terminal');
29933
+ } else if (action === 'switch-terminal-session') {
29934
+ const sid = actionBtn.dataset.sessionId;
29935
+ if (sid) this.switchTerminalSession(sid);
29936
+ } else if (action === 'close-terminal-session') {
29937
+ e.stopPropagation();
29938
+ const sid = actionBtn.dataset.sessionId;
29939
+ if (sid) this.closeTerminalSession(sid);
29940
+ } else if (action === 'scm-stage-file') {
29941
+ e.stopPropagation();
29942
+ const p = actionBtn.dataset.scmPath;
29943
+ if (p) {
29944
+ this.stageGitFile(p);
29945
+ this.showScmModal();
29946
+ }
29947
+ } else if (action === 'scm-unstage-file') {
29948
+ e.stopPropagation();
29949
+ const p = actionBtn.dataset.scmPath;
29950
+ if (p) {
29951
+ this.unstageGitFile(p);
29952
+ this.showScmModal();
29953
+ }
29954
+ } else if (action === 'scm-stage-all') {
29955
+ this.stageAllGitFiles();
29956
+ this.showScmModal();
29957
+ } else if (action === 'scm-commit') {
29958
+ const msgInput = this.container.querySelector('#cl-scm-commit-input');
29959
+ const msg = msgInput ? msgInput.value.trim() : '';
29960
+ if (msg) {
29961
+ this.commitGitChanges(msg);
29962
+ this.showScmModal();
29963
+ }
29964
+ } else if (action === 'scm-open-file') {
29965
+ const p = actionBtn.dataset.scmPath;
29966
+ this.closeModal();
29967
+ if (p && Object.prototype.hasOwnProperty.call(this.files, p)) {
29968
+ this.openFile(p);
29969
+ }
29398
29970
  } else if (action === 'toggle-hint') {
29399
29971
  const box = this.container.querySelector('#cl-hint-box');
29400
29972
  if (box) box.classList.toggle('open');
@@ -31038,6 +31610,7 @@ int main() {
31038
31610
  }
31039
31611
 
31040
31612
  async _handleReplCommand(cmd) {
31613
+ if (this.isRunning) return;
31041
31614
  const trimmed = (cmd || '').trim();
31042
31615
  if (!trimmed) return;
31043
31616
  if (this.replHistory[this.replHistory.length - 1] !== trimmed) {
@@ -31046,7 +31619,19 @@ int main() {
31046
31619
  this.replHistoryIdx = -1;
31047
31620
  const cwdShort = (this.cwd || '/workspace').replace(/^\/workspace\/?/, '') || '~';
31048
31621
  const promptPrefix = this.inRepl ? '> ' : `codelab:${cwdShort}$ `;
31049
- this.terminalLogs.push({ type: 'system', text: `${promptPrefix}${trimmed}` });
31622
+ const echoLine = `${promptPrefix}${trimmed}`;
31623
+ this.terminalLogs.push({ type: 'system', text: echoLine });
31624
+ if (this.terminalLogs.length > 2000) {
31625
+ this.terminalLogs.splice(0, this.terminalLogs.length - 2000);
31626
+ }
31627
+ const termLogEl = this.container ? this.container.querySelector('#cl-terminal-log') : null;
31628
+ const ptyOwnsDom = Boolean(this.ptyEngine && this.ptyEngine.container);
31629
+ if (termLogEl && typeof document !== 'undefined' && !ptyOwnsDom) {
31630
+ const echoEl = document.createElement('div');
31631
+ echoEl.className = 'codelab-log-line system';
31632
+ echoEl.innerHTML = ansiToHtml ? ansiToHtml(echoLine) : escapeHtml(echoLine);
31633
+ termLogEl.appendChild(echoEl);
31634
+ }
31050
31635
 
31051
31636
  if (this.inRepl) {
31052
31637
  if (trimmed === '.exit' || trimmed === 'exit') {
@@ -31056,7 +31641,7 @@ int main() {
31056
31641
  return;
31057
31642
  }
31058
31643
  if (trimmed === '.clear' || trimmed === 'clear') {
31059
- this.terminalLogs = [];
31644
+ this._clearTerminalLogs();
31060
31645
  this._renderDrawerBody();
31061
31646
  return;
31062
31647
  }
@@ -31109,7 +31694,7 @@ int main() {
31109
31694
  }
31110
31695
 
31111
31696
  if (trimmed === 'clear' || trimmed === 'cls') {
31112
- this.terminalLogs = [];
31697
+ this._clearTerminalLogs();
31113
31698
  this._renderDrawerBody();
31114
31699
  return;
31115
31700
  }
@@ -31169,7 +31754,7 @@ int main() {
31169
31754
  this._syncVfsSnapshot(null, true);
31170
31755
 
31171
31756
  if (shellRes && shellRes.clear) {
31172
- this.terminalLogs = [];
31757
+ this._clearTerminalLogs();
31173
31758
  this._renderDrawerBody();
31174
31759
  return;
31175
31760
  }
@@ -31382,6 +31967,10 @@ int main() {
31382
31967
  return bytes;
31383
31968
  }
31384
31969
 
31970
+ exportZip(options = {}) {
31971
+ return this.exportProjectZip(options);
31972
+ }
31973
+
31385
31974
  importProjectZip(zipBytes) {
31386
31975
  const zipMod = root.CodeLabZip;
31387
31976
  if (!zipMod || typeof zipMod.extractZip !== 'function') {
@@ -31394,6 +31983,42 @@ int main() {
31394
31983
  return true;
31395
31984
  }
31396
31985
 
31986
+ importZip(zipBytes) {
31987
+ return this.importProjectZip(zipBytes);
31988
+ }
31989
+
31990
+ async saveProjectToStorage(id) {
31991
+ if (!root.CodeLabStorage || typeof root.CodeLabStorage.createWorkspaceStorage !== 'function') {
31992
+ return false;
31993
+ }
31994
+ if (!this._idbStorage) {
31995
+ this._idbStorage = root.CodeLabStorage.createWorkspaceStorage();
31996
+ }
31997
+ const projectId = id || this.labId || 'workspace';
31998
+ return this._idbStorage.saveProject({
31999
+ id: projectId,
32000
+ name: this.title || projectId,
32001
+ files: { ...(this.files || {}) },
32002
+ updatedAt: Date.now()
32003
+ });
32004
+ }
32005
+
32006
+ async loadProjectFromStorage(id) {
32007
+ if (!root.CodeLabStorage || typeof root.CodeLabStorage.createWorkspaceStorage !== 'function') {
32008
+ return null;
32009
+ }
32010
+ if (!this._idbStorage) {
32011
+ this._idbStorage = root.CodeLabStorage.createWorkspaceStorage();
32012
+ }
32013
+ const projectId = id || this.labId || 'workspace';
32014
+ const loaded = await this._idbStorage.loadProject(projectId);
32015
+ if (loaded && loaded.files && typeof loaded.files === 'object') {
32016
+ this.setFiles(loaded.files);
32017
+ this._syncFilesToShellVfs();
32018
+ }
32019
+ return loaded;
32020
+ }
32021
+
31397
32022
  searchWorkspace(options) {
31398
32023
  const searchMod = root.CodeLabSearch;
31399
32024
  if (!searchMod || typeof searchMod.searchInFiles !== 'function') {
@@ -31407,21 +32032,113 @@ int main() {
31407
32032
  if (!searchMod || typeof searchMod.replaceInFiles !== 'function') {
31408
32033
  throw new Error('CodeLabSearch engine is not loaded');
31409
32034
  }
31410
- const res = searchMod.replaceInFiles(this.files || {}, options);
31411
- if (res && res.files && res.filesModified > 0) {
31412
- this.setFiles(res.files);
32035
+ const res = searchMod.replaceInFiles(this.files || {}, options, options && options.replacement);
32036
+ const nextFiles = res && (res.updatedFiles || res.files);
32037
+ const modifiedCount = res && (typeof res.filesModified === 'number' ? res.filesModified : (Array.isArray(res.filesAffected) ? res.filesAffected.length : 0));
32038
+ if (nextFiles && modifiedCount > 0) {
32039
+ this.setFiles(nextFiles);
31413
32040
  this._syncFilesToShellVfs();
31414
32041
  }
31415
32042
  return res;
31416
32043
  }
31417
32044
 
32045
+ _getGitState() {
32046
+ const scmMod = root.CodeLabScm;
32047
+ if (this.shell && this.shell.gitState) {
32048
+ return this.shell.gitState;
32049
+ }
32050
+ if (!this._gitState && scmMod && typeof scmMod.createGitState === 'function') {
32051
+ this._gitState = scmMod.createGitState(this.files || {});
32052
+ }
32053
+ return this._gitState || null;
32054
+ }
32055
+
31418
32056
  getGitStatus() {
31419
32057
  const scmMod = root.CodeLabScm;
31420
32058
  if (!scmMod || typeof scmMod.computeGitStatus !== 'function') {
31421
32059
  return [];
31422
32060
  }
31423
- const gs = (this.shell && this.shell.gitState) ? this.shell.gitState : scmMod.createGitState(this.files || {});
31424
- return scmMod.computeGitStatus(gs, this.files || {});
32061
+ const gs = this._getGitState() || scmMod.createGitState(this.files || {});
32062
+ const res = scmMod.computeGitStatus(this.files || {}, '/workspace', gs);
32063
+ return res && Array.isArray(res.entries) ? res.entries : (Array.isArray(res) ? res : []);
32064
+ }
32065
+
32066
+ stageGitFile(relPath) {
32067
+ if (!relPath) return false;
32068
+ const gs = this._getGitState();
32069
+ if (!gs) return false;
32070
+ const scmMod = root.CodeLabScm;
32071
+ if (gs.staged instanceof Set) {
32072
+ gs.staged.add(relPath);
32073
+ } else if (scmMod && typeof scmMod.stageFile === 'function') {
32074
+ const currentContent = Object.prototype.hasOwnProperty.call(this.files, relPath) ? this.files[relPath] : null;
32075
+ scmMod.stageFile(gs, relPath, currentContent);
32076
+ }
32077
+ return true;
32078
+ }
32079
+
32080
+ unstageGitFile(relPath) {
32081
+ if (!relPath) return false;
32082
+ const gs = this._getGitState();
32083
+ if (!gs || !gs.staged || typeof gs.staged.delete !== 'function') return false;
32084
+ gs.staged.delete(relPath);
32085
+ return true;
32086
+ }
32087
+
32088
+ stageAllGitFiles() {
32089
+ const entries = this.getGitStatus();
32090
+ for (const entry of entries) {
32091
+ if (!entry.staged) {
32092
+ this.stageGitFile(entry.path);
32093
+ }
32094
+ }
32095
+ return true;
32096
+ }
32097
+
32098
+ commitGitChanges(message) {
32099
+ const msg = typeof message === 'string' ? message.trim() : '';
32100
+ if (!msg) return null;
32101
+ const gs = this._getGitState();
32102
+ if (!gs) return null;
32103
+ const scmMod = root.CodeLabScm;
32104
+ if (gs.staged instanceof Set) {
32105
+ if (gs.staged.size === 0) return null;
32106
+ if (!gs.headSnapshot) gs.headSnapshot = {};
32107
+ for (const relPath of gs.staged) {
32108
+ if (Object.prototype.hasOwnProperty.call(this.files, relPath)) {
32109
+ gs.headSnapshot[relPath] = this.files[relPath];
32110
+ } else {
32111
+ delete gs.headSnapshot[relPath];
32112
+ }
32113
+ }
32114
+ gs.headFiles = Object.assign({}, gs.headSnapshot);
32115
+ const hash = scmMod && typeof scmMod.computeShortCommitHash === 'function'
32116
+ ? scmMod.computeShortCommitHash(`${gs.branch || 'main'}:${msg}:${Date.now()}`)
32117
+ : Math.random().toString(16).slice(2, 9);
32118
+ if (!Array.isArray(gs.commits)) gs.commits = [];
32119
+ gs.commits.unshift({
32120
+ hash,
32121
+ author: 'CodeLab Developer <dev@codelab.internal>',
32122
+ date: new Date().toUTCString(),
32123
+ timestamp: Date.now(),
32124
+ message: msg
32125
+ });
32126
+ gs.headCommit = hash;
32127
+ gs.staged.clear();
32128
+ this._syncFilesToShellVfs();
32129
+ return hash;
32130
+ }
32131
+ if (scmMod && typeof scmMod.commitChanges === 'function') {
32132
+ try {
32133
+ const hash = scmMod.commitChanges(gs, msg);
32134
+ if (gs.headFiles) gs.headSnapshot = Object.assign({}, gs.headFiles);
32135
+ this._syncFilesToShellVfs();
32136
+ return hash;
32137
+ } catch (_err) {
32138
+ return null;
32139
+ }
32140
+ }
32141
+ return null;
31425
32142
  }
31426
32143
 
31427
32144
  getDiagnostics() {
@@ -31439,12 +32156,20 @@ int main() {
31439
32156
  const slot = this.container ? this.container.querySelector('#cl-modal-slot') : null;
31440
32157
  if (!slot) return;
31441
32158
  const q = String(initialQuery || '');
31442
- const results = q ? this.searchWorkspace({ query: q }) : { matches: [], totalMatches: 0, filesMatched: 0 };
31443
- const rowsHtml = (results.matches || []).map((m) => `
31444
- <div class="codelab-search-match" data-cl-file="${escapeHtml(m.file)}" style="padding:6px 8px;border-bottom:1px solid var(--cl-border);cursor:pointer;font-family:var(--cl-font-mono);font-size:12px;">
31445
- <strong>${escapeHtml(m.file)}:${m.line}:${m.column}</strong> — <span>${escapeHtml(m.lineText)}</span>
31446
- </div>
31447
- `).join('');
32159
+ const renderRows = (queryText) => {
32160
+ const res = queryText ? this.searchWorkspace({ query: queryText }) : { matches: [], totalMatches: 0, filesMatched: 0 };
32161
+ if (!queryText) {
32162
+ return '<div style="color:var(--cl-fg-muted);font-size:12px;">Enter a query to search across workspace files.</div>';
32163
+ }
32164
+ if (!res.matches || res.matches.length === 0) {
32165
+ return '<div style="color:var(--cl-fg-muted);font-size:12px;">No matches found in workspace.</div>';
32166
+ }
32167
+ return res.matches.map((m) => `
32168
+ <div class="codelab-search-match" data-cl-file="${escapeHtml(m.file)}" data-cl-search-file="${escapeHtml(m.file)}" data-cl-search-line="${m.line || 1}" data-cl-search-col="${m.column || 1}" role="button" tabindex="0" style="padding:6px 8px;border-bottom:1px solid var(--cl-border);cursor:pointer;font-family:var(--cl-font-mono);font-size:12px;">
32169
+ <strong>${escapeHtml(m.file)}:${m.line}:${m.column}</strong> — <span>${escapeHtml(m.lineText)}</span>
32170
+ </div>
32171
+ `).join('');
32172
+ };
31448
32173
  slot.innerHTML = `
31449
32174
  <div class="codelab-modal-backdrop">
31450
32175
  <div class="codelab-modal" role="dialog" aria-modal="true" aria-label="Search Across Workspace">
@@ -31453,36 +32178,82 @@ int main() {
31453
32178
  <button type="button" class="codelab-btn" data-cl-action="close-modal">Close (Esc)</button>
31454
32179
  </div>
31455
32180
  <div class="codelab-modal__body">
31456
- <div style="display:flex;gap:8px;margin-bottom:8px;">
31457
- <input id="cl-search-query-input" type="text" value="${escapeHtml(q)}" placeholder="Search text or regex..." style="flex:1;padding:6px 8px;" />
31458
- <input id="cl-search-replace-input" type="text" placeholder="Replace with..." style="flex:1;padding:6px 8px;" />
32181
+ <div style="display:flex;gap:8px;margin-bottom:8px;align-items:center;">
32182
+ <input id="cl-search-query-input" class="codelab-modal-input" type="text" value="${escapeHtml(q)}" placeholder="Search text or regex..." />
32183
+ <input id="cl-search-replace-input" class="codelab-modal-input" type="text" placeholder="Replace with..." />
32184
+ <button type="button" id="cl-search-replace-all-btn" class="codelab-btn codelab-btn--primary" style="padding:5px 10px;font-size:12px;white-space:nowrap;">Replace All</button>
31459
32185
  </div>
31460
- <div id="cl-search-results-list">${rowsHtml || '<div style="color:var(--cl-fg-muted);font-size:12px;">Enter a query to search across workspace files.</div>'}</div>
32186
+ <div id="cl-search-results-list" style="max-height:320px;overflow-y:auto;">${renderRows(q)}</div>
31461
32187
  </div>
31462
32188
  </div>
31463
32189
  </div>
31464
32190
  `;
32191
+ const queryInput = slot.querySelector('#cl-search-query-input');
32192
+ const replaceInput = slot.querySelector('#cl-search-replace-input');
32193
+ const replaceBtn = slot.querySelector('#cl-search-replace-all-btn');
32194
+ const listEl = slot.querySelector('#cl-search-results-list');
32195
+ if (queryInput && listEl) {
32196
+ queryInput.addEventListener('input', () => {
32197
+ listEl.innerHTML = renderRows(queryInput.value || '');
32198
+ });
32199
+ if (typeof queryInput.focus === 'function') queryInput.focus();
32200
+ }
32201
+ if (replaceBtn && queryInput && replaceInput && listEl) {
32202
+ const triggerReplace = () => {
32203
+ const queryVal = queryInput.value || '';
32204
+ if (!queryVal) return;
32205
+ this.replaceInWorkspace({ query: queryVal, replacement: replaceInput.value || '' });
32206
+ listEl.innerHTML = renderRows(queryVal);
32207
+ };
32208
+ replaceBtn.addEventListener('click', triggerReplace);
32209
+ replaceInput.addEventListener('keydown', (e) => {
32210
+ if (e.key === 'Enter') {
32211
+ e.preventDefault();
32212
+ triggerReplace();
32213
+ }
32214
+ });
32215
+ }
31465
32216
  }
31466
32217
 
31467
32218
  showScmModal() {
31468
32219
  const slot = this.container ? this.container.querySelector('#cl-modal-slot') : null;
31469
32220
  if (!slot) return;
31470
32221
  const statusList = this.getGitStatus();
31471
- const rowsHtml = statusList.map((entry) => `
31472
- <div class="codelab-scm-entry" data-scm-path="${escapeHtml(entry.path)}" style="display:flex;justify-content:space-between;padding:6px 8px;border-bottom:1px solid var(--cl-border);font-family:var(--cl-font-mono);font-size:12px;">
31473
- <span>${escapeHtml(entry.path)}</span>
31474
- <span>${escapeHtml(entry.worktree !== ' ' ? entry.worktree : entry.index)}</span>
31475
- </div>
31476
- `).join('');
32222
+ const gs = this._getGitState();
32223
+ const branch = (gs && gs.branch) ? gs.branch : 'main';
32224
+ const hasStaged = statusList.some((e) => e.staged);
32225
+ const hasUnstaged = statusList.some((e) => !e.staged);
32226
+ const rowsHtml = statusList.map((entry) => {
32227
+ const badge = entry.staged ? `Staged (${entry.index})` : (entry.worktree !== ' ' ? entry.worktree : entry.index);
32228
+ const actionBtn = entry.staged
32229
+ ? `<button type="button" class="codelab-btn" data-cl-action="scm-unstage-file" data-scm-path="${escapeHtml(entry.path)}" style="padding:2px 8px;font-size:11px;">Unstage</button>`
32230
+ : `<button type="button" class="codelab-btn" data-cl-action="scm-stage-file" data-scm-path="${escapeHtml(entry.path)}" style="padding:2px 8px;font-size:11px;">Stage</button>`;
32231
+ return `
32232
+ <div class="codelab-scm-entry" data-scm-path="${escapeHtml(entry.path)}" style="display:flex;justify-content:space-between;align-items:center;padding:6px 8px;border-bottom:1px solid var(--cl-border);font-family:var(--cl-font-mono);font-size:12px;">
32233
+ <span data-cl-action="scm-open-file" data-scm-path="${escapeHtml(entry.path)}" style="cursor:pointer;text-decoration:underline;">${escapeHtml(entry.path)}</span>
32234
+ <span style="display:inline-flex;align-items:center;gap:8px;">
32235
+ <span>${escapeHtml(badge)}</span>
32236
+ ${actionBtn}
32237
+ </span>
32238
+ </div>
32239
+ `;
32240
+ }).join('');
31477
32241
  slot.innerHTML = `
31478
32242
  <div class="codelab-modal-backdrop">
31479
32243
  <div class="codelab-modal" role="dialog" aria-modal="true" aria-label="Source Control">
31480
32244
  <div class="codelab-modal__header">
31481
- <span>Source Control (Git Status)</span>
31482
- <button type="button" class="codelab-btn" data-cl-action="close-modal">Close (Esc)</button>
32245
+ <span>Source Control (Git Status · ${escapeHtml(branch)})</span>
32246
+ <div style="display:flex;gap:6px;align-items:center;">
32247
+ ${hasUnstaged ? `<button type="button" class="codelab-btn" data-cl-action="scm-stage-all" style="padding:3px 8px;font-size:11px;">Stage All</button>` : ''}
32248
+ <button type="button" class="codelab-btn" data-cl-action="close-modal">Close (Esc)</button>
32249
+ </div>
31483
32250
  </div>
31484
32251
  <div class="codelab-modal__body">
31485
- <div id="cl-scm-status-list">${rowsHtml || '<div style="color:var(--cl-fg-muted);font-size:12px;">Working tree clean</div>'}</div>
32252
+ <div style="display:flex;gap:8px;margin-bottom:8px;align-items:center;">
32253
+ <input id="cl-scm-commit-input" class="codelab-modal-input" type="text" placeholder="Commit message (e.g. feat: update module)..." />
32254
+ <button type="button" id="cl-scm-commit-btn" class="codelab-btn codelab-btn--primary" data-cl-action="scm-commit" ${hasStaged ? '' : 'disabled'} style="padding:5px 10px;font-size:12px;white-space:nowrap;">Commit</button>
32255
+ </div>
32256
+ <div id="cl-scm-status-list" style="max-height:300px;overflow-y:auto;">${rowsHtml || '<div style="color:var(--cl-fg-muted);font-size:12px;">Working tree clean</div>'}</div>
31486
32257
  </div>
31487
32258
  </div>
31488
32259
  </div>
@@ -31494,11 +32265,14 @@ int main() {
31494
32265
  const slot = this.container ? this.container.querySelector('#cl-modal-slot') : null;
31495
32266
  if (!slot) return;
31496
32267
  const items = this.getDiagnostics();
31497
- const rowsHtml = items.map((d) => `
31498
- <div class="codelab-problem-entry" data-problem-file="${escapeHtml(d.file)}" style="padding:6px 8px;border-bottom:1px solid var(--cl-border);font-family:var(--cl-font-mono);font-size:12px;">
31499
- <strong>[${escapeHtml(d.severity)}] ${escapeHtml(d.file)}:${d.line}:${d.column}</strong> — ${escapeHtml(d.message)}
31500
- </div>
31501
- `).join('');
32268
+ const rowsHtml = items.map((d) => {
32269
+ const col = d.col || d.column || 1;
32270
+ return `
32271
+ <div class="codelab-problem-entry" data-problem-file="${escapeHtml(d.file || '')}" data-cl-problem-file="${escapeHtml(d.file || '')}" data-cl-problem-line="${d.line || 1}" data-cl-problem-col="${col}" role="button" tabindex="0" style="padding:6px 8px;border-bottom:1px solid var(--cl-border);cursor:pointer;font-family:var(--cl-font-mono);font-size:12px;">
32272
+ <strong>[${escapeHtml(d.severity)}] ${escapeHtml(d.file || '')}:${d.line || 1}:${col}</strong> — ${escapeHtml(d.message || '')}
32273
+ </div>
32274
+ `;
32275
+ }).join('');
31502
32276
  slot.innerHTML = `
31503
32277
  <div class="codelab-modal-backdrop">
31504
32278
  <div class="codelab-modal" role="dialog" aria-modal="true" aria-label="Problems and Diagnostics">
@@ -31514,6 +32288,40 @@ int main() {
31514
32288
  `;
31515
32289
  }
31516
32290
 
32291
+ _clearTerminalLogs() {
32292
+ if (Array.isArray(this.terminalLogs)) {
32293
+ this.terminalLogs.length = 0;
32294
+ } else {
32295
+ this.terminalLogs = [];
32296
+ }
32297
+ if (Array.isArray(this._terminalSessions)) {
32298
+ const active = this._terminalSessions.find((s) => s.id === this._activeTerminalSessionId);
32299
+ if (active) {
32300
+ active.logs = this.terminalLogs;
32301
+ }
32302
+ }
32303
+ }
32304
+
32305
+ _renderTerminalSessionsBar() {
32306
+ if (!this.container || typeof this.container.querySelector !== 'function') return;
32307
+ const bar = this.container.querySelector('#cl-terminal-sessions');
32308
+ if (!bar) return;
32309
+ const sessions = this._ensureTerminalSessions();
32310
+ if (sessions.length <= 1) {
32311
+ bar.innerHTML = '';
32312
+ return;
32313
+ }
32314
+ bar.innerHTML = sessions.map((s) => {
32315
+ const isActive = s.id === this._activeTerminalSessionId;
32316
+ return `
32317
+ <span class="codelab-session-pill ${isActive ? 'active' : ''}" data-cl-action="switch-terminal-session" data-session-id="${escapeHtml(s.id)}" role="button" tabindex="0" title="Switch to ${escapeHtml(s.name)}">
32318
+ <span>${escapeHtml(s.name)}</span>
32319
+ <span data-cl-action="close-terminal-session" data-session-id="${escapeHtml(s.id)}" title="Close session" style="margin-left:2px;opacity:0.75;">&times;</span>
32320
+ </span>
32321
+ `;
32322
+ }).join('');
32323
+ }
32324
+
31517
32325
  _ensureTerminalSessions() {
31518
32326
  if (!Array.isArray(this._terminalSessions) || this._terminalSessions.length === 0) {
31519
32327
  this._terminalSessions = [
@@ -31926,6 +32734,13 @@ int main() {
31926
32734
  this._editorResizeObserver.disconnect();
31927
32735
  this._editorResizeObserver = null;
31928
32736
  }
32737
+ if (this._diffManager && typeof this._diffManager.closeInlineDiff === 'function') {
32738
+ try {
32739
+ this._diffManager.closeInlineDiff();
32740
+ } catch (err) {
32741
+ this.logger.debug('diffManager.closeInlineDiff failed during destroy.', err);
32742
+ }
32743
+ }
31929
32744
  if (this.editor) {
31930
32745
  this.editor.dispose();
31931
32746
  this.editor = null;
@@ -41369,12 +42184,19 @@ inline void assertBool(bool cond, bool expected, const char* expr, int line) {
41369
42184
  const db = await openToolchainIdb();
41370
42185
  if (!db) return null;
41371
42186
  return new Promise((resolve) => {
42187
+ const closeDb = () => {
42188
+ try {
42189
+ db.close();
42190
+ } catch (err) {
42191
+ }
42192
+ };
41372
42193
  try {
41373
42194
  const tx = db.transaction(IDB_STORE, "readonly");
41374
42195
  const store = tx.objectStore(IDB_STORE);
41375
42196
  const req = store.get(key);
41376
42197
  req.onsuccess = () => {
41377
42198
  const val = req.result;
42199
+ closeDb();
41378
42200
  if (val instanceof Uint8Array) {
41379
42201
  memoryAssetCache.set(key, val);
41380
42202
  resolve(val);
@@ -41386,8 +42208,12 @@ inline void assertBool(bool cond, bool expected, const char* expr, int line) {
41386
42208
  resolve(null);
41387
42209
  }
41388
42210
  };
41389
- req.onerror = () => resolve(null);
42211
+ req.onerror = () => {
42212
+ closeDb();
42213
+ resolve(null);
42214
+ };
41390
42215
  } catch (err) {
42216
+ closeDb();
41391
42217
  if (err) resolve(null);
41392
42218
  }
41393
42219
  });
@@ -41397,13 +42223,26 @@ inline void assertBool(bool cond, bool expected, const char* expr, int line) {
41397
42223
  const db = await openToolchainIdb();
41398
42224
  if (!db) return;
41399
42225
  return new Promise((resolve) => {
42226
+ const closeDb = () => {
42227
+ try {
42228
+ db.close();
42229
+ } catch (err) {
42230
+ }
42231
+ };
41400
42232
  try {
41401
42233
  const tx = db.transaction(IDB_STORE, "readwrite");
41402
42234
  const store = tx.objectStore(IDB_STORE);
41403
42235
  store.put(data, key);
41404
- tx.oncomplete = () => resolve();
41405
- tx.onerror = () => resolve();
42236
+ tx.oncomplete = () => {
42237
+ closeDb();
42238
+ resolve();
42239
+ };
42240
+ tx.onerror = () => {
42241
+ closeDb();
42242
+ resolve();
42243
+ };
41406
42244
  } catch (err) {
42245
+ closeDb();
41407
42246
  if (err) resolve();
41408
42247
  }
41409
42248
  });
@@ -41425,15 +42264,19 @@ inline void assertBool(bool cond, bool expected, const char* expr, int line) {
41425
42264
  continue;
41426
42265
  }
41427
42266
  const sizeOctal = readString(offset + 124, 12);
41428
- const size = parseInt(sizeOctal || "0", 8) || 0;
42267
+ const size = Math.max(0, parseInt(sizeOctal || "0", 8) || 0);
41429
42268
  const typeFlag = tarBytes[offset + 156];
41430
42269
  const prefix = readString(offset + 345, 155);
41431
42270
  const fullName = prefix ? `${prefix}/${name}` : name;
41432
- const cleanRel = fullName.replace(/^\.?\/+/, "");
41433
- const targetPath = baseDir === "/" ? `/${cleanRel}` : `${baseDir.replace(/\/+$/, "")}/${cleanRel}`;
42271
+ const rawRel = fullName.replace(/^\.?\/+/, "");
42272
+ const rawSegments = rawRel.split("/").filter(Boolean);
42273
+ const hasDotDot = rawSegments.some((seg) => seg === "..");
42274
+ const cleanRel = hasDotDot ? "" : rawSegments.filter((seg) => seg !== ".").join("/");
42275
+ const cleanBase = baseDir === "/" ? "" : baseDir.replace(/\/+$/, "");
42276
+ const targetPath = `${cleanBase}/${cleanRel}`;
41434
42277
  const dataStart = offset + 512;
41435
- const dataEnd = dataStart + size;
41436
- if (cleanRel) {
42278
+ const dataEnd = Math.min(tarBytes.length, dataStart + size);
42279
+ if (cleanRel && !hasDotDot) {
41437
42280
  if (typeFlag === 53 || fullName.endsWith("/")) {
41438
42281
  if (!vfs.existsSync(targetPath)) {
41439
42282
  vfs.mkdirSync(targetPath, { recursive: true });
@@ -41885,10 +42728,22 @@ inline void assertBool(bool cond, bool expected, const char* expr, int line) {
41885
42728
  percent: 100,
41886
42729
  message: `Compiling ${sourceFiles.map((s) => s.split("/").pop()).join(", ")} with Clang (${std}, ${optLevel})...`
41887
42730
  });
42731
+ const buildDir = `/tmp/build_${Date.now()}_${Math.random().toString(36).slice(2, 6)}`;
42732
+ if (!vfs.existsSync(buildDir)) {
42733
+ vfs.mkdirSync(buildDir, { recursive: true });
42734
+ }
42735
+ const cleanupBuildDir = () => {
42736
+ try {
42737
+ if (typeof vfs.rmSync === "function") {
42738
+ vfs.rmSync(buildDir, { recursive: true, force: true });
42739
+ }
42740
+ } catch (err) {
42741
+ }
42742
+ };
41888
42743
  const objectFiles = [];
41889
42744
  for (let i = 0; i < sourceFiles.length; i++) {
41890
42745
  const srcPath = sourceFiles[i];
41891
- const objPath = `/tmp/obj_${i}.o`;
42746
+ const objPath = `${buildDir}/obj_${i}.o`;
41892
42747
  objectFiles.push(objPath);
41893
42748
  const clangArgs = [
41894
42749
  "clang++",
@@ -41923,6 +42778,7 @@ inline void assertBool(bool cond, bool expected, const char* expr, int line) {
41923
42778
  onStderr: handleErr
41924
42779
  });
41925
42780
  if (compileStep.exitCode !== 0) {
42781
+ cleanupBuildDir();
41926
42782
  return {
41927
42783
  ok: false,
41928
42784
  exitCode: compileStep.exitCode,
@@ -41962,6 +42818,7 @@ inline void assertBool(bool cond, bool expected, const char* expr, int line) {
41962
42818
  onStdout: handleOut,
41963
42819
  onStderr: handleErr
41964
42820
  });
42821
+ cleanupBuildDir();
41965
42822
  if (linkStep.exitCode !== 0 || !vfs.existsSync(outputPath)) {
41966
42823
  return {
41967
42824
  ok: false,
@@ -47984,68 +48841,73 @@ assert_false = ASSERT_FALSE
47984
48841
  if (this.pyodide) return this.pyodide;
47985
48842
  if (this._loadingPromise) return this._loadingPromise;
47986
48843
  this._loadingPromise = (async () => {
47987
- this._emitProgress({
47988
- stage: "downloading",
47989
- percent: 10,
47990
- message: "Initializing CPython 3.12 WebAssembly (Pyodide)..."
47991
- });
47992
- if (typeof window !== "undefined") {
47993
- const cdn = this.options.cdnBaseUrl || DEFAULT_PYTHON_CDN_BASE_URL;
47994
- if (!window.loadPyodide) {
47995
- await new Promise((resolve, reject) => {
47996
- const script = document.createElement("script");
47997
- script.src = `${cdn.replace(/\/+$/, "")}/pyodide.js`;
47998
- script.onload = () => resolve();
47999
- script.onerror = () => reject(new Error(`Failed to load pyodide.js from ${script.src}`));
48000
- document.head.appendChild(script);
48001
- });
48002
- }
48844
+ try {
48003
48845
  this._emitProgress({
48004
- stage: "extracting",
48005
- percent: 50,
48006
- message: "Bootstrapping Python runtime environment..."
48846
+ stage: "downloading",
48847
+ percent: 10,
48848
+ message: "Initializing CPython 3.12 WebAssembly (Pyodide)..."
48007
48849
  });
48008
- const loadPyodideFn = window.loadPyodide;
48009
- this.pyodide = await loadPyodideFn({
48010
- indexURL: cdn
48011
- });
48012
- } else {
48013
- this.pyodide = {
48014
- FS: {
48015
- files: /* @__PURE__ */ new Map(),
48016
- writeFile(p, content) {
48017
- this.files.set(p, typeof content === "string" ? content : String(content));
48018
- },
48019
- readFile(p, opts) {
48020
- return this.files.get(p) || "";
48021
- },
48022
- unlink(p) {
48023
- this.files.delete(p);
48850
+ if (typeof window !== "undefined") {
48851
+ const cdn = this.options.cdnBaseUrl || DEFAULT_PYTHON_CDN_BASE_URL;
48852
+ if (!window.loadPyodide) {
48853
+ await new Promise((resolve, reject) => {
48854
+ const script = document.createElement("script");
48855
+ script.src = `${cdn.replace(/\/+$/, "")}/pyodide.js`;
48856
+ script.onload = () => resolve();
48857
+ script.onerror = () => reject(new Error(`Failed to load pyodide.js from ${script.src}`));
48858
+ document.head.appendChild(script);
48859
+ });
48860
+ }
48861
+ this._emitProgress({
48862
+ stage: "extracting",
48863
+ percent: 50,
48864
+ message: "Bootstrapping Python runtime environment..."
48865
+ });
48866
+ const loadPyodideFn = window.loadPyodide;
48867
+ this.pyodide = await loadPyodideFn({
48868
+ indexURL: cdn
48869
+ });
48870
+ } else {
48871
+ this.pyodide = {
48872
+ FS: {
48873
+ files: /* @__PURE__ */ new Map(),
48874
+ writeFile(p, content) {
48875
+ this.files.set(p, typeof content === "string" ? content : String(content));
48876
+ },
48877
+ readFile(p, opts) {
48878
+ return this.files.get(p) || "";
48879
+ },
48880
+ unlink(p) {
48881
+ this.files.delete(p);
48882
+ },
48883
+ mkdirTree(_p) {
48884
+ }
48024
48885
  },
48025
- mkdirTree(_p) {
48886
+ runPythonAsync: async (code) => {
48887
+ return `Execution mock: ${code.slice(0, 30)}`;
48026
48888
  }
48027
- },
48028
- runPythonAsync: async (code) => {
48029
- return `Execution mock: ${code.slice(0, 30)}`;
48030
- }
48031
- };
48032
- }
48033
- if (this.options.preloadPackages && Array.isArray(this.options.preloadPackages)) {
48034
- for (const pkg of this.options.preloadPackages) {
48035
- try {
48036
- if (typeof this.pyodide.loadPackage === "function") {
48037
- await this.pyodide.loadPackage(pkg);
48889
+ };
48890
+ }
48891
+ if (this.options.preloadPackages && Array.isArray(this.options.preloadPackages)) {
48892
+ for (const pkg of this.options.preloadPackages) {
48893
+ try {
48894
+ if (typeof this.pyodide.loadPackage === "function") {
48895
+ await this.pyodide.loadPackage(pkg);
48896
+ }
48897
+ } catch (err) {
48038
48898
  }
48039
- } catch (err) {
48040
48899
  }
48041
48900
  }
48901
+ this._emitProgress({
48902
+ stage: "ready",
48903
+ percent: 100,
48904
+ message: "Python 3.12 WebAssembly Toolchain Ready"
48905
+ });
48906
+ return this.pyodide;
48907
+ } catch (err) {
48908
+ this._loadingPromise = null;
48909
+ throw err;
48042
48910
  }
48043
- this._emitProgress({
48044
- stage: "ready",
48045
- percent: 100,
48046
- message: "Python 3.12 WebAssembly Toolchain Ready"
48047
- });
48048
- return this.pyodide;
48049
48911
  })();
48050
48912
  return this._loadingPromise;
48051
48913
  }
@@ -48089,18 +48951,34 @@ assert_false = ASSERT_FALSE
48089
48951
  };
48090
48952
  const pyodide = await this.ensureLoaded();
48091
48953
  if (req.vfs && pyodide.FS) {
48092
- try {
48093
- const vfsEntries = req.vfs.readdirSync("/workspace", { recursive: true });
48094
- for (const entry of vfsEntries) {
48095
- const fullPath = `/workspace/${entry}`;
48096
- if (!req.vfs.statSync(fullPath).isDirectory()) {
48097
- const content = req.vfs.readFileSync(fullPath, "utf8");
48098
- pyodide.FS.mkdirTree("/workspace");
48099
- pyodide.FS.writeFile(fullPath, content);
48954
+ const syncVfsDir = (dirPath) => {
48955
+ try {
48956
+ if (typeof pyodide.FS.mkdirTree === "function") {
48957
+ pyodide.FS.mkdirTree(dirPath);
48100
48958
  }
48959
+ const entries = req.vfs.readdirSync(dirPath);
48960
+ for (const entry of entries) {
48961
+ if (!entry || entry === "." || entry === "..") continue;
48962
+ const fullPath = `${dirPath === "/" ? "" : dirPath}/${entry}`;
48963
+ try {
48964
+ const st = req.vfs.statSync(fullPath);
48965
+ if (st && typeof st.isDirectory === "function" && st.isDirectory()) {
48966
+ syncVfsDir(fullPath);
48967
+ } else {
48968
+ const parentDir = fullPath.slice(0, fullPath.lastIndexOf("/")) || "/workspace";
48969
+ if (typeof pyodide.FS.mkdirTree === "function") {
48970
+ pyodide.FS.mkdirTree(parentDir);
48971
+ }
48972
+ const content = req.vfs.readFileSync(fullPath, "utf8");
48973
+ pyodide.FS.writeFile(fullPath, content);
48974
+ }
48975
+ } catch (err) {
48976
+ }
48977
+ }
48978
+ } catch (err) {
48101
48979
  }
48102
- } catch (err) {
48103
- }
48980
+ };
48981
+ syncVfsDir("/workspace");
48104
48982
  }
48105
48983
  if (pyodide.FS) {
48106
48984
  try {
@@ -48146,45 +49024,19 @@ assert_false = ASSERT_FALSE
48146
49024
  }
48147
49025
  });
48148
49026
  }
48149
- const rawLines = codeToRun.split("\n");
48150
- const futureImports = [];
48151
- const bodyLines = [];
48152
- let inDocstring = false;
48153
- let docChar = "";
48154
- for (const l of rawLines) {
48155
- const t = l.trim();
48156
- if (!inDocstring && (t.startsWith('"""') || t.startsWith("'''"))) {
48157
- if (t.length > 3 && (t.endsWith('"""') || t.endsWith("'''"))) {
48158
- bodyLines.push(l);
48159
- continue;
48160
- }
48161
- inDocstring = true;
48162
- docChar = t.slice(0, 3);
48163
- bodyLines.push(l);
48164
- continue;
48165
- }
48166
- if (inDocstring) {
48167
- if (t.endsWith(docChar)) inDocstring = false;
48168
- bodyLines.push(l);
48169
- continue;
48170
- }
48171
- if (/^from\s+__future__\s+import\s+/.test(t)) {
48172
- futureImports.push(t);
48173
- } else {
48174
- bodyLines.push(l);
48175
- }
48176
- }
49027
+ const fileLabel = JSON.stringify(req.entry || "<exec>");
49028
+ const encodedCode = JSON.stringify(codeToRun);
48177
49029
  const runnerWrapper = `
48178
- ${futureImports.join("\n")}
48179
49030
  import sys, tracemalloc
48180
49031
  if '/usr/lib/python' not in sys.path:
48181
49032
  sys.path.insert(0, '/usr/lib/python')
48182
49033
  if '/workspace' not in sys.path:
48183
49034
  sys.path.insert(0, '/workspace')
48184
49035
 
49036
+ _cl_user_code = ${encodedCode}
48185
49037
  tracemalloc.start()
48186
49038
  try:
48187
- ${bodyLines.map((l) => " " + l).join("\n")}
49039
+ exec(compile(_cl_user_code, ${fileLabel}, 'exec'), globals())
48188
49040
  finally:
48189
49041
  _, _peak = tracemalloc.get_traced_memory()
48190
49042
  tracemalloc.stop()
@@ -48227,20 +49079,38 @@ finally:
48227
49079
  }
48228
49080
  }
48229
49081
  if (req.vfs && pyodide.FS && typeof pyodide.FS.readdir === "function") {
48230
- try {
48231
- const files = pyodide.FS.readdir("/workspace");
48232
- for (const f of files) {
48233
- if (f !== "." && f !== "..") {
48234
- const p = `/workspace/${f}`;
49082
+ const syncBackPyodideDir = (dirPath) => {
49083
+ try {
49084
+ const entries = pyodide.FS.readdir(dirPath);
49085
+ for (const f of entries) {
49086
+ if (!f || f === "." || f === "..") continue;
49087
+ const p = `${dirPath}/${f}`;
48235
49088
  try {
48236
- const content = pyodide.FS.readFile(p, { encoding: "utf8" });
48237
- req.vfs.writeFileSync(p, content);
49089
+ let isDir = false;
49090
+ if (typeof pyodide.FS.stat === "function" && typeof pyodide.FS.isDir === "function") {
49091
+ const st = pyodide.FS.stat(p);
49092
+ isDir = Boolean(pyodide.FS.isDir(st.mode));
49093
+ }
49094
+ if (isDir) {
49095
+ if (typeof req.vfs.mkdirSync === "function" && !req.vfs.existsSync(p)) {
49096
+ req.vfs.mkdirSync(p, { recursive: true });
49097
+ }
49098
+ syncBackPyodideDir(p);
49099
+ } else {
49100
+ const parentDir = p.slice(0, p.lastIndexOf("/")) || "/workspace";
49101
+ if (typeof req.vfs.mkdirSync === "function" && !req.vfs.existsSync(parentDir)) {
49102
+ req.vfs.mkdirSync(parentDir, { recursive: true });
49103
+ }
49104
+ const content = pyodide.FS.readFile(p, { encoding: "utf8" });
49105
+ req.vfs.writeFileSync(p, content);
49106
+ }
48238
49107
  } catch (err) {
48239
49108
  }
48240
49109
  }
49110
+ } catch (err) {
48241
49111
  }
48242
- } catch (err) {
48243
- }
49112
+ };
49113
+ syncBackPyodideDir("/workspace");
48244
49114
  }
48245
49115
  const durationMs = performance.now() - start;
48246
49116
  return {