wasm-idle 1.2.0 → 1.4.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 (105) hide show
  1. package/README.md +250 -146
  2. package/dist/container/clang-runtime.js +32 -8
  3. package/dist/container/runtime-adapter.d.ts +2 -0
  4. package/dist/container/runtime-adapter.js +37 -8
  5. package/dist/index.d.ts +1 -0
  6. package/dist/index.js +1 -0
  7. package/dist/playground/assetBridge.js +10 -8
  8. package/dist/playground/assets.d.ts +4 -0
  9. package/dist/playground/assets.js +9 -4
  10. package/dist/playground/c3.js +1 -1
  11. package/dist/playground/compiledLldb.d.ts +2 -0
  12. package/dist/playground/compiledLldb.js +37 -2
  13. package/dist/playground/d.d.ts +1 -0
  14. package/dist/playground/d.js +18 -8
  15. package/dist/playground/index.d.ts +1 -1
  16. package/dist/playground/index.js +7 -0
  17. package/dist/playground/{java-debug-FMHDKUN6.js → java-debug-64JGCLTC.js} +1 -1
  18. package/dist/playground/java-debug-notices.txt +26 -1
  19. package/dist/playground/java.js +3 -2
  20. package/dist/playground/javaDebugBridge.js +42 -7
  21. package/dist/playground/javaDebugSource.js +4 -4
  22. package/dist/playground/javaMain.d.ts +3 -0
  23. package/dist/playground/javaMain.js +2 -0
  24. package/dist/playground/javaRuntimeErrors.d.ts +2 -1
  25. package/dist/playground/javaRuntimeErrors.js +9 -2
  26. package/dist/playground/javaSource.d.ts +1 -1
  27. package/dist/playground/javaSource.js +7 -2
  28. package/dist/playground/lldbSession.d.ts +2 -0
  29. package/dist/playground/lldbSession.js +60 -4
  30. package/dist/playground/objectivec.d.ts +1 -1
  31. package/dist/playground/objectivec.js +2 -1
  32. package/dist/playground/options.d.ts +1 -1
  33. package/dist/playground/python.d.ts +3 -0
  34. package/dist/playground/python.js +122 -2
  35. package/dist/playground/pythonCompileOptions.d.ts +52 -0
  36. package/dist/playground/pythonCompileOptions.js +40 -0
  37. package/dist/playground/scala.d.ts +34 -0
  38. package/dist/playground/scala.js +397 -0
  39. package/dist/playground/scalaAssets.d.ts +16 -0
  40. package/dist/playground/scalaAssets.js +51 -0
  41. package/dist/playground/scalaDiagnostics.d.ts +3 -0
  42. package/dist/playground/scalaDiagnostics.js +29 -0
  43. package/dist/playground/staticRuntimeModuleVersion.d.ts +1 -1
  44. package/dist/playground/staticRuntimeModuleVersion.js +1 -1
  45. package/dist/playground/staticWorkerRuntime.d.ts +2 -0
  46. package/dist/playground/staticWorkerRuntime.js +85 -11
  47. package/dist/playground/tinygo.js +21 -8
  48. package/dist/playground/tinygoExecutableGraph.js +1 -1
  49. package/dist/playground/v.d.ts +1 -0
  50. package/dist/playground/v.js +17 -7
  51. package/dist/playground/wasmC3Version.d.ts +8 -8
  52. package/dist/playground/wasmC3Version.js +8 -8
  53. package/dist/playground/wasmDebugVersion.d.ts +1 -1
  54. package/dist/playground/wasmDebugVersion.js +1 -1
  55. package/dist/playground/wasmDotnetVersion.d.ts +1 -1
  56. package/dist/playground/wasmDotnetVersion.js +1 -1
  57. package/dist/playground/wasmGoVersion.d.ts +1 -1
  58. package/dist/playground/wasmGoVersion.js +1 -1
  59. package/dist/playground/wasmLispVersion.d.ts +5 -0
  60. package/dist/playground/wasmLispVersion.js +5 -0
  61. package/dist/playground/wasmOcamlVersion.d.ts +4 -4
  62. package/dist/playground/wasmOcamlVersion.js +3 -3
  63. package/dist/playground/wasmPrologVersion.d.ts +17 -17
  64. package/dist/playground/wasmPrologVersion.js +16 -16
  65. package/dist/playground/wasmTinyGoVersion.d.ts +57 -57
  66. package/dist/playground/wasmTinyGoVersion.js +57 -57
  67. package/dist/playground/wasmTypeScriptVersion.d.ts +3 -3
  68. package/dist/playground/wasmTypeScriptVersion.js +3 -3
  69. package/dist/playground/wasmZigVersion.d.ts +7 -7
  70. package/dist/playground/wasmZigVersion.js +7 -7
  71. package/dist/playground/worker/java.js +18 -4
  72. package/dist/playground/worker/javaDebugEvaluator.js +2 -2
  73. package/dist/playground/worker/javaDebugRuntime.js +8 -1
  74. package/dist/playground/worker/javaStreaming.js +4 -2
  75. package/dist/playground/worker/ocaml.js +11 -10
  76. package/dist/playground/worker/python.js +45 -165
  77. package/dist/playground/worker/pythonCompile.d.ts +4 -0
  78. package/dist/playground/worker/pythonCompile.js +127 -0
  79. package/dist/playground/worker/pythonDebug.d.ts +20 -0
  80. package/dist/playground/worker/pythonDebug.js +205 -0
  81. package/dist/playground/worker/scala/UPSTREAM-LICENSE.txt +201 -0
  82. package/dist/playground/worker/scala/UPSTREAM-NOTICE.txt +108 -0
  83. package/dist/playground/worker/scala/asset-bootstrap.d.ts +6 -0
  84. package/dist/playground/worker/scala/asset-bootstrap.js +58 -0
  85. package/dist/playground/worker/scala/asset-receipts.d.ts +7 -0
  86. package/dist/playground/worker/scala/asset-receipts.js +58 -0
  87. package/dist/playground/worker/scala/compiler.worker.d.ts +1 -0
  88. package/dist/playground/worker/scala/compiler.worker.js +204 -0
  89. package/dist/playground/worker/scala/execution.worker.d.ts +1 -0
  90. package/dist/playground/worker/scala/execution.worker.js +89 -0
  91. package/dist/playground/worker/scala/memory-fs.d.ts +29 -0
  92. package/dist/playground/worker/scala/memory-fs.js +333 -0
  93. package/dist/playground/worker/scala/runner.d.ts +1 -0
  94. package/dist/playground/worker/scala/runner.js +36 -0
  95. package/dist/playground/worker/zig.d.ts +2 -1
  96. package/dist/playground/worker/zig.js +212 -86
  97. package/dist/playground/worker/zigDebug.d.ts +39 -0
  98. package/dist/playground/worker/zigDebug.js +156 -0
  99. package/dist/playground/zig.d.ts +27 -4
  100. package/dist/playground/zig.js +266 -23
  101. package/dist/playground/zigDebugValues.d.ts +20 -0
  102. package/dist/playground/zigDebugValues.js +248 -0
  103. package/dist/pythonCompiler.d.ts +8 -0
  104. package/dist/pythonCompiler.js +52 -0
  105. package/package.json +37 -26
@@ -33,10 +33,8 @@ const outerAssetIdentity = (url, receipt) => JSON.stringify([url, receipt.bytes,
33
33
  function appendTrailingNewline(text) {
34
34
  return text.endsWith('\n') ? text : `${text}\n`;
35
35
  }
36
- function normalizeAssetLoader(programSource, runtimePromiseKey) {
37
- let normalizedSource = programSource.includes('($=>async a=>{')
38
- ? programSource.replace('($=>async a=>{', `globalThis.${runtimePromiseKey}=($=>async a=>{`)
39
- : programSource;
36
+ function normalizeAssetLoader(programSource) {
37
+ const normalizedSource = programSource;
40
38
  const assetLoaderPattern = /function ([A-Za-z$_][\w$]*)\(([A-Za-z$_][\w$]*)\)\{const ([A-Za-z$_][\w$]*)=([A-Za-z$_][\w$]*)\?new URL\(\2,\4\):\2;return fetch\(\3\)\}/;
41
39
  const matchedLoader = normalizedSource.match(assetLoaderPattern);
42
40
  if (!matchedLoader) {
@@ -255,7 +253,6 @@ async function executeCompileResult(result, log = false, stdin) {
255
253
  const programArtifact = getJsArtifact(result);
256
254
  const assetFiles = result.artifacts.filter((artifact) => artifact.kind === 'wasm' || artifact.kind === 'asset');
257
255
  const assetResolverKey = '__wasm_of_js_of_ocaml_resolve_asset';
258
- const runtimePromiseKey = '__wasm_of_js_of_ocaml_runtime_promise';
259
256
  const stdinHookKey = '__wasmIdleOcamlReadStdin';
260
257
  const sourceDir = programArtifact.path.replace(/\/[^/]+$/, '');
261
258
  const createdObjectUrls = [];
@@ -424,7 +421,7 @@ async function executeCompileResult(result, log = false, stdin) {
424
421
  runtimeGlobal['module'] = { exports: {} };
425
422
  runtimeGlobal['exports'] = runtimeGlobal['module'].exports;
426
423
  try {
427
- let normalizedSource = normalizeAssetLoader(programArtifact.data, runtimePromiseKey);
424
+ let normalizedSource = normalizeAssetLoader(programArtifact.data);
428
425
  const stdinReadReplacement = 'read($1,$2,$3,$4){var e=globalThis.__wasmIdleOcamlReadStdin?globalThis.__wasmIdleOcamlReadStdin($3):null;if(e==null)return 0;var h=e.length,f=new Uint8Array(h),i=0;for(;i<h;i++)f[i]=e.charCodeAt(i);var g=f.length<$3?f.length:$3;$1.set(f.subarray(0,g),$2);return g}';
429
426
  const patchedSource = normalizedSource.replace(/read\(([A-Za-z$_][\w$]*),([A-Za-z$_][\w$]*),([A-Za-z$_][\w$]*),([A-Za-z$_][\w$]*)\)\{cz\(\4,mc,aha,ow\)\}/, stdinReadReplacement);
430
427
  normalizedSource =
@@ -433,12 +430,17 @@ async function executeCompileResult(result, log = false, stdin) {
433
430
  : normalizedSource.replace(/read\(([A-Za-z$_][\w$]*),([A-Za-z$_][\w$]*),([A-Za-z$_][\w$]*),([A-Za-z$_][\w$]*)\)\{[^{}]+\}(?=seek\([A-Za-z$_][\w$]*,[A-Za-z$_][\w$]*,[A-Za-z$_][\w$]*\)\{[^{}]+\}pos\(\)\{return-1\}close\(\)\{this\.log=undefined\}check_stream_semantics\([A-Za-z$_][\w$]*\)\{\})/, stdinReadReplacement);
434
431
  normalizedSource = normalizedSource
435
432
  .replace(/\bfs\.readSync\(/g, 'globalThis.fs.readSync(')
436
- .replace(/read:\(([^)]*)\)=>[A-Za-z$_][\w$]*\.readSync\(/g, 'read:($1)=>globalThis.fs.readSync(');
433
+ .replace(/read:\(([^)]*)\)=>[A-Za-z$_][\w$]*\.readSync\(/g, 'read:($1)=>globalThis.fs.readSync(')
434
+ .replace(
435
+ // wasm_of_ocaml 6.5 checks its registered virtual files before
436
+ // falling back to Node's five-argument readSync. Preserve that path.
437
+ /\breturn [A-Za-z$_][\w$]*\.readSync\(([A-Za-z$_][\w$]*),([A-Za-z$_][\w$]*),([A-Za-z$_][\w$]*),([A-Za-z$_][\w$]*),([A-Za-z$_][\w$]*)\)\}/g, 'return globalThis.fs.readSync($1,$2,$3,$4,$5)}');
437
438
  if (log && normalizedSource === programArtifact.data) {
438
439
  console.warn('[wasm-idle:ocaml-worker] stdin runtime patch did not match generated JS');
439
440
  }
440
- new Function(`${normalizedSource}\n//# sourceURL=${programArtifact.path}`)();
441
- const runtimePromise = globalThis[runtimePromiseKey];
441
+ // The generated script's completion value is its async Wasm initializer.
442
+ // Evaluate in a fresh function scope without depending on minified names.
443
+ const runtimePromise = new Function('return eval(arguments[0])')(`${normalizedSource}\n//# sourceURL=${programArtifact.path}`);
442
444
  if (runtimePromise instanceof Promise) {
443
445
  await runtimePromise;
444
446
  }
@@ -451,7 +453,6 @@ async function executeCompileResult(result, log = false, stdin) {
451
453
  if (originalInstantiateStreaming) {
452
454
  WebAssembly.instantiateStreaming = originalInstantiateStreaming;
453
455
  }
454
- delete globalThis[runtimePromiseKey];
455
456
  delete globalThis[assetResolverKey];
456
457
  if (!hadProcess) {
457
458
  delete runtimeGlobal['process'];
@@ -4,9 +4,10 @@ import { parsePythonPackageLock } from '../pythonPackageLock';
4
4
  import { WASM_APECODE_VERSION, WASM_APECODE_WHEELS } from '../wasmApecodeVersion';
5
5
  import { withCachedPyodideModule } from './runtimeModule';
6
6
  import { createPythonExecutionHelpers } from './pythonExecution';
7
+ import { compilePythonBytecode } from './pythonCompile';
7
8
  import { createPythonWorkspaceImports } from './pythonWorkspaceImports';
8
9
  import { createPythonWorkspaceFiles } from './pythonWorkspaceFiles';
9
- import { PYTHON_DEBUG_PREVIEW } from './pythonDebugPreview';
10
+ import { createPythonDebugHelpers } from './pythonDebug';
10
11
  import { createPythonStdio, PYTHON_FLUSH_HOOK_FACTORY } from './pythonStdio';
11
12
  import { fetchRuntimeAssetBytes } from './runtimeAssetFetch';
12
13
  import { configureWorkerRuntimeAssetAllowlist, configureWorkerRuntimeAssets, handleWorkerAssetMessage, loadWorkerRuntimeAsset } from './assets';
@@ -28,6 +29,7 @@ let installedApecodeVersion;
28
29
  let executionHelpers;
29
30
  let invalidateWorkspaceImports;
30
31
  let syncWorkspaceFiles;
32
+ let debugHelpers;
31
33
  let debugPauseSequence = 0;
32
34
  let installPythonFlushHooks;
33
35
  const PYTHON_EXTENSIONS = {
@@ -491,7 +493,7 @@ None
491
493
  self.onmessage = async (event) => {
492
494
  if (handleWorkerAssetMessage(event.data))
493
495
  return;
494
- const { code, buffer, debugBuffer, watchBuffer, watchResultBuffer, load, interrupt, assets, prepare, stdin, debug = false, breakpoints = [], pauseOnEntry = false, activePath, debugPath, workspaceFiles, language = 'python', extension } = event.data;
496
+ const { code, buffer, debugBuffer, watchBuffer, watchResultBuffer, load, interrupt, assets, compile, fileName, optimize, invalidationMode, timestamp, maxArtifactBytes, prepare, stdin, debug = false, breakpoints = [], pauseOnEntry = false, activePath, debugPath, workspaceFiles, language = 'python', extension } = event.data;
495
497
  const isHy = language === 'hy';
496
498
  const isAheui = language === 'aheui';
497
499
  const isApecode = language === 'apecode';
@@ -522,6 +524,28 @@ self.onmessage = async (event) => {
522
524
  self.postMessage({ error: e.message || 'Unknown error' });
523
525
  }
524
526
  }
527
+ else if (compile) {
528
+ try {
529
+ if (language !== 'python')
530
+ throw new Error('Bytecode compilation is supported only for Python');
531
+ await loadPyodide(baseUrl);
532
+ postProgress(10, 'Compiling Python bytecode');
533
+ const compiled = compilePythonBytecode(pyodide, code, fileName, optimize, maxArtifactBytes, {
534
+ invalidationMode,
535
+ timestamp
536
+ });
537
+ postProgress(100, 'Python bytecode ready');
538
+ self.postMessage({ compiled }, [compiled.data.buffer]);
539
+ }
540
+ catch (e) {
541
+ self.postMessage({
542
+ error: e.message || 'Unknown error',
543
+ ...(e.code === 'output-limit'
544
+ ? { outputLimit: { actual: e.actual, limit: e.limit } }
545
+ : {})
546
+ });
547
+ }
548
+ }
525
549
  else if (prepare) {
526
550
  preparedPackagesKey = undefined;
527
551
  try {
@@ -641,6 +665,8 @@ self.onmessage = async (event) => {
641
665
  }
642
666
  }
643
667
  };
668
+ let debugTrace;
669
+ const debugTraceName = `__wasm_idle_python_debug_trace_${ts}`;
644
670
  const debugPauseName = `__wasm_idle_python_debug_pause_${ts}`;
645
671
  const debugWaitName = `__wasm_idle_python_debug_wait_${ts}`;
646
672
  const debugReadWatchName = `__wasm_idle_python_debug_watch_read_${ts}`;
@@ -740,7 +766,6 @@ self.onmessage = async (event) => {
740
766
  (isHy ? '__wasm_idle_user__.hy' : '__wasm_idle_user__.py');
741
767
  const debugFilename = normalizeWorkspacePath(debugPath || '') || executionFilename;
742
768
  const executionFilenameLiteral = JSON.stringify(executionFilename);
743
- const debugFilenameLiteral = JSON.stringify(debugFilename);
744
769
  const normalizedBreakpoints = JSON.stringify([...(Array.isArray(breakpoints) ? breakpoints : [])]
745
770
  .map((value) => Number(value))
746
771
  .filter((value) => Number.isInteger(value) && value > 0));
@@ -758,6 +783,18 @@ self.onmessage = async (event) => {
758
783
  await getExecutionHelpers().run(code, executionFilename, self[executionReadyName]);
759
784
  }
760
785
  else {
786
+ if (debug) {
787
+ debugHelpers ??= createPythonDebugHelpers(pyodide, imageHook);
788
+ debugTrace = debugHelpers.createTrace(debugFilename, normalizedBreakpoints, !!pauseOnEntry, {
789
+ state: self[debugBreakpointStateName],
790
+ readBreakpoints: self[debugReadBreakpointsName],
791
+ pause: self[debugPauseName],
792
+ wait: self[debugWaitName],
793
+ readWatch: self[debugReadWatchName],
794
+ writeWatch: self[debugWriteWatchName]
795
+ });
796
+ self[debugTraceName] = debugTrace;
797
+ }
761
798
  await pyodide.runPythonAsync(`import ast
762
799
  import builtins
763
800
  import inspect
@@ -766,162 +803,9 @@ import os
766
803
  import sys
767
804
  import types
768
805
  from js import ${executionReadyName} as __wasm_idle_execution_ready
769
- ${debug ? `from js import ${debugPauseName}, ${debugWaitName}` : ''}
770
- ${debug ? `from js import ${debugReadWatchName}, ${debugWriteWatchName}` : ''}
771
- ${debug ? `from js import ${debugReadBreakpointsName}` : ''}
772
- ${debug ? `from js import ${debugBreakpointStateName} as __wasm_idle_debug_breakpoint_state` : ''}
773
-
774
- ${imageHook}
775
-
776
- ${debug
777
- ? `
778
- import os as __wasm_idle_debug_os
779
-
780
- # Direct compilation uses relative paths; imported modules use absolute paths.
781
- # Capture both identities before user code can change the working directory.
782
- __wasm_idle_debug_source_filenames = {
783
- ${debugFilenameLiteral},
784
- __wasm_idle_debug_os.path.abspath(${debugFilenameLiteral}),
785
- }
786
- __wasm_idle_debug_breakpoints = set(${normalizedBreakpoints})
787
- __wasm_idle_debug_breakpoint_version = -1
788
- __wasm_idle_debug_pause_on_entry = ${pauseOnEntry ? 'True' : 'False'}
789
- __wasm_idle_debug_step_mode = None
790
- __wasm_idle_debug_next_depth = None
791
- __wasm_idle_debug_step_out_depth = None
792
-
793
- def __wasm_idle_debug_refresh_breakpoints():
794
- global __wasm_idle_debug_breakpoints
795
- global __wasm_idle_debug_breakpoint_version
796
- if __wasm_idle_debug_breakpoint_state.version == __wasm_idle_debug_breakpoint_version:
797
- return
798
- payload = ${debugReadBreakpointsName}(__wasm_idle_debug_breakpoint_version)
799
- # JavaScript null crosses Pyodide as JsNull rather than Python None.
800
- if not isinstance(payload, str):
801
- return
802
- snapshot = json.loads(payload)
803
- version = int(snapshot.get("version", -1))
804
- if version == __wasm_idle_debug_breakpoint_version:
805
- return
806
- __wasm_idle_debug_breakpoint_version = version
807
- __wasm_idle_debug_breakpoints = set(int(line) for line in snapshot.get("lines", []) if int(line) > 0)
808
-
809
- def __wasm_idle_debug_depth(frame):
810
- depth = 0
811
- current = frame
812
- while current is not None:
813
- if current.f_code.co_filename in __wasm_idle_debug_source_filenames:
814
- depth += 1
815
- current = current.f_back
816
- return depth
806
+ ${debug ? `from js import ${debugTraceName} as __wasm_idle_debug_trace` : ''}
817
807
 
818
- ${PYTHON_DEBUG_PREVIEW}
819
-
820
- def __wasm_idle_debug_locals(frame, start=0, count=50):
821
- locals_preview = []
822
- index = 0
823
- for name, value in frame.f_locals.items():
824
- if name == "__builtins__" or name.startswith("__wasm_idle_") or name.startswith("."):
825
- continue
826
- if index >= start:
827
- preview = __wasm_idle_debug_preview(value)
828
- if len(preview) > 200:
829
- preview = preview[:197] + "..."
830
- suffix = "… [" + str(index) + "]"
831
- display_name = name if len(name) <= 256 else name[:256-len(suffix)] + suffix
832
- locals_preview.append({"name": display_name, "value": preview})
833
- if len(locals_preview) >= count:
834
- break
835
- index += 1
836
- return locals_preview
837
-
838
- def __wasm_idle_debug_stack(frame):
839
- stack = []
840
- current = frame
841
- while current is not None:
842
- if current.f_code.co_filename in __wasm_idle_debug_source_filenames:
843
- stack.append({"functionName": current.f_code.co_name, "line": current.f_lineno})
844
- current = current.f_back
845
- return stack
846
-
847
- def __wasm_idle_debug_trace(frame, event, arg):
848
- global __wasm_idle_debug_pause_on_entry
849
- global __wasm_idle_debug_step_mode
850
- global __wasm_idle_debug_next_depth
851
- global __wasm_idle_debug_step_out_depth
852
-
853
- if frame.f_code.co_filename not in __wasm_idle_debug_source_filenames:
854
- return None
855
- if event != "line":
856
- return __wasm_idle_debug_trace
857
-
858
- __wasm_idle_debug_refresh_breakpoints()
859
- # Returning from a trace callback executes this event; a later event on the same
860
- # line is another loop iteration, not a replay of the previous stop.
861
- needs_depth = __wasm_idle_debug_step_mode in ("next", "out")
862
- depth = __wasm_idle_debug_depth(frame) if needs_depth else None
863
- line = frame.f_lineno
864
-
865
- reason = None
866
- if __wasm_idle_debug_pause_on_entry:
867
- reason = "entry"
868
- elif line in __wasm_idle_debug_breakpoints:
869
- reason = "breakpoint"
870
- elif __wasm_idle_debug_step_mode == "step":
871
- reason = "step"
872
- elif __wasm_idle_debug_step_mode == "next" and __wasm_idle_debug_next_depth is not None and depth <= __wasm_idle_debug_next_depth:
873
- reason = "nextLine"
874
- elif __wasm_idle_debug_step_mode == "out" and __wasm_idle_debug_step_out_depth is not None and depth <= __wasm_idle_debug_step_out_depth:
875
- reason = "stepOut"
876
-
877
- if reason is None:
878
- return __wasm_idle_debug_trace
879
-
880
- if depth is None:
881
- depth = __wasm_idle_debug_depth(frame)
882
- __wasm_idle_debug_pause_on_entry = False
883
- __wasm_idle_debug_step_mode = None
884
- __wasm_idle_debug_next_depth = None
885
- __wasm_idle_debug_step_out_depth = None
886
-
887
- sys.stdout.flush()
888
- sys.stderr.flush()
889
- pause_reference = ${debugPauseName}(line, reason, json.dumps(__wasm_idle_debug_locals(frame)), json.dumps(__wasm_idle_debug_stack(frame)))
890
- while True:
891
- command = ${debugWaitName}()
892
- if command < 0:
893
- raise KeyboardInterrupt()
894
- if command == 6:
895
- try:
896
- request = json.loads(${debugReadWatchName}())
897
- start = max(0, int(request.get("start", 0)))
898
- count = max(1, min(50, int(request.get("count", 50))))
899
- page = __wasm_idle_debug_locals(frame, start, count) if request.get("reference") == pause_reference else []
900
- ${debugWriteWatchName}(json.dumps(page))
901
- except Exception:
902
- ${debugWriteWatchName}("[]")
903
- continue
904
- if command != 5:
905
- break
906
- try:
907
- expression = ${debugReadWatchName}()
908
- result = __wasm_idle_debug_preview(eval(expression, frame.f_globals, frame.f_locals))
909
- except Exception as error:
910
- result = "?" if error.__class__.__name__ == "NameError" else "error"
911
- ${debugWriteWatchName}(result)
912
- if command == 2:
913
- __wasm_idle_debug_step_mode = "step"
914
- elif command == 3:
915
- __wasm_idle_debug_step_mode = "next"
916
- __wasm_idle_debug_next_depth = depth
917
- elif command == 4:
918
- __wasm_idle_debug_step_mode = "out"
919
- __wasm_idle_debug_step_out_depth = max(0, depth - 1)
920
- return __wasm_idle_debug_trace
921
-
922
- sys.settrace(__wasm_idle_debug_trace)
923
- `
924
- : ''}
808
+ ${debug ? 'sys.settrace(__wasm_idle_debug_trace)' : imageHook}
925
809
 
926
810
  ${isHy
927
811
  ? `
@@ -986,13 +870,7 @@ finally:
986
870
  __wasm_idle_globals.pop(${JSON.stringify(executionReadyName)}, None)
987
871
  del __wasm_idle_execution_ready
988
872
  sys.settrace(None)
989
- ${debug
990
- ? `
991
- __wasm_idle_debug_step_mode = None
992
- __wasm_idle_debug_next_depth = None
993
- __wasm_idle_debug_step_out_depth = None
994
- `
995
- : ''}
873
+ ${debug ? 'del __wasm_idle_debug_trace' : ''}
996
874
  `}
997
875
  `);
998
876
  }
@@ -1019,6 +897,8 @@ finally:
1019
897
  delete self[debugWriteWatchName];
1020
898
  delete self[debugReadBreakpointsName];
1021
899
  delete self[debugBreakpointStateName];
900
+ delete self[debugTraceName];
901
+ debugTrace?.destroy();
1022
902
  }
1023
903
  }
1024
904
  };
@@ -0,0 +1,4 @@
1
+ import type { PyodideInterface } from 'pyodide';
2
+ import { type PythonCompileOptions, type PythonCompileResult } from '../pythonCompileOptions';
3
+ /** Compile with CPython without executing source or resolving its imports. */
4
+ export declare function compilePythonBytecode(runtime: PyodideInterface, code: string, fileName: string, optimize: 0 | 1 | 2, maxArtifactBytes: number, options?: Pick<PythonCompileOptions, 'invalidationMode' | 'timestamp'>): PythonCompileResult;
@@ -0,0 +1,127 @@
1
+ import { OutputLimitError } from '@wasm-idle/core';
2
+ import { resolvePythonBytecodeOptions } from '../pythonCompileOptions';
3
+ const PYTHON_COMPILE = String.raw `
4
+ def compile_bytecode(source, filename, optimization, byte_limit, invalidation_mode, timestamp):
5
+ import codecs
6
+ import importlib.util
7
+ import io
8
+ import os
9
+ import platform
10
+ import py_compile
11
+ import sys
12
+ import tempfile
13
+ import tokenize
14
+
15
+ source_text = source.removeprefix("\ufeff")
16
+ encoding = "utf-8"
17
+ # Read only the coding-cookie metadata. detect_encoding also validates
18
+ # header bytes, which do not yet exist in the declared encoding.
19
+ # Universal newlines apply only to this scan, preserving the source hash.
20
+ with io.StringIO(source_text, newline=None) as lines:
21
+ for _ in range(2):
22
+ header = lines.readline().encode("ascii", "replace")
23
+ cookie = tokenize.cookie_re.match(header)
24
+ if cookie:
25
+ encoding = tokenize._get_normal_name(cookie.group(1).decode("ascii"))
26
+ try:
27
+ codecs.lookup(encoding)
28
+ except LookupError:
29
+ raise SyntaxError("unknown encoding: " + encoding) from None
30
+ break
31
+ if not tokenize.blank_re.match(header):
32
+ break
33
+ if source.startswith("\ufeff"):
34
+ if encoding != "utf-8":
35
+ raise SyntaxError("encoding problem: utf-8")
36
+ encoding = "utf-8-sig"
37
+ # Encode the original text; py_compile validates the actual source bytes.
38
+ encoded_source = source_text.encode(encoding)
39
+ mode = {
40
+ "checked-hash": py_compile.PycInvalidationMode.CHECKED_HASH,
41
+ "unchecked-hash": py_compile.PycInvalidationMode.UNCHECKED_HASH,
42
+ "timestamp": py_compile.PycInvalidationMode.TIMESTAMP,
43
+ "normalized": py_compile.PycInvalidationMode.CHECKED_HASH,
44
+ }[invalidation_mode]
45
+
46
+ with tempfile.TemporaryDirectory(prefix="wasm-idle-pyc-") as directory:
47
+ source_path = os.path.join(directory, "main.py")
48
+ output_path = os.path.join(directory, "output.pyc")
49
+ with open(source_path, "wb") as source_file:
50
+ source_file.write(encoded_source)
51
+ if invalidation_mode == "timestamp":
52
+ os.utime(source_path, (timestamp, timestamp))
53
+ py_compile.compile(
54
+ source_path,
55
+ cfile=output_path,
56
+ dfile=filename,
57
+ doraise=True,
58
+ optimize=optimization,
59
+ invalidation_mode=mode,
60
+ )
61
+ size = os.path.getsize(output_path)
62
+ if size > byte_limit:
63
+ return {"byteLimitExceeded": size}
64
+ with open(output_path, "rb") as output_file:
65
+ data = output_file.read()
66
+ if invalidation_mode == "normalized":
67
+ # Preserve the runtime magic and complete code object, but remove the
68
+ # source hash, flags, timestamp and source size for source-free artifacts.
69
+ data = data[:4] + bytes(12) + data[16:]
70
+ return {
71
+ "data": data,
72
+ "pythonVersion": platform.python_version(),
73
+ "cacheTag": sys.implementation.cache_tag,
74
+ "magicNumber": importlib.util.MAGIC_NUMBER.hex(),
75
+ }
76
+
77
+ compile_bytecode(source, filename, optimization, byte_limit, invalidation_mode, timestamp)
78
+ `;
79
+ /** Compile with CPython without executing source or resolving its imports. */
80
+ export function compilePythonBytecode(runtime, code, fileName, optimize, maxArtifactBytes, options = {}) {
81
+ if (typeof code !== 'string')
82
+ throw new TypeError('Python source must be a string');
83
+ if (typeof fileName !== 'string' || !/\.py$/i.test(fileName))
84
+ throw new TypeError('Python source file name must end in .py');
85
+ if (![0, 1, 2].includes(optimize))
86
+ throw new TypeError('Python optimization must be 0, 1, or 2');
87
+ if (!Number.isSafeInteger(maxArtifactBytes) || maxArtifactBytes <= 0)
88
+ throw new TypeError('Python artifact byte limit must be a positive safe integer');
89
+ const { invalidationMode, timestamp } = resolvePythonBytecodeOptions(options);
90
+ // A private namespace keeps source and filenames out of executable bridge text.
91
+ const globals = runtime.toPy({
92
+ source: code,
93
+ filename: fileName,
94
+ optimization: optimize,
95
+ byte_limit: maxArtifactBytes,
96
+ invalidation_mode: invalidationMode,
97
+ timestamp: timestamp ?? 0
98
+ });
99
+ try {
100
+ const result = runtime.runPython(PYTHON_COMPILE, { globals });
101
+ try {
102
+ const converted = result.toJs({
103
+ dict_converter: Object.fromEntries,
104
+ create_pyproxies: false
105
+ });
106
+ if ('byteLimitExceeded' in converted) {
107
+ throw new OutputLimitError(`Python bytecode is ${converted.byteLimitExceeded} bytes; limit is ${maxArtifactBytes}`, {
108
+ runtimeId: 'PYTHON3',
109
+ phase: 'compile',
110
+ actual: converted.byteLimitExceeded,
111
+ limit: maxArtifactBytes
112
+ });
113
+ }
114
+ return {
115
+ ...converted,
116
+ path: fileName.replace(/\.py$/i, '.pyc'),
117
+ data: Uint8Array.from(converted.data)
118
+ };
119
+ }
120
+ finally {
121
+ result.destroy();
122
+ }
123
+ }
124
+ finally {
125
+ globals.destroy();
126
+ }
127
+ }
@@ -0,0 +1,20 @@
1
+ import type { PyodideInterface } from 'pyodide';
2
+ /** Fixed code is reusable; every run still gets its own breakpoint and stepping state. */
3
+ export declare const PYTHON_DEBUG_TRACE: string;
4
+ export declare const PYTHON_DEBUG_FACTORY: string;
5
+ interface PythonDebugBridge {
6
+ state: {
7
+ readonly version: number;
8
+ };
9
+ readBreakpoints(knownVersion: number): string | null;
10
+ pause(line: number, reason: string, locals: string, stack: string): number;
11
+ wait(): number;
12
+ readWatch(): string;
13
+ writeWatch(value: string): void;
14
+ }
15
+ /** The worker retains only fixed code; callers destroy each run's returned trace proxy. */
16
+ export declare function createPythonDebugHelpers(runtime: PyodideInterface, imageHook: string): {
17
+ createTrace(filename: string, breakpoints: string, pauseOnEntry: boolean, bridge: PythonDebugBridge): any;
18
+ dispose(): void;
19
+ };
20
+ export {};