sandboxedjs 0.1.32 → 0.1.33

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.
package/dist/index.cjs CHANGED
@@ -17924,20 +17924,570 @@ def _install():
17924
17924
 
17925
17925
  _install()
17926
17926
  `;
17927
+ var PROCESS_PY = `
17928
+ import io, os, shlex, subprocess, sys
17929
+ import _sbx_host as _host
17930
+ from pyodide.ffi import can_run_sync, run_sync
17931
+
17932
+ _PIPE = subprocess.PIPE
17933
+ _DEVNULL = subprocess.DEVNULL
17934
+ _STDOUT = subprocess.STDOUT
17935
+
17936
+
17937
+ def _argv_for(args, shell):
17938
+ if shell:
17939
+ line = args if isinstance(args, str) else " ".join(str(a) for a in args)
17940
+ return ["sh", "-c", line]
17941
+ if isinstance(args, (str, bytes)):
17942
+ return shlex.split(args if isinstance(args, str) else args.decode())
17943
+ return [str(a) for a in args]
17944
+
17945
+
17946
+ def _require_blocking(what):
17947
+ if not can_run_sync():
17948
+ raise OSError(
17949
+ "cannot " + what + " on this host: WebAssembly stack switching "
17950
+ "(JSPI) is unavailable."
17951
+ )
17952
+
17953
+
17954
+ def _to_bytes_result(value):
17955
+ if value is None:
17956
+ return b""
17957
+ to_bytes = getattr(value, "to_bytes", None)
17958
+ return to_bytes() if to_bytes is not None else bytes(value.to_py())
17959
+
17960
+
17961
+ class _ChildReader(io.RawIOBase):
17962
+ """One of a running child's output streams.
17963
+
17964
+ Reads suspend only for as long as the child takes to produce the next
17965
+ bytes, so \`for line in p.stdout\` follows a child that is still running
17966
+ instead of waiting for it to exit.
17967
+ """
17968
+
17969
+ def __init__(self, child_id, which):
17970
+ self._id = child_id
17971
+ self._which = which
17972
+
17973
+ def readable(self):
17974
+ return True
17975
+
17976
+ def readinto(self, target):
17977
+ want = len(target)
17978
+ if want == 0:
17979
+ return 0
17980
+ _require_blocking("read from a child process")
17981
+ data = _to_bytes_result(run_sync(_host.proc_read(self._id, self._which, want)))
17982
+ target[: len(data)] = data
17983
+ return len(data)
17984
+
17985
+
17986
+ class _ChildWriter(io.RawIOBase):
17987
+ """A running child's standard input."""
17988
+
17989
+ def __init__(self, child_id):
17990
+ self._id = child_id
17991
+
17992
+ def writable(self):
17993
+ return True
17994
+
17995
+ def write(self, data):
17996
+ if isinstance(data, str):
17997
+ text = data
17998
+ else:
17999
+ text = bytes(data).decode("utf-8", "replace")
18000
+ _host.proc_write(self._id, text)
18001
+ return len(data)
18002
+
18003
+ def close(self):
18004
+ if not self.closed:
18005
+ _host.proc_close_stdin(self._id)
18006
+ super().close()
18007
+
18008
+
18009
+ class SbxPopen:
18010
+ """A child process, run through the container's kernel.
18011
+
18012
+ The child is a real, live process: it starts when \`Popen\` is constructed
18013
+ and runs on the host's event loop while Python carries on. The parent only
18014
+ suspends when it actually reads, waits, or communicates \u2014 which is what
18015
+ makes streaming from a long-running child work rather than deadlocking on
18016
+ a single interpreter stack.
18017
+ """
18018
+
18019
+ def __init__(self, args, bufsize=-1, executable=None, stdin=None, stdout=None,
18020
+ stderr=None, preexec_fn=None, close_fds=True, shell=False, cwd=None,
18021
+ env=None, universal_newlines=None, startupinfo=None, creationflags=0,
18022
+ restore_signals=True, start_new_session=False, pass_fds=(), *,
18023
+ text=None, encoding=None, errors=None, **kwargs):
18024
+ self.args = args
18025
+ self.returncode = None
18026
+ self._text = bool(text or encoding or errors or universal_newlines)
18027
+ self._encoding = encoding or "utf-8"
18028
+ self._errors = errors or "replace"
18029
+ self._merge_err = stderr == _STDOUT
18030
+ self._closed = False
18031
+
18032
+ argv = _argv_for(args, shell)
18033
+ env_map = None if env is None else {str(k): str(v) for k, v in dict(env).items()}
18034
+ self._id = _host.proc_start(
18035
+ argv, None if cwd is None else str(cwd), env_map, self._merge_err
18036
+ )
18037
+ self.pid = int(_host.proc_pid(self._id))
18038
+
18039
+ self.stdin = self._wrap_writer() if stdin == _PIPE else None
18040
+ self.stdout = self._wrap_reader(1) if stdout == _PIPE else None
18041
+ # When merged there is only one stream, and it is stream 1.
18042
+ self.stderr = self._wrap_reader(2) if stderr == _PIPE and not self._merge_err else None
18043
+
18044
+ # Output nobody captured belongs on the parent's own streams, or a
18045
+ # program's diagnostics would vanish rather than being seen.
18046
+ self._drain_out = stdout is None
18047
+ self._drain_err = stderr is None and not self._merge_err
18048
+
18049
+ def _wrap_reader(self, which):
18050
+ raw = io.BufferedReader(_ChildReader(self._id, which))
18051
+ if self._text:
18052
+ return io.TextIOWrapper(raw, encoding=self._encoding, errors=self._errors)
18053
+ return raw
18054
+
18055
+ def _wrap_writer(self):
18056
+ raw = io.BufferedWriter(_ChildWriter(self._id))
18057
+ if self._text:
18058
+ return io.TextIOWrapper(raw, encoding=self._encoding, errors=self._errors)
18059
+ return raw
18060
+
18061
+ def _read_all(self, which):
18062
+ _require_blocking("read from a child process")
18063
+ parts = []
18064
+ while True:
18065
+ chunk = _to_bytes_result(run_sync(_host.proc_read(self._id, which, 65536)))
18066
+ if not chunk:
18067
+ break
18068
+ parts.append(chunk)
18069
+ return b"".join(parts)
18070
+
18071
+ def _decode(self, raw):
18072
+ return raw.decode(self._encoding, self._errors) if self._text else raw
18073
+
18074
+ def communicate(self, input=None, timeout=None):
18075
+ if input is not None and self.stdin is not None:
18076
+ if isinstance(input, bytes):
18077
+ input = input.decode(self._encoding, "replace")
18078
+ self.stdin.write(input)
18079
+ if self.stdin is not None:
18080
+ try:
18081
+ self.stdin.close()
18082
+ except Exception:
18083
+ pass
18084
+
18085
+ out = self.stdout.read() if self.stdout is not None else None
18086
+ err = self.stderr.read() if self.stderr is not None else None
18087
+ self.wait()
18088
+ self._flush_uncaptured()
18089
+ return out, err
18090
+
18091
+ def _flush_uncaptured(self):
18092
+ if self._drain_out:
18093
+ text = self._decode_raw(self._read_all(1))
18094
+ if text:
18095
+ sys.stdout.write(text)
18096
+ if self._drain_err:
18097
+ text = self._decode_raw(self._read_all(2))
18098
+ if text:
18099
+ sys.stderr.write(text)
18100
+ self._drain_out = False
18101
+ self._drain_err = False
18102
+
18103
+ def _decode_raw(self, raw):
18104
+ return raw.decode(self._encoding, "replace")
18105
+
18106
+ def poll(self):
18107
+ code = _host.proc_poll(self._id)
18108
+ if code is not None:
18109
+ self.returncode = int(code)
18110
+ return self.returncode
18111
+
18112
+ def wait(self, timeout=None):
18113
+ _require_blocking("wait for a child process")
18114
+ self.returncode = int(run_sync(_host.proc_wait(self._id)))
18115
+ return self.returncode
18116
+
18117
+ def kill(self):
18118
+ self.send_signal("SIGKILL")
18119
+
18120
+ def terminate(self):
18121
+ self.send_signal("SIGTERM")
18122
+
18123
+ def send_signal(self, sig):
18124
+ _host.proc_kill(self._id, sig if isinstance(sig, str) else "SIGTERM")
18125
+
18126
+ def __del__(self):
18127
+ try:
18128
+ _host.proc_release(self._id)
18129
+ except Exception:
18130
+ pass
18131
+
18132
+ def __enter__(self):
18133
+ return self
18134
+
18135
+ def __exit__(self, *exc):
18136
+ if self.stdin is not None:
18137
+ try:
18138
+ self.stdin.close()
18139
+ except Exception:
18140
+ pass
18141
+ self.wait()
18142
+ self._flush_uncaptured()
18143
+ for stream in (self.stdout, self.stderr):
18144
+ if stream is not None:
18145
+ try:
18146
+ stream.close()
18147
+ except Exception:
18148
+ pass
18149
+ # The host holds the process and its pipes until it is told the child
18150
+ # is finished with; a loop spawning children would otherwise keep every
18151
+ # one of them alive. Safe here only because the child has been waited
18152
+ # for and everything anyone wanted has been read.
18153
+ _host.proc_release(self._id)
18154
+ return False
18155
+
18156
+
18157
+ def _system(command):
18158
+ with SbxPopen(command, shell=True) as child:
18159
+ pass
18160
+ # os.system returns a wait status, not an exit code.
18161
+ return (child.returncode or 0) << 8
18162
+
18163
+
18164
+ def _popen(command, mode="r", buffering=-1):
18165
+ if "w" in mode:
18166
+ raise OSError("os.popen with mode 'w' is not supported in this container")
18167
+ child = SbxPopen(command, shell=True, stdout=_PIPE, text=True)
18168
+ stream = child.stdout
18169
+ inner = stream.close
18170
+
18171
+ def close():
18172
+ inner()
18173
+ code = child.wait()
18174
+ return None if code == 0 else code << 8
18175
+
18176
+ stream.close = close
18177
+ return stream
18178
+
18179
+
18180
+ def _install_processes():
18181
+ subprocess.Popen = SbxPopen
18182
+ os.system = _system
18183
+ os.popen = _popen
18184
+
18185
+
18186
+ _install_processes()
18187
+ `;
18188
+ var NETWORK_PY = `
18189
+ import builtins, email.message, io, sys, urllib.error, urllib.request, urllib.response
18190
+ import _sbx_host as _host
18191
+ from pyodide.ffi import can_run_sync, run_sync
18192
+
18193
+
18194
+ def _fetch(request):
18195
+ if not can_run_sync():
18196
+ raise urllib.error.URLError(
18197
+ "cannot make a request on this host: WebAssembly stack switching "
18198
+ "(JSPI) is unavailable."
18199
+ )
18200
+ body = request.data
18201
+ if isinstance(body, str):
18202
+ body = body.encode()
18203
+ try:
18204
+ result = run_sync(
18205
+ _host.http(
18206
+ request.full_url,
18207
+ request.get_method(),
18208
+ [[k, v] for k, v in request.header_items()],
18209
+ body,
18210
+ )
18211
+ )
18212
+ except Exception as error:
18213
+ raise urllib.error.URLError(str(error)) from None
18214
+
18215
+ headers = email.message.Message()
18216
+ for pair in result.headers.to_py():
18217
+ headers[str(pair[0])] = str(pair[1])
18218
+ payload = result.body.to_bytes()
18219
+ response = urllib.response.addinfourl(
18220
+ io.BytesIO(payload), headers, str(result.url), int(result.status)
18221
+ )
18222
+ response.msg = str(result.statusText)
18223
+ return response
18224
+
18225
+
18226
+ class _SbxHTTPHandler(urllib.request.HTTPHandler):
18227
+ """Both schemes, from one handler.
18228
+
18229
+ Pyodide builds urllib without \`ssl\`, so \`HTTPSHandler\` does not exist to
18230
+ subclass \u2014 and https is the scheme most callers actually want. Serving
18231
+ both from a subclass of the one handler that does exist keeps
18232
+ \`build_opener\` treating this as a replacement rather than stacking it
18233
+ alongside the original.
18234
+ """
18235
+
18236
+ def http_open(self, request):
18237
+ return _fetch(request)
18238
+
18239
+ def https_open(self, request):
18240
+ return _fetch(request)
18241
+
18242
+ https_request = urllib.request.HTTPHandler.do_request_
18243
+
18244
+
18245
+ def _raw_fetch(url, method, headers, body):
18246
+ """One request, through the container's network path."""
18247
+ if not can_run_sync():
18248
+ raise urllib.error.URLError(
18249
+ "cannot make a request on this host: WebAssembly stack switching "
18250
+ "(JSPI) is unavailable."
18251
+ )
18252
+ if isinstance(body, str):
18253
+ body = body.encode()
18254
+ result = run_sync(
18255
+ _host.http(url, method, [[str(k), str(v)] for k, v in dict(headers).items()], body)
18256
+ )
18257
+ return {
18258
+ "status": int(result.status),
18259
+ "reason": str(result.statusText),
18260
+ "headers": [(str(p[0]), str(p[1])) for p in result.headers.to_py()],
18261
+ "body": result.body.to_bytes(),
18262
+ "url": str(result.url),
18263
+ }
18264
+
18265
+
18266
+ # \u2500\u2500 Routing third-party HTTP stacks \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500
18267
+ #
18268
+ # A library that brings its own transport does not go through urllib, and in
18269
+ # Pyodide several of them reach JavaScript's fetch directly \u2014 which leaves the
18270
+ # container's network policy behind entirely. They cannot all be patched at
18271
+ # boot either, because pip installs them later.
18272
+ #
18273
+ # So: adapters are registered by module name and applied the moment that module
18274
+ # is first imported, whenever that happens. Supporting another stack is a small
18275
+ # function registered here, not a change to the machinery.
18276
+
18277
+ _ADAPTERS = {}
18278
+
18279
+
18280
+ def _register_adapter(name):
18281
+ def decorate(fn):
18282
+ _ADAPTERS[name] = fn
18283
+ return fn
18284
+
18285
+ return decorate
18286
+
18287
+
18288
+ def _apply_adapter(name):
18289
+ fn = _ADAPTERS.pop(name, None)
18290
+ if fn is None:
18291
+ return
18292
+ try:
18293
+ fn()
18294
+ except Exception:
18295
+ # A stack we cannot adapt must not stop the import that triggered it.
18296
+ pass
18297
+
18298
+
18299
+ def _install_import_hook():
18300
+ real_import = builtins.__import__
18301
+
18302
+ def hooked(name, globals=None, locals=None, fromlist=(), level=0):
18303
+ module = real_import(name, globals, locals, fromlist, level)
18304
+ root = name.split(".")[0] if level == 0 else None
18305
+ if root in _ADAPTERS:
18306
+ _apply_adapter(root)
18307
+ return module
18308
+
18309
+ builtins.__import__ = hooked
18310
+
18311
+
18312
+ @_register_adapter("requests")
18313
+ def _adapt_requests():
18314
+ """Replace the transport, not the API.
18315
+
18316
+ \`HTTPAdapter.send\` is the single seam every requests call passes through,
18317
+ below sessions, redirects, cookies and retries and above the urllib3
18318
+ transport that would otherwise reach the network on its own. Replacing it
18319
+ leaves everything callers actually use intact.
18320
+ """
18321
+ import requests
18322
+ from requests.adapters import HTTPAdapter
18323
+ from requests.structures import CaseInsensitiveDict
18324
+
18325
+ native_send = HTTPAdapter.send
18326
+
18327
+ def send(self, request, stream=False, timeout=None, verify=True, cert=None, proxies=None):
18328
+ if not can_run_sync():
18329
+ # Without stack switching this transport cannot run at all. Falling
18330
+ # back to the library's own is better than breaking requests on
18331
+ # such a host \u2014 but the container's network policy is not the part
18332
+ # that degrades, so a forbidden host is still refused.
18333
+ if not _host.policy_allows(request.url):
18334
+ raise requests.exceptions.ConnectionError(
18335
+ "outbound network access is disabled for this container "
18336
+ "(enable with network: { allowOutbound: true })"
18337
+ )
18338
+ return native_send(self, request, stream, timeout, verify, cert, proxies)
18339
+ try:
18340
+ result = _raw_fetch(request.url, request.method, request.headers, request.body)
18341
+ except Exception as error:
18342
+ raise requests.exceptions.ConnectionError(str(error)) from None
18343
+ response = requests.Response()
18344
+ response.status_code = result["status"]
18345
+ response.reason = result["reason"]
18346
+ response.headers = CaseInsensitiveDict(result["headers"])
18347
+ response.url = result["url"]
18348
+ response.request = request
18349
+ response.raw = io.BytesIO(result["body"])
18350
+ response.encoding = requests.utils.get_encoding_from_headers(response.headers)
18351
+ return response
18352
+
18353
+ HTTPAdapter.send = send
18354
+
18355
+
18356
+ def _install_network():
18357
+ urllib.request.HTTPHandler = _SbxHTTPHandler
18358
+ urllib.request.HTTPSHandler = _SbxHTTPHandler
18359
+ urllib.request.install_opener(urllib.request.build_opener(_SbxHTTPHandler))
18360
+ _install_import_hook()
18361
+ for already_imported in [n for n in _ADAPTERS if n in sys.modules]:
18362
+ _apply_adapter(already_imported)
18363
+
18364
+
18365
+ _install_network()
18366
+ `;
18367
+ async function httpForPython(slot, url, method, headers, body) {
18368
+ const current = slot.current;
18369
+ if (!current) throw new Error("no program is bound");
18370
+ const result = await performRequest(current.ctx, new URL(url), {
18371
+ method,
18372
+ headers: Object.fromEntries(headers),
18373
+ ...body ? { body } : {}
18374
+ });
18375
+ return {
18376
+ status: result.status,
18377
+ statusText: result.statusText,
18378
+ headers: Object.entries(result.headers),
18379
+ body: result.body,
18380
+ url: result.url
18381
+ };
18382
+ }
18383
+ async function resuming(py, slot, work) {
18384
+ const parent = slot.current;
18385
+ try {
18386
+ return await work();
18387
+ } finally {
18388
+ if (parent && slot.current !== parent) bindProgram(py, parent);
18389
+ }
18390
+ }
17927
18391
  function installSyscallBridge(py) {
17928
- const slot = py.__sbxStdin ??= { active: null };
18392
+ const slot = py.__sbxSlot ??= { current: null };
18393
+ const children = /* @__PURE__ */ new Map();
18394
+ let lastChildId = 0;
17929
18395
  py.registerJsModule("_sbx_host", {
17930
18396
  /* Not `?.` and `??`: `buffered` returns undefined to mean "you will have
17931
18397
  * to wait", and a nullish default would quietly turn that into end-of-file —
17932
18398
  * which is exactly the silent EOF this bridge exists to remove. */
17933
- buffered: (size) => slot.active ? slot.active.buffered(size) : EMPTY,
17934
- read: (size) => slot.active ? slot.active.read(size) : Promise.resolve(EMPTY),
17935
- isatty: () => slot.active?.isatty() ?? false
18399
+ buffered: (size) => slot.current ? slot.current.stdin.buffered(size) : EMPTY,
18400
+ read: (size) => slot.current ? slot.current.stdin.read(size) : Promise.resolve(EMPTY),
18401
+ isatty: () => slot.current?.stdin.isatty() ?? false,
18402
+ proc_start: (argv, cwd, env2, merge) => {
18403
+ const current = slot.current;
18404
+ if (!current) throw new Error("no program is bound");
18405
+ const { ctx } = current;
18406
+ const stdin = new Pipe();
18407
+ stdin.interactive = true;
18408
+ const stdout = new Pipe();
18409
+ const stderr = merge ? stdout : new Pipe();
18410
+ const proc = ctx.kernel.spawn(argv, {
18411
+ cwd: cwd ?? ctx.cwd,
18412
+ env: env2 ?? ctx.env,
18413
+ cred: ctx.cred,
18414
+ stdin,
18415
+ stdout,
18416
+ stderr
18417
+ });
18418
+ void proc.wait().then(() => {
18419
+ stdout.end();
18420
+ if (stderr !== stdout) stderr.end();
18421
+ });
18422
+ const id = ++lastChildId;
18423
+ children.set(id, { proc, stdin, stdout, stderr });
18424
+ return id;
18425
+ },
18426
+ proc_read: (id, which2, size) => {
18427
+ const child = children.get(id);
18428
+ if (!child) return Promise.resolve(EMPTY);
18429
+ const pipe = which2 === 2 ? child.stderr : child.stdout;
18430
+ return resuming(py, slot, async () => await pipe.read(size) ?? EMPTY);
18431
+ },
18432
+ proc_write: (id, text2) => {
18433
+ children.get(id)?.stdin.write(text2);
18434
+ },
18435
+ proc_close_stdin: (id) => {
18436
+ children.get(id)?.stdin.end();
18437
+ },
18438
+ /* Non-blocking on purpose: `poll()` must be able to say "still running". */
18439
+ proc_poll: (id) => children.get(id)?.proc.exitCode ?? void 0,
18440
+ proc_pid: (id) => children.get(id)?.proc.pid ?? 0,
18441
+ proc_wait: (id) => {
18442
+ const child = children.get(id);
18443
+ if (!child) return Promise.resolve(0);
18444
+ return resuming(py, slot, () => child.proc.wait());
18445
+ },
18446
+ proc_kill: (id, signal) => {
18447
+ const child = children.get(id);
18448
+ if (!child) return;
18449
+ const current = slot.current;
18450
+ current?.ctx.kernel.procs.signal(child.proc.pid, signal);
18451
+ },
18452
+ proc_release: (id) => {
18453
+ children.delete(id);
18454
+ },
18455
+ http: (url, method, headers, body) => resuming(py, slot, () => httpForPython(slot, url, method, headers, body)),
18456
+ /* So Python can enforce the container's policy even on a host where it
18457
+ * cannot route the request itself. */
18458
+ policy_allows: (url) => {
18459
+ const current = slot.current;
18460
+ if (!current) return false;
18461
+ const net = current.ctx.kernel.net;
18462
+ try {
18463
+ return net.isLocal(new URL(url).hostname) || net.outboundAllowed(url);
18464
+ } catch {
18465
+ return false;
18466
+ }
18467
+ }
17936
18468
  });
17937
18469
  py.runPython(BRIDGE_PY);
18470
+ py.runPython(PROCESS_PY);
18471
+ py.runPython(NETWORK_PY);
17938
18472
  }
17939
- function bindStdin(py, host2) {
17940
- py.__sbxStdin.active = host2;
18473
+ function bindProgram(py, binding) {
18474
+ py.__sbxSlot.current = binding;
18475
+ const { ctx, stdin } = binding;
18476
+ const decoder8 = new TextDecoder();
18477
+ py.setStdout({
18478
+ write: (buffer) => (ctx.write(decoder8.decode(buffer)), buffer.length)
18479
+ });
18480
+ py.setStderr({
18481
+ write: (buffer) => (ctx.stderr.write(decoder8.decode(buffer)), buffer.length)
18482
+ });
18483
+ py.setStdin({
18484
+ read: (buffer) => {
18485
+ const ready = stdin.buffered(buffer.length);
18486
+ if (!ready || ready.length === 0) return 0;
18487
+ buffer.set(ready);
18488
+ return ready.length;
18489
+ }
18490
+ });
17941
18491
  }
17942
18492
 
17943
18493
  // src/runtime/cpython.ts
@@ -18128,30 +18678,9 @@ async function runCPythonProgram(ctx, source, argv, scriptDir = null) {
18128
18678
  });
18129
18679
  } catch {
18130
18680
  }
18131
- const decoder8 = new TextDecoder();
18132
- py.setStdout({
18133
- write: (buffer) => {
18134
- ctx.write(decoder8.decode(buffer));
18135
- return buffer.length;
18136
- }
18137
- });
18138
- py.setStderr({
18139
- write: (buffer) => {
18140
- ctx.stderr.write(decoder8.decode(buffer));
18141
- return buffer.length;
18142
- }
18143
- });
18144
18681
  const stdinHost = createStdinHost(ctx);
18145
18682
  await stdinHost.prime();
18146
- bindStdin(py, stdinHost);
18147
- py.setStdin({
18148
- read: (buffer) => {
18149
- const ready = stdinHost.buffered(buffer.length);
18150
- if (!ready || ready.length === 0) return 0;
18151
- buffer.set(ready);
18152
- return ready.length;
18153
- }
18154
- });
18683
+ bindProgram(py, { ctx, stdin: stdinHost });
18155
18684
  try {
18156
18685
  bootstrap(py, ctx, argv, scriptDir);
18157
18686
  } catch (error) {
@@ -18190,9 +18719,7 @@ async function runCPythonRepl(ctx) {
18190
18719
  }
18191
18720
  mountContainerDirs(py, ctx);
18192
18721
  bootstrap(py, ctx, [""], null);
18193
- const decoder8 = new TextDecoder();
18194
- py.setStdout({ write: (data) => (ctx.write(decoder8.decode(data)), data.length) });
18195
- py.setStderr({ write: (data) => (ctx.stderr.write(decoder8.decode(data)), data.length) });
18722
+ bindProgram(py, { ctx, stdin: createStdinHost(ctx) });
18196
18723
  ctx.line(`Python ${String(py.runPython("import sys; sys.version.split()[0]"))} (Pyodide)`);
18197
18724
  ctx.line('Type "help()" for more information.');
18198
18725
  let source = "";
@@ -18252,6 +18779,13 @@ var micropip = defineCommand({
18252
18779
  ctx.stderr.write("pip: no packages specified\n");
18253
18780
  return 1;
18254
18781
  }
18782
+ const index = "https://pypi.org";
18783
+ if (!ctx.kernel.net.outboundAllowed(index)) {
18784
+ ctx.stderr.write(
18785
+ "pip: outbound network access is disabled for this container (enable with network: { allowOutbound: true })\n"
18786
+ );
18787
+ return 1;
18788
+ }
18255
18789
  let py;
18256
18790
  try {
18257
18791
  py = await interpreterFor(ctx);