wasm-idle 1.1.2 → 1.3.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 (136) hide show
  1. package/README.md +211 -91
  2. package/dist/container/bash-profile.d.ts +80 -0
  3. package/dist/container/bash-profile.js +328 -0
  4. package/dist/{playground/container → container}/binding.d.ts +21 -8
  5. package/dist/{playground/container → container}/binding.js +109 -25
  6. package/dist/{playground/container → container}/clang-runtime.d.ts +11 -7
  7. package/dist/container/clang-runtime.js +561 -0
  8. package/dist/container/client.d.ts +14 -0
  9. package/dist/{playground/container → container}/client.js +2 -6
  10. package/dist/{playground/container → container}/explorer.d.ts +1 -1
  11. package/dist/container/index.d.ts +11 -0
  12. package/dist/container/index.js +11 -0
  13. package/dist/container/owner-worker.d.ts +19 -0
  14. package/dist/container/owner-worker.js +464 -0
  15. package/dist/{playground/container → container}/protocol.d.ts +12 -1
  16. package/dist/{playground/container → container}/runtime-adapter.d.ts +13 -11
  17. package/dist/{playground/container → container}/runtime-adapter.js +104 -41
  18. package/dist/{playground/container → container}/shell-control.d.ts +2 -2
  19. package/dist/{playground/container → container}/shell-control.js +93 -36
  20. package/dist/{playground/container → container}/workspace.d.ts +5 -1
  21. package/dist/index.d.ts +2 -1
  22. package/dist/index.js +1 -0
  23. package/dist/playground/assetBridge.js +5 -2
  24. package/dist/playground/assets.d.ts +8 -0
  25. package/dist/playground/clang.d.ts +5 -1
  26. package/dist/playground/clang.js +61 -5
  27. package/dist/playground/compiledLldb.d.ts +41 -0
  28. package/dist/playground/compiledLldb.js +167 -0
  29. package/dist/playground/d.d.ts +4 -1
  30. package/dist/playground/d.js +78 -9
  31. package/dist/playground/debugDeadline.d.ts +12 -0
  32. package/dist/playground/debugDeadline.js +34 -0
  33. package/dist/playground/debugMailbox.d.ts +12 -0
  34. package/dist/playground/debugMailbox.js +77 -0
  35. package/dist/playground/go.js +9 -4
  36. package/dist/playground/goDebugInstrumentation.js +24 -44
  37. package/dist/playground/java-debug-HUZVAK4F.js +124 -0
  38. package/dist/playground/java-debug-notices.txt +492 -0
  39. package/dist/playground/java.d.ts +17 -1
  40. package/dist/playground/java.js +159 -3
  41. package/dist/playground/javaDebug.d.ts +62 -0
  42. package/dist/playground/javaDebug.js +305 -0
  43. package/dist/playground/javaDebugBridge.d.ts +6 -0
  44. package/dist/playground/javaDebugBridge.js +250 -0
  45. package/dist/playground/javaDebugSource.d.ts +9 -0
  46. package/dist/playground/javaDebugSource.js +4 -0
  47. package/dist/playground/javaRuntimeErrors.js +34 -1
  48. package/dist/playground/lean4Assets.d.ts +1 -25
  49. package/dist/playground/lean4Assets.js +2 -123
  50. package/dist/playground/lfortranAssets.d.ts +2 -2
  51. package/dist/playground/lldbSession.d.ts +24 -2
  52. package/dist/playground/lldbSession.js +322 -59
  53. package/dist/playground/lldbSourcePath.d.ts +2 -0
  54. package/dist/playground/lldbSourcePath.js +9 -0
  55. package/dist/playground/lua.d.ts +20 -1
  56. package/dist/playground/lua.js +190 -8
  57. package/dist/playground/luaDebug.d.ts +1 -0
  58. package/dist/playground/luaDebug.js +1 -0
  59. package/dist/playground/nim.d.ts +1 -0
  60. package/dist/playground/nim.js +8 -0
  61. package/dist/playground/objectivec.d.ts +7 -6
  62. package/dist/playground/objectivec.js +75 -9
  63. package/dist/playground/options.d.ts +10 -4
  64. package/dist/playground/python.d.ts +11 -1
  65. package/dist/playground/python.js +203 -8
  66. package/dist/playground/pythonCompileOptions.d.ts +49 -0
  67. package/dist/playground/pythonCompileOptions.js +40 -0
  68. package/dist/playground/ruby.d.ts +10 -1
  69. package/dist/playground/ruby.js +66 -1
  70. package/dist/playground/rubyDebug.d.ts +21 -0
  71. package/dist/playground/rubyDebug.js +128 -0
  72. package/dist/playground/rust.d.ts +5 -1
  73. package/dist/playground/rust.js +128 -46
  74. package/dist/playground/sandbox.d.ts +8 -1
  75. package/dist/playground/staticRuntimeModuleVersion.d.ts +1 -1
  76. package/dist/playground/staticRuntimeModuleVersion.js +1 -1
  77. package/dist/playground/staticWorkerRuntime.js +8 -2
  78. package/dist/playground/stdinBuffer.d.ts +1 -1
  79. package/dist/playground/stdinBuffer.js +19 -2
  80. package/dist/playground/tinygo.js +7 -0
  81. package/dist/playground/typescript.js +8 -0
  82. package/dist/playground/v.d.ts +3 -2
  83. package/dist/playground/v.js +66 -12
  84. package/dist/playground/wasmC3Version.d.ts +2 -2
  85. package/dist/playground/wasmC3Version.js +2 -2
  86. package/dist/playground/wasmDebugVersion.d.ts +1 -1
  87. package/dist/playground/wasmDebugVersion.js +1 -1
  88. package/dist/playground/wasmLean4Version.d.ts +1 -110
  89. package/dist/playground/wasmLean4Version.js +2 -111
  90. package/dist/playground/wasmLfortranVersion.d.ts +2 -2
  91. package/dist/playground/wasmLfortranVersion.js +2 -2
  92. package/dist/playground/wasmLuaVersion.d.ts +1 -1
  93. package/dist/playground/wasmLuaVersion.js +1 -1
  94. package/dist/playground/wasmPrologVersion.d.ts +17 -17
  95. package/dist/playground/wasmPrologVersion.js +16 -16
  96. package/dist/playground/wasmRustVersion.d.ts +26 -38
  97. package/dist/playground/wasmRustVersion.js +25 -40
  98. package/dist/playground/wasmTypeScriptVersion.d.ts +3 -3
  99. package/dist/playground/wasmTypeScriptVersion.js +3 -3
  100. package/dist/playground/worker/clang.js +1 -1
  101. package/dist/playground/worker/cobol.js +1 -1
  102. package/dist/playground/worker/d.js +51 -2
  103. package/dist/playground/worker/fortran.js +1 -1
  104. package/dist/playground/worker/java.js +188 -35
  105. package/dist/playground/worker/javaDebugEvaluator.d.ts +16 -0
  106. package/dist/playground/worker/javaDebugEvaluator.js +44 -0
  107. package/dist/playground/worker/javaDebugRuntime.d.ts +24 -0
  108. package/dist/playground/worker/javaDebugRuntime.js +315 -0
  109. package/dist/playground/worker/javaOutput.d.ts +11 -0
  110. package/dist/playground/worker/javaOutput.js +54 -0
  111. package/dist/playground/worker/lua.js +13 -0
  112. package/dist/playground/worker/python.js +81 -23
  113. package/dist/playground/worker/pythonCompile.d.ts +4 -0
  114. package/dist/playground/worker/pythonCompile.js +122 -0
  115. package/dist/playground/worker/ruby.js +13 -0
  116. package/dist/playground/worker/rubyDebugPreview.d.ts +2 -0
  117. package/dist/playground/worker/rubyDebugPreview.js +80 -0
  118. package/dist/playground/worker/rubyTracepoint.d.ts +16 -0
  119. package/dist/playground/worker/rubyTracepoint.js +162 -0
  120. package/dist/playground/worker/rust.js +4 -1
  121. package/dist/playground/worker/v.js +30 -5
  122. package/dist/playground/zig.js +4 -0
  123. package/dist/pythonCompiler.d.ts +8 -0
  124. package/dist/pythonCompiler.js +52 -0
  125. package/package.json +76 -28
  126. package/dist/playground/container/ContainerExplorer.svelte +0 -307
  127. package/dist/playground/container/ContainerExplorer.svelte.d.ts +0 -14
  128. package/dist/playground/container/clang-runtime.js +0 -343
  129. package/dist/playground/container/client.d.ts +0 -15
  130. package/dist/playground/container/owner.worker.d.ts +0 -1
  131. package/dist/playground/container/owner.worker.js +0 -390
  132. package/dist/playground/container/release.d.ts +0 -31
  133. package/dist/playground/container/release.js +0 -612
  134. /package/dist/{playground/container → container}/explorer.js +0 -0
  135. /package/dist/{playground/container → container}/protocol.js +0 -0
  136. /package/dist/{playground/container → container}/workspace.js +0 -0
