@innovatorved/code-lab 0.7.0 → 0.7.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 (159) hide show
  1. package/ARCHITECTURE.md +2 -2
  2. package/CHANGELOG.md +30 -0
  3. package/README.md +6 -6
  4. package/dist/code-lab-sql.esm.js +19 -19
  5. package/dist/code-lab-sql.umd.js +20 -20
  6. package/dist/code-lab.css +1 -1
  7. package/dist/code-lab.d.ts +47 -38
  8. package/dist/code-lab.esm.js +1183 -1909
  9. package/dist/code-lab.js +1182 -1906
  10. package/dist/extensions/cpp.esm.js +132 -8760
  11. package/dist/extensions/cpp.js +124 -8770
  12. package/dist/extensions/guided-lab.esm.js +33 -6836
  13. package/dist/extensions/guided-lab.js +33 -6854
  14. package/dist/extensions/javascript.esm.js +1 -36
  15. package/dist/extensions/javascript.js +1 -58
  16. package/dist/extensions/python.esm.js +113 -8122
  17. package/dist/extensions/python.js +113 -8140
  18. package/dist/extensions/typescript.esm.js +1 -55
  19. package/dist/extensions/typescript.js +1 -77
  20. package/dist/index.d.ts +1 -1
  21. package/dist/logger.d.ts +4 -20
  22. package/dist/modular-kernel.d.ts +0 -5
  23. package/dist/packages/core/src/errors.d.ts +5 -1
  24. package/dist/packages/fs/src/backends.d.ts +0 -27
  25. package/dist/packages/fs/src/index.d.ts +1 -1
  26. package/dist/packages/ui/src/html.d.ts +1 -0
  27. package/dist/packages/ui/src/index.d.ts +1 -0
  28. package/dist/{apps/web/src/index.d.ts → packages/ui/src/kernel.d.ts} +3 -11
  29. package/dist/packages/ui/src/observability.d.ts +1 -1
  30. package/dist/packages/ui/src/settings-dialog.d.ts +0 -1
  31. package/dist/preview-sw.js +1 -1
  32. package/dist/runtime.d.ts +3 -0
  33. package/dist/runtime.esm.js +78 -78
  34. package/dist/runtime.js +78 -78
  35. package/dist/schemas.d.ts +10 -1
  36. package/dist/schemas.esm.js +33 -6815
  37. package/dist/schemas.js +33 -6831
  38. package/dist/shell.esm.js +277 -285
  39. package/dist/shell.js +277 -285
  40. package/dist/terminal.esm.js +9 -7
  41. package/dist/terminal.js +7 -7
  42. package/dist/workbench/command-palette.d.ts +0 -4
  43. package/dist/workbench/editor.d.ts +0 -4
  44. package/dist/workbench/index.d.ts +0 -22
  45. package/dist/workbench/intellisense.d.ts +1 -8
  46. package/dist/workbench/xterm-adapter.d.ts +0 -1
  47. package/package.json +4 -13
  48. package/dist/code-lab.umd.js +0 -6117
  49. package/dist/packages/editor/src/index.d.ts +0 -118
  50. package/dist/packages/preview/src/index.d.ts +0 -34
  51. package/dist/packages/runtime/src/index.d.ts +0 -47
  52. package/dist/packages/terminal/src/index.d.ts +0 -54
  53. package/dist/workbench/drawer.d.ts +0 -18
  54. package/dist/workbench/file-tree.d.ts +0 -11
  55. package/dist/workbench/guided-pane.d.ts +0 -11
  56. package/dist/workbench/styles.d.ts +0 -4
  57. package/dist/workbench/toolbar.d.ts +0 -17
  58. package/packages/commands/README.md +0 -7
  59. package/packages/commands/package.json +0 -16
  60. package/packages/commands/src/index.ts +0 -467
  61. package/packages/commands/tsconfig.json +0 -22
  62. package/packages/core/README.md +0 -12
  63. package/packages/core/package.json +0 -13
  64. package/packages/core/src/di.ts +0 -147
  65. package/packages/core/src/disposable.ts +0 -112
  66. package/packages/core/src/errors.ts +0 -205
  67. package/packages/core/src/events.ts +0 -157
  68. package/packages/core/src/index.ts +0 -49
  69. package/packages/core/src/path.ts +0 -118
  70. package/packages/core/src/registry.ts +0 -61
  71. package/packages/core/tsconfig.json +0 -19
  72. package/packages/editor/README.md +0 -9
  73. package/packages/editor/package.json +0 -18
  74. package/packages/editor/src/index.ts +0 -344
  75. package/packages/editor/tsconfig.json +0 -24
  76. package/packages/fs/README.md +0 -7
  77. package/packages/fs/package.json +0 -16
  78. package/packages/fs/src/backends.ts +0 -301
  79. package/packages/fs/src/index.ts +0 -18
  80. package/packages/fs/src/types.ts +0 -44
  81. package/packages/fs/src/vfs-service.ts +0 -257
  82. package/packages/fs/tsconfig.json +0 -22
  83. package/packages/preview/README.md +0 -3
  84. package/packages/preview/package.json +0 -16
  85. package/packages/preview/src/index.ts +0 -125
  86. package/packages/preview/tsconfig.json +0 -22
  87. package/packages/runtime/README.md +0 -3
  88. package/packages/runtime/package.json +0 -17
  89. package/packages/runtime/src/index.ts +0 -134
  90. package/packages/runtime/tsconfig.json +0 -23
  91. package/packages/settings/README.md +0 -7
  92. package/packages/settings/package.json +0 -16
  93. package/packages/settings/src/builtin-schemas.ts +0 -262
  94. package/packages/settings/src/configuration-service.ts +0 -609
  95. package/packages/settings/src/index.ts +0 -38
  96. package/packages/settings/src/jsonc.ts +0 -189
  97. package/packages/settings/src/schema.ts +0 -164
  98. package/packages/settings/tsconfig.json +0 -22
  99. package/packages/sql/README.md +0 -12
  100. package/packages/sql/package.json +0 -13
  101. package/packages/sql/src/completions.ts +0 -359
  102. package/packages/sql/src/diagnostics.ts +0 -200
  103. package/packages/sql/src/formatter.ts +0 -271
  104. package/packages/sql/src/index.ts +0 -54
  105. package/packages/sql/src/sql-editor.ts +0 -802
  106. package/packages/sql/src/styles.ts +0 -524
  107. package/packages/sql/src/tokenizer.ts +0 -457
  108. package/packages/sql/src/types.ts +0 -148
  109. package/packages/sql/tsconfig.json +0 -19
  110. package/packages/terminal/README.md +0 -3
  111. package/packages/terminal/package.json +0 -16
  112. package/packages/terminal/src/index.ts +0 -183
  113. package/packages/terminal/tsconfig.json +0 -22
  114. package/packages/ui/README.md +0 -8
  115. package/packages/ui/package.json +0 -18
  116. package/packages/ui/src/index.ts +0 -40
  117. package/packages/ui/src/observability.ts +0 -173
  118. package/packages/ui/src/plugin-registry.ts +0 -289
  119. package/packages/ui/src/settings-dialog.ts +0 -939
  120. package/packages/ui/src/themes.ts +0 -333
  121. package/packages/ui/tsconfig.json +0 -24
  122. package/src/code-lab.css +0 -8584
  123. package/src/csp.ts +0 -590
  124. package/src/diagnostics.ts +0 -287
  125. package/src/extensions/cpp.ts +0 -2389
  126. package/src/extensions/guided-lab.ts +0 -64
  127. package/src/extensions/javascript.ts +0 -54
  128. package/src/extensions/python.ts +0 -1737
  129. package/src/extensions/typescript.ts +0 -85
  130. package/src/extensions/umbrella.ts +0 -5
  131. package/src/html.ts +0 -88
  132. package/src/index.ts +0 -129
  133. package/src/logger.ts +0 -139
  134. package/src/modular-kernel.ts +0 -11
  135. package/src/preview-sw.js +0 -296
  136. package/src/runtime/test-harness.ts +0 -57
  137. package/src/runtime.ts +0 -10480
  138. package/src/sample.html +0 -304
  139. package/src/schemas.ts +0 -366
  140. package/src/scm.ts +0 -2453
  141. package/src/search.ts +0 -433
  142. package/src/shell.ts +0 -10987
  143. package/src/storage.ts +0 -773
  144. package/src/terminal.ts +0 -1400
  145. package/src/workbench/command-palette.ts +0 -381
  146. package/src/workbench/diff-editor.ts +0 -470
  147. package/src/workbench/drawer.ts +0 -157
  148. package/src/workbench/editor.ts +0 -49
  149. package/src/workbench/file-tree.ts +0 -51
  150. package/src/workbench/guided-pane.ts +0 -43
  151. package/src/workbench/icons.ts +0 -255
  152. package/src/workbench/index.ts +0 -44
  153. package/src/workbench/intellisense.ts +0 -1871
  154. package/src/workbench/share.ts +0 -128
  155. package/src/workbench/styles.ts +0 -211
  156. package/src/workbench/toolbar.ts +0 -182
  157. package/src/workbench/xterm-adapter.ts +0 -1571
  158. package/src/workbench.ts +0 -22132
  159. package/src/zip.ts +0 -348
@@ -1,1737 +0,0 @@
1
- import { PythonExtensionOptions, PythonExtensionOptionsSchema, PythonToolchainProgress } from '../schemas';
2
- import type { DiagnosticItem } from '../diagnostics';
3
- import { CodeLabTestParser, type TestResultItem } from '../runtime/test-harness';
4
-
5
- export const DEFAULT_PYTHON_CDN_BASE_URL = 'https://cdn.jsdelivr.net/pyodide/v0.27.2/full/';
6
-
7
- export const PYTHON_TOOLCHAIN_PRESETS = {
8
- latest: 'https://cdn.jsdelivr.net/pyodide/v0.27.2/full/',
9
- v0_26: 'https://cdn.jsdelivr.net/pyodide/v0.26.4/full/'
10
- };
11
-
12
- /**
13
- * Built-in Python modules seeded into `/usr/lib/python` inside the VirtualFS.
14
- */
15
- export const BUILTIN_PYTHON_MODULES: Record<string, string> = {
16
- '/usr/lib/python/codelab_dsa.py': `# CodeLab <codelab_dsa.py> - Data Structures & Algorithms Utilities
17
- from typing import Optional, List, Any
18
-
19
- class ListNode:
20
- def __init__(self, val: int = 0, next: Optional['ListNode'] = None):
21
- self.val = val
22
- self.next = next
23
-
24
- def __repr__(self):
25
- vals = []
26
- curr = self
27
- while curr and len(vals) < 50:
28
- vals.append(str(curr.val))
29
- curr = curr.next
30
- if curr:
31
- vals.append("...")
32
- return "[" + " -> ".join(vals) + "]"
33
-
34
- class TreeNode:
35
- def __init__(self, val: int = 0, left: Optional['TreeNode'] = None, right: Optional['TreeNode'] = None):
36
- self.val = val
37
- self.left = left
38
- self.right = right
39
-
40
- def __repr__(self):
41
- return f"TreeNode({self.val})"
42
-
43
- def build_linked_list(vals: List[int]) -> Optional[ListNode]:
44
- if not vals:
45
- return None
46
- dummy = ListNode(0)
47
- tail = dummy
48
- for v in vals:
49
- tail.next = ListNode(v)
50
- tail = tail.next
51
- return dummy.next
52
-
53
- def linked_list_to_list(head: Optional[ListNode]) -> List[int]:
54
- out = []
55
- curr = head
56
- while curr is not None:
57
- out.append(curr.val)
58
- curr = curr.next
59
- return out
60
-
61
- def build_binary_tree(vals: List[Optional[int]]) -> Optional[TreeNode]:
62
- if not vals or vals[0] is None:
63
- return None
64
- root = TreeNode(vals[0])
65
- queue = [root]
66
- i = 1
67
- while queue and i < len(vals):
68
- curr = queue.pop(0)
69
- if i < len(vals) and vals[i] is not None:
70
- curr.left = TreeNode(vals[i])
71
- queue.append(curr.left)
72
- i += 1
73
- if i < len(vals) and vals[i] is not None:
74
- curr.right = TreeNode(vals[i])
75
- queue.append(curr.right)
76
- i += 1
77
- return root
78
-
79
- def binary_tree_to_list(root: Optional[TreeNode]) -> List[Optional[int]]:
80
- if not root:
81
- return []
82
- out = []
83
- queue = [root]
84
- while queue:
85
- curr = queue.pop(0)
86
- if curr is not None:
87
- out.append(curr.val)
88
- queue.append(curr.left)
89
- queue.append(curr.right)
90
- else:
91
- out.append(None)
92
- while out and out[-1] is None:
93
- out.pop()
94
- return out
95
-
96
- import heapq
97
-
98
- class MinHeap:
99
- def __init__(self, items: Optional[List[Any]] = None):
100
- self._data = list(items) if items else []
101
- heapq.heapify(self._data)
102
-
103
- def push(self, val: Any):
104
- heapq.heappush(self._data, val)
105
-
106
- def pop(self) -> Any:
107
- return heapq.heappop(self._data)
108
-
109
- def peek(self) -> Optional[Any]:
110
- return self._data[0] if self._data else None
111
-
112
- def __len__(self) -> int:
113
- return len(self._data)
114
-
115
- class MaxHeap:
116
- def __init__(self, items: Optional[List[Any]] = None):
117
- self._data = [-x for x in items] if items else []
118
- heapq.heapify(self._data)
119
-
120
- def push(self, val: Any):
121
- heapq.heappush(self._data, -val)
122
-
123
- def pop(self) -> Any:
124
- return -heapq.heappop(self._data)
125
-
126
- def peek(self) -> Optional[Any]:
127
- return -self._data[0] if self._data else None
128
-
129
- def __len__(self) -> int:
130
- return len(self._data)
131
- `,
132
-
133
- '/usr/lib/python/codelab_test.py': `# CodeLab <codelab_test.py> - Structured Test Harness
134
- import json
135
- import time
136
- import sys
137
- import traceback
138
- from typing import Any, Callable
139
-
140
- _SUITE_NAME = "Default Test Suite"
141
- _PASSED_COUNT = 0
142
- _FAILED_COUNT = 0
143
- _TOTAL_COUNT = 0
144
-
145
- def DESCRIBE(name: str):
146
- global _SUITE_NAME
147
- _SUITE_NAME = str(name)
148
-
149
- def TEST(name: str, fn: Callable[[], Any]):
150
- global _PASSED_COUNT, _FAILED_COUNT, _TOTAL_COUNT
151
- _TOTAL_COUNT += 1
152
- start = time.perf_counter()
153
- err_obj = None
154
- passed = False
155
- try:
156
- fn()
157
- passed = True
158
- _PASSED_COUNT += 1
159
- except AssertionError as e:
160
- _FAILED_COUNT += 1
161
- msg = str(e) or "Assertion failed"
162
- err_obj = {"name": "AssertionError", "message": msg, "stack": traceback.format_exc()}
163
- except Exception as e:
164
- _FAILED_COUNT += 1
165
- err_obj = {"name": type(e).__name__, "message": str(e), "stack": traceback.format_exc()}
166
- finally:
167
- duration_ms = round((time.perf_counter() - start) * 1000, 2)
168
- event = {
169
- "name": name,
170
- "passed": passed,
171
- "durationMs": duration_ms,
172
- "error": err_obj
173
- }
174
- print(f"__CODELAB_TEST__:{json.dumps(event)}", flush=True)
175
-
176
- def ASSERT_TRUE(condition: bool, msg: str = "Expected condition to be True"):
177
- if not bool(condition):
178
- raise AssertionError(msg)
179
-
180
- def ASSERT_FALSE(condition: bool, msg: str = "Expected condition to be False"):
181
- if bool(condition):
182
- raise AssertionError(msg)
183
-
184
- def ASSERT_EQ(actual: Any, expected: Any, msg: str = None):
185
- if actual != expected:
186
- err = msg or f"Assertion failed: expected {expected!r}, got {actual!r}"
187
- raise AssertionError(err)
188
-
189
- def ASSERT_NE(actual: Any, expected: Any, msg: str = None):
190
- if actual == expected:
191
- err = msg or f"Assertion failed: expected value not equal to {expected!r}"
192
- raise AssertionError(err)
193
-
194
- def CODELAB_TEST_EXIT_CODE() -> int:
195
- return 0 if _FAILED_COUNT == 0 else 1
196
-
197
- def _reset_codelab_test() -> None:
198
- global _SUITE_NAME, _PASSED_COUNT, _FAILED_COUNT, _TOTAL_COUNT
199
- _SUITE_NAME = "Default Test Suite"
200
- _PASSED_COUNT = 0
201
- _FAILED_COUNT = 0
202
- _TOTAL_COUNT = 0
203
-
204
- from contextlib import contextmanager
205
-
206
- @contextmanager
207
- def describe(name: str):
208
- DESCRIBE(name)
209
- yield
210
-
211
- @contextmanager
212
- def it(name: str):
213
- global _TOTAL_COUNT, _PASSED_COUNT, _FAILED_COUNT
214
- _TOTAL_COUNT += 1
215
- start = time.perf_counter()
216
- passed = False
217
- err_obj = None
218
- try:
219
- yield
220
- passed = True
221
- _PASSED_COUNT += 1
222
- except AssertionError as e:
223
- _FAILED_COUNT += 1
224
- err_obj = {"name": "AssertionError", "message": str(e) or "Assertion failed", "stack": traceback.format_exc()}
225
- except Exception as e:
226
- _FAILED_COUNT += 1
227
- err_obj = {"name": type(e).__name__, "message": str(e), "stack": traceback.format_exc()}
228
- finally:
229
- duration_ms = round((time.perf_counter() - start) * 1000, 2)
230
- event = {"name": name, "passed": passed, "durationMs": duration_ms, "error": err_obj}
231
- print(f"__CODELAB_TEST__:{json.dumps(event)}", flush=True)
232
-
233
- test = it
234
- assert_equal = ASSERT_EQ
235
- assert_true = ASSERT_TRUE
236
- assert_false = ASSERT_FALSE
237
- `
238
- };
239
-
240
- export const CODELAB_PYTHON_LIBS = BUILTIN_PYTHON_MODULES;
241
-
242
- export interface ExtendedPythonExtensionOptions extends PythonExtensionOptions {
243
- [key: string]: any;
244
- }
245
-
246
- export interface PythonCompileResult {
247
- ok: boolean;
248
- exitCode: number;
249
- stdout: string;
250
- stderr: string;
251
- peakMemoryBytes: number;
252
- durationMs: number;
253
- testResults?: TestResultItem[];
254
- }
255
-
256
- export interface PythonSymbolDoc {
257
- label: string;
258
- kind?: string;
259
- detail: string;
260
- documentation: string;
261
- insertText?: string;
262
- module?: string;
263
- complexity?: string;
264
- }
265
-
266
- export const PYTHON_COMPLETIONS_AND_HOVERS: Record<string, PythonSymbolDoc> = {
267
- 'collections.deque': {
268
- label: 'collections.deque',
269
- detail: 'class collections.deque([iterable[, maxlen]])',
270
- documentation: 'Double-ended queue with $O(1)$ appends and pops from either end.\n\n- Module: `collections`\n- append/pop/appendleft/popleft: $O(1)$',
271
- insertText: 'from collections import deque\n${1:dq} = deque()',
272
- module: 'collections',
273
- complexity: 'O(1) end operations'
274
- },
275
- 'collections.defaultdict': {
276
- label: 'collections.defaultdict',
277
- detail: 'class collections.defaultdict(default_factory=None, /[, ...])',
278
- documentation: 'Dict subclass that calls a factory function to supply missing values.\n\n- Module: `collections`',
279
- insertText: 'from collections import defaultdict\n${1:d} = defaultdict(${2:list})',
280
- module: 'collections',
281
- complexity: 'O(1) average lookup'
282
- },
283
- 'collections.Counter': {
284
- label: 'collections.Counter',
285
- detail: 'class collections.Counter([iterable-or-mapping])',
286
- documentation: 'Dict subclass for counting hashable items.\n\n- Module: `collections`',
287
- insertText: 'from collections import Counter\n${1:counts} = Counter(${2:items})',
288
- module: 'collections',
289
- complexity: 'O(N) initialization'
290
- },
291
- 'heapq.heappush': {
292
- label: 'heapq.heappush',
293
- detail: 'heapq.heappush(heap, item)',
294
- documentation: 'Pushes item onto heap, maintaining the min-heap invariant.\n\n- Module: `heapq`\n- Complexity: $O(\\log N)$',
295
- insertText: 'heapq.heappush(${1:heap}, ${2:item})',
296
- module: 'heapq',
297
- complexity: 'O(log N)'
298
- },
299
- 'heapq.heappop': {
300
- label: 'heapq.heappop',
301
- detail: 'heapq.heappop(heap)',
302
- documentation: 'Pops and returns the smallest item from heap, maintaining invariant.\n\n- Module: `heapq`\n- Complexity: $O(\\log N)$',
303
- insertText: 'heapq.heappop(${1:heap})',
304
- module: 'heapq',
305
- complexity: 'O(log N)'
306
- },
307
- 'bisect.bisect_left': {
308
- label: 'bisect.bisect_left',
309
- detail: 'bisect.bisect_left(a, x, lo=0, hi=len(a))',
310
- documentation: 'Locates the insertion point for x in a to maintain sorted order (leftmost index).\n\n- Module: `bisect`\n- Complexity: $O(\\log N)$',
311
- insertText: 'bisect.bisect_left(${1:a}, ${2:x})',
312
- module: 'bisect',
313
- complexity: 'O(log N)'
314
- },
315
- 'functools.lru_cache': {
316
- label: 'functools.lru_cache',
317
- detail: '@functools.lru_cache(maxsize=128, typed=False)',
318
- documentation: 'Decorator to wrap a function with a memoizing callable that saves up to maxsize results.\n\n- Module: `functools`',
319
- insertText: '@lru_cache(maxsize=None)\ndef ${1:fn}(${2:args}):\n pass',
320
- module: 'functools',
321
- complexity: 'O(1) cached lookup'
322
- },
323
- 'codelab_dsa.ListNode': {
324
- label: 'ListNode',
325
- detail: 'class ListNode(val=0, next=None)',
326
- documentation: 'LeetCode / DSA standard singly-linked list node.\n\n- Module: `codelab_dsa`',
327
- insertText: 'ListNode(${1:val})',
328
- module: 'codelab_dsa',
329
- complexity: 'O(1)'
330
- },
331
- 'codelab_dsa.TreeNode': {
332
- label: 'TreeNode',
333
- detail: 'class TreeNode(val=0, left=None, right=None)',
334
- documentation: 'LeetCode / DSA standard binary tree node.\n\n- Module: `codelab_dsa`',
335
- insertText: 'TreeNode(${1:val})',
336
- module: 'codelab_dsa',
337
- complexity: 'O(1)'
338
- },
339
- 'codelab_dsa.build_linked_list': {
340
- label: 'build_linked_list',
341
- detail: 'build_linked_list(vals: list[int]) -> Optional[ListNode]',
342
- documentation: 'Builds a singly-linked list from a Python list of integers.\n\n- Module: `codelab_dsa`\n- Complexity: $O(N)$',
343
- insertText: 'build_linked_list([${1:1, 2, 3}])',
344
- module: 'codelab_dsa',
345
- complexity: 'O(N)'
346
- },
347
- 'codelab_dsa.linked_list_to_list': {
348
- label: 'linked_list_to_list',
349
- detail: 'linked_list_to_list(head: Optional[ListNode]) -> list[int]',
350
- documentation: 'Traverses a linked list and collects values into a Python list.\n\n- Module: `codelab_dsa`\n- Complexity: $O(N)$',
351
- insertText: 'linked_list_to_list(${1:head})',
352
- module: 'codelab_dsa',
353
- complexity: 'O(N)'
354
- },
355
- 'codelab_dsa.build_binary_tree': {
356
- label: 'build_binary_tree',
357
- detail: 'build_binary_tree(vals: list[Optional[int]]) -> Optional[TreeNode]',
358
- documentation: 'Constructs a binary tree level-by-level from a list containing None for null nodes.\n\n- Module: `codelab_dsa`\n- Complexity: $O(N)$',
359
- insertText: 'build_binary_tree([${1:1, 2, 3}])',
360
- module: 'codelab_dsa',
361
- complexity: 'O(N)'
362
- },
363
- 'codelab_test.DESCRIBE': {
364
- label: 'DESCRIBE',
365
- detail: 'DESCRIBE(name: str)',
366
- documentation: 'Defines the active test suite description in CodeLab test harness.\n\n- Module: `codelab_test`',
367
- insertText: 'DESCRIBE("${1:Suite Name}")\n',
368
- module: 'codelab_test',
369
- complexity: 'Test Suite Header'
370
- },
371
- 'codelab_test.TEST': {
372
- label: 'TEST',
373
- detail: 'TEST(name: str, fn: Callable)',
374
- documentation: 'Runs a single test case; emits structured __CODELAB_TEST__ telemetry.\n\n- Module: `codelab_test`',
375
- insertText: 'def test_${1:case}():\n ASSERT_EQ(${2:actual}, ${3:expected})\n\nTEST("${4:description}", test_${1:case})',
376
- module: 'codelab_test',
377
- complexity: 'Test Case Runner'
378
- },
379
- 'codelab_test.ASSERT_EQ': {
380
- label: 'ASSERT_EQ',
381
- detail: 'ASSERT_EQ(actual, expected, msg=None)',
382
- documentation: 'Asserts that actual == expected; logs failure message if not.\n\n- Module: `codelab_test`',
383
- insertText: 'ASSERT_EQ(${1:actual}, ${2:expected})',
384
- module: 'codelab_test',
385
- complexity: 'Assertion'
386
- },
387
- 'codelab_test.ASSERT_TRUE': {
388
- label: 'ASSERT_TRUE',
389
- detail: 'ASSERT_TRUE(condition, msg=None)',
390
- documentation: 'Asserts condition is True.\n\n- Module: `codelab_test`',
391
- insertText: 'ASSERT_TRUE(${1:condition})',
392
- module: 'codelab_test',
393
- complexity: 'Assertion'
394
- },
395
- 'codelab_test.ASSERT_FALSE': {
396
- label: 'ASSERT_FALSE',
397
- detail: 'ASSERT_FALSE(condition, msg=None)',
398
- documentation: 'Asserts condition is False.\n\n- Module: `codelab_test`',
399
- insertText: 'ASSERT_FALSE(${1:condition})',
400
- module: 'codelab_test',
401
- complexity: 'Assertion'
402
- },
403
- 'codelab_test.CODELAB_TEST_EXIT_CODE': {
404
- label: 'CODELAB_TEST_EXIT_CODE',
405
- detail: 'CODELAB_TEST_EXIT_CODE() -> int',
406
- documentation: 'Returns 0 if all tests passed, 1 if any failed.\n\n- Module: `codelab_test`',
407
- insertText: 'sys.exit(CODELAB_TEST_EXIT_CODE())',
408
- module: 'codelab_test',
409
- complexity: 'Exit Code'
410
- }
411
- };
412
-
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
- }
494
-
495
- /**
496
- * Registers Monaco Python completion, hover, signature help, definition, and symbol providers.
497
- */
498
- export function registerMonacoPythonLanguageService(
499
- monacoInstance: any,
500
- getWorkspaceFiles?: () => Record<string, string>
501
- ): boolean {
502
- if (typeof getWorkspaceFiles === 'function') {
503
- _pyWorkspaceFilesGetter = getWorkspaceFiles;
504
- }
505
- if (!monacoInstance || !monacoInstance.languages) return false;
506
- if (_monacoPyInstances.has(monacoInstance)) return true;
507
- _monacoPyInstances.add(monacoInstance);
508
-
509
- try {
510
- const CIK = monacoInstance.languages.CompletionItemKind || {};
511
- const CITR = monacoInstance.languages.CompletionItemInsertTextRule || {};
512
-
513
- monacoInstance.languages.registerCompletionItemProvider('python', {
514
- triggerCharacters: ['.', ' '],
515
- provideCompletionItems(model: any, position: any) {
516
- const wordInfo = model.getWordUntilPosition(position);
517
- const range = {
518
- startLineNumber: position.lineNumber,
519
- endLineNumber: position.lineNumber,
520
- startColumn: wordInfo.startColumn,
521
- endColumn: wordInfo.endColumn
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
- }
553
-
554
- const seen = new Set<string>();
555
- const suggestions = Object.keys(PYTHON_COMPLETIONS_AND_HOVERS).map((key) => {
556
- const item = PYTHON_COMPLETIONS_AND_HOVERS[key];
557
- seen.add(item.label);
558
- return {
559
- label: item.label,
560
- kind: CIK.Function ?? 1,
561
- detail: item.detail,
562
- documentation: { value: item.documentation },
563
- insertText: item.insertText || item.label,
564
- insertTextRules: CITR.InsertAsSnippet,
565
- range
566
- };
567
- });
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
-
584
- return { suggestions };
585
- }
586
- });
587
-
588
- monacoInstance.languages.registerHoverProvider('python', {
589
- provideHover(model: any, position: any) {
590
- const word = model.getWordAtPosition(position);
591
- if (!word) return null;
592
-
593
- let item: PythonSymbolDoc | null = null;
594
- for (const k of Object.keys(PYTHON_COMPLETIONS_AND_HOVERS)) {
595
- if (k === word.word || k.endsWith('.' + word.word)) {
596
- item = PYTHON_COMPLETIONS_AND_HOVERS[k];
597
- break;
598
- }
599
- }
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
- }
614
-
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;
632
- }
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
-
704
- return true;
705
- } catch (err) {
706
- if (typeof console !== 'undefined' && console.warn) {
707
- console.warn('[Python Monaco Intelligence Error]:', err);
708
- }
709
- return false;
710
- }
711
- }
712
-
713
- /**
714
- * Tier-1 instant Python static AST and syntax checker.
715
- */
716
- export function analyzePythonSource(source: string, filename = 'main.py'): DiagnosticItem[] {
717
- const diagnostics: DiagnosticItem[] = [];
718
- if (!source || typeof source !== 'string') return diagnostics;
719
-
720
- const lines = source.split('\n');
721
-
722
- // 1. Bracket stack matching
723
- const stack: Array<{ char: string; line: number; col: number }> = [];
724
- const matching: Record<string, string> = { ')': '(', ']': '[', '}': '{' };
725
-
726
- let expectIndentAfterLine = 0;
727
- let expectIndentMin = 0;
728
- let inTripleQuote: string | null = null;
729
-
730
- for (let l = 0; l < lines.length; l++) {
731
- const line = lines[l];
732
- const lineNum = l + 1;
733
- let inStr = false;
734
- let strChar = '';
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
-
747
- // Check mixed tab and space indentation
748
- const indentMatch = line.match(/^([ \t]+)/);
749
- const indentLen = indentMatch ? indentMatch[1].length : 0;
750
- if (indentMatch) {
751
- const indent = indentMatch[1];
752
- if (indent.includes('\t') && indent.includes(' ')) {
753
- diagnostics.push({
754
- id: `py-tab-space-mix-${lineNum}`,
755
- file: filename,
756
- line: lineNum,
757
- startLineNumber: lineNum,
758
- col: 1,
759
- startColumn: 1,
760
- severity: 'warning',
761
- message: 'Inconsistent use of tabs and spaces in indentation.',
762
- source: 'python-linter'
763
- } as any);
764
- }
765
- }
766
-
767
- const trimmed = line.trim();
768
-
769
- // Check expected indentation after ':'
770
- if (expectIndentAfterLine > 0 && trimmed && !trimmed.startsWith('#')) {
771
- if (indentLen <= expectIndentMin) {
772
- diagnostics.push({
773
- id: `py-indent-error-${lineNum}`,
774
- file: filename,
775
- line: lineNum,
776
- startLineNumber: lineNum,
777
- col: 1,
778
- startColumn: 1,
779
- severity: 'error',
780
- message: `IndentationError: expected an indented block after statement on line ${expectIndentAfterLine}.`,
781
- source: 'python-linter'
782
- } as any);
783
- }
784
- expectIndentAfterLine = 0;
785
- }
786
-
787
- const stackDepthAtLineStart = stack.length;
788
- let commentCol = -1;
789
-
790
- for (let c = 0; c < line.length; c++) {
791
- const ch = line[c];
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
- }
807
-
808
- if (ch === '"' || ch === '\'') {
809
- if (!inStr) {
810
- inStr = true;
811
- strChar = ch;
812
- } else if (strChar === ch && (c === 0 || line[c - 1] !== '\\')) {
813
- inStr = false;
814
- }
815
- continue;
816
- }
817
-
818
- if (inStr) continue;
819
-
820
- if (ch === '(' || ch === '[' || ch === '{') {
821
- stack.push({ char: ch, line: lineNum, col: c + 1 });
822
- } else if (ch === ')' || ch === ']' || ch === '}') {
823
- const expected = matching[ch];
824
- const last = stack.pop();
825
- if (!last) {
826
- diagnostics.push({
827
- id: `py-bracket-unmatched-${lineNum}-${c + 1}`,
828
- file: filename,
829
- line: lineNum,
830
- startLineNumber: lineNum,
831
- col: c + 1,
832
- startColumn: c + 1,
833
- severity: 'error',
834
- message: `Unmatched closing bracket '${ch}'.`,
835
- source: 'python-linter'
836
- } as any);
837
- } else if (last.char !== expected) {
838
- diagnostics.push({
839
- id: `py-bracket-mismatch-${lineNum}-${c + 1}`,
840
- file: filename,
841
- line: lineNum,
842
- startLineNumber: lineNum,
843
- col: c + 1,
844
- startColumn: c + 1,
845
- severity: 'error',
846
- message: `Mismatched bracket: expected closing for '${last.char}' from line ${last.line}, found '${ch}'.`,
847
- source: 'python-linter'
848
- } as any);
849
- }
850
- }
851
- }
852
-
853
- if (inStr && !inTripleQuote && !line.endsWith('\\')) {
854
- diagnostics.push({
855
- id: `py-eol-string-${lineNum}`,
856
- file: filename,
857
- line: lineNum,
858
- startLineNumber: lineNum,
859
- col: line.length,
860
- startColumn: line.length,
861
- severity: 'error',
862
- message: 'SyntaxError: EOL while scanning string literal.',
863
- source: 'python-linter'
864
- } as any);
865
- }
866
-
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 {
894
- expectIndentAfterLine = lineNum;
895
- expectIndentMin = indentLen;
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);
904
- }
905
- }
906
-
907
- for (const unclosed of stack) {
908
- diagnostics.push({
909
- id: `py-unclosed-bracket-${unclosed.line}-${unclosed.col}`,
910
- file: filename,
911
- line: unclosed.line,
912
- startLineNumber: unclosed.line,
913
- col: unclosed.col,
914
- startColumn: unclosed.col,
915
- severity: 'error',
916
- message: `SyntaxError: closing parenthesis does not match or unclosed bracket '${unclosed.char}' opened on line ${unclosed.line}.`,
917
- source: 'python-linter'
918
- } as any);
919
- }
920
-
921
- return diagnostics;
922
- }
923
-
924
- /**
925
- * Parses Python tracebacks and SyntaxErrors from stderr and pushes into DiagnosticsStore & Monaco markers.
926
- */
927
- export function applyPythonTracebackDiagnostics(
928
- stderrText: string,
929
- diagnosticsStore?: any,
930
- monacoInstance?: any,
931
- activeModel?: any
932
- ): DiagnosticItem[] {
933
- const diagnostics: DiagnosticItem[] = [];
934
- if (!stderrText || typeof stderrText !== 'string') return diagnostics;
935
-
936
- if (diagnosticsStore && typeof diagnosticsStore.clear === 'function') {
937
- diagnosticsStore.clear('python');
938
- }
939
-
940
- // Regex matching Python File ".../workspace/<file>.py", line <N>
941
- const tbRegex = /File\s+["'](?:(?:\/workspace\/)?([^"']+))["'],\s+line\s+(\d+)(?:,\s+in\s+([A-Za-z0-9_<>]+))?/g;
942
- let lastFile = 'main.py';
943
- let lastLine = 1;
944
- let match: RegExpExecArray | null;
945
-
946
- while ((match = tbRegex.exec(stderrText)) !== null) {
947
- lastFile = match[1].replace(/^\/workspace\//, '');
948
- lastLine = parseInt(match[2], 10) || 1;
949
- }
950
-
951
- // Look for exception line e.g. "NameError: name 'foo' is not defined" or "SyntaxError: invalid syntax"
952
- const lines = stderrText.trim().split('\n');
953
- const errLine = lines[lines.length - 1] || 'Python Execution Error';
954
-
955
- if (errLine.includes('Error:') || errLine.includes('Exception:') || errLine.includes('Error')) {
956
- const item: DiagnosticItem = {
957
- id: `python-error-${lastFile}-${lastLine}`,
958
- file: lastFile,
959
- line: lastLine,
960
- startLineNumber: lastLine,
961
- col: 1,
962
- startColumn: 1,
963
- severity: 'error',
964
- message: `[Python] ${errLine.trim()}`,
965
- source: 'python'
966
- } as any;
967
- diagnostics.push(item);
968
- if (diagnosticsStore && typeof diagnosticsStore.add === 'function') {
969
- diagnosticsStore.add(item);
970
- }
971
- }
972
-
973
- if (monacoInstance && activeModel && typeof monacoInstance.editor?.setModelMarkers === 'function') {
974
- const markers = diagnostics.map((d) => ({
975
- startLineNumber: d.line,
976
- startColumn: d.col || 1,
977
- endLineNumber: d.line,
978
- endColumn: 100,
979
- message: d.message,
980
- severity: monacoInstance.MarkerSeverity.Error
981
- }));
982
- monacoInstance.editor.setModelMarkers(activeModel, 'python', markers);
983
- }
984
-
985
- return diagnostics;
986
- }
987
-
988
- /**
989
- * Deterministic PEP 8 / 4-space indentation formatter.
990
- */
991
- export function formatPythonSource(code: string): string {
992
- if (!code || typeof code !== 'string') return code;
993
- const lines = code.split('\n');
994
- const formatted: string[] = [];
995
- let indentLevel = 0;
996
- let emptyCount = 0;
997
-
998
- for (let i = 0; i < lines.length; i++) {
999
- const rawLine = lines[i];
1000
- const trimmed = rawLine.trim();
1001
-
1002
- if (!trimmed) {
1003
- emptyCount++;
1004
- if (emptyCount <= 1 && formatted.length > 0) {
1005
- formatted.push('');
1006
- }
1007
- continue;
1008
- }
1009
- emptyCount = 0;
1010
-
1011
- if (trimmed.startsWith('#')) {
1012
- formatted.push(' '.repeat(indentLevel) + trimmed);
1013
- continue;
1014
- }
1015
-
1016
- // Dedent before checking line if it starts with dedent keywords
1017
- if (/^(?:elif\b|else:|except\b|finally:|return\b|pass\b|raise\b)/.test(trimmed)) {
1018
- if (/^(?:elif\b|else:|except\b|finally:)/.test(trimmed) && indentLevel > 0) {
1019
- indentLevel--;
1020
- }
1021
- }
1022
-
1023
- formatted.push(' '.repeat(indentLevel) + trimmed);
1024
-
1025
- if (trimmed.endsWith(':')) {
1026
- indentLevel++;
1027
- }
1028
- }
1029
-
1030
- while (formatted.length > 0 && formatted[formatted.length - 1] === '') {
1031
- formatted.pop();
1032
- }
1033
- return formatted.join('\n') + '\n';
1034
- }
1035
-
1036
- /**
1037
- * Pyodide (CPython 3.12 WebAssembly) Toolchain Manager with IndexedDB cache.
1038
- */
1039
- export class PythonToolchainManager {
1040
- public readonly options: ExtendedPythonExtensionOptions;
1041
- public pyodide: any = null;
1042
- private _loadingPromise: Promise<any> | null = null;
1043
-
1044
- constructor(options: ExtendedPythonExtensionOptions = {}) {
1045
- this.options = PythonExtensionOptionsSchema.parse(options);
1046
- }
1047
-
1048
- public isLoaded(): boolean {
1049
- return this.pyodide !== null;
1050
- }
1051
-
1052
- public async preload(): Promise<any> {
1053
- return this.ensureLoaded();
1054
- }
1055
-
1056
- private _emitProgress(evt: PythonToolchainProgress) {
1057
- if (typeof this.options.onProgress === 'function') {
1058
- try {
1059
- this.options.onProgress(evt);
1060
- } catch (err) {
1061
- if (typeof console !== 'undefined' && console.warn) {
1062
- console.warn('[Python progress callback warning]:', err);
1063
- }
1064
- }
1065
- }
1066
- }
1067
-
1068
- private static _scriptPromises = new Map<string, Promise<void>>();
1069
-
1070
- public async ensureLoaded(): Promise<any> {
1071
- if (this.pyodide) return this.pyodide;
1072
- if (this._loadingPromise) return this._loadingPromise;
1073
-
1074
- this._loadingPromise = (async () => {
1075
- try {
1076
- this._emitProgress({
1077
- stage: 'downloading',
1078
- percent: 10,
1079
- message: 'Initializing CPython 3.12 WebAssembly (Pyodide)...'
1080
- });
1081
-
1082
- // Browser environment: load pyodide.js from CDN (deduplicated across concurrent instances)
1083
- if (typeof window !== 'undefined' && typeof document !== 'undefined' && !(this.options as any).headlessMock) {
1084
- const cdn = this.options.cdnBaseUrl || DEFAULT_PYTHON_CDN_BASE_URL;
1085
- const scriptUrl = `${cdn.replace(/\/+$/, '')}/pyodide.js`;
1086
- if (!(window as any).loadPyodide) {
1087
- let scriptPromise = PythonToolchainManager._scriptPromises.get(scriptUrl);
1088
- if (!scriptPromise) {
1089
- scriptPromise = new Promise<void>((resolve, reject) => {
1090
- const existing = typeof document.querySelector === 'function'
1091
- ? document.querySelector(`script[data-codelab-pyodide="${scriptUrl}"]`) as HTMLScriptElement | null
1092
- : null;
1093
- if (existing && (window as any).loadPyodide) {
1094
- resolve();
1095
- return;
1096
- }
1097
- const script = document.createElement('script');
1098
- script.src = scriptUrl;
1099
- script.setAttribute('data-codelab-pyodide', scriptUrl);
1100
- script.onload = () => resolve();
1101
- script.onerror = () => {
1102
- PythonToolchainManager._scriptPromises.delete(scriptUrl);
1103
- reject(new Error(`Failed to load pyodide.js from ${scriptUrl}`));
1104
- };
1105
- document.head.appendChild(script);
1106
- });
1107
- PythonToolchainManager._scriptPromises.set(scriptUrl, scriptPromise);
1108
- }
1109
- await scriptPromise;
1110
- }
1111
-
1112
- this._emitProgress({
1113
- stage: 'extracting',
1114
- percent: 50,
1115
- message: 'Bootstrapping Python runtime environment...'
1116
- });
1117
-
1118
- const loadPyodideFn = (window as any).loadPyodide;
1119
- this.pyodide = await loadPyodideFn({
1120
- indexURL: cdn
1121
- });
1122
- } else {
1123
- // Node / Bun headless mock toolchain for hermetic offline test runs (binary-safe)
1124
- const dirs = new Set<string>(['/', '/workspace', '/usr', '/usr/lib', '/usr/lib/python']);
1125
- const files = new Map<string, Uint8Array>();
1126
- const encoder = new TextEncoder();
1127
- const decoder = new TextDecoder('utf-8', { fatal: false });
1128
- const ensureDirs = (p: string) => {
1129
- const parts = p.split('/').filter(Boolean);
1130
- let cur = '';
1131
- for (const seg of parts) {
1132
- cur += '/' + seg;
1133
- dirs.add(cur);
1134
- }
1135
- };
1136
- this.pyodide = {
1137
- FS: {
1138
- files,
1139
- dirs,
1140
- mkdirTree(p: string) {
1141
- ensureDirs(p);
1142
- },
1143
- writeFile(p: string, content: any) {
1144
- const slashIdx = p.lastIndexOf('/');
1145
- if (slashIdx > 0) ensureDirs(p.slice(0, slashIdx));
1146
- if (content instanceof Uint8Array) {
1147
- files.set(p, content.slice());
1148
- } else if (ArrayBuffer.isView(content)) {
1149
- files.set(p, new Uint8Array(content.buffer, content.byteOffset, content.byteLength).slice());
1150
- } else {
1151
- files.set(p, encoder.encode(typeof content === 'string' ? content : String(content ?? '')));
1152
- }
1153
- },
1154
- readFile(p: string, opts?: any) {
1155
- const raw = files.get(p);
1156
- if (!raw) return opts && opts.encoding === 'utf8' ? '' : new Uint8Array(0);
1157
- if (opts && opts.encoding === 'utf8') {
1158
- return decoder.decode(raw);
1159
- }
1160
- return raw.slice();
1161
- },
1162
- unlink(p: string) {
1163
- files.delete(p);
1164
- },
1165
- readdir(dirPath: string) {
1166
- const prefix = dirPath === '/' ? '/' : dirPath.replace(/\/+$/, '') + '/';
1167
- const children = new Set<string>(['.', '..']);
1168
- for (const d of dirs) {
1169
- if (d.startsWith(prefix)) {
1170
- const rest = d.slice(prefix.length);
1171
- if (rest && !rest.includes('/')) children.add(rest);
1172
- }
1173
- }
1174
- for (const f of files.keys()) {
1175
- if (f.startsWith(prefix)) {
1176
- const rest = f.slice(prefix.length);
1177
- if (rest && !rest.includes('/')) children.add(rest);
1178
- }
1179
- }
1180
- return Array.from(children);
1181
- },
1182
- stat(p: string) {
1183
- if (dirs.has(p)) return { mode: 0o040755 };
1184
- if (files.has(p)) return { mode: 0o100644 };
1185
- throw new Error(`ENOENT: ${p}`);
1186
- },
1187
- isDir(mode: number) {
1188
- return (mode & 0o170000) === 0o040000;
1189
- }
1190
- },
1191
- runPythonAsync: async (code: string) => {
1192
- return `Execution mock: ${code.slice(0, 30)}`;
1193
- }
1194
- };
1195
- }
1196
-
1197
- // Preload specified packages if any
1198
- if (this.options.preloadPackages && Array.isArray(this.options.preloadPackages)) {
1199
- for (const pkg of this.options.preloadPackages) {
1200
- try {
1201
- if (typeof this.pyodide.loadPackage === 'function') {
1202
- await this.pyodide.loadPackage(pkg);
1203
- }
1204
- } catch (err) {
1205
- void err;
1206
- }
1207
- }
1208
- }
1209
-
1210
- this._emitProgress({
1211
- stage: 'ready',
1212
- percent: 100,
1213
- message: 'Python 3.12 WebAssembly Toolchain Ready'
1214
- });
1215
-
1216
- return this.pyodide;
1217
- } catch (err) {
1218
- this._loadingPromise = null;
1219
- throw err;
1220
- }
1221
- })();
1222
-
1223
- return this._loadingPromise;
1224
- }
1225
-
1226
- public async installPackages(packages: string[]): Promise<{ ok: boolean; installed: string[]; error?: string }> {
1227
- const pyodide = await this.ensureLoaded();
1228
- const installed: string[] = [];
1229
- for (const pkg of packages) {
1230
- if (!pkg || pkg.startsWith('-')) continue;
1231
- try {
1232
- if (typeof pyodide.loadPackage === 'function') {
1233
- await pyodide.loadPackage(pkg);
1234
- installed.push(pkg);
1235
- } else if (pyodide.FS) {
1236
- installed.push(pkg);
1237
- }
1238
- } catch (err: any) {
1239
- return { ok: false, installed, error: err?.message || String(err) };
1240
- }
1241
- }
1242
- return { ok: true, installed };
1243
- }
1244
-
1245
- public async execute(req: {
1246
- entry?: string;
1247
- source?: string;
1248
- vfs?: any;
1249
- stdin?: string;
1250
- testFilter?: string | string[];
1251
- onStdout?: (msg: string) => void;
1252
- onStderr?: (msg: string) => void;
1253
- }): Promise<PythonCompileResult> {
1254
- const start = performance.now();
1255
- let stdoutAcc = '';
1256
- let stderrAcc = '';
1257
- const testResults: TestResultItem[] = [];
1258
- const testParser = new CodeLabTestParser((item) => {
1259
- testResults.push(item);
1260
- });
1261
-
1262
- const handleOut = (msg: string) => {
1263
- stdoutAcc += msg;
1264
- const lines = msg.split('\n');
1265
- for (const line of lines) {
1266
- testParser.parseLine(line);
1267
- }
1268
- if (req.onStdout) req.onStdout(msg);
1269
- };
1270
-
1271
- const handleErr = (msg: string) => {
1272
- stderrAcc += msg;
1273
- if (req.onStderr) req.onStderr(msg);
1274
- };
1275
-
1276
- const pyodide = await this.ensureLoaded();
1277
-
1278
- // 1. Sync VFS files into Pyodide FS (binary-safe + prune files deleted in VFS)
1279
- const vfsSnapshotFiles = new Set<string>();
1280
- if (req.vfs && pyodide.FS) {
1281
- const syncVfsDir = (dirPath: string) => {
1282
- try {
1283
- if (typeof pyodide.FS.mkdirTree === 'function') {
1284
- pyodide.FS.mkdirTree(dirPath);
1285
- }
1286
- const entries = req.vfs.readdirSync(dirPath);
1287
- for (const entry of entries) {
1288
- if (!entry || entry === '.' || entry === '..') continue;
1289
- const fullPath = `${dirPath === '/' ? '' : dirPath}/${entry}`;
1290
- try {
1291
- const st = req.vfs.statSync(fullPath);
1292
- if (st && typeof st.isDirectory === 'function' && st.isDirectory()) {
1293
- syncVfsDir(fullPath);
1294
- } else {
1295
- const parentDir = fullPath.slice(0, fullPath.lastIndexOf('/')) || '/workspace';
1296
- if (typeof pyodide.FS.mkdirTree === 'function') {
1297
- pyodide.FS.mkdirTree(parentDir);
1298
- }
1299
- const rawContent = req.vfs.readFileSync(fullPath);
1300
- pyodide.FS.writeFile(fullPath, rawContent);
1301
- vfsSnapshotFiles.add(fullPath);
1302
- }
1303
- } catch (err) {
1304
- void err;
1305
- }
1306
- }
1307
- } catch (err) {
1308
- void err;
1309
- }
1310
- };
1311
- syncVfsDir('/workspace');
1312
-
1313
- // Prune stale files in Pyodide FS that no longer exist in VFS before execution
1314
- if (typeof pyodide.FS.readdir === 'function' && typeof pyodide.FS.unlink === 'function') {
1315
- const pruneStalePyodideFiles = (dirPath: string) => {
1316
- try {
1317
- const pyEntries = pyodide.FS.readdir(dirPath);
1318
- for (const f of pyEntries) {
1319
- if (!f || f === '.' || f === '..') continue;
1320
- const p = `${dirPath}/${f}`;
1321
- let isDir = false;
1322
- if (typeof pyodide.FS.stat === 'function' && typeof pyodide.FS.isDir === 'function') {
1323
- try {
1324
- isDir = Boolean(pyodide.FS.isDir(pyodide.FS.stat(p).mode));
1325
- } catch (err) {
1326
- void err;
1327
- }
1328
- }
1329
- if (isDir) {
1330
- pruneStalePyodideFiles(p);
1331
- } else if (!vfsSnapshotFiles.has(p)) {
1332
- try {
1333
- pyodide.FS.unlink(p);
1334
- } catch (err) {
1335
- void err;
1336
- }
1337
- }
1338
- }
1339
- } catch (err) {
1340
- void err;
1341
- }
1342
- };
1343
- pruneStalePyodideFiles('/workspace');
1344
- }
1345
- }
1346
-
1347
- // Seed builtin /usr/lib/python modules
1348
- if (pyodide.FS) {
1349
- try {
1350
- pyodide.FS.mkdirTree('/usr/lib/python');
1351
- for (const [p, content] of Object.entries(BUILTIN_PYTHON_MODULES)) {
1352
- pyodide.FS.writeFile(p, content);
1353
- }
1354
- } catch (err) {
1355
- void err;
1356
- }
1357
- }
1358
-
1359
- let codeToRun = req.source;
1360
- if (!codeToRun && req.entry && req.vfs) {
1361
- try {
1362
- codeToRun = req.vfs.readFileSync(req.entry.startsWith('/') ? req.entry : `/workspace/${req.entry}`, 'utf8');
1363
- } catch (err: any) {
1364
- handleErr(`FileNotFoundError: [Errno 2] No such file or directory: '${req.entry}'\n`);
1365
- return {
1366
- ok: false,
1367
- exitCode: 1,
1368
- stdout: stdoutAcc,
1369
- stderr: stderrAcc,
1370
- peakMemoryBytes: 0,
1371
- durationMs: performance.now() - start
1372
- };
1373
- }
1374
- }
1375
-
1376
- codeToRun = codeToRun || '';
1377
-
1378
- let peakMemoryBytes = 1024 * 1024; // 1 MB default estimate
1379
- let exitCode = 0;
1380
-
1381
- try {
1382
- if (typeof window !== 'undefined' && pyodide.setStdout) {
1383
- pyodide.setStdout({ batched: (msg: string) => handleOut(msg + '\n') });
1384
- pyodide.setStderr({ batched: (msg: string) => handleErr(msg + '\n') });
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) {
1403
- let pos = 0;
1404
- pyodide.setStdin({
1405
- stdin: () => {
1406
- if (pos < effectiveStdin.length) {
1407
- return effectiveStdin.charCodeAt(pos++);
1408
- }
1409
- return null;
1410
- }
1411
- });
1412
- }
1413
-
1414
- const fileLabel = JSON.stringify(req.entry || '<exec>');
1415
- const encodedCode = JSON.stringify(codeToRun);
1416
- const runnerWrapper = `
1417
- import sys, builtins, tracemalloc
1418
- if '/usr/lib/python' not in sys.path:
1419
- sys.path.insert(0, '/usr/lib/python')
1420
- if '/workspace' not in sys.path:
1421
- sys.path.insert(0, '/workspace')
1422
- if 'codelab_test' in sys.modules and hasattr(sys.modules['codelab_test'], '_reset_codelab_test'):
1423
- sys.modules['codelab_test']._reset_codelab_test()
1424
-
1425
- _cl_orig_input = builtins.input
1426
- ${prePromptedInteractive ? `builtins.input = lambda _prompt='': sys.stdin.readline().rstrip('\\r\\n')` : ''}
1427
- _cl_user_code = ${encodedCode}
1428
- _cl_ns = {'__name__': '__main__', '__file__': ${fileLabel}, '__builtins__': __builtins__}
1429
- tracemalloc.start()
1430
- try:
1431
- exec(compile(_cl_user_code, ${fileLabel}, 'exec'), _cl_ns)
1432
- finally:
1433
- builtins.input = _cl_orig_input
1434
- _, _peak = tracemalloc.get_traced_memory()
1435
- tracemalloc.stop()
1436
- `;
1437
- await pyodide.runPythonAsync(runnerWrapper);
1438
- if (pyodide.globals && typeof pyodide.globals.get === 'function') {
1439
- try {
1440
- const rawPeak = pyodide.globals.get('_peak');
1441
- if (typeof rawPeak === 'number' && rawPeak > 0) {
1442
- peakMemoryBytes = rawPeak;
1443
- }
1444
- } catch (err) {
1445
- void err;
1446
- }
1447
- }
1448
- } else {
1449
- // Mock Node/Bun execution
1450
- if (req.source && /sys\.exit\(\s*(\d+)?\s*\)/.test(req.source)) {
1451
- const m = req.source.match(/sys\.exit\(\s*(\d+)?\s*\)/);
1452
- exitCode = m && m[1] !== undefined ? parseInt(m[1], 10) : 0;
1453
- if (exitCode !== 0) {
1454
- handleErr(`SystemExit: ${exitCode}\n`);
1455
- }
1456
- } else {
1457
- handleOut(`[Python 3.12 Wasm]: Executed ${req.entry || 'snippet'}\n`);
1458
- }
1459
- }
1460
- } catch (err: any) {
1461
- const errMsg = err && err.message ? err.message : String(err);
1462
- const isSystemExit = /SystemExit(?::\s*([0-9]+|None)?)?/.test(errMsg);
1463
- if (isSystemExit) {
1464
- const match = errMsg.match(/SystemExit(?::\s*([0-9]+))?/);
1465
- exitCode = match && match[1] !== undefined ? parseInt(match[1], 10) : 0;
1466
- if (exitCode !== 0) {
1467
- handleErr(errMsg + '\n');
1468
- }
1469
- } else {
1470
- exitCode = 1;
1471
- handleErr(errMsg + '\n');
1472
- }
1473
- }
1474
-
1475
- // 2. Sync back files from Pyodide FS into VFS (binary-safe + propagate Python deletions)
1476
- if (req.vfs && pyodide.FS && typeof pyodide.FS.readdir === 'function') {
1477
- const pyFilesAfter = new Set<string>();
1478
- const syncBackPyodideDir = (dirPath: string) => {
1479
- try {
1480
- const entries = pyodide.FS.readdir(dirPath);
1481
- for (const f of entries) {
1482
- if (!f || f === '.' || f === '..') continue;
1483
- const p = `${dirPath}/${f}`;
1484
- try {
1485
- let isDir = false;
1486
- if (typeof pyodide.FS.stat === 'function' && typeof pyodide.FS.isDir === 'function') {
1487
- const st = pyodide.FS.stat(p);
1488
- isDir = Boolean(pyodide.FS.isDir(st.mode));
1489
- }
1490
- if (isDir) {
1491
- if (typeof req.vfs.mkdirSync === 'function' && !req.vfs.existsSync(p)) {
1492
- req.vfs.mkdirSync(p, { recursive: true });
1493
- }
1494
- syncBackPyodideDir(p);
1495
- } else {
1496
- const parentDir = p.slice(0, p.lastIndexOf('/')) || '/workspace';
1497
- if (typeof req.vfs.mkdirSync === 'function' && !req.vfs.existsSync(parentDir)) {
1498
- req.vfs.mkdirSync(parentDir, { recursive: true });
1499
- }
1500
- const rawBytes = pyodide.FS.readFile(p);
1501
- req.vfs.writeFileSync(p, rawBytes);
1502
- pyFilesAfter.add(p);
1503
- }
1504
- } catch (err) {
1505
- void err;
1506
- }
1507
- }
1508
- } catch (err) {
1509
- void err;
1510
- }
1511
- };
1512
- syncBackPyodideDir('/workspace');
1513
-
1514
- if (typeof req.vfs.unlinkSync === 'function') {
1515
- for (const existedBefore of vfsSnapshotFiles) {
1516
- if (!pyFilesAfter.has(existedBefore)) {
1517
- try {
1518
- req.vfs.unlinkSync(existedBefore);
1519
- } catch (err) {
1520
- void err;
1521
- }
1522
- }
1523
- }
1524
- }
1525
- }
1526
-
1527
- const durationMs = performance.now() - start;
1528
-
1529
- return {
1530
- ok: exitCode === 0,
1531
- exitCode,
1532
- stdout: stdoutAcc,
1533
- stderr: stderrAcc,
1534
- peakMemoryBytes,
1535
- durationMs,
1536
- testResults
1537
- };
1538
- }
1539
- }
1540
-
1541
- /**
1542
- * Seeds `/usr/lib/python` headers and libraries into the VirtualFS.
1543
- */
1544
- export function seedPythonModulesIntoVfs(vfs: any) {
1545
- if (!vfs) return;
1546
- for (const [p, content] of Object.entries(BUILTIN_PYTHON_MODULES)) {
1547
- const withoutSlash = p.replace(/^\//, '');
1548
- if (typeof vfs.writeFileSync === 'function') {
1549
- try {
1550
- if (typeof vfs.mkdirSync === 'function') {
1551
- vfs.mkdirSync('/usr/lib/python', { recursive: true });
1552
- }
1553
- } catch (err) {
1554
- void err;
1555
- }
1556
- try {
1557
- vfs.writeFileSync(p, content);
1558
- } catch (err) {
1559
- void err;
1560
- }
1561
- }
1562
- if (vfs.files && typeof vfs.files === 'object') {
1563
- vfs.files[p] = content;
1564
- vfs.files[withoutSlash] = content;
1565
- }
1566
- if (typeof vfs === 'object' && typeof vfs.writeFileSync !== 'function') {
1567
- vfs[p] = content;
1568
- vfs[withoutSlash] = content;
1569
- }
1570
- }
1571
- }
1572
-
1573
- /**
1574
- * Registers the Python compiler toolchain on the global runtime.
1575
- */
1576
- export function registerPythonCompilerOnRuntime(toolchain: PythonToolchainManager) {
1577
- const compilerFn = async (req: any) => {
1578
- return toolchain.execute(req);
1579
- };
1580
-
1581
- if (typeof globalThis !== 'undefined') {
1582
- (globalThis as any).__codelabPythonCompiler = compilerFn;
1583
- (globalThis as any).__codelabPythonToolchain = toolchain;
1584
- }
1585
- if (typeof window !== 'undefined') {
1586
- (window as any).__codelabPythonCompiler = compilerFn;
1587
- (window as any).__codelabPythonToolchain = toolchain;
1588
- }
1589
- return compilerFn;
1590
- }
1591
-
1592
- function installPythonExtension(workbench: any, options: ExtendedPythonExtensionOptions = {}) {
1593
- const toolchain = new PythonToolchainManager(options);
1594
- const compilerFn = registerPythonCompilerOnRuntime(toolchain);
1595
-
1596
- if (!workbench) return toolchain;
1597
-
1598
- workbench.pythonToolchain = toolchain;
1599
- workbench.pythonCompiler = compilerFn;
1600
- workbench.pythonOptions = toolchain.options;
1601
- if (workbench.shell && workbench.shell.options) {
1602
- workbench.shell.options.pythonCompiler = compilerFn;
1603
- workbench.shell.options.pythonToolchain = toolchain;
1604
- }
1605
-
1606
- const getWsFiles = () => (workbench && workbench.files ? workbench.files : {});
1607
- if (typeof window !== 'undefined' && (window as any).monaco) {
1608
- registerMonacoPythonLanguageService((window as any).monaco, getWsFiles);
1609
- }
1610
- if (!Array.isArray(workbench._monacoReadyHooks)) {
1611
- workbench._monacoReadyHooks = [];
1612
- }
1613
- workbench._monacoReadyHooks.push((monaco: any) => {
1614
- registerMonacoPythonLanguageService(monaco, getWsFiles);
1615
- });
1616
-
1617
- if (!workbench.enabledLanguages || !(workbench.enabledLanguages instanceof Set)) {
1618
- workbench.enabledLanguages = new Set(['js', 'py']);
1619
- } else {
1620
- workbench.enabledLanguages.add('py');
1621
- }
1622
-
1623
- if (options.files && typeof options.files === 'object') {
1624
- workbench.pyFiles = { ...(workbench.pyFiles || {}), ...options.files };
1625
- if (workbench.guidedConfig) {
1626
- workbench.guidedConfig.pyFiles = { ...(workbench.guidedConfig.pyFiles || {}), ...options.files };
1627
- }
1628
- }
1629
- if (options.starterFiles && typeof options.starterFiles === 'object') {
1630
- if (!workbench.guidedConfig) workbench.guidedConfig = {};
1631
- workbench.guidedConfig.pyStarterFiles = {
1632
- ...(workbench.guidedConfig.pyStarterFiles || {}),
1633
- ...options.starterFiles
1634
- };
1635
- }
1636
- if (options.solutionFiles && typeof options.solutionFiles === 'object') {
1637
- if (!workbench.guidedConfig) workbench.guidedConfig = {};
1638
- workbench.guidedConfig.pySolutionFiles = {
1639
- ...(workbench.guidedConfig.pySolutionFiles || {}),
1640
- ...options.solutionFiles
1641
- };
1642
- }
1643
-
1644
- if (workbench.vfs) {
1645
- seedPythonModulesIntoVfs(workbench.vfs);
1646
- }
1647
-
1648
- workbench.hasMultipleLanguages = workbench.enabledLanguages.size > 1;
1649
-
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
- };
1683
-
1684
- if (options.preload) {
1685
- toolchain.ensureLoaded().catch((err) => {
1686
- if (typeof workbench._appendTerminalOutput === 'function') {
1687
- workbench._appendTerminalOutput('stderr', `[Python Toolchain preload warning]: ${err.message || err}\n`);
1688
- }
1689
- });
1690
- }
1691
-
1692
- if (options.activate && typeof workbench.setLanguage === 'function') {
1693
- workbench.setLanguage('py');
1694
- } else if (typeof workbench._refreshToolbarAndTabs === 'function') {
1695
- workbench._refreshToolbarAndTabs();
1696
- } else if (typeof workbench._renderShell === 'function' && workbench.container) {
1697
- workbench._renderShell();
1698
- if (typeof workbench._bindEvents === 'function') workbench._bindEvents();
1699
- if (typeof workbench._renderFileLists === 'function') workbench._renderFileLists();
1700
- }
1701
-
1702
- return toolchain;
1703
- }
1704
-
1705
- /**
1706
- * Real Python 3.12 (CPython WebAssembly via Pyodide) Extension for CodeLab.
1707
- */
1708
- export function pythonExtension(workbenchOrOptions?: any, maybeOptions?: ExtendedPythonExtensionOptions): any {
1709
- if (workbenchOrOptions === null) {
1710
- const toolchain = new PythonToolchainManager(maybeOptions || {});
1711
- registerPythonCompilerOnRuntime(toolchain);
1712
- return toolchain;
1713
- }
1714
- if (
1715
- workbenchOrOptions === undefined ||
1716
- (typeof workbenchOrOptions === 'object' &&
1717
- !('enabledLanguages' in workbenchOrOptions) &&
1718
- !('container' in workbenchOrOptions) &&
1719
- !('_renderShell' in workbenchOrOptions))
1720
- ) {
1721
- const opts = (workbenchOrOptions || {}) as ExtendedPythonExtensionOptions;
1722
- const plugin: any = (wb: any, runOpts: any = {}) => {
1723
- return installPythonExtension(wb, { ...opts, ...(runOpts || {}) });
1724
- };
1725
- plugin.extensionName = 'python';
1726
- plugin.languageId = 'py';
1727
- plugin.install = plugin;
1728
- return plugin;
1729
- }
1730
- return installPythonExtension(workbenchOrOptions, maybeOptions);
1731
- }
1732
-
1733
- export function createPythonExtension(options: ExtendedPythonExtensionOptions = {}) {
1734
- return pythonExtension(options);
1735
- }
1736
-
1737
- export default pythonExtension;