@innovatorved/code-lab 0.4.0 → 0.6.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (82) hide show
  1. package/ARCHITECTURE.md +4 -4
  2. package/CHANGELOG.md +36 -0
  3. package/README.md +6 -30
  4. package/dist/code-lab-sql.esm.js +1 -1
  5. package/dist/code-lab-sql.umd.js +2 -2
  6. package/dist/code-lab.css +32 -5818
  7. package/dist/code-lab.d.ts +1 -1
  8. package/dist/code-lab.esm.js +4655 -64400
  9. package/dist/code-lab.js +4540 -64286
  10. package/dist/code-lab.umd.js +4540 -64286
  11. package/dist/diagnostics.d.ts +3 -0
  12. package/dist/extensions/cpp.d.ts +2 -2
  13. package/dist/extensions/cpp.esm.js +1804 -14725
  14. package/dist/extensions/cpp.js +1804 -14725
  15. package/dist/extensions/guided-lab.esm.js +2938 -16127
  16. package/dist/extensions/guided-lab.js +2938 -16127
  17. package/dist/extensions/python.d.ts +2 -2
  18. package/dist/extensions/python.esm.js +1765 -14698
  19. package/dist/extensions/python.js +1765 -14698
  20. package/dist/index.d.ts +1 -1
  21. package/dist/packages/settings/src/configuration-service.d.ts +7 -0
  22. package/dist/packages/settings/src/index.d.ts +1 -1
  23. package/dist/packages/ui/src/index.d.ts +2 -2
  24. package/dist/packages/ui/src/plugin-registry.d.ts +1 -0
  25. package/dist/packages/ui/src/settings-dialog.d.ts +31 -3
  26. package/dist/packages/ui/src/themes.d.ts +5 -0
  27. package/dist/preview-sw.js +4 -188
  28. package/dist/runtime.esm.js +109 -10284
  29. package/dist/runtime.js +107 -10284
  30. package/dist/schemas.d.ts +2 -2
  31. package/dist/schemas.esm.js +2938 -16127
  32. package/dist/schemas.js +2941 -16130
  33. package/dist/scm.d.ts +296 -14
  34. package/dist/shell.esm.js +811 -9178
  35. package/dist/shell.js +811 -9178
  36. package/dist/storage.d.ts +56 -0
  37. package/dist/terminal.esm.js +20 -1347
  38. package/dist/terminal.js +20 -1347
  39. package/dist/workbench/command-palette.d.ts +16 -1
  40. package/dist/workbench/diff-editor.d.ts +27 -1
  41. package/dist/workbench/icons.d.ts +6 -2
  42. package/dist/workbench/index.d.ts +33 -1
  43. package/dist/workbench/intellisense.d.ts +194 -0
  44. package/dist/workbench/styles.d.ts +1 -1
  45. package/dist/workbench/xterm-adapter.d.ts +122 -0
  46. package/package.json +8 -2
  47. package/packages/commands/package.json +1 -1
  48. package/packages/core/package.json +1 -1
  49. package/packages/editor/package.json +1 -1
  50. package/packages/fs/package.json +1 -1
  51. package/packages/preview/package.json +1 -1
  52. package/packages/runtime/package.json +1 -1
  53. package/packages/settings/package.json +1 -1
  54. package/packages/settings/src/builtin-schemas.ts +17 -6
  55. package/packages/settings/src/configuration-service.ts +72 -6
  56. package/packages/settings/src/index.ts +1 -0
  57. package/packages/sql/package.json +1 -1
  58. package/packages/terminal/package.json +1 -1
  59. package/packages/ui/package.json +1 -1
  60. package/packages/ui/src/index.ts +4 -0
  61. package/packages/ui/src/plugin-registry.ts +17 -2
  62. package/packages/ui/src/settings-dialog.ts +393 -99
  63. package/packages/ui/src/themes.ts +183 -24
  64. package/src/code-lab.css +2763 -444
  65. package/src/diagnostics.ts +139 -7
  66. package/src/extensions/cpp.ts +337 -71
  67. package/src/extensions/python.ts +375 -75
  68. package/src/index.ts +1 -1
  69. package/src/runtime.ts +272 -43
  70. package/src/schemas.ts +2 -2
  71. package/src/scm.ts +2172 -74
  72. package/src/shell.ts +1999 -193
  73. package/src/storage.ts +401 -5
  74. package/src/terminal.ts +148 -12
  75. package/src/workbench/command-palette.ts +289 -48
  76. package/src/workbench/diff-editor.ts +240 -78
  77. package/src/workbench/icons.ts +250 -46
  78. package/src/workbench/index.ts +7 -1
  79. package/src/workbench/intellisense.ts +1859 -0
  80. package/src/workbench/styles.ts +25 -19
  81. package/src/workbench/xterm-adapter.ts +1566 -0
  82. package/src/workbench.ts +13446 -3881
@@ -410,19 +410,108 @@ export const PYTHON_COMPLETIONS_AND_HOVERS: Record<string, PythonSymbolDoc> = {
410
410
  }
411
411
  };
412
412
 
413
- let _monacoPyRegistered = false;
413
+ let _pyWorkspaceFilesGetter: (() => Record<string, string>) | null = null;
414
+ const _monacoPyInstances = new WeakSet<object>();
415
+
416
+ function collectWorkspacePythonSymbols(currentModelValue: string, currentUriPath = 'main.py') {
417
+ const files: Record<string, string> = _pyWorkspaceFilesGetter ? { ...(_pyWorkspaceFilesGetter() || {}) } : {};
418
+ const cleanCurrent = String(currentUriPath || 'main.py').replace(/^file:\/\/\/workspace\//, '').replace(/^\/workspace\//, '').replace(/^\/+/, '') || 'main.py';
419
+ if (currentModelValue) {
420
+ files[cleanCurrent] = currentModelValue;
421
+ }
422
+
423
+ const defs: Array<{
424
+ name: string;
425
+ kind: 'function' | 'class' | 'method' | 'module';
426
+ detail: string;
427
+ doc: string;
428
+ params: string[];
429
+ file: string;
430
+ line: number;
431
+ col: number;
432
+ }> = [];
433
+
434
+ for (const [filePath, src] of Object.entries(files)) {
435
+ if (!/\.py$/i.test(filePath)) continue;
436
+ const modName = filePath.replace(/\.py$/i, '').replace(/\//g, '.');
437
+ defs.push({
438
+ name: modName.split('.').pop() || modName,
439
+ kind: 'module',
440
+ detail: `module ${modName}`,
441
+ doc: `Workspace Python module \`${filePath}\``,
442
+ params: [],
443
+ file: filePath,
444
+ line: 1,
445
+ col: 1
446
+ });
447
+
448
+ const lines = String(src || '').split('\n');
449
+ for (let i = 0; i < lines.length; i++) {
450
+ const line = lines[i];
451
+ const fnMatch = line.match(/^(\s*)(?:async\s+)?def\s+([A-Za-z_][A-Za-z0-9_]*)\s*\(([^)]*)\)(?:\s*->\s*([^:]+))?\s*:/);
452
+ if (fnMatch) {
453
+ const indent = fnMatch[1].length;
454
+ const name = fnMatch[2];
455
+ const rawParams = fnMatch[3].trim();
456
+ const ret = fnMatch[4] ? ` -> ${fnMatch[4].trim()}` : '';
457
+ const params = rawParams
458
+ ? rawParams.split(',').map((p) => p.trim()).filter((p) => p && p !== 'self' && p !== 'cls')
459
+ : [];
460
+ // Check optional docstring on following line
461
+ const nextTrim = (lines[i + 1] || '').trim();
462
+ const docMatch = nextTrim.match(/^(?:"""|''')([\s\S]*?)(?:"""|''')?$/);
463
+ defs.push({
464
+ name,
465
+ kind: indent > 0 ? 'method' : 'function',
466
+ detail: `def ${name}(${rawParams})${ret}`,
467
+ doc: docMatch && docMatch[1] ? docMatch[1].trim() : `Defined in \`${filePath}:${i + 1}\``,
468
+ params,
469
+ file: filePath,
470
+ line: i + 1,
471
+ col: line.indexOf(name) + 1
472
+ });
473
+ continue;
474
+ }
475
+ const clsMatch = line.match(/^\s*class\s+([A-Za-z_][A-Za-z0-9_]*)(?:\(([^)]*)\))?\s*:/);
476
+ if (clsMatch) {
477
+ const name = clsMatch[1];
478
+ const bases = clsMatch[2] ? `(${clsMatch[2].trim()})` : '';
479
+ defs.push({
480
+ name,
481
+ kind: 'class',
482
+ detail: `class ${name}${bases}`,
483
+ doc: `Class defined in \`${filePath}:${i + 1}\``,
484
+ params: [],
485
+ file: filePath,
486
+ line: i + 1,
487
+ col: line.indexOf(name) + 1
488
+ });
489
+ }
490
+ }
491
+ }
492
+ return defs;
493
+ }
414
494
 
415
495
  /**
416
- * Registers Monaco Python completion and hover providers.
496
+ * Registers Monaco Python completion, hover, signature help, definition, and symbol providers.
417
497
  */
418
- export function registerMonacoPythonLanguageService(monacoInstance: any): boolean {
498
+ export function registerMonacoPythonLanguageService(
499
+ monacoInstance: any,
500
+ getWorkspaceFiles?: () => Record<string, string>
501
+ ): boolean {
502
+ if (typeof getWorkspaceFiles === 'function') {
503
+ _pyWorkspaceFilesGetter = getWorkspaceFiles;
504
+ }
419
505
  if (!monacoInstance || !monacoInstance.languages) return false;
420
- if (_monacoPyRegistered) return true;
421
- _monacoPyRegistered = true;
506
+ if (_monacoPyInstances.has(monacoInstance)) return true;
507
+ _monacoPyInstances.add(monacoInstance);
422
508
 
423
509
  try {
510
+ const CIK = monacoInstance.languages.CompletionItemKind || {};
511
+ const CITR = monacoInstance.languages.CompletionItemInsertTextRule || {};
512
+
424
513
  monacoInstance.languages.registerCompletionItemProvider('python', {
425
- triggerCharacters: ['.'],
514
+ triggerCharacters: ['.', ' '],
426
515
  provideCompletionItems(model: any, position: any) {
427
516
  const wordInfo = model.getWordUntilPosition(position);
428
517
  const range = {
@@ -431,20 +520,67 @@ export function registerMonacoPythonLanguageService(monacoInstance: any): boolea
431
520
  startColumn: wordInfo.startColumn,
432
521
  endColumn: wordInfo.endColumn
433
522
  };
523
+ const fullSource = typeof model.getValue === 'function' ? model.getValue() : '';
524
+ const linePrefix = typeof model.getLineContent === 'function'
525
+ ? String(model.getLineContent(position.lineNumber) || '').slice(0, position.column - 1)
526
+ : '';
527
+
528
+ // `self.` attribute & method completion inside classes
529
+ if (/self\.[A-Za-z0-9_]*$/.test(linePrefix)) {
530
+ const members = new Map<string, { kind: any; detail: string }>();
531
+ const attrRe = /\bself\.([A-Za-z_][A-Za-z0-9_]*)\s*=/g;
532
+ let m: RegExpExecArray | null;
533
+ while ((m = attrRe.exec(fullSource)) !== null) {
534
+ members.set(m[1], { kind: CIK.Field ?? 4, detail: 'instance attribute' });
535
+ }
536
+ const methodRe = /^\s+def\s+([A-Za-z_][A-Za-z0-9_]*)\s*\(\s*self\b([^)]*)\)/gm;
537
+ while ((m = methodRe.exec(fullSource)) !== null) {
538
+ if (!m[1].startsWith('__')) {
539
+ members.set(m[1], { kind: CIK.Method ?? 0, detail: `method(${m[2].replace(/^\s*,\s*/, '').trim()})` });
540
+ }
541
+ }
542
+ return {
543
+ suggestions: Array.from(members.entries()).map(([name, info]) => ({
544
+ label: name,
545
+ kind: info.kind,
546
+ detail: info.detail,
547
+ insertText: info.kind === (CIK.Method ?? 0) ? `${name}($0)` : name,
548
+ insertTextRules: CITR.InsertAsSnippet,
549
+ range
550
+ }))
551
+ };
552
+ }
434
553
 
554
+ const seen = new Set<string>();
435
555
  const suggestions = Object.keys(PYTHON_COMPLETIONS_AND_HOVERS).map((key) => {
436
556
  const item = PYTHON_COMPLETIONS_AND_HOVERS[key];
557
+ seen.add(item.label);
437
558
  return {
438
559
  label: item.label,
439
- kind: monacoInstance.languages.CompletionItemKind.Function,
560
+ kind: CIK.Function ?? 1,
440
561
  detail: item.detail,
441
562
  documentation: { value: item.documentation },
442
563
  insertText: item.insertText || item.label,
443
- insertTextRules: monacoInstance.languages.CompletionItemInsertTextRule.InsertAsSnippet,
564
+ insertTextRules: CITR.InsertAsSnippet,
444
565
  range
445
566
  };
446
567
  });
447
568
 
569
+ const wsDefs = collectWorkspacePythonSymbols(fullSource, model.uri?.path || 'main.py');
570
+ for (const def of wsDefs) {
571
+ if (seen.has(def.name)) continue;
572
+ seen.add(def.name);
573
+ suggestions.push({
574
+ label: def.name,
575
+ kind: def.kind === 'class' ? (CIK.Class ?? 5) : def.kind === 'module' ? (CIK.Module ?? 8) : (CIK.Function ?? 1),
576
+ detail: def.detail,
577
+ documentation: { value: def.doc },
578
+ insertText: def.kind === 'function' ? `${def.name}(${def.params.length ? '$1' : ''})` : def.name,
579
+ insertTextRules: CITR.InsertAsSnippet,
580
+ range
581
+ });
582
+ }
583
+
448
584
  return { suggestions };
449
585
  }
450
586
  });
@@ -461,22 +597,110 @@ export function registerMonacoPythonLanguageService(monacoInstance: any): boolea
461
597
  break;
462
598
  }
463
599
  }
464
- if (!item) return null;
600
+ if (item) {
601
+ return {
602
+ range: {
603
+ startLineNumber: position.lineNumber,
604
+ endLineNumber: position.lineNumber,
605
+ startColumn: word.startColumn,
606
+ endColumn: word.endColumn
607
+ },
608
+ contents: [
609
+ { value: `**${item.label}** — \`${item.detail}\`` },
610
+ { value: item.documentation }
611
+ ]
612
+ };
613
+ }
465
614
 
466
- return {
467
- range: {
468
- startLineNumber: position.lineNumber,
469
- endLineNumber: position.lineNumber,
470
- startColumn: word.startColumn,
471
- endColumn: word.endColumn
472
- },
473
- contents: [
474
- { value: `**${item.label}** — \`${item.detail}\`` },
475
- { value: item.documentation }
476
- ]
477
- };
615
+ const wsDefs = collectWorkspacePythonSymbols(model.getValue?.() || '', model.uri?.path || 'main.py');
616
+ const wsHit = wsDefs.find((d) => d.name === word.word && d.kind !== 'module');
617
+ if (wsHit) {
618
+ return {
619
+ range: {
620
+ startLineNumber: position.lineNumber,
621
+ endLineNumber: position.lineNumber,
622
+ startColumn: word.startColumn,
623
+ endColumn: word.endColumn
624
+ },
625
+ contents: [
626
+ { value: `\`\`\`python\n${wsHit.detail}\n\`\`\`` },
627
+ { value: wsHit.doc }
628
+ ]
629
+ };
630
+ }
631
+ return null;
478
632
  }
479
633
  });
634
+
635
+ if (typeof monacoInstance.languages.registerSignatureHelpProvider === 'function') {
636
+ monacoInstance.languages.registerSignatureHelpProvider('python', {
637
+ signatureHelpTriggerCharacters: ['(', ','],
638
+ provideSignatureHelp(model: any, position: any) {
639
+ const linePrefix = String(model.getLineContent?.(position.lineNumber) || '').slice(0, position.column - 1);
640
+ const callMatch = linePrefix.match(/([A-Za-z_][A-Za-z0-9_]*)\s*\(([^()]*)$/);
641
+ if (!callMatch) return null;
642
+ const fnName = callMatch[1];
643
+ const activeParam = (callMatch[2].match(/,/g) || []).length;
644
+
645
+ const builtinKey = Object.keys(PYTHON_COMPLETIONS_AND_HOVERS).find(
646
+ (k) => k === fnName || k.endsWith('.' + fnName)
647
+ );
648
+ if (builtinKey) {
649
+ const doc = PYTHON_COMPLETIONS_AND_HOVERS[builtinKey];
650
+ const inner = doc.detail.match(/\(([^)]*)\)/)?.[1] || '';
651
+ const params = inner ? inner.split(',').map((p) => ({ label: p.trim() })) : [];
652
+ return {
653
+ value: {
654
+ signatures: [{ label: doc.detail, documentation: doc.documentation, parameters: params }],
655
+ activeSignature: 0,
656
+ activeParameter: Math.min(activeParam, Math.max(0, params.length - 1))
657
+ },
658
+ dispose() {}
659
+ };
660
+ }
661
+
662
+ const wsDefs = collectWorkspacePythonSymbols(model.getValue?.() || '', model.uri?.path || 'main.py');
663
+ const wsFn = wsDefs.find((d) => d.name === fnName && (d.kind === 'function' || d.kind === 'method'));
664
+ if (wsFn) {
665
+ const params = wsFn.params.map((p) => ({ label: p }));
666
+ return {
667
+ value: {
668
+ signatures: [{ label: wsFn.detail, documentation: wsFn.doc, parameters: params }],
669
+ activeSignature: 0,
670
+ activeParameter: Math.min(activeParam, Math.max(0, params.length - 1))
671
+ },
672
+ dispose() {}
673
+ };
674
+ }
675
+ return null;
676
+ }
677
+ });
678
+ }
679
+
680
+ if (typeof monacoInstance.languages.registerDefinitionProvider === 'function' && monacoInstance.Uri) {
681
+ monacoInstance.languages.registerDefinitionProvider('python', {
682
+ provideDefinition(model: any, position: any) {
683
+ const word = model.getWordAtPosition(position);
684
+ if (!word) return null;
685
+ const wsDefs = collectWorkspacePythonSymbols(model.getValue?.() || '', model.uri?.path || 'main.py');
686
+ const hit = wsDefs.find((d) => d.name === word.word && d.kind !== 'module');
687
+ if (!hit) return null;
688
+ const uri = typeof monacoInstance.Uri.file === 'function'
689
+ ? monacoInstance.Uri.file('/workspace/' + hit.file.replace(/^\/+/, ''))
690
+ : model.uri;
691
+ return {
692
+ uri,
693
+ range: {
694
+ startLineNumber: hit.line,
695
+ startColumn: hit.col,
696
+ endLineNumber: hit.line,
697
+ endColumn: hit.col + hit.name.length
698
+ }
699
+ };
700
+ }
701
+ });
702
+ }
703
+
480
704
  return true;
481
705
  } catch (err) {
482
706
  if (typeof console !== 'undefined' && console.warn) {
@@ -501,6 +725,7 @@ export function analyzePythonSource(source: string, filename = 'main.py'): Diagn
501
725
 
502
726
  let expectIndentAfterLine = 0;
503
727
  let expectIndentMin = 0;
728
+ let inTripleQuote: string | null = null;
504
729
 
505
730
  for (let l = 0; l < lines.length; l++) {
506
731
  const line = lines[l];
@@ -508,6 +733,17 @@ export function analyzePythonSource(source: string, filename = 'main.py'): Diagn
508
733
  let inStr = false;
509
734
  let strChar = '';
510
735
 
736
+ if (inTripleQuote) {
737
+ const closeIdx = line.indexOf(inTripleQuote);
738
+ if (closeIdx === -1) {
739
+ continue;
740
+ }
741
+ inTripleQuote = null;
742
+ // Continue scanning after closing triple quote on this line if needed
743
+ const rest = line.slice(closeIdx + 3).trim();
744
+ if (!rest || rest.startsWith('#')) continue;
745
+ }
746
+
511
747
  // Check mixed tab and space indentation
512
748
  const indentMatch = line.match(/^([ \t]+)/);
513
749
  const indentLen = indentMatch ? indentMatch[1].length : 0;
@@ -548,9 +784,26 @@ export function analyzePythonSource(source: string, filename = 'main.py'): Diagn
548
784
  expectIndentAfterLine = 0;
549
785
  }
550
786
 
787
+ const stackDepthAtLineStart = stack.length;
788
+ let commentCol = -1;
789
+
551
790
  for (let c = 0; c < line.length; c++) {
552
791
  const ch = line[c];
553
- if (!inStr && ch === '#') break; // Comment
792
+ if (!inStr && ch === '#') {
793
+ commentCol = c;
794
+ break; // Comment
795
+ }
796
+
797
+ if (!inStr && (line.slice(c, c + 3) === '"""' || line.slice(c, c + 3) === "'''")) {
798
+ const delim = line.slice(c, c + 3);
799
+ const endSameLine = line.indexOf(delim, c + 3);
800
+ if (endSameLine !== -1) {
801
+ c = endSameLine + 2;
802
+ continue;
803
+ }
804
+ inTripleQuote = delim;
805
+ break;
806
+ }
554
807
 
555
808
  if (ch === '"' || ch === '\'') {
556
809
  if (!inStr) {
@@ -597,7 +850,7 @@ export function analyzePythonSource(source: string, filename = 'main.py'): Diagn
597
850
  }
598
851
  }
599
852
 
600
- if (inStr && !line.includes('"""') && !line.includes("'''")) {
853
+ if (inStr && !inTripleQuote && !line.endsWith('\\')) {
601
854
  diagnostics.push({
602
855
  id: `py-eol-string-${lineNum}`,
603
856
  file: filename,
@@ -611,24 +864,43 @@ export function analyzePythonSource(source: string, filename = 'main.py'): Diagn
611
864
  } as any);
612
865
  }
613
866
 
614
- // Check missing colon or setup expected indentation
615
- if (/^(?:def\b|class\b|if\b|elif\b|else\b|for\b|while\b|try\b|finally\b|except\b|with\b)/.test(trimmed)) {
616
- if (!trimmed.endsWith(':')) {
617
- diagnostics.push({
618
- id: `py-missing-colon-${lineNum}`,
619
- file: filename,
620
- line: lineNum,
621
- startLineNumber: lineNum,
622
- col: line.length,
623
- startColumn: line.length,
624
- severity: 'error',
625
- message: `SyntaxError: expected ':' at end of line.`,
626
- source: 'python-linter'
627
- } as any);
628
- } else if (trimmed.endsWith(':')) {
867
+ // Strip inline comment before checking compound statement header `:`
868
+ const codeOnlyTrimmed = (commentCol >= 0 ? line.slice(0, commentCol) : line).trim();
869
+
870
+ // Check missing colon or setup expected indentation only when brackets are balanced
871
+ if (
872
+ !inTripleQuote &&
873
+ stack.length === 0 &&
874
+ stackDepthAtLineStart === 0 &&
875
+ !codeOnlyTrimmed.endsWith('\\') &&
876
+ /^(?:(?:async\s+)?def\b|class\b|if\b|elif\b|else\b|for\b|while\b|try\b|finally\b|except\b|(?:async\s+)?with\b)/.test(codeOnlyTrimmed)
877
+ ) {
878
+ if (!codeOnlyTrimmed.endsWith(':')) {
879
+ // Allow single-line suites e.g. `if x: return 1`
880
+ if (!/:/.test(codeOnlyTrimmed)) {
881
+ diagnostics.push({
882
+ id: `py-missing-colon-${lineNum}`,
883
+ file: filename,
884
+ line: lineNum,
885
+ startLineNumber: lineNum,
886
+ col: line.length,
887
+ startColumn: line.length,
888
+ severity: 'error',
889
+ message: `SyntaxError: expected ':' at end of line.`,
890
+ source: 'python-linter'
891
+ } as any);
892
+ }
893
+ } else {
629
894
  expectIndentAfterLine = lineNum;
630
895
  expectIndentMin = indentLen;
631
896
  }
897
+ } else if (!inTripleQuote && stack.length === 0 && stackDepthAtLineStart > 0 && codeOnlyTrimmed.endsWith(':')) {
898
+ // End of multiline `def foo(\n a: int\n) -> int:`
899
+ let headerLine = l - 1;
900
+ while (headerLine > 0 && !lines[headerLine].trim()) headerLine--;
901
+ const baseIndent = (lines[headerLine]?.match(/^([ \t]+)/)?.[1] || '').length;
902
+ expectIndentAfterLine = lineNum;
903
+ expectIndentMin = Math.min(indentLen, baseIndent);
632
904
  }
633
905
  }
634
906
 
@@ -1110,12 +1382,29 @@ export class PythonToolchainManager {
1110
1382
  if (typeof window !== 'undefined' && pyodide.setStdout) {
1111
1383
  pyodide.setStdout({ batched: (msg: string) => handleOut(msg + '\n') });
1112
1384
  pyodide.setStderr({ batched: (msg: string) => handleErr(msg + '\n') });
1113
- if (req.stdin && pyodide.setStdin) {
1385
+ let effectiveStdin = req.stdin || '';
1386
+ let prePromptedInteractive = false;
1387
+ if (!effectiveStdin && typeof (req as any).onRequestStdin === 'function' && /\binput\s*\(/.test(codeToRun)) {
1388
+ const promptMatches = Array.from(codeToRun.matchAll(/\binput\s*\(\s*(?:(['"])((?:\\.|(?!\1).)*)\1)?\s*\)/g));
1389
+ const collectedLines: string[] = [];
1390
+ const maxPrompts = Math.min(8, Math.max(1, promptMatches.length));
1391
+ for (let pi = 0; pi < maxPrompts; pi++) {
1392
+ const rawPrompt = promptMatches[pi]?.[2] || '';
1393
+ const ans = await (req as any).onRequestStdin(rawPrompt);
1394
+ if (ans === null || ans === undefined) break;
1395
+ collectedLines.push(String(ans));
1396
+ }
1397
+ if (collectedLines.length > 0) {
1398
+ effectiveStdin = collectedLines.join('\n') + '\n';
1399
+ prePromptedInteractive = true;
1400
+ }
1401
+ }
1402
+ if (effectiveStdin && pyodide.setStdin) {
1114
1403
  let pos = 0;
1115
1404
  pyodide.setStdin({
1116
1405
  stdin: () => {
1117
- if (pos < req.stdin!.length) {
1118
- return req.stdin!.charCodeAt(pos++);
1406
+ if (pos < effectiveStdin.length) {
1407
+ return effectiveStdin.charCodeAt(pos++);
1119
1408
  }
1120
1409
  return null;
1121
1410
  }
@@ -1125,7 +1414,7 @@ export class PythonToolchainManager {
1125
1414
  const fileLabel = JSON.stringify(req.entry || '<exec>');
1126
1415
  const encodedCode = JSON.stringify(codeToRun);
1127
1416
  const runnerWrapper = `
1128
- import sys, tracemalloc
1417
+ import sys, builtins, tracemalloc
1129
1418
  if '/usr/lib/python' not in sys.path:
1130
1419
  sys.path.insert(0, '/usr/lib/python')
1131
1420
  if '/workspace' not in sys.path:
@@ -1133,12 +1422,15 @@ if '/workspace' not in sys.path:
1133
1422
  if 'codelab_test' in sys.modules and hasattr(sys.modules['codelab_test'], '_reset_codelab_test'):
1134
1423
  sys.modules['codelab_test']._reset_codelab_test()
1135
1424
 
1425
+ _cl_orig_input = builtins.input
1426
+ ${prePromptedInteractive ? `builtins.input = lambda _prompt='': sys.stdin.readline().rstrip('\\r\\n')` : ''}
1136
1427
  _cl_user_code = ${encodedCode}
1137
1428
  _cl_ns = {'__name__': '__main__', '__file__': ${fileLabel}, '__builtins__': __builtins__}
1138
1429
  tracemalloc.start()
1139
1430
  try:
1140
1431
  exec(compile(_cl_user_code, ${fileLabel}, 'exec'), _cl_ns)
1141
1432
  finally:
1433
+ builtins.input = _cl_orig_input
1142
1434
  _, _peak = tracemalloc.get_traced_memory()
1143
1435
  tracemalloc.stop()
1144
1436
  `;
@@ -1311,9 +1603,16 @@ function installPythonExtension(workbench: any, options: ExtendedPythonExtension
1311
1603
  workbench.shell.options.pythonToolchain = toolchain;
1312
1604
  }
1313
1605
 
1606
+ const getWsFiles = () => (workbench && workbench.files ? workbench.files : {});
1314
1607
  if (typeof window !== 'undefined' && (window as any).monaco) {
1315
- registerMonacoPythonLanguageService((window as any).monaco);
1608
+ registerMonacoPythonLanguageService((window as any).monaco, getWsFiles);
1316
1609
  }
1610
+ if (!Array.isArray(workbench._monacoReadyHooks)) {
1611
+ workbench._monacoReadyHooks = [];
1612
+ }
1613
+ workbench._monacoReadyHooks.push((monaco: any) => {
1614
+ registerMonacoPythonLanguageService(monaco, getWsFiles);
1615
+ });
1317
1616
 
1318
1617
  if (!workbench.enabledLanguages || !(workbench.enabledLanguages instanceof Set)) {
1319
1618
  workbench.enabledLanguages = new Set(['js', 'py']);
@@ -1348,38 +1647,39 @@ function installPythonExtension(workbench: any, options: ExtendedPythonExtension
1348
1647
 
1349
1648
  workbench.hasMultipleLanguages = workbench.enabledLanguages.size > 1;
1350
1649
 
1351
- // Debounced static syntax & traceback linter
1352
- if (workbench._diagnosticsStore) {
1353
- let pyLintTimer: any = null;
1354
- workbench._pyLintHandler = (file: string, code: string) => {
1355
- if (!file || !file.endsWith('.py')) return;
1356
- if (pyLintTimer) clearTimeout(pyLintTimer);
1357
- pyLintTimer = setTimeout(() => {
1358
- const diags = analyzePythonSource(code, file);
1359
- workbench._diagnosticsStore.clear('python-linter');
1360
- for (const d of diags) {
1361
- workbench._diagnosticsStore.add(d);
1362
- }
1363
- if (typeof window !== 'undefined' && (window as any).monaco) {
1364
- const model = (workbench.models && typeof workbench.models.get === 'function' && workbench.models.get(file))
1365
- || (workbench.activeFile === file && workbench.editor ? workbench.editor.getModel() : null);
1366
- if (model) {
1367
- const markers = diags.map((d) => ({
1368
- startLineNumber: d.line,
1369
- startColumn: d.col || 1,
1370
- endLineNumber: d.line,
1371
- endColumn: (d.col || 1) + 20,
1372
- message: d.message,
1373
- severity: d.severity === 'error'
1374
- ? (window as any).monaco.MarkerSeverity.Error
1375
- : (window as any).monaco.MarkerSeverity.Warning
1376
- }));
1377
- (window as any).monaco.editor.setModelMarkers(model, 'python-linter', markers);
1378
- }
1379
- }
1380
- }, 180);
1381
- };
1382
- }
1650
+ // Synchronous static syntax & traceback linter (resolves _diagnosticsStore dynamically)
1651
+ workbench._pyLintHandler = (file: string, code: string) => {
1652
+ if (!file || !/\.py$/i.test(file)) return;
1653
+ const diags = analyzePythonSource(String(code ?? ''), file);
1654
+ const store = workbench ? workbench._diagnosticsStore : null;
1655
+ if (store && typeof store.setFileDiagnostics === 'function') {
1656
+ store.setFileDiagnostics(file, 'python-linter', diags);
1657
+ } else if (store && typeof store.clear === 'function' && typeof store.add === 'function') {
1658
+ store.clear('python-linter');
1659
+ for (const d of diags) {
1660
+ store.add(d);
1661
+ }
1662
+ }
1663
+ if (typeof window !== 'undefined' && (window as any).monaco) {
1664
+ const model =
1665
+ (workbench.models && typeof workbench.models.get === 'function' && workbench.models.get(file)) ||
1666
+ (workbench.activeFile === file && workbench.editor ? workbench.editor.getModel() : null);
1667
+ if (model) {
1668
+ const markers = diags.map((d) => ({
1669
+ startLineNumber: d.line,
1670
+ startColumn: d.col || 1,
1671
+ endLineNumber: d.endLine || d.line,
1672
+ endColumn: d.endCol || (d.col || 1) + 20,
1673
+ message: d.message,
1674
+ severity:
1675
+ d.severity === 'error'
1676
+ ? (window as any).monaco.MarkerSeverity.Error
1677
+ : (window as any).monaco.MarkerSeverity.Warning
1678
+ }));
1679
+ (window as any).monaco.editor.setModelMarkers(model, 'python-linter', markers);
1680
+ }
1681
+ }
1682
+ };
1383
1683
 
1384
1684
  if (options.preload) {
1385
1685
  toolchain.ensureLoaded().catch((err) => {
package/src/index.ts CHANGED
@@ -1,5 +1,5 @@
1
1
  /**
2
- * @innovatorved/code-lab v0.4.0
2
+ * @innovatorved/code-lab v0.6.0
3
3
  * Browser-native IDE, POSIX Shell, Web Worker Node.js/Bun Runtime, WASI C++20 Toolchain, Python 3.12 WebAssembly, and Git Engine.
4
4
  */
5
5