@@ -0,0 +1,122 @@
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
+ }[invalidation_mode]
44
+
45
+ with tempfile.TemporaryDirectory(prefix="wasm-idle-pyc-") as directory:
46
+ source_path = os.path.join(directory, "main.py")
47
+ output_path = os.path.join(directory, "output.pyc")
48
+ with open(source_path, "wb") as source_file:
49
+ source_file.write(encoded_source)
50
+ if invalidation_mode == "timestamp":
51
+ os.utime(source_path, (timestamp, timestamp))
52
+ py_compile.compile(
53
+ source_path,
54
+ cfile=output_path,
55
+ dfile=filename,
56
+ doraise=True,
57
+ optimize=optimization,
58
+ invalidation_mode=mode,
59
+ )
60
+ size = os.path.getsize(output_path)
61
+ if size > byte_limit:
62
+ return {"byteLimitExceeded": size}
63
+ with open(output_path, "rb") as output_file:
64
+ data = output_file.read()
65
+ return {
66
+ "data": data,
67
+ "pythonVersion": platform.python_version(),
68
+ "cacheTag": sys.implementation.cache_tag,
69
+ "magicNumber": importlib.util.MAGIC_NUMBER.hex(),
70
+ }
71
+
72
+ compile_bytecode(source, filename, optimization, byte_limit, invalidation_mode, timestamp)
73
+ `;
74
+ /** Compile with CPython without executing source or resolving its imports. */
75
+ export function compilePythonBytecode(runtime, code, fileName, optimize, maxArtifactBytes, options = {}) {
76
+ if (typeof code !== 'string')
77
+ throw new TypeError('Python source must be a string');
78
+ if (typeof fileName !== 'string' || !/\.py$/i.test(fileName))
79
+ throw new TypeError('Python source file name must end in .py');
80
+ if (![0, 1, 2].includes(optimize))
81
+ throw new TypeError('Python optimization must be 0, 1, or 2');
82
+ if (!Number.isSafeInteger(maxArtifactBytes) || maxArtifactBytes <= 0)
83
+ throw new TypeError('Python artifact byte limit must be a positive safe integer');
84
+ const { invalidationMode, timestamp } = resolvePythonBytecodeOptions(options);
85
+ // A private namespace keeps source and filenames out of executable bridge text.
86
+ const globals = runtime.toPy({
87
+ source: code,
88
+ filename: fileName,
89
+ optimization: optimize,
90
+ byte_limit: maxArtifactBytes,
91
+ invalidation_mode: invalidationMode,
92
+ timestamp: timestamp ?? 0
93
+ });
94
+ try {
95
+ const result = runtime.runPython(PYTHON_COMPILE, { globals });
96
+ try {
97
+ const converted = result.toJs({
98
+ dict_converter: Object.fromEntries,
99
+ create_pyproxies: false
100
+ });
101
+ if ('byteLimitExceeded' in converted) {
102
+ throw new OutputLimitError(`Python bytecode is ${converted.byteLimitExceeded} bytes; limit is ${maxArtifactBytes}`, {
103
+ runtimeId: 'PYTHON3',
104
+ phase: 'compile',
105
+ actual: converted.byteLimitExceeded,
106
+ limit: maxArtifactBytes
107
+ });
108
+ }
109
+ return {
110
+ ...converted,
111
+ path: fileName.replace(/\.py$/i, '.pyc'),
112
+ data: Uint8Array.from(converted.data)
113
+ };
114
+ }
115
+ finally {
116
+ result.destroy();
117
+ }
118
+ }
119
+ finally {
120
+ globals.destroy();
121
+ }
122
+ }
@@ -1,5 +1,7 @@
1
1
  import { waitForBufferedStdin } from '../stdinBuffer';
2
2
  import { importRuntimeModule } from '../runtimeModule';
3
+ import { readDebugCommand } from '../debugMailbox';
4
+ import { executeRubyTracepoint } from './rubyTracepoint';
3
5
  import { createReadonlyGolfscriptMount } from './golfscriptMount';
4
6
  import { GOLFSCRIPT_RUNTIME_DIRECTORY, WASM_GOLFSCRIPT_INTERPRETER_RECEIPT } from '../wasmGolfscriptVersion';
5
7
  import { RUBY_RUNTIME_VERIFIED_WASM_URL, normalizeWorkspacePath, RUBY_SPLIT_PROTOCOL, verifyRubySplitPayload, rewriteRubySplitRuntimeModule, parseRubyStdlibPack, createRubyStdlibPreopens, rewriteVerifiedRubyRuntimeModule, verifyRubyRuntimePreflightPayload, verifyRuntimeAssetIntegrity, AssetTooLargeError } from '@wasm-idle/core';
@@ -514,6 +516,17 @@ end`);
514
516
  execution.flushOutput();
515
517
  }
516
518
  }
519
+ else if (message.rubyDebug) {
520
+ const debug = message.rubyDebug;
521
+ await executeRubyTracepoint(vm, code, {
522
+ path: activePath,
523
+ debugPath: debug.sourcePath,
524
+ breakpoints: debug.breakpoints,
525
+ sourceBreakpoints: debug.sourceBreakpoints,
526
+ pauseOnEntry: debug.pauseOnEntry,
527
+ files: workspaceFiles
528
+ }, (message) => postMessage({ rubyDebug: message }), (blocking) => readDebugCommand(debug.buffer, blocking, () => postMessage({ rubyDebug: { consumed: true } }), 'Ruby'));
529
+ }
517
530
  else {
518
531
  vm.eval(code);
519
532
  }
@@ -0,0 +1,2 @@
1
+ /** Automatic locals must not dispatch user inspection or container overrides. */
2
+ export declare const RUBY_DEBUG_PREVIEW: string;
@@ -0,0 +1,80 @@
1
+ /** Automatic locals must not dispatch user inspection or container overrides. */
2
+ export const RUBY_DEBUG_PREVIEW = String.raw `
3
+ debug_class = Kernel.instance_method(:class)
4
+ debug_equal = BasicObject.instance_method(:equal?)
5
+ debug_type_name = Module.instance_method(:name)
6
+ debug_string_slice = String.instance_method(:byteslice)
7
+ debug_string_size = String.instance_method(:bytesize)
8
+ debug_string_length = String.instance_method(:length)
9
+ debug_string_characters = String.instance_method(:[])
10
+ debug_string_encode = String.instance_method(:encode)
11
+ debug_string_inspect = String.instance_method(:inspect)
12
+ debug_integer_bits = Integer.instance_method(:bit_length)
13
+ debug_integer_text = Integer.instance_method(:to_s)
14
+ debug_integer_greater = Integer.instance_method(:>)
15
+ debug_integer_at_least = Integer.instance_method(:>=)
16
+ debug_integer_at_most = Integer.instance_method(:<=)
17
+ debug_integer_add = Integer.instance_method(:+)
18
+ debug_float_text = Float.instance_method(:to_s)
19
+ debug_symbol_name = Symbol.instance_method(:name)
20
+ debug_array_size = Array.instance_method(:length)
21
+ debug_array_get = Array.instance_method(:[])
22
+ debug_array_append = Array.instance_method(:<<)
23
+ debug_array_join = Array.instance_method(:join)
24
+ debug_hash_size = Hash.instance_method(:length)
25
+ debug_hash_each = Hash.instance_method(:each_pair)
26
+ preview_join = ->(*parts) { debug_array_join.bind_call(parts, '') }
27
+ preview_type = ->(value) do
28
+ kind = debug_class.bind_call(value)
29
+ name = debug_type_name.bind_call(kind)
30
+ name ? debug_string_encode.bind_call(debug_string_slice.bind_call(name, 0, 64), 'UTF-8', invalid: :replace, undef: :replace) : 'Object'
31
+ rescue StandardError
32
+ 'Object'
33
+ end
34
+ preview_value = nil
35
+ preview_value = ->(value, depth = 0) do
36
+ next '...' if debug_integer_at_least.bind_call(depth, 2)
37
+ next 'nil' if debug_equal.bind_call(value, nil)
38
+ next 'true' if debug_equal.bind_call(value, true)
39
+ next 'false' if debug_equal.bind_call(value, false)
40
+ kind = debug_class.bind_call(value)
41
+ text = if debug_equal.bind_call(kind, Integer)
42
+ bits = debug_integer_bits.bind_call(value)
43
+ debug_integer_at_most.bind_call(bits, 256) ? debug_integer_text.bind_call(value) : preview_join.call('<Integer: ', debug_integer_text.bind_call(bits), ' bits>')
44
+ elsif debug_equal.bind_call(kind, Float)
45
+ debug_float_text.bind_call(value)
46
+ elsif debug_equal.bind_call(kind, String) || debug_equal.bind_call(kind, Symbol)
47
+ string = debug_equal.bind_call(kind, Symbol) ? debug_symbol_name.bind_call(value) : value
48
+ prefix = debug_string_slice.bind_call(string, 0, 128)
49
+ prefix = debug_string_encode.bind_call(prefix, 'UTF-8', invalid: :replace, undef: :replace)
50
+ quoted = debug_string_inspect.bind_call(prefix)
51
+ preview_join.call(debug_equal.bind_call(kind, Symbol) ? ':' : '', quoted, debug_integer_greater.bind_call(debug_string_size.bind_call(string), 128) ? '...' : '')
52
+ elsif debug_equal.bind_call(kind, Array)
53
+ size = debug_array_size.bind_call(value)
54
+ items = []
55
+ limit = debug_integer_greater.bind_call(size, 8) ? 8 : size
56
+ # Integer#times can dispatch an overridden #succ in the pinned Ruby runtime.
57
+ index = 0
58
+ while debug_integer_greater.bind_call(limit, index)
59
+ debug_array_append.bind_call(items, preview_value.call(debug_array_get.bind_call(value, index), debug_integer_add.bind_call(depth, 1)))
60
+ index = debug_integer_add.bind_call(index, 1)
61
+ end
62
+ debug_array_append.bind_call(items, '...') if debug_integer_greater.bind_call(size, 8)
63
+ preview_join.call('[', debug_array_join.bind_call(items, ', '), ']')
64
+ elsif debug_equal.bind_call(kind, Hash)
65
+ items = []
66
+ debug_hash_each.bind_call(value) do |key, item|
67
+ next_depth = debug_integer_add.bind_call(depth, 1)
68
+ debug_array_append.bind_call(items, preview_join.call(preview_value.call(key, next_depth), '=>', preview_value.call(item, next_depth)))
69
+ break if debug_integer_at_least.bind_call(debug_array_size.bind_call(items), 6)
70
+ end
71
+ debug_array_append.bind_call(items, '...') if debug_integer_greater.bind_call(debug_hash_size.bind_call(value), 6)
72
+ preview_join.call('{', debug_array_join.bind_call(items, ', '), '}')
73
+ else
74
+ preview_join.call('<', preview_type.call(value), ' object>')
75
+ end
76
+ debug_integer_greater.bind_call(debug_string_length.bind_call(text), 512) ? preview_join.call(debug_string_characters.bind_call(text, 0, 509), '...') : text
77
+ rescue StandardError
78
+ preview_join.call('<', preview_type.call(value), ' object>')
79
+ end
80
+ `;
@@ -0,0 +1,16 @@
1
+ import type { DebugSourceBreakpoints } from '../options';
2
+ export interface RubyTracepointOptions {
3
+ path: string;
4
+ debugPath?: string;
5
+ breakpoints: number[];
6
+ sourceBreakpoints?: DebugSourceBreakpoints[];
7
+ pauseOnEntry: boolean;
8
+ files: Array<{
9
+ path: string;
10
+ content: string;
11
+ }>;
12
+ }
13
+ /** Real CRuby TracePoint and Binding APIs; user source is passed unchanged as eval data. */
14
+ export declare function executeRubyTracepoint(vm: {
15
+ eval(source: string): unknown;
16
+ }, source: string, options: RubyTracepointOptions, notify: (message: any) => void, read: (blocking: boolean) => string | null): Promise<void>;
@@ -0,0 +1,162 @@
1
+ import { RUBY_DEBUG_PREVIEW } from './rubyDebugPreview';
2
+ /** Real CRuby TracePoint and Binding APIs; user source is passed unchanged as eval data. */
3
+ export async function executeRubyTracepoint(vm, source, options, notify, read) {
4
+ const files = [...options.files, { path: options.path, content: source }];
5
+ const hashes = {};
6
+ for (const file of files) {
7
+ const digest = await crypto.subtle.digest('SHA-256', new TextEncoder().encode(file.content));
8
+ hashes[file.path] = [...new Uint8Array(digest)]
9
+ .map((byte) => byte.toString(16).padStart(2, '0'))
10
+ .join('');
11
+ }
12
+ const key = `__wasmIdleRubyDebug_${crypto.randomUUID().replaceAll('-', '')}`;
13
+ const globals = globalThis;
14
+ globals[key] = {
15
+ notify: (json) => {
16
+ if (json.length > 2_000_000)
17
+ throw new Error('Ruby debugger snapshot exceeds its limit');
18
+ notify(JSON.parse(json));
19
+ },
20
+ read: (blocking) => read(blocking) ?? '{"op":"stop"}'
21
+ };
22
+ const data = JSON.stringify({ ...options, source, files, hashes, key });
23
+ const literal = `'${data.replace(/\\/g, '\\\\').replace(/'/g, "\\'")}'`;
24
+ try {
25
+ vm.eval(String.raw `
26
+ require 'json'
27
+ require 'js'
28
+ Class.new do
29
+ def self.run(settings)
30
+ bridge = JS.global[settings['key']]
31
+ send_event = ->(value) { bridge.call(:notify, JSON.generate(value)) }
32
+ read_command = ->(blocking) do
33
+ text = bridge.call(:read, blocking).to_s
34
+ text.empty? ? nil : JSON.parse(text)
35
+ end
36
+ display_path = ->(path) do
37
+ path = path == settings['path'] ? (settings['debugPath'] || path) : path
38
+ '/workspace/' + path.sub(%r{\A(?:/workspace/|/+)}, '')
39
+ end
40
+ known = settings['files'].to_h { |file| [file['path'], file['content']] }
41
+ breakpoints = {}
42
+ executable = {}
43
+ known.each do |path, content|
44
+ next unless path == settings['path'] || path.end_with?('.rb')
45
+ begin
46
+ lines = []
47
+ collect = ->(iseq) do
48
+ lines.concat(iseq.trace_points.select { |_, event| event == :line }.map(&:first))
49
+ iseq.each_child { |child| collect.call(child) }
50
+ end
51
+ collect.call(RubyVM::InstructionSequence.compile(content, path, path, 1))
52
+ executable[display_path.call(path)] = lines.uniq.sort
53
+ rescue NameError, NoMethodError, SyntaxError
54
+ executable[display_path.call(path)] = []
55
+ end
56
+ end
57
+ set_breakpoints = ->(path, lines) do
58
+ path = display_path.call(path)
59
+ available = executable[path] || []
60
+ resolved = lines.uniq.map do |line|
61
+ actual = available.find { |candidate| candidate >= line }
62
+ {requestedLine:line, line:actual || line, verified:!actual.nil?, message:actual ? nil : 'No executable Ruby line'}
63
+ end
64
+ breakpoints[path] = resolved.select { |item| item[:verified] }.map { |item| item[:line] }
65
+ send_event.call({event:{type:'breakpoints',sourcePath:path,breakpoints:resolved}})
66
+ end
67
+ set_breakpoints.call(display_path.call(settings['path']), settings['breakpoints'])
68
+ (settings['sourceBreakpoints'] || []).each { |item| set_breakpoints.call(item['sourcePath'], item['lines']) }
69
+ format_value = ->(value) do
70
+ begin
71
+ value.inspect.encode('UTF-8', invalid: :replace, undef: :replace)[0,512]
72
+ rescue Exception => error
73
+ '<' + error.class.to_s + ' while inspecting>'
74
+ end
75
+ end
76
+ ${RUBY_DEBUG_PREVIEW}
77
+ local_values = ->(binding) do
78
+ binding.local_variables.first(50).map do |name|
79
+ value = binding.local_variable_get(name)
80
+ {name:name.to_s,value:preview_value.call(value),type:preview_type.call(value),variablesReference:0}
81
+ end
82
+ end
83
+ frames = []
84
+ mode = settings['pauseOnEntry'] ? 'entry' : 'continue'
85
+ target_depth = 0
86
+ pause_requested = false
87
+ stop_number = 0
88
+ trace = TracePoint.new(:line, :call, :return, :b_call, :b_return, :class, :end) do |point|
89
+ path = point.path.sub(%r{\A/+}, '')
90
+ next unless known.key?(path)
91
+ case point.event
92
+ when :return, :b_return, :end
93
+ frames.pop unless frames.empty?
94
+ next
95
+ when :call, :b_call, :class
96
+ frames << {binding:point.binding,path:path,line:point.lineno,name:point.method_id.to_s.empty? ? '<block>' : point.method_id.to_s}
97
+ next
98
+ end
99
+ frames << {binding:point.binding,path:path,line:point.lineno,name:'<main>'} if frames.empty?
100
+ frame = frames.last
101
+ frame[:binding] = point.binding
102
+ frame[:path] = path
103
+ frame[:line] = point.lineno
104
+ while (command = read_command.call(false))
105
+ case command['op']
106
+ when 'stop' then raise Interrupt, 'Ruby debugger stopped'
107
+ when 'pause' then pause_requested = true
108
+ when 'breakpoints' then set_breakpoints.call(command['sourcePath'], command['lines'])
109
+ end
110
+ end
111
+ breakpoint = (breakpoints[display_path.call(path)] || []).include?(point.lineno)
112
+ stepping = mode == 'entry' || mode == 'stepInto' || (mode == 'nextLine' && frames.length <= target_depth) || (mode == 'stepOut' && frames.length < target_depth)
113
+ next unless pause_requested || breakpoint || stepping
114
+ reason = pause_requested ? 'pause' : breakpoint ? 'breakpoint' : mode == 'entry' ? 'entry' : mode == 'stepInto' ? 'step' : mode
115
+ pause_requested = false
116
+ stop_number += 1
117
+ bindings = {}
118
+ snapshots = frames.reverse.first(32).each_with_index.map do |item, index|
119
+ id = stop_number * 1000 + index + 1
120
+ bindings[id] = item[:binding]
121
+ {id:id,functionName:item[:name],line:item[:line],sourcePath:display_path.call(item[:path]),sourceContentSha256:settings['hashes'][item[:path]],locals:local_values.call(item[:binding])}
122
+ end
123
+ top = snapshots.first
124
+ send_event.call({frames:snapshots,event:{type:'pause',reason:reason,line:top[:line],sourcePath:top[:sourcePath],sourceContentSha256:top[:sourceContentSha256],frameId:top[:id],threadId:1,locals:top[:locals],callStack:snapshots.map { |item| item.reject { |key,_| key == :locals } },scopes:[{name:'Locals',variablesReference:top[:id],namedVariables:top[:locals].length,expensive:false,variables:top[:locals]}],capabilities:{readMemory:false,writeMemory:false,dataBreakpoints:false}}})
125
+ loop do
126
+ command = read_command.call(true)
127
+ next unless command
128
+ case command['op']
129
+ when 'stop' then raise Interrupt, 'Ruby debugger stopped'
130
+ when 'breakpoints' then set_breakpoints.call(command['sourcePath'], command['lines'])
131
+ when 'evaluate'
132
+ begin
133
+ binding = bindings.fetch(command['frameId'])
134
+ value = format_value.call(binding.eval(command['expression']))
135
+ send_event.call({response:{id:command['id'],value:value}})
136
+ rescue Exception => error
137
+ send_event.call({response:{id:command['id'],error:error.class.to_s + ': ' + error.message}})
138
+ end
139
+ when 'control'
140
+ mode = command['command']
141
+ target_depth = frames.length
142
+ send_event.call({event:{type:'resume',command:mode}})
143
+ break
144
+ end
145
+ end
146
+ end
147
+ begin
148
+ trace.enable
149
+ eval(settings['source'], TOPLEVEL_BINDING, settings['path'], 1)
150
+ ensure
151
+ trace.disable
152
+ STDOUT.flush
153
+ STDERR.flush
154
+ end
155
+ end
156
+ end.run(JSON.parse(${literal}))
157
+ `);
158
+ }
159
+ finally {
160
+ delete globals[key];
161
+ }
162
+ }
@@ -406,7 +406,7 @@ function createRustDebugHost(options) {
406
406
  };
407
407
  }
408
408
  self.onmessage = async (event) => {
409
- const { load, persistentCache, compilerUrl: nextCompilerUrl, runtimeProfile: nextRuntimeProfile, verifiedModuleUrls: nextVerifiedModuleUrls, executableGraphFingerprint: nextExecutableGraphFingerprint, debugModuleUrl: nextDebugModuleUrl, buffer, debugBuffer, code, prepare, args = [], stdin, targetTriple = 'wasm32-wasip1', log, debug = false, debugMode: requestedDebugMode, breakpoints = [], pauseOnEntry = false, limits: executionLimits } = event.data;
409
+ const { load, persistentCache, compilerUrl: nextCompilerUrl, runtimeProfile: nextRuntimeProfile, verifiedModuleUrls: nextVerifiedModuleUrls, executableGraphFingerprint: nextExecutableGraphFingerprint, debugModuleUrl: nextDebugModuleUrl, buffer, debugBuffer, code, prepare, args = [], stdin, targetTriple = 'wasm32-wasip1', optimizationProfile: requestedOptimizationProfile = 'interactive', log, debug = false, debugMode: requestedDebugMode, breakpoints = [], pauseOnEntry = false, limits: executionLimits } = event.data;
410
410
  const nextRustcModuleBroker = event.data.rustcModuleBroker;
411
411
  let rustcModuleBroker;
412
412
  let ownsExecution = false;
@@ -452,6 +452,7 @@ self.onmessage = async (event) => {
452
452
  if (debugMode !== 'none' && debugMode !== 'trace' && debugMode !== 'lldb') {
453
453
  throw new Error(`Unsupported Rust debug mode: ${String(debugMode)}`);
454
454
  }
455
+ const optimizationProfile = debugMode === 'none' ? requestedOptimizationProfile : 'interactive';
455
456
  const nonDebugResourceLimits = debugMode === 'none' ? snapshotRustNonDebugResourceLimits(executionLimits) : undefined;
456
457
  stdinBufferRust = new Int32Array(buffer);
457
458
  debugBufferRust = debugBuffer ? new Int32Array(debugBuffer) : null;
@@ -485,6 +486,7 @@ self.onmessage = async (event) => {
485
486
  const compileCacheKey = [
486
487
  executableGraphFingerprint,
487
488
  debugMode,
489
+ optimizationProfile,
488
490
  targetTriple,
489
491
  ...(nonDebugResourceLimits
490
492
  ? [String(nonDebugResourceLimits.maxAssetDeliveryBytes)]
@@ -519,6 +521,7 @@ self.onmessage = async (event) => {
519
521
  ...(assetCache ? { assetCache } : {}),
520
522
  code: compileCode,
521
523
  debugMode,
524
+ optimizationProfile,
522
525
  ...(nonDebugResourceLimits
523
526
  ? {
524
527
  workerLimits: nonDebugResourceLimits.compilerLimits,
@@ -1,3 +1,4 @@
1
+ import { normalizeLldbWorkspacePath } from '../lldbSourcePath';
1
2
  import { waitForBufferedStdin } from '../stdinBuffer';
2
3
  import { configureWorkerRuntimeAssets, handleWorkerAssetMessage } from './assets';
3
4
  import { createVCompiler, executeBrowserVArtifact } from '@wasm-idle/llvm-core/v';
@@ -44,7 +45,7 @@ async function loadVRuntime(clangAssets, vBaseUrl, maxAssetBytes, log) {
44
45
  self.onmessage = async (event) => {
45
46
  if (handleWorkerAssetMessage(event.data))
46
47
  return;
47
- const { code, buffer, load, log, prepare, compileArgs, programArgs, activePath, workspaceFiles, stdin, clangAssets, vBaseUrl, maxAssetBytes } = event.data;
48
+ const { code, buffer, load, log, prepare, compileArgs, programArgs, activePath, workspaceFiles, stdin, clangAssets, vBaseUrl, maxAssetBytes, debugMode } = event.data;
48
49
  if (load) {
49
50
  try {
50
51
  await loadVRuntime(clangAssets, vBaseUrl, maxAssetBytes, log);
@@ -54,7 +55,7 @@ self.onmessage = async (event) => {
54
55
  postMessage({ error: error?.message || String(error) });
55
56
  }
56
57
  }
57
- else if (typeof log === 'boolean' && !code) {
58
+ else if (code === '' || (typeof log === 'boolean' && code === undefined)) {
58
59
  // The compiler receives the current logging preference for every compilation.
59
60
  if (typeof code === 'string')
60
61
  postMessage({ results: true });
@@ -69,10 +70,16 @@ self.onmessage = async (event) => {
69
70
  initialStdinV = hasInitialStdinV ? stdin : null;
70
71
  initialStdinConsumedV = false;
71
72
  try {
72
- const files = (workspaceFiles || []);
73
+ const lldb = debugMode === 'lldb';
74
+ const files = (workspaceFiles || []).map((file) => ({
75
+ ...file,
76
+ path: lldb ? normalizeLldbWorkspacePath(file.path) : file.path
77
+ }));
78
+ const fileName = resolveInputPath(lldb ? normalizeLldbWorkspacePath(activePath || '') : activePath);
73
79
  const result = await compiler.compile({
74
- code: ensureTrailingNewline(code),
75
- fileName: resolveInputPath(activePath),
80
+ code: lldb ? code : ensureTrailingNewline(code),
81
+ fileName,
82
+ debugMode: lldb ? 'lldb' : 'none',
76
83
  compileArgs: compileArgs || [],
77
84
  workspaceFiles: files,
78
85
  log,
@@ -85,6 +92,24 @@ self.onmessage = async (event) => {
85
92
  if (!result.success || !result.artifact) {
86
93
  throw new Error(result.stderr || 'V did not produce a WebAssembly program.');
87
94
  }
95
+ if (lldb && !prepare) {
96
+ const descriptor = result.artifact.debug;
97
+ if (!descriptor)
98
+ throw new Error('V compiler did not produce a DWARF descriptor.');
99
+ const sources = new Map(files.map((file) => [`/workspace/${file.path}`, file.content]));
100
+ sources.set(`/workspace/${fileName}`, code);
101
+ postMessage({
102
+ lldbArtifact: {
103
+ bytes: result.artifact.bytes,
104
+ descriptor,
105
+ sources: descriptor.files.map((file) => ({
106
+ ...file,
107
+ content: sources.get(file.path)
108
+ }))
109
+ }
110
+ });
111
+ return;
112
+ }
88
113
  if (!prepare) {
89
114
  const execution = await executeBrowserVArtifact(result.artifact, {
90
115
  args: programArgs || [],
@@ -453,6 +453,10 @@ class Zig {
453
453
  return Promise.reject(this.releaseBeforeSession(activeOperation, 'Zig execution cancelled'));
454
454
  }
455
455
  ({ compileArgs, programArgs } = resolveSandboxExecutionArgs('ZIG', args, options));
456
+ const debugMode = options.debugMode ?? (options.debug ? 'trace' : 'none');
457
+ if (debugMode !== 'none') {
458
+ throw new RuntimeConfigurationError('Zig source debugging is unavailable: the current Wasm compiler does not emit DWARF.');
459
+ }
456
460
  limits = resolveExecutionLimits(options.limits);
457
461
  const workspaceFiles = options.workspaceFiles ?? [];
458
462
  const activePath = options.activePath ?? 'main.zig';
@@ -0,0 +1,8 @@
1
+ import type { PythonCompileOptions, PythonCompileResult } from './playground/pythonCompileOptions';
2
+ export type { PythonCompileOptions, PythonCompileResult } from './playground/pythonCompileOptions';
3
+ /**
4
+ * Compile one source file without executing it or loading its imports.
5
+ * A dedicated worker keeps compilation independent of active playground sessions.
6
+ * Its runtime, temporary files, and proxies are disposed on every exit path.
7
+ */
8
+ export declare function compilePython(code: string, options?: PythonCompileOptions): Promise<PythonCompileResult>;
@@ -0,0 +1,52 @@
1
+ import { TimeoutError } from '@wasm-idle/core';
2
+ import { resolvePythonCompileRequest } from './playground/pythonCompileOptions';
3
+ /**
4
+ * Compile one source file without executing it or loading its imports.
5
+ * A dedicated worker keeps compilation independent of active playground sessions.
6
+ * Its runtime, temporary files, and proxies are disposed on every exit path.
7
+ */
8
+ export async function compilePython(code, options = {}) {
9
+ const request = { ...options, ...resolvePythonCompileRequest(code, options) };
10
+ request.signal?.throwIfAborted();
11
+ const importStartedAt = performance.now();
12
+ const { startupTimeoutMs } = request.limits;
13
+ const startupTimeout = new TimeoutError(`Python runtime startup timed out after ${startupTimeoutMs} ms`, { runtimeId: 'PYTHON3', phase: 'startup', timeoutMs: startupTimeoutMs });
14
+ let timeout;
15
+ let onAbort;
16
+ // Native imports cannot be cancelled, but callers must not wait for a stalled chunk.
17
+ // The race also handles late import failures without creating a compiler afterward.
18
+ const { default: Python } = await Promise.race([
19
+ import('./playground/python'),
20
+ new Promise((_resolve, reject) => {
21
+ timeout = setTimeout(() => reject(startupTimeout), startupTimeoutMs);
22
+ onAbort = () => reject(request.signal?.reason);
23
+ request.signal?.addEventListener('abort', onAbort, { once: true });
24
+ if (request.signal?.aborted)
25
+ onAbort();
26
+ })
27
+ ]).finally(() => {
28
+ if (timeout !== undefined)
29
+ clearTimeout(timeout);
30
+ if (onAbort)
31
+ request.signal?.removeEventListener('abort', onAbort);
32
+ });
33
+ request.signal?.throwIfAborted();
34
+ const remainingStartupMs = Math.ceil(startupTimeoutMs - (performance.now() - importStartedAt));
35
+ if (remainingStartupMs <= 0)
36
+ throw startupTimeout;
37
+ const compiler = new Python();
38
+ try {
39
+ await compiler.load(request.runtimeAssets, '', false, [], { ...request, limits: { ...request.limits, startupTimeoutMs: remainingStartupMs } }, request.progress);
40
+ return await compiler.compile(code, request);
41
+ }
42
+ catch (error) {
43
+ if (request.signal?.aborted && error === request.signal.reason)
44
+ throw error;
45
+ if (typeof error === 'string')
46
+ throw new Error(error);
47
+ throw error;
48
+ }
49
+ finally {
50
+ await compiler.dispose();
51
+ }
52
+ }