{
  "version": 3,
  "sources": ["../node_modules/@msgpack/msgpack/src/utils/int.ts", "../node_modules/@msgpack/msgpack/src/utils/utf8.ts", "../node_modules/@msgpack/msgpack/src/ExtData.ts", "../node_modules/@msgpack/msgpack/src/DecodeError.ts", "../node_modules/@msgpack/msgpack/src/timestamp.ts", "../node_modules/@msgpack/msgpack/src/ExtensionCodec.ts", "../node_modules/@msgpack/msgpack/src/utils/typedArrays.ts", "../node_modules/@msgpack/msgpack/src/Encoder.ts", "../node_modules/@msgpack/msgpack/src/encode.ts", "../node_modules/@msgpack/msgpack/src/utils/prettyByte.ts", "../node_modules/@msgpack/msgpack/src/CachedKeyDecoder.ts", "../node_modules/@msgpack/msgpack/src/Decoder.ts", "../node_modules/@msgpack/msgpack/src/decode.ts", "../node_modules/@msgpack/msgpack/src/utils/stream.ts", "../node_modules/@msgpack/msgpack/src/decodeAsync.ts", "../node_modules/@msgpack/msgpack/src/index.ts", "../webR/webr-main.ts", "../webR/error.ts", "../webR/compat.ts", "../webR/emscripten.ts", "../webR/robj.ts", "../webR/utils-r.ts", "../webR/chan/task-common.ts", "../webR/robj-worker.ts", "../webR/utils.ts", "../webR/chan/task-main.ts", "../webR/chan/queue.ts", "../webR/chan/message.ts", "../webR/payload.ts", "../webR/chan/channel.ts", "../webR/chan/task-worker.ts", "../webR/chan/channel-shared.ts", "../webR/chan/channel-service.ts", "../webR/chan/channel-postmessage.ts", "../webR/chan/channel-common.ts", "../webR/config.ts", "../webR/robj-main.ts", "../webR/proxy.ts", "../webR/console.ts"],
  "sourcesContent": ["// Integer Utility\n\nexport const UINT32_MAX = 0xffff_ffff;\n\n// DataView extension to handle int64 / uint64,\n// where the actual range is 53-bits integer (a.k.a. safe integer)\n\nexport function setUint64(view: DataView, offset: number, value: number): void {\n  const high = value / 0x1_0000_0000;\n  const low = value; // high bits are truncated by DataView\n  view.setUint32(offset, high);\n  view.setUint32(offset + 4, low);\n}\n\nexport function setInt64(view: DataView, offset: number, value: number): void {\n  const high = Math.floor(value / 0x1_0000_0000);\n  const low = value; // high bits are truncated by DataView\n  view.setUint32(offset, high);\n  view.setUint32(offset + 4, low);\n}\n\nexport function getInt64(view: DataView, offset: number): number {\n  const high = view.getInt32(offset);\n  const low = view.getUint32(offset + 4);\n  return high * 0x1_0000_0000 + low;\n}\n\nexport function getUint64(view: DataView, offset: number): number {\n  const high = view.getUint32(offset);\n  const low = view.getUint32(offset + 4);\n  return high * 0x1_0000_0000 + low;\n}\n", "/* eslint-disable @typescript-eslint/no-unnecessary-condition */\nimport { UINT32_MAX } from \"./int\";\n\nconst TEXT_ENCODING_AVAILABLE =\n  (typeof process === \"undefined\" || process?.env?.[\"TEXT_ENCODING\"] !== \"never\") &&\n  typeof TextEncoder !== \"undefined\" &&\n  typeof TextDecoder !== \"undefined\";\n\nexport function utf8Count(str: string): number {\n  const strLength = str.length;\n\n  let byteLength = 0;\n  let pos = 0;\n  while (pos < strLength) {\n    let value = str.charCodeAt(pos++);\n\n    if ((value & 0xffffff80) === 0) {\n      // 1-byte\n      byteLength++;\n      continue;\n    } else if ((value & 0xfffff800) === 0) {\n      // 2-bytes\n      byteLength += 2;\n    } else {\n      // handle surrogate pair\n      if (value >= 0xd800 && value <= 0xdbff) {\n        // high surrogate\n        if (pos < strLength) {\n          const extra = str.charCodeAt(pos);\n          if ((extra & 0xfc00) === 0xdc00) {\n            ++pos;\n            value = ((value & 0x3ff) << 10) + (extra & 0x3ff) + 0x10000;\n          }\n        }\n      }\n\n      if ((value & 0xffff0000) === 0) {\n        // 3-byte\n        byteLength += 3;\n      } else {\n        // 4-byte\n        byteLength += 4;\n      }\n    }\n  }\n  return byteLength;\n}\n\nexport function utf8EncodeJs(str: string, output: Uint8Array, outputOffset: number): void {\n  const strLength = str.length;\n  let offset = outputOffset;\n  let pos = 0;\n  while (pos < strLength) {\n    let value = str.charCodeAt(pos++);\n\n    if ((value & 0xffffff80) === 0) {\n      // 1-byte\n      output[offset++] = value;\n      continue;\n    } else if ((value & 0xfffff800) === 0) {\n      // 2-bytes\n      output[offset++] = ((value >> 6) & 0x1f) | 0xc0;\n    } else {\n      // handle surrogate pair\n      if (value >= 0xd800 && value <= 0xdbff) {\n        // high surrogate\n        if (pos < strLength) {\n          const extra = str.charCodeAt(pos);\n          if ((extra & 0xfc00) === 0xdc00) {\n            ++pos;\n            value = ((value & 0x3ff) << 10) + (extra & 0x3ff) + 0x10000;\n          }\n        }\n      }\n\n      if ((value & 0xffff0000) === 0) {\n        // 3-byte\n        output[offset++] = ((value >> 12) & 0x0f) | 0xe0;\n        output[offset++] = ((value >> 6) & 0x3f) | 0x80;\n      } else {\n        // 4-byte\n        output[offset++] = ((value >> 18) & 0x07) | 0xf0;\n        output[offset++] = ((value >> 12) & 0x3f) | 0x80;\n        output[offset++] = ((value >> 6) & 0x3f) | 0x80;\n      }\n    }\n\n    output[offset++] = (value & 0x3f) | 0x80;\n  }\n}\n\nconst sharedTextEncoder = TEXT_ENCODING_AVAILABLE ? new TextEncoder() : undefined;\nexport const TEXT_ENCODER_THRESHOLD = !TEXT_ENCODING_AVAILABLE\n  ? UINT32_MAX\n  : typeof process !== \"undefined\" && process?.env?.[\"TEXT_ENCODING\"] !== \"force\"\n  ? 200\n  : 0;\n\nfunction utf8EncodeTEencode(str: string, output: Uint8Array, outputOffset: number): void {\n  output.set(sharedTextEncoder!.encode(str), outputOffset);\n}\n\nfunction utf8EncodeTEencodeInto(str: string, output: Uint8Array, outputOffset: number): void {\n  sharedTextEncoder!.encodeInto(str, output.subarray(outputOffset));\n}\n\nexport const utf8EncodeTE = sharedTextEncoder?.encodeInto ? utf8EncodeTEencodeInto : utf8EncodeTEencode;\n\nconst CHUNK_SIZE = 0x1_000;\n\nexport function utf8DecodeJs(bytes: Uint8Array, inputOffset: number, byteLength: number): string {\n  let offset = inputOffset;\n  const end = offset + byteLength;\n\n  const units: Array<number> = [];\n  let result = \"\";\n  while (offset < end) {\n    const byte1 = bytes[offset++]!;\n    if ((byte1 & 0x80) === 0) {\n      // 1 byte\n      units.push(byte1);\n    } else if ((byte1 & 0xe0) === 0xc0) {\n      // 2 bytes\n      const byte2 = bytes[offset++]! & 0x3f;\n      units.push(((byte1 & 0x1f) << 6) | byte2);\n    } else if ((byte1 & 0xf0) === 0xe0) {\n      // 3 bytes\n      const byte2 = bytes[offset++]! & 0x3f;\n      const byte3 = bytes[offset++]! & 0x3f;\n      units.push(((byte1 & 0x1f) << 12) | (byte2 << 6) | byte3);\n    } else if ((byte1 & 0xf8) === 0xf0) {\n      // 4 bytes\n      const byte2 = bytes[offset++]! & 0x3f;\n      const byte3 = bytes[offset++]! & 0x3f;\n      const byte4 = bytes[offset++]! & 0x3f;\n      let unit = ((byte1 & 0x07) << 0x12) | (byte2 << 0x0c) | (byte3 << 0x06) | byte4;\n      if (unit > 0xffff) {\n        unit -= 0x10000;\n        units.push(((unit >>> 10) & 0x3ff) | 0xd800);\n        unit = 0xdc00 | (unit & 0x3ff);\n      }\n      units.push(unit);\n    } else {\n      units.push(byte1);\n    }\n\n    if (units.length >= CHUNK_SIZE) {\n      result += String.fromCharCode(...units);\n      units.length = 0;\n    }\n  }\n\n  if (units.length > 0) {\n    result += String.fromCharCode(...units);\n  }\n\n  return result;\n}\n\nconst sharedTextDecoder = TEXT_ENCODING_AVAILABLE ? new TextDecoder() : null;\nexport const TEXT_DECODER_THRESHOLD = !TEXT_ENCODING_AVAILABLE\n  ? UINT32_MAX\n  : typeof process !== \"undefined\" && process?.env?.[\"TEXT_DECODER\"] !== \"force\"\n  ? 200\n  : 0;\n\nexport function utf8DecodeTD(bytes: Uint8Array, inputOffset: number, byteLength: number): string {\n  const stringBytes = bytes.subarray(inputOffset, inputOffset + byteLength);\n  return sharedTextDecoder!.decode(stringBytes);\n}\n", "/**\n * ExtData is used to handle Extension Types that are not registered to ExtensionCodec.\n */\nexport class ExtData {\n  constructor(readonly type: number, readonly data: Uint8Array) {}\n}\n", "export class DecodeError extends Error {\n  constructor(message: string) {\n    super(message);\n\n    // fix the prototype chain in a cross-platform way\n    const proto: typeof DecodeError.prototype = Object.create(DecodeError.prototype);\n    Object.setPrototypeOf(this, proto);\n\n    Object.defineProperty(this, \"name\", {\n      configurable: true,\n      enumerable: false,\n      value: DecodeError.name,\n    });\n  }\n}\n", "// https://github.com/msgpack/msgpack/blob/master/spec.md#timestamp-extension-type\nimport { DecodeError } from \"./DecodeError\";\nimport { getInt64, setInt64 } from \"./utils/int\";\n\nexport const EXT_TIMESTAMP = -1;\n\nexport type TimeSpec = {\n  sec: number;\n  nsec: number;\n};\n\nconst TIMESTAMP32_MAX_SEC = 0x100000000 - 1; // 32-bit unsigned int\nconst TIMESTAMP64_MAX_SEC = 0x400000000 - 1; // 34-bit unsigned int\n\nexport function encodeTimeSpecToTimestamp({ sec, nsec }: TimeSpec): Uint8Array {\n  if (sec >= 0 && nsec >= 0 && sec <= TIMESTAMP64_MAX_SEC) {\n    // Here sec >= 0 && nsec >= 0\n    if (nsec === 0 && sec <= TIMESTAMP32_MAX_SEC) {\n      // timestamp 32 = { sec32 (unsigned) }\n      const rv = new Uint8Array(4);\n      const view = new DataView(rv.buffer);\n      view.setUint32(0, sec);\n      return rv;\n    } else {\n      // timestamp 64 = { nsec30 (unsigned), sec34 (unsigned) }\n      const secHigh = sec / 0x100000000;\n      const secLow = sec & 0xffffffff;\n      const rv = new Uint8Array(8);\n      const view = new DataView(rv.buffer);\n      // nsec30 | secHigh2\n      view.setUint32(0, (nsec << 2) | (secHigh & 0x3));\n      // secLow32\n      view.setUint32(4, secLow);\n      return rv;\n    }\n  } else {\n    // timestamp 96 = { nsec32 (unsigned), sec64 (signed) }\n    const rv = new Uint8Array(12);\n    const view = new DataView(rv.buffer);\n    view.setUint32(0, nsec);\n    setInt64(view, 4, sec);\n    return rv;\n  }\n}\n\nexport function encodeDateToTimeSpec(date: Date): TimeSpec {\n  const msec = date.getTime();\n  const sec = Math.floor(msec / 1e3);\n  const nsec = (msec - sec * 1e3) * 1e6;\n\n  // Normalizes { sec, nsec } to ensure nsec is unsigned.\n  const nsecInSec = Math.floor(nsec / 1e9);\n  return {\n    sec: sec + nsecInSec,\n    nsec: nsec - nsecInSec * 1e9,\n  };\n}\n\nexport function encodeTimestampExtension(object: unknown): Uint8Array | null {\n  if (object instanceof Date) {\n    const timeSpec = encodeDateToTimeSpec(object);\n    return encodeTimeSpecToTimestamp(timeSpec);\n  } else {\n    return null;\n  }\n}\n\nexport function decodeTimestampToTimeSpec(data: Uint8Array): TimeSpec {\n  const view = new DataView(data.buffer, data.byteOffset, data.byteLength);\n\n  // data may be 32, 64, or 96 bits\n  switch (data.byteLength) {\n    case 4: {\n      // timestamp 32 = { sec32 }\n      const sec = view.getUint32(0);\n      const nsec = 0;\n      return { sec, nsec };\n    }\n    case 8: {\n      // timestamp 64 = { nsec30, sec34 }\n      const nsec30AndSecHigh2 = view.getUint32(0);\n      const secLow32 = view.getUint32(4);\n      const sec = (nsec30AndSecHigh2 & 0x3) * 0x100000000 + secLow32;\n      const nsec = nsec30AndSecHigh2 >>> 2;\n      return { sec, nsec };\n    }\n    case 12: {\n      // timestamp 96 = { nsec32 (unsigned), sec64 (signed) }\n\n      const sec = getInt64(view, 4);\n      const nsec = view.getUint32(0);\n      return { sec, nsec };\n    }\n    default:\n      throw new DecodeError(`Unrecognized data size for timestamp (expected 4, 8, or 12): ${data.length}`);\n  }\n}\n\nexport function decodeTimestampExtension(data: Uint8Array): Date {\n  const timeSpec = decodeTimestampToTimeSpec(data);\n  return new Date(timeSpec.sec * 1e3 + timeSpec.nsec / 1e6);\n}\n\nexport const timestampExtension = {\n  type: EXT_TIMESTAMP,\n  encode: encodeTimestampExtension,\n  decode: decodeTimestampExtension,\n};\n", "// ExtensionCodec to handle MessagePack extensions\n\nimport { ExtData } from \"./ExtData\";\nimport { timestampExtension } from \"./timestamp\";\n\nexport type ExtensionDecoderType<ContextType> = (\n  data: Uint8Array,\n  extensionType: number,\n  context: ContextType,\n) => unknown;\n\nexport type ExtensionEncoderType<ContextType> = (input: unknown, context: ContextType) => Uint8Array | null;\n\n// immutable interface to ExtensionCodec\nexport type ExtensionCodecType<ContextType> = {\n  // eslint-disable-next-line @typescript-eslint/naming-convention\n  __brand?: ContextType;\n  tryToEncode(object: unknown, context: ContextType): ExtData | null;\n  decode(data: Uint8Array, extType: number, context: ContextType): unknown;\n};\n\nexport class ExtensionCodec<ContextType = undefined> implements ExtensionCodecType<ContextType> {\n  public static readonly defaultCodec: ExtensionCodecType<undefined> = new ExtensionCodec();\n\n  // ensures ExtensionCodecType<X> matches ExtensionCodec<X>\n  // this will make type errors a lot more clear\n  // eslint-disable-next-line @typescript-eslint/naming-convention\n  __brand?: ContextType;\n\n  // built-in extensions\n  private readonly builtInEncoders: Array<ExtensionEncoderType<ContextType> | undefined | null> = [];\n  private readonly builtInDecoders: Array<ExtensionDecoderType<ContextType> | undefined | null> = [];\n\n  // custom extensions\n  private readonly encoders: Array<ExtensionEncoderType<ContextType> | undefined | null> = [];\n  private readonly decoders: Array<ExtensionDecoderType<ContextType> | undefined | null> = [];\n\n  public constructor() {\n    this.register(timestampExtension);\n  }\n\n  public register({\n    type,\n    encode,\n    decode,\n  }: {\n    type: number;\n    encode: ExtensionEncoderType<ContextType>;\n    decode: ExtensionDecoderType<ContextType>;\n  }): void {\n    if (type >= 0) {\n      // custom extensions\n      this.encoders[type] = encode;\n      this.decoders[type] = decode;\n    } else {\n      // built-in extensions\n      const index = 1 + type;\n      this.builtInEncoders[index] = encode;\n      this.builtInDecoders[index] = decode;\n    }\n  }\n\n  public tryToEncode(object: unknown, context: ContextType): ExtData | null {\n    // built-in extensions\n    for (let i = 0; i < this.builtInEncoders.length; i++) {\n      const encodeExt = this.builtInEncoders[i];\n      if (encodeExt != null) {\n        const data = encodeExt(object, context);\n        if (data != null) {\n          const type = -1 - i;\n          return new ExtData(type, data);\n        }\n      }\n    }\n\n    // custom extensions\n    for (let i = 0; i < this.encoders.length; i++) {\n      const encodeExt = this.encoders[i];\n      if (encodeExt != null) {\n        const data = encodeExt(object, context);\n        if (data != null) {\n          const type = i;\n          return new ExtData(type, data);\n        }\n      }\n    }\n\n    if (object instanceof ExtData) {\n      // to keep ExtData as is\n      return object;\n    }\n    return null;\n  }\n\n  public decode(data: Uint8Array, type: number, context: ContextType): unknown {\n    const decodeExt = type < 0 ? this.builtInDecoders[-1 - type] : this.decoders[type];\n    if (decodeExt) {\n      return decodeExt(data, type, context);\n    } else {\n      // decode() does not fail, returns ExtData instead.\n      return new ExtData(type, data);\n    }\n  }\n}\n", "export function ensureUint8Array(buffer: ArrayLike<number> | Uint8Array | ArrayBufferView | ArrayBuffer): Uint8Array {\n  if (buffer instanceof Uint8Array) {\n    return buffer;\n  } else if (ArrayBuffer.isView(buffer)) {\n    return new Uint8Array(buffer.buffer, buffer.byteOffset, buffer.byteLength);\n  } else if (buffer instanceof ArrayBuffer) {\n    return new Uint8Array(buffer);\n  } else {\n    // ArrayLike<number>\n    return Uint8Array.from(buffer);\n  }\n}\n\nexport function createDataView(buffer: ArrayLike<number> | ArrayBufferView | ArrayBuffer): DataView {\n  if (buffer instanceof ArrayBuffer) {\n    return new DataView(buffer);\n  }\n\n  const bufferView = ensureUint8Array(buffer);\n  return new DataView(bufferView.buffer, bufferView.byteOffset, bufferView.byteLength);\n}\n", "import { utf8EncodeJs, utf8Count, TEXT_ENCODER_THRESHOLD, utf8EncodeTE } from \"./utils/utf8\";\nimport { ExtensionCodec, ExtensionCodecType } from \"./ExtensionCodec\";\nimport { setInt64, setUint64 } from \"./utils/int\";\nimport { ensureUint8Array } from \"./utils/typedArrays\";\nimport type { ExtData } from \"./ExtData\";\n\nexport const DEFAULT_MAX_DEPTH = 100;\nexport const DEFAULT_INITIAL_BUFFER_SIZE = 2048;\n\nexport class Encoder<ContextType = undefined> {\n  private pos = 0;\n  private view = new DataView(new ArrayBuffer(this.initialBufferSize));\n  private bytes = new Uint8Array(this.view.buffer);\n\n  public constructor(\n    private readonly extensionCodec: ExtensionCodecType<ContextType> = ExtensionCodec.defaultCodec as any,\n    private readonly context: ContextType = undefined as any,\n    private readonly maxDepth = DEFAULT_MAX_DEPTH,\n    private readonly initialBufferSize = DEFAULT_INITIAL_BUFFER_SIZE,\n    private readonly sortKeys = false,\n    private readonly forceFloat32 = false,\n    private readonly ignoreUndefined = false,\n    private readonly forceIntegerToFloat = false,\n  ) {}\n\n  private reinitializeState() {\n    this.pos = 0;\n  }\n\n  /**\n   * This is almost equivalent to {@link Encoder#encode}, but it returns an reference of the encoder's internal buffer and thus much faster than {@link Encoder#encode}.\n   *\n   * @returns Encodes the object and returns a shared reference the encoder's internal buffer.\n   */\n  public encodeSharedRef(object: unknown): Uint8Array {\n    this.reinitializeState();\n    this.doEncode(object, 1);\n    return this.bytes.subarray(0, this.pos);\n  }\n\n  /**\n   * @returns Encodes the object and returns a copy of the encoder's internal buffer.\n   */\n  public encode(object: unknown): Uint8Array {\n    this.reinitializeState();\n    this.doEncode(object, 1);\n    return this.bytes.slice(0, this.pos);\n  }\n\n  private doEncode(object: unknown, depth: number): void {\n    if (depth > this.maxDepth) {\n      throw new Error(`Too deep objects in depth ${depth}`);\n    }\n\n    if (object == null) {\n      this.encodeNil();\n    } else if (typeof object === \"boolean\") {\n      this.encodeBoolean(object);\n    } else if (typeof object === \"number\") {\n      this.encodeNumber(object);\n    } else if (typeof object === \"string\") {\n      this.encodeString(object);\n    } else {\n      this.encodeObject(object, depth);\n    }\n  }\n\n  private ensureBufferSizeToWrite(sizeToWrite: number) {\n    const requiredSize = this.pos + sizeToWrite;\n\n    if (this.view.byteLength < requiredSize) {\n      this.resizeBuffer(requiredSize * 2);\n    }\n  }\n\n  private resizeBuffer(newSize: number) {\n    const newBuffer = new ArrayBuffer(newSize);\n    const newBytes = new Uint8Array(newBuffer);\n    const newView = new DataView(newBuffer);\n\n    newBytes.set(this.bytes);\n\n    this.view = newView;\n    this.bytes = newBytes;\n  }\n\n  private encodeNil() {\n    this.writeU8(0xc0);\n  }\n\n  private encodeBoolean(object: boolean) {\n    if (object === false) {\n      this.writeU8(0xc2);\n    } else {\n      this.writeU8(0xc3);\n    }\n  }\n  private encodeNumber(object: number) {\n    if (Number.isSafeInteger(object) && !this.forceIntegerToFloat) {\n      if (object >= 0) {\n        if (object < 0x80) {\n          // positive fixint\n          this.writeU8(object);\n        } else if (object < 0x100) {\n          // uint 8\n          this.writeU8(0xcc);\n          this.writeU8(object);\n        } else if (object < 0x10000) {\n          // uint 16\n          this.writeU8(0xcd);\n          this.writeU16(object);\n        } else if (object < 0x100000000) {\n          // uint 32\n          this.writeU8(0xce);\n          this.writeU32(object);\n        } else {\n          // uint 64\n          this.writeU8(0xcf);\n          this.writeU64(object);\n        }\n      } else {\n        if (object >= -0x20) {\n          // negative fixint\n          this.writeU8(0xe0 | (object + 0x20));\n        } else if (object >= -0x80) {\n          // int 8\n          this.writeU8(0xd0);\n          this.writeI8(object);\n        } else if (object >= -0x8000) {\n          // int 16\n          this.writeU8(0xd1);\n          this.writeI16(object);\n        } else if (object >= -0x80000000) {\n          // int 32\n          this.writeU8(0xd2);\n          this.writeI32(object);\n        } else {\n          // int 64\n          this.writeU8(0xd3);\n          this.writeI64(object);\n        }\n      }\n    } else {\n      // non-integer numbers\n      if (this.forceFloat32) {\n        // float 32\n        this.writeU8(0xca);\n        this.writeF32(object);\n      } else {\n        // float 64\n        this.writeU8(0xcb);\n        this.writeF64(object);\n      }\n    }\n  }\n\n  private writeStringHeader(byteLength: number) {\n    if (byteLength < 32) {\n      // fixstr\n      this.writeU8(0xa0 + byteLength);\n    } else if (byteLength < 0x100) {\n      // str 8\n      this.writeU8(0xd9);\n      this.writeU8(byteLength);\n    } else if (byteLength < 0x10000) {\n      // str 16\n      this.writeU8(0xda);\n      this.writeU16(byteLength);\n    } else if (byteLength < 0x100000000) {\n      // str 32\n      this.writeU8(0xdb);\n      this.writeU32(byteLength);\n    } else {\n      throw new Error(`Too long string: ${byteLength} bytes in UTF-8`);\n    }\n  }\n\n  private encodeString(object: string) {\n    const maxHeaderSize = 1 + 4;\n    const strLength = object.length;\n\n    if (strLength > TEXT_ENCODER_THRESHOLD) {\n      const byteLength = utf8Count(object);\n      this.ensureBufferSizeToWrite(maxHeaderSize + byteLength);\n      this.writeStringHeader(byteLength);\n      utf8EncodeTE(object, this.bytes, this.pos);\n      this.pos += byteLength;\n    } else {\n      const byteLength = utf8Count(object);\n      this.ensureBufferSizeToWrite(maxHeaderSize + byteLength);\n      this.writeStringHeader(byteLength);\n      utf8EncodeJs(object, this.bytes, this.pos);\n      this.pos += byteLength;\n    }\n  }\n\n  private encodeObject(object: unknown, depth: number) {\n    // try to encode objects with custom codec first of non-primitives\n    const ext = this.extensionCodec.tryToEncode(object, this.context);\n    if (ext != null) {\n      this.encodeExtension(ext);\n    } else if (Array.isArray(object)) {\n      this.encodeArray(object, depth);\n    } else if (ArrayBuffer.isView(object)) {\n      this.encodeBinary(object);\n    } else if (typeof object === \"object\") {\n      this.encodeMap(object as Record<string, unknown>, depth);\n    } else {\n      // symbol, function and other special object come here unless extensionCodec handles them.\n      throw new Error(`Unrecognized object: ${Object.prototype.toString.apply(object)}`);\n    }\n  }\n\n  private encodeBinary(object: ArrayBufferView) {\n    const size = object.byteLength;\n    if (size < 0x100) {\n      // bin 8\n      this.writeU8(0xc4);\n      this.writeU8(size);\n    } else if (size < 0x10000) {\n      // bin 16\n      this.writeU8(0xc5);\n      this.writeU16(size);\n    } else if (size < 0x100000000) {\n      // bin 32\n      this.writeU8(0xc6);\n      this.writeU32(size);\n    } else {\n      throw new Error(`Too large binary: ${size}`);\n    }\n    const bytes = ensureUint8Array(object);\n    this.writeU8a(bytes);\n  }\n\n  private encodeArray(object: Array<unknown>, depth: number) {\n    const size = object.length;\n    if (size < 16) {\n      // fixarray\n      this.writeU8(0x90 + size);\n    } else if (size < 0x10000) {\n      // array 16\n      this.writeU8(0xdc);\n      this.writeU16(size);\n    } else if (size < 0x100000000) {\n      // array 32\n      this.writeU8(0xdd);\n      this.writeU32(size);\n    } else {\n      throw new Error(`Too large array: ${size}`);\n    }\n    for (const item of object) {\n      this.doEncode(item, depth + 1);\n    }\n  }\n\n  private countWithoutUndefined(object: Record<string, unknown>, keys: ReadonlyArray<string>): number {\n    let count = 0;\n\n    for (const key of keys) {\n      if (object[key] !== undefined) {\n        count++;\n      }\n    }\n\n    return count;\n  }\n\n  private encodeMap(object: Record<string, unknown>, depth: number) {\n    const keys = Object.keys(object);\n    if (this.sortKeys) {\n      keys.sort();\n    }\n\n    const size = this.ignoreUndefined ? this.countWithoutUndefined(object, keys) : keys.length;\n\n    if (size < 16) {\n      // fixmap\n      this.writeU8(0x80 + size);\n    } else if (size < 0x10000) {\n      // map 16\n      this.writeU8(0xde);\n      this.writeU16(size);\n    } else if (size < 0x100000000) {\n      // map 32\n      this.writeU8(0xdf);\n      this.writeU32(size);\n    } else {\n      throw new Error(`Too large map object: ${size}`);\n    }\n\n    for (const key of keys) {\n      const value = object[key];\n\n      if (!(this.ignoreUndefined && value === undefined)) {\n        this.encodeString(key);\n        this.doEncode(value, depth + 1);\n      }\n    }\n  }\n\n  private encodeExtension(ext: ExtData) {\n    const size = ext.data.length;\n    if (size === 1) {\n      // fixext 1\n      this.writeU8(0xd4);\n    } else if (size === 2) {\n      // fixext 2\n      this.writeU8(0xd5);\n    } else if (size === 4) {\n      // fixext 4\n      this.writeU8(0xd6);\n    } else if (size === 8) {\n      // fixext 8\n      this.writeU8(0xd7);\n    } else if (size === 16) {\n      // fixext 16\n      this.writeU8(0xd8);\n    } else if (size < 0x100) {\n      // ext 8\n      this.writeU8(0xc7);\n      this.writeU8(size);\n    } else if (size < 0x10000) {\n      // ext 16\n      this.writeU8(0xc8);\n      this.writeU16(size);\n    } else if (size < 0x100000000) {\n      // ext 32\n      this.writeU8(0xc9);\n      this.writeU32(size);\n    } else {\n      throw new Error(`Too large extension object: ${size}`);\n    }\n    this.writeI8(ext.type);\n    this.writeU8a(ext.data);\n  }\n\n  private writeU8(value: number) {\n    this.ensureBufferSizeToWrite(1);\n\n    this.view.setUint8(this.pos, value);\n    this.pos++;\n  }\n\n  private writeU8a(values: ArrayLike<number>) {\n    const size = values.length;\n    this.ensureBufferSizeToWrite(size);\n\n    this.bytes.set(values, this.pos);\n    this.pos += size;\n  }\n\n  private writeI8(value: number) {\n    this.ensureBufferSizeToWrite(1);\n\n    this.view.setInt8(this.pos, value);\n    this.pos++;\n  }\n\n  private writeU16(value: number) {\n    this.ensureBufferSizeToWrite(2);\n\n    this.view.setUint16(this.pos, value);\n    this.pos += 2;\n  }\n\n  private writeI16(value: number) {\n    this.ensureBufferSizeToWrite(2);\n\n    this.view.setInt16(this.pos, value);\n    this.pos += 2;\n  }\n\n  private writeU32(value: number) {\n    this.ensureBufferSizeToWrite(4);\n\n    this.view.setUint32(this.pos, value);\n    this.pos += 4;\n  }\n\n  private writeI32(value: number) {\n    this.ensureBufferSizeToWrite(4);\n\n    this.view.setInt32(this.pos, value);\n    this.pos += 4;\n  }\n\n  private writeF32(value: number) {\n    this.ensureBufferSizeToWrite(4);\n    this.view.setFloat32(this.pos, value);\n    this.pos += 4;\n  }\n\n  private writeF64(value: number) {\n    this.ensureBufferSizeToWrite(8);\n    this.view.setFloat64(this.pos, value);\n    this.pos += 8;\n  }\n\n  private writeU64(value: number) {\n    this.ensureBufferSizeToWrite(8);\n\n    setUint64(this.view, this.pos, value);\n    this.pos += 8;\n  }\n\n  private writeI64(value: number) {\n    this.ensureBufferSizeToWrite(8);\n\n    setInt64(this.view, this.pos, value);\n    this.pos += 8;\n  }\n}\n", "import { Encoder } from \"./Encoder\";\nimport type { ExtensionCodecType } from \"./ExtensionCodec\";\nimport type { ContextOf, SplitUndefined } from \"./context\";\n\nexport type EncodeOptions<ContextType = undefined> = Partial<\n  Readonly<{\n    extensionCodec: ExtensionCodecType<ContextType>;\n\n    /**\n     * The maximum depth in nested objects and arrays.\n     *\n     * Defaults to 100.\n     */\n    maxDepth: number;\n\n    /**\n     * The initial size of the internal buffer.\n     *\n     * Defaults to 2048.\n     */\n    initialBufferSize: number;\n\n    /**\n     * If `true`, the keys of an object is sorted. In other words, the encoded\n     * binary is canonical and thus comparable to another encoded binary.\n     *\n     * Defaults to `false`. If enabled, it spends more time in encoding objects.\n     */\n    sortKeys: boolean;\n    /**\n     * If `true`, non-integer numbers are encoded in float32, not in float64 (the default).\n     *\n     * Only use it if precisions don't matter.\n     *\n     * Defaults to `false`.\n     */\n    forceFloat32: boolean;\n\n    /**\n     * If `true`, an object property with `undefined` value are ignored.\n     * e.g. `{ foo: undefined }` will be encoded as `{}`, as `JSON.stringify()` does.\n     *\n     * Defaults to `false`. If enabled, it spends more time in encoding objects.\n     */\n    ignoreUndefined: boolean;\n\n    /**\n     * If `true`, integer numbers are encoded as floating point numbers,\n     * with the `forceFloat32` option taken into account.\n     *\n     * Defaults to `false`.\n     */\n    forceIntegerToFloat: boolean;\n  }>\n> &\n  ContextOf<ContextType>;\n\nconst defaultEncodeOptions: EncodeOptions = {};\n\n/**\n * It encodes `value` in the MessagePack format and\n * returns a byte buffer.\n *\n * The returned buffer is a slice of a larger `ArrayBuffer`, so you have to use its `#byteOffset` and `#byteLength` in order to convert it to another typed arrays including NodeJS `Buffer`.\n */\nexport function encode<ContextType = undefined>(\n  value: unknown,\n  options: EncodeOptions<SplitUndefined<ContextType>> = defaultEncodeOptions as any,\n): Uint8Array {\n  const encoder = new Encoder(\n    options.extensionCodec,\n    (options as typeof options & { context: any }).context,\n    options.maxDepth,\n    options.initialBufferSize,\n    options.sortKeys,\n    options.forceFloat32,\n    options.ignoreUndefined,\n    options.forceIntegerToFloat,\n  );\n  return encoder.encodeSharedRef(value);\n}\n", "export function prettyByte(byte: number): string {\n  return `${byte < 0 ? \"-\" : \"\"}0x${Math.abs(byte).toString(16).padStart(2, \"0\")}`;\n}\n", "import { utf8DecodeJs } from \"./utils/utf8\";\n\nconst DEFAULT_MAX_KEY_LENGTH = 16;\nconst DEFAULT_MAX_LENGTH_PER_KEY = 16;\n\nexport interface KeyDecoder {\n  canBeCached(byteLength: number): boolean;\n  decode(bytes: Uint8Array, inputOffset: number, byteLength: number): string;\n}\ninterface KeyCacheRecord {\n  readonly bytes: Uint8Array;\n  readonly str: string;\n}\n\nexport class CachedKeyDecoder implements KeyDecoder {\n  hit = 0;\n  miss = 0;\n  private readonly caches: Array<Array<KeyCacheRecord>>;\n\n  constructor(readonly maxKeyLength = DEFAULT_MAX_KEY_LENGTH, readonly maxLengthPerKey = DEFAULT_MAX_LENGTH_PER_KEY) {\n    // avoid `new Array(N)`, which makes a sparse array,\n    // because a sparse array is typically slower than a non-sparse array.\n    this.caches = [];\n    for (let i = 0; i < this.maxKeyLength; i++) {\n      this.caches.push([]);\n    }\n  }\n\n  public canBeCached(byteLength: number): boolean {\n    return byteLength > 0 && byteLength <= this.maxKeyLength;\n  }\n\n  private find(bytes: Uint8Array, inputOffset: number, byteLength: number): string | null {\n    const records = this.caches[byteLength - 1]!;\n\n    FIND_CHUNK: for (const record of records) {\n      const recordBytes = record.bytes;\n\n      for (let j = 0; j < byteLength; j++) {\n        if (recordBytes[j] !== bytes[inputOffset + j]) {\n          continue FIND_CHUNK;\n        }\n      }\n      return record.str;\n    }\n    return null;\n  }\n\n  private store(bytes: Uint8Array, value: string) {\n    const records = this.caches[bytes.length - 1]!;\n    const record: KeyCacheRecord = { bytes, str: value };\n\n    if (records.length >= this.maxLengthPerKey) {\n      // `records` are full!\n      // Set `record` to an arbitrary position.\n      records[(Math.random() * records.length) | 0] = record;\n    } else {\n      records.push(record);\n    }\n  }\n\n  public decode(bytes: Uint8Array, inputOffset: number, byteLength: number): string {\n    const cachedValue = this.find(bytes, inputOffset, byteLength);\n    if (cachedValue != null) {\n      this.hit++;\n      return cachedValue;\n    }\n    this.miss++;\n\n    const str = utf8DecodeJs(bytes, inputOffset, byteLength);\n    // Ensure to copy a slice of bytes because the byte may be NodeJS Buffer and Buffer#slice() returns a reference to its internal ArrayBuffer.\n    const slicedCopyOfBytes = Uint8Array.prototype.slice.call(bytes, inputOffset, inputOffset + byteLength);\n    this.store(slicedCopyOfBytes, str);\n    return str;\n  }\n}\n", "import { prettyByte } from \"./utils/prettyByte\";\nimport { ExtensionCodec, ExtensionCodecType } from \"./ExtensionCodec\";\nimport { getInt64, getUint64, UINT32_MAX } from \"./utils/int\";\nimport { utf8DecodeJs, TEXT_DECODER_THRESHOLD, utf8DecodeTD } from \"./utils/utf8\";\nimport { createDataView, ensureUint8Array } from \"./utils/typedArrays\";\nimport { CachedKeyDecoder, KeyDecoder } from \"./CachedKeyDecoder\";\nimport { DecodeError } from \"./DecodeError\";\n\nconst enum State {\n  ARRAY,\n  MAP_KEY,\n  MAP_VALUE,\n}\n\ntype MapKeyType = string | number;\n\nconst isValidMapKeyType = (key: unknown): key is MapKeyType => {\n  const keyType = typeof key;\n\n  return keyType === \"string\" || keyType === \"number\";\n};\n\ntype StackMapState = {\n  type: State.MAP_KEY | State.MAP_VALUE;\n  size: number;\n  key: MapKeyType | null;\n  readCount: number;\n  map: Record<string, unknown>;\n};\n\ntype StackArrayState = {\n  type: State.ARRAY;\n  size: number;\n  array: Array<unknown>;\n  position: number;\n};\n\ntype StackState = StackArrayState | StackMapState;\n\nconst HEAD_BYTE_REQUIRED = -1;\n\nconst EMPTY_VIEW = new DataView(new ArrayBuffer(0));\nconst EMPTY_BYTES = new Uint8Array(EMPTY_VIEW.buffer);\n\n// IE11: Hack to support IE11.\n// IE11: Drop this hack and just use RangeError when IE11 is obsolete.\nexport const DataViewIndexOutOfBoundsError: typeof Error = (() => {\n  try {\n    // IE11: The spec says it should throw RangeError,\n    // IE11: but in IE11 it throws TypeError.\n    EMPTY_VIEW.getInt8(0);\n  } catch (e: any) {\n    return e.constructor;\n  }\n  throw new Error(\"never reached\");\n})();\n\nconst MORE_DATA = new DataViewIndexOutOfBoundsError(\"Insufficient data\");\n\nconst sharedCachedKeyDecoder = new CachedKeyDecoder();\n\nexport class Decoder<ContextType = undefined> {\n  private totalPos = 0;\n  private pos = 0;\n\n  private view = EMPTY_VIEW;\n  private bytes = EMPTY_BYTES;\n  private headByte = HEAD_BYTE_REQUIRED;\n  private readonly stack: Array<StackState> = [];\n\n  public constructor(\n    private readonly extensionCodec: ExtensionCodecType<ContextType> = ExtensionCodec.defaultCodec as any,\n    private readonly context: ContextType = undefined as any,\n    private readonly maxStrLength = UINT32_MAX,\n    private readonly maxBinLength = UINT32_MAX,\n    private readonly maxArrayLength = UINT32_MAX,\n    private readonly maxMapLength = UINT32_MAX,\n    private readonly maxExtLength = UINT32_MAX,\n    private readonly keyDecoder: KeyDecoder | null = sharedCachedKeyDecoder,\n  ) {}\n\n  private reinitializeState() {\n    this.totalPos = 0;\n    this.headByte = HEAD_BYTE_REQUIRED;\n    this.stack.length = 0;\n\n    // view, bytes, and pos will be re-initialized in setBuffer()\n  }\n\n  private setBuffer(buffer: ArrayLike<number> | BufferSource): void {\n    this.bytes = ensureUint8Array(buffer);\n    this.view = createDataView(this.bytes);\n    this.pos = 0;\n  }\n\n  private appendBuffer(buffer: ArrayLike<number> | BufferSource) {\n    if (this.headByte === HEAD_BYTE_REQUIRED && !this.hasRemaining(1)) {\n      this.setBuffer(buffer);\n    } else {\n      const remainingData = this.bytes.subarray(this.pos);\n      const newData = ensureUint8Array(buffer);\n\n      // concat remainingData + newData\n      const newBuffer = new Uint8Array(remainingData.length + newData.length);\n      newBuffer.set(remainingData);\n      newBuffer.set(newData, remainingData.length);\n      this.setBuffer(newBuffer);\n    }\n  }\n\n  private hasRemaining(size: number) {\n    return this.view.byteLength - this.pos >= size;\n  }\n\n  private createExtraByteError(posToShow: number): Error {\n    const { view, pos } = this;\n    return new RangeError(`Extra ${view.byteLength - pos} of ${view.byteLength} byte(s) found at buffer[${posToShow}]`);\n  }\n\n  /**\n   * @throws {@link DecodeError}\n   * @throws {@link RangeError}\n   */\n  public decode(buffer: ArrayLike<number> | BufferSource): unknown {\n    this.reinitializeState();\n    this.setBuffer(buffer);\n\n    const object = this.doDecodeSync();\n    if (this.hasRemaining(1)) {\n      throw this.createExtraByteError(this.pos);\n    }\n    return object;\n  }\n\n  public *decodeMulti(buffer: ArrayLike<number> | BufferSource): Generator<unknown, void, unknown> {\n    this.reinitializeState();\n    this.setBuffer(buffer);\n\n    while (this.hasRemaining(1)) {\n      yield this.doDecodeSync();\n    }\n  }\n\n  public async decodeAsync(stream: AsyncIterable<ArrayLike<number> | BufferSource>): Promise<unknown> {\n    let decoded = false;\n    let object: unknown;\n    for await (const buffer of stream) {\n      if (decoded) {\n        throw this.createExtraByteError(this.totalPos);\n      }\n\n      this.appendBuffer(buffer);\n\n      try {\n        object = this.doDecodeSync();\n        decoded = true;\n      } catch (e) {\n        if (!(e instanceof DataViewIndexOutOfBoundsError)) {\n          throw e; // rethrow\n        }\n        // fallthrough\n      }\n      this.totalPos += this.pos;\n    }\n\n    if (decoded) {\n      if (this.hasRemaining(1)) {\n        throw this.createExtraByteError(this.totalPos);\n      }\n      return object;\n    }\n\n    const { headByte, pos, totalPos } = this;\n    throw new RangeError(\n      `Insufficient data in parsing ${prettyByte(headByte)} at ${totalPos} (${pos} in the current buffer)`,\n    );\n  }\n\n  public decodeArrayStream(\n    stream: AsyncIterable<ArrayLike<number> | BufferSource>,\n  ): AsyncGenerator<unknown, void, unknown> {\n    return this.decodeMultiAsync(stream, true);\n  }\n\n  public decodeStream(stream: AsyncIterable<ArrayLike<number> | BufferSource>): AsyncGenerator<unknown, void, unknown> {\n    return this.decodeMultiAsync(stream, false);\n  }\n\n  private async *decodeMultiAsync(stream: AsyncIterable<ArrayLike<number> | BufferSource>, isArray: boolean) {\n    let isArrayHeaderRequired = isArray;\n    let arrayItemsLeft = -1;\n\n    for await (const buffer of stream) {\n      if (isArray && arrayItemsLeft === 0) {\n        throw this.createExtraByteError(this.totalPos);\n      }\n\n      this.appendBuffer(buffer);\n\n      if (isArrayHeaderRequired) {\n        arrayItemsLeft = this.readArraySize();\n        isArrayHeaderRequired = false;\n        this.complete();\n      }\n\n      try {\n        while (true) {\n          yield this.doDecodeSync();\n          if (--arrayItemsLeft === 0) {\n            break;\n          }\n        }\n      } catch (e) {\n        if (!(e instanceof DataViewIndexOutOfBoundsError)) {\n          throw e; // rethrow\n        }\n        // fallthrough\n      }\n      this.totalPos += this.pos;\n    }\n  }\n\n  private doDecodeSync(): unknown {\n    DECODE: while (true) {\n      const headByte = this.readHeadByte();\n      let object: unknown;\n\n      if (headByte >= 0xe0) {\n        // negative fixint (111x xxxx) 0xe0 - 0xff\n        object = headByte - 0x100;\n      } else if (headByte < 0xc0) {\n        if (headByte < 0x80) {\n          // positive fixint (0xxx xxxx) 0x00 - 0x7f\n          object = headByte;\n        } else if (headByte < 0x90) {\n          // fixmap (1000 xxxx) 0x80 - 0x8f\n          const size = headByte - 0x80;\n          if (size !== 0) {\n            this.pushMapState(size);\n            this.complete();\n            continue DECODE;\n          } else {\n            object = {};\n          }\n        } else if (headByte < 0xa0) {\n          // fixarray (1001 xxxx) 0x90 - 0x9f\n          const size = headByte - 0x90;\n          if (size !== 0) {\n            this.pushArrayState(size);\n            this.complete();\n            continue DECODE;\n          } else {\n            object = [];\n          }\n        } else {\n          // fixstr (101x xxxx) 0xa0 - 0xbf\n          const byteLength = headByte - 0xa0;\n          object = this.decodeUtf8String(byteLength, 0);\n        }\n      } else if (headByte === 0xc0) {\n        // nil\n        object = null;\n      } else if (headByte === 0xc2) {\n        // false\n        object = false;\n      } else if (headByte === 0xc3) {\n        // true\n        object = true;\n      } else if (headByte === 0xca) {\n        // float 32\n        object = this.readF32();\n      } else if (headByte === 0xcb) {\n        // float 64\n        object = this.readF64();\n      } else if (headByte === 0xcc) {\n        // uint 8\n        object = this.readU8();\n      } else if (headByte === 0xcd) {\n        // uint 16\n        object = this.readU16();\n      } else if (headByte === 0xce) {\n        // uint 32\n        object = this.readU32();\n      } else if (headByte === 0xcf) {\n        // uint 64\n        object = this.readU64();\n      } else if (headByte === 0xd0) {\n        // int 8\n        object = this.readI8();\n      } else if (headByte === 0xd1) {\n        // int 16\n        object = this.readI16();\n      } else if (headByte === 0xd2) {\n        // int 32\n        object = this.readI32();\n      } else if (headByte === 0xd3) {\n        // int 64\n        object = this.readI64();\n      } else if (headByte === 0xd9) {\n        // str 8\n        const byteLength = this.lookU8();\n        object = this.decodeUtf8String(byteLength, 1);\n      } else if (headByte === 0xda) {\n        // str 16\n        const byteLength = this.lookU16();\n        object = this.decodeUtf8String(byteLength, 2);\n      } else if (headByte === 0xdb) {\n        // str 32\n        const byteLength = this.lookU32();\n        object = this.decodeUtf8String(byteLength, 4);\n      } else if (headByte === 0xdc) {\n        // array 16\n        const size = this.readU16();\n        if (size !== 0) {\n          this.pushArrayState(size);\n          this.complete();\n          continue DECODE;\n        } else {\n          object = [];\n        }\n      } else if (headByte === 0xdd) {\n        // array 32\n        const size = this.readU32();\n        if (size !== 0) {\n          this.pushArrayState(size);\n          this.complete();\n          continue DECODE;\n        } else {\n          object = [];\n        }\n      } else if (headByte === 0xde) {\n        // map 16\n        const size = this.readU16();\n        if (size !== 0) {\n          this.pushMapState(size);\n          this.complete();\n          continue DECODE;\n        } else {\n          object = {};\n        }\n      } else if (headByte === 0xdf) {\n        // map 32\n        const size = this.readU32();\n        if (size !== 0) {\n          this.pushMapState(size);\n          this.complete();\n          continue DECODE;\n        } else {\n          object = {};\n        }\n      } else if (headByte === 0xc4) {\n        // bin 8\n        const size = this.lookU8();\n        object = this.decodeBinary(size, 1);\n      } else if (headByte === 0xc5) {\n        // bin 16\n        const size = this.lookU16();\n        object = this.decodeBinary(size, 2);\n      } else if (headByte === 0xc6) {\n        // bin 32\n        const size = this.lookU32();\n        object = this.decodeBinary(size, 4);\n      } else if (headByte === 0xd4) {\n        // fixext 1\n        object = this.decodeExtension(1, 0);\n      } else if (headByte === 0xd5) {\n        // fixext 2\n        object = this.decodeExtension(2, 0);\n      } else if (headByte === 0xd6) {\n        // fixext 4\n        object = this.decodeExtension(4, 0);\n      } else if (headByte === 0xd7) {\n        // fixext 8\n        object = this.decodeExtension(8, 0);\n      } else if (headByte === 0xd8) {\n        // fixext 16\n        object = this.decodeExtension(16, 0);\n      } else if (headByte === 0xc7) {\n        // ext 8\n        const size = this.lookU8();\n        object = this.decodeExtension(size, 1);\n      } else if (headByte === 0xc8) {\n        // ext 16\n        const size = this.lookU16();\n        object = this.decodeExtension(size, 2);\n      } else if (headByte === 0xc9) {\n        // ext 32\n        const size = this.lookU32();\n        object = this.decodeExtension(size, 4);\n      } else {\n        throw new DecodeError(`Unrecognized type byte: ${prettyByte(headByte)}`);\n      }\n\n      this.complete();\n\n      const stack = this.stack;\n      while (stack.length > 0) {\n        // arrays and maps\n        const state = stack[stack.length - 1]!;\n        if (state.type === State.ARRAY) {\n          state.array[state.position] = object;\n          state.position++;\n          if (state.position === state.size) {\n            stack.pop();\n            object = state.array;\n          } else {\n            continue DECODE;\n          }\n        } else if (state.type === State.MAP_KEY) {\n          if (!isValidMapKeyType(object)) {\n            throw new DecodeError(\"The type of key must be string or number but \" + typeof object);\n          }\n          if (object === \"__proto__\") {\n            throw new DecodeError(\"The key __proto__ is not allowed\");\n          }\n\n          state.key = object;\n          state.type = State.MAP_VALUE;\n          continue DECODE;\n        } else {\n          // it must be `state.type === State.MAP_VALUE` here\n\n          state.map[state.key!] = object;\n          state.readCount++;\n\n          if (state.readCount === state.size) {\n            stack.pop();\n            object = state.map;\n          } else {\n            state.key = null;\n            state.type = State.MAP_KEY;\n            continue DECODE;\n          }\n        }\n      }\n\n      return object;\n    }\n  }\n\n  private readHeadByte(): number {\n    if (this.headByte === HEAD_BYTE_REQUIRED) {\n      this.headByte = this.readU8();\n      // console.log(\"headByte\", prettyByte(this.headByte));\n    }\n\n    return this.headByte;\n  }\n\n  private complete(): void {\n    this.headByte = HEAD_BYTE_REQUIRED;\n  }\n\n  private readArraySize(): number {\n    const headByte = this.readHeadByte();\n\n    switch (headByte) {\n      case 0xdc:\n        return this.readU16();\n      case 0xdd:\n        return this.readU32();\n      default: {\n        if (headByte < 0xa0) {\n          return headByte - 0x90;\n        } else {\n          throw new DecodeError(`Unrecognized array type byte: ${prettyByte(headByte)}`);\n        }\n      }\n    }\n  }\n\n  private pushMapState(size: number) {\n    if (size > this.maxMapLength) {\n      throw new DecodeError(`Max length exceeded: map length (${size}) > maxMapLengthLength (${this.maxMapLength})`);\n    }\n\n    this.stack.push({\n      type: State.MAP_KEY,\n      size,\n      key: null,\n      readCount: 0,\n      map: {},\n    });\n  }\n\n  private pushArrayState(size: number) {\n    if (size > this.maxArrayLength) {\n      throw new DecodeError(`Max length exceeded: array length (${size}) > maxArrayLength (${this.maxArrayLength})`);\n    }\n\n    this.stack.push({\n      type: State.ARRAY,\n      size,\n      array: new Array<unknown>(size),\n      position: 0,\n    });\n  }\n\n  private decodeUtf8String(byteLength: number, headerOffset: number): string {\n    if (byteLength > this.maxStrLength) {\n      throw new DecodeError(\n        `Max length exceeded: UTF-8 byte length (${byteLength}) > maxStrLength (${this.maxStrLength})`,\n      );\n    }\n\n    if (this.bytes.byteLength < this.pos + headerOffset + byteLength) {\n      throw MORE_DATA;\n    }\n\n    const offset = this.pos + headerOffset;\n    let object: string;\n    if (this.stateIsMapKey() && this.keyDecoder?.canBeCached(byteLength)) {\n      object = this.keyDecoder.decode(this.bytes, offset, byteLength);\n    } else if (byteLength > TEXT_DECODER_THRESHOLD) {\n      object = utf8DecodeTD(this.bytes, offset, byteLength);\n    } else {\n      object = utf8DecodeJs(this.bytes, offset, byteLength);\n    }\n    this.pos += headerOffset + byteLength;\n    return object;\n  }\n\n  private stateIsMapKey(): boolean {\n    if (this.stack.length > 0) {\n      const state = this.stack[this.stack.length - 1]!;\n      return state.type === State.MAP_KEY;\n    }\n    return false;\n  }\n\n  private decodeBinary(byteLength: number, headOffset: number): Uint8Array {\n    if (byteLength > this.maxBinLength) {\n      throw new DecodeError(`Max length exceeded: bin length (${byteLength}) > maxBinLength (${this.maxBinLength})`);\n    }\n\n    if (!this.hasRemaining(byteLength + headOffset)) {\n      throw MORE_DATA;\n    }\n\n    const offset = this.pos + headOffset;\n    const object = this.bytes.subarray(offset, offset + byteLength);\n    this.pos += headOffset + byteLength;\n    return object;\n  }\n\n  private decodeExtension(size: number, headOffset: number): unknown {\n    if (size > this.maxExtLength) {\n      throw new DecodeError(`Max length exceeded: ext length (${size}) > maxExtLength (${this.maxExtLength})`);\n    }\n\n    const extType = this.view.getInt8(this.pos + headOffset);\n    const data = this.decodeBinary(size, headOffset + 1 /* extType */);\n    return this.extensionCodec.decode(data, extType, this.context);\n  }\n\n  private lookU8() {\n    return this.view.getUint8(this.pos);\n  }\n\n  private lookU16() {\n    return this.view.getUint16(this.pos);\n  }\n\n  private lookU32() {\n    return this.view.getUint32(this.pos);\n  }\n\n  private readU8(): number {\n    const value = this.view.getUint8(this.pos);\n    this.pos++;\n    return value;\n  }\n\n  private readI8(): number {\n    const value = this.view.getInt8(this.pos);\n    this.pos++;\n    return value;\n  }\n\n  private readU16(): number {\n    const value = this.view.getUint16(this.pos);\n    this.pos += 2;\n    return value;\n  }\n\n  private readI16(): number {\n    const value = this.view.getInt16(this.pos);\n    this.pos += 2;\n    return value;\n  }\n\n  private readU32(): number {\n    const value = this.view.getUint32(this.pos);\n    this.pos += 4;\n    return value;\n  }\n\n  private readI32(): number {\n    const value = this.view.getInt32(this.pos);\n    this.pos += 4;\n    return value;\n  }\n\n  private readU64(): number {\n    const value = getUint64(this.view, this.pos);\n    this.pos += 8;\n    return value;\n  }\n\n  private readI64(): number {\n    const value = getInt64(this.view, this.pos);\n    this.pos += 8;\n    return value;\n  }\n\n  private readF32() {\n    const value = this.view.getFloat32(this.pos);\n    this.pos += 4;\n    return value;\n  }\n\n  private readF64() {\n    const value = this.view.getFloat64(this.pos);\n    this.pos += 8;\n    return value;\n  }\n}\n", "import { Decoder } from \"./Decoder\";\nimport type { ExtensionCodecType } from \"./ExtensionCodec\";\nimport type { ContextOf, SplitUndefined } from \"./context\";\n\nexport type DecodeOptions<ContextType = undefined> = Readonly<\n  Partial<{\n    extensionCodec: ExtensionCodecType<ContextType>;\n\n    /**\n     * Maximum string length.\n     *\n     * Defaults to 4_294_967_295 (UINT32_MAX).\n     */\n    maxStrLength: number;\n    /**\n     * Maximum binary length.\n     *\n     * Defaults to 4_294_967_295 (UINT32_MAX).\n     */\n    maxBinLength: number;\n    /**\n     * Maximum array length.\n     *\n     * Defaults to 4_294_967_295 (UINT32_MAX).\n     */\n    maxArrayLength: number;\n    /**\n     * Maximum map length.\n     *\n     * Defaults to 4_294_967_295 (UINT32_MAX).\n     */\n    maxMapLength: number;\n    /**\n     * Maximum extension length.\n     *\n     * Defaults to 4_294_967_295 (UINT32_MAX).\n     */\n    maxExtLength: number;\n  }>\n> &\n  ContextOf<ContextType>;\n\nexport const defaultDecodeOptions: DecodeOptions = {};\n\n/**\n * It decodes a single MessagePack object in a buffer.\n *\n * This is a synchronous decoding function.\n * See other variants for asynchronous decoding: {@link decodeAsync()}, {@link decodeStream()}, or {@link decodeArrayStream()}.\n *\n * @throws {@link RangeError} if the buffer is incomplete, including the case where the buffer is empty.\n * @throws {@link DecodeError} if the buffer contains invalid data.\n */\nexport function decode<ContextType = undefined>(\n  buffer: ArrayLike<number> | BufferSource,\n  options: DecodeOptions<SplitUndefined<ContextType>> = defaultDecodeOptions as any,\n): unknown {\n  const decoder = new Decoder(\n    options.extensionCodec,\n    (options as typeof options & { context: any }).context,\n    options.maxStrLength,\n    options.maxBinLength,\n    options.maxArrayLength,\n    options.maxMapLength,\n    options.maxExtLength,\n  );\n  return decoder.decode(buffer);\n}\n\n/**\n * It decodes multiple MessagePack objects in a buffer.\n * This is corresponding to {@link decodeMultiStream()}.\n *\n * @throws {@link RangeError} if the buffer is incomplete, including the case where the buffer is empty.\n * @throws {@link DecodeError} if the buffer contains invalid data.\n */\nexport function decodeMulti<ContextType = undefined>(\n  buffer: ArrayLike<number> | BufferSource,\n  options: DecodeOptions<SplitUndefined<ContextType>> = defaultDecodeOptions as any,\n): Generator<unknown, void, unknown> {\n  const decoder = new Decoder(\n    options.extensionCodec,\n    (options as typeof options & { context: any }).context,\n    options.maxStrLength,\n    options.maxBinLength,\n    options.maxArrayLength,\n    options.maxMapLength,\n    options.maxExtLength,\n  );\n  return decoder.decodeMulti(buffer);\n}\n", "// utility for whatwg streams\n\n// The living standard of whatwg streams says\n// ReadableStream is also AsyncIterable, but\n// as of June 2019, no browser implements it.\n// See https://streams.spec.whatwg.org/ for details\nexport type ReadableStreamLike<T> = AsyncIterable<T> | ReadableStream<T>;\n\nexport function isAsyncIterable<T>(object: ReadableStreamLike<T>): object is AsyncIterable<T> {\n  return (object as any)[Symbol.asyncIterator] != null;\n}\n\nfunction assertNonNull<T>(value: T | null | undefined): asserts value is T {\n  if (value == null) {\n    throw new Error(\"Assertion Failure: value must not be null nor undefined\");\n  }\n}\n\nexport async function* asyncIterableFromStream<T>(stream: ReadableStream<T>): AsyncIterable<T> {\n  const reader = stream.getReader();\n\n  try {\n    while (true) {\n      const { done, value } = await reader.read();\n      if (done) {\n        return;\n      }\n      assertNonNull(value);\n      yield value;\n    }\n  } finally {\n    reader.releaseLock();\n  }\n}\n\nexport function ensureAsyncIterable<T>(streamLike: ReadableStreamLike<T>): AsyncIterable<T> {\n  if (isAsyncIterable(streamLike)) {\n    return streamLike;\n  } else {\n    return asyncIterableFromStream(streamLike);\n  }\n}\n", "import { Decoder } from \"./Decoder\";\nimport { ensureAsyncIterable } from \"./utils/stream\";\nimport { defaultDecodeOptions } from \"./decode\";\nimport type { ReadableStreamLike } from \"./utils/stream\";\nimport type { DecodeOptions } from \"./decode\";\nimport type { SplitUndefined } from \"./context\";\n\n/**\n * @throws {@link RangeError} if the buffer is incomplete, including the case where the buffer is empty.\n * @throws {@link DecodeError} if the buffer contains invalid data.\n */\n export async function decodeAsync<ContextType>(\n  streamLike: ReadableStreamLike<ArrayLike<number> | BufferSource>,\n  options: DecodeOptions<SplitUndefined<ContextType>> = defaultDecodeOptions as any,\n): Promise<unknown> {\n  const stream = ensureAsyncIterable(streamLike);\n\n  const decoder = new Decoder(\n    options.extensionCodec,\n    (options as typeof options & { context: any }).context,\n    options.maxStrLength,\n    options.maxBinLength,\n    options.maxArrayLength,\n    options.maxMapLength,\n    options.maxExtLength,\n  );\n  return decoder.decodeAsync(stream);\n}\n\n/**\n * @throws {@link RangeError} if the buffer is incomplete, including the case where the buffer is empty.\n * @throws {@link DecodeError} if the buffer contains invalid data.\n */\n export function decodeArrayStream<ContextType>(\n  streamLike: ReadableStreamLike<ArrayLike<number> | BufferSource>,\n  options: DecodeOptions<SplitUndefined<ContextType>> = defaultDecodeOptions as any,\n): AsyncGenerator<unknown, void, unknown> {\n  const stream = ensureAsyncIterable(streamLike);\n\n  const decoder = new Decoder(\n    options.extensionCodec,\n    (options as typeof options & { context: any }).context,\n    options.maxStrLength,\n    options.maxBinLength,\n    options.maxArrayLength,\n    options.maxMapLength,\n    options.maxExtLength,\n  );\n\n  return decoder.decodeArrayStream(stream);\n}\n\n/**\n * @throws {@link RangeError} if the buffer is incomplete, including the case where the buffer is empty.\n * @throws {@link DecodeError} if the buffer contains invalid data.\n */\nexport function decodeMultiStream<ContextType>(\n  streamLike: ReadableStreamLike<ArrayLike<number> | BufferSource>,\n  options: DecodeOptions<SplitUndefined<ContextType>> = defaultDecodeOptions as any,\n): AsyncGenerator<unknown, void, unknown> {\n  const stream = ensureAsyncIterable(streamLike);\n\n  const decoder = new Decoder(\n    options.extensionCodec,\n    (options as typeof options & { context: any }).context,\n    options.maxStrLength,\n    options.maxBinLength,\n    options.maxArrayLength,\n    options.maxMapLength,\n    options.maxExtLength,\n  );\n\n  return decoder.decodeStream(stream);\n}\n\n/**\n * @deprecated Use {@link decodeMultiStream()} instead.\n */\nexport function decodeStream<ContextType>(\n  streamLike: ReadableStreamLike<ArrayLike<number> | BufferSource>,\n  options: DecodeOptions<SplitUndefined<ContextType>> = defaultDecodeOptions as any,\n): AsyncGenerator<unknown, void, unknown> {\n  return decodeMultiStream(streamLike, options);\n}\n", "// Main Functions:\n\nimport { encode } from \"./encode\";\nexport { encode };\nimport type { EncodeOptions } from \"./encode\";\nexport type { EncodeOptions };\n\nimport { decode, decodeMulti } from \"./decode\";\nexport { decode, decodeMulti };\nimport type { DecodeOptions } from \"./decode\";\nexport { DecodeOptions };\n\nimport { decodeAsync, decodeArrayStream, decodeMultiStream, decodeStream } from \"./decodeAsync\";\nexport { decodeAsync, decodeArrayStream, decodeMultiStream, decodeStream };\n\nimport { Decoder, DataViewIndexOutOfBoundsError } from \"./Decoder\";\nimport { DecodeError } from \"./DecodeError\";\nexport { Decoder, DecodeError, DataViewIndexOutOfBoundsError };\n\nimport { Encoder } from \"./Encoder\";\nexport { Encoder };\n\n// Utilitiies for Extension Types:\n\nimport { ExtensionCodec } from \"./ExtensionCodec\";\nexport { ExtensionCodec };\nimport type { ExtensionCodecType, ExtensionDecoderType, ExtensionEncoderType } from \"./ExtensionCodec\";\nexport type { ExtensionCodecType, ExtensionDecoderType, ExtensionEncoderType };\nimport { ExtData } from \"./ExtData\";\nexport { ExtData };\n\nimport {\n  EXT_TIMESTAMP,\n  encodeDateToTimeSpec,\n  encodeTimeSpecToTimestamp,\n  decodeTimestampToTimeSpec,\n  encodeTimestampExtension,\n  decodeTimestampExtension,\n} from \"./timestamp\";\nexport {\n  EXT_TIMESTAMP,\n  encodeDateToTimeSpec,\n  encodeTimeSpecToTimestamp,\n  decodeTimestampToTimeSpec,\n  encodeTimestampExtension,\n  decodeTimestampExtension,\n};\n", "/**\n * The webR JavaScript API.\n * @module WebR\n */\n\nimport { ChannelMain } from './chan/channel';\nimport { newChannelMain, ChannelType } from './chan/channel-common';\nimport { Message } from './chan/message';\nimport { BASE_URL, PKG_BASE_URL, WEBR_VERSION } from './config';\nimport { EmPtr } from './emscripten';\nimport { WebRPayloadPtr } from './payload';\nimport { newRProxy, newRClassProxy } from './proxy';\nimport { isRObject, RCharacter, RComplex, RDouble } from './robj-main';\nimport { REnvironment, RSymbol, RInteger, RList, RDataFrame } from './robj-main';\nimport { RLogical, RNull, RObject, RPairlist, RRaw, RString, RCall } from './robj-main';\nimport { replaceInObject } from './utils';\nimport * as RWorker from './robj-worker';\nimport { WebRError, WebRPayloadError } from './error';\n\nimport {\n  CaptureRMessage,\n  EvalRMessage,\n  EvalRMessageOutputType,\n  EvalRMessageRaw,\n  EvalROptions,\n  FSMessage,\n  FSMountMessage,\n  FSSyncfsMessage,\n  FSReadFileMessage,\n  FSWriteFileMessage,\n  InstallPackagesOptions,\n  InvokeWasmFunctionMessage,\n  NewShelterMessage,\n  ShelterDestroyMessage,\n  ShelterMessage,\n} from './webr-chan';\n\nexport { Console, ConsoleCallbacks } from './console';\nexport * from './robj-main';\nexport * from './error';\nexport * from './webr-chan';\nexport { ChannelType } from './chan/channel-common';\n\n/**\n * The webR FS API for interacting with the Emscripten Virtual File System.\n */\nexport interface WebRFS {\n  /**\n   * Lookup information about a file or directory node in the Emscripten\n   * virtual file system.\n   * @param {string} path Path to the requested node.\n   * @returns {Promise<FSNode>} The requested node.\n   */\n  lookupPath: (path: string) => Promise<FSNode>;\n  /**\n   * Create a directory on the Emscripten virtual file system.\n   * @param {string} path Path of the directory to create.\n   * @returns {Promise<FSNode>} The newly created directory node.\n   */\n  mkdir: (path: string) => Promise<FSNode>;\n  /**\n   * Get the content of a file on the Emscripten virtual file system.\n   * @param {string} path Path of the file to read.\n   * @param {string} [flags] Open the file with the specified flags.\n   * @returns {Promise<Uint8Array>} The content of the requested file.\n   */\n  readFile: (path: string, flags?: string) => Promise<Uint8Array>;\n  /**\n   * Remove a directory on the Emscripten virtual file system.\n   * @param {string} path Path of the directory to remove.\n   */\n  rmdir: (path: string) => Promise<void>;\n  /**\n   * Write a new file to the Emscripten virtual file system.\n   * @param {string} path Path of the new file.\n   * @param {Uint8Array} data The content of the new file.\n   * @param {string} [flags] Open the file with the specified flags.\n   */\n  writeFile: (path: string, data: ArrayBufferView, flags?: string) => Promise<void>;\n  /**\n   * Unlink a node on the Emscripten virtual file system. If that node was the\n   * last link to a file it is is deleted.\n   * @param {string} path Path of the target node.\n   */\n  unlink: (path: string) => Promise<void>;\n}\n\n/** A filesystem entry in the Emscripten Virtual File System */\nexport type FSNode = {\n  id: number;\n  name: string;\n  mode: number;\n  isFolder: boolean;\n  contents?: { [key: string]: FSNode };\n  mounted: null | {\n    mountpoint: string;\n    root: FSNode;\n  }\n};\n\n/** An Emscripten Filesystem type */\nexport type FSType = 'NODEFS' | 'WORKERFS' | 'IDBFS';\n\n/**\n * Configuration settings to be used when mounting Filesystem objects with\n * Emscripten\n */\nexport type FSMountOptions<T extends FSType = FSType> =\n  T extends 'NODEFS' ? { root: string } : {\n    blobs?: Array<{ name: string, data: Blob | ArrayBufferLike }>;\n    files?: Array<File | FileList>;\n    packages?: Array<{ metadata: FSMetaData, blob: Blob | ArrayBufferLike }>;\n  };\n\n/**\n * Emscripten filesystem image metadata\n */\nexport type FSMetaData = {\n  files: {\n    filename: string;\n    start: number;\n    end: number;\n  }[],\n  gzip?: boolean;\n};\n\n/**\n * The configuration settings to be used when starting webR.\n */\nexport interface WebROptions {\n  /**\n   * Command line arguments to be passed to R.\n   * Default: `[]`.\n   */\n  RArgs?: string[];\n\n  /**\n   * Environment variables to be made available for the R process.\n   * Default: `{ R_HOME: '/usr/lib/R', R_ENABLE_JIT: 0 }`.\n   */\n  REnv?: { [key: string]: string };\n\n  /**\n   * The base URL used for downloading R WebAssembly binaries.\n   *  Default: `'https://webr.r-wasm.org/[version]/'`\n   */\n  baseUrl?: string;\n\n  /**\n   * The repo URL to use when downloading R WebAssembly packages.\n   * Default: `'https://repo.r-wasm.org/`\n   */\n  repoUrl?: string;\n\n  /**\n   * The base URL from where to load JavaScript worker scripts when loading\n   * webR with the ServiceWorker communication channel mode.\n   * Default: `''`\n   */\n  serviceWorkerUrl?: string;\n\n  /**\n   * The WebAssembly user's home directory and initial working directory.\n   * Default: `'/home/web_user'`\n   */\n  homedir?: string;\n\n  /**\n   * Start R in interactive mode?\n   * Default: `true`.\n   */\n  interactive?: boolean;\n\n  /**\n   * Set the communication channel type to be used.\n   * Default: `channelType.Automatic`\n   */\n  channelType?: (typeof ChannelType)[keyof typeof ChannelType];\n\n  /**\n   * Create the lazy virtual filesystem entries before starting R?\n   * Default: `true`.\n   */\n  createLazyFilesystem?: boolean;\n}\n\nconst defaultEnv = {\n  FONTCONFIG_PATH: '/etc/fonts',\n  R_HOME: '/usr/lib/R',\n  R_ENABLE_JIT: '0',\n  WEBR: '1',\n  WEBR_VERSION: WEBR_VERSION,\n};\n\nconst defaultOptions = {\n  RArgs: [],\n  REnv: defaultEnv,\n  baseUrl: BASE_URL,\n  serviceWorkerUrl: '',\n  repoUrl: PKG_BASE_URL,\n  homedir: '/home/web_user',\n  interactive: true,\n  channelType: ChannelType.Automatic,\n  createLazyFilesystem: true,\n};\n\n/**\n * The webR class is used to initialize and interact with the webR system.\n *\n * Start webR by constructing an instance of the WebR class, optionally passing\n * an options argument of type {@link WebROptions}. WebR will begin to download\n * and start a version of R built for WebAssembly in a worker thread.\n */\nexport class WebR {\n  #chan: ChannelMain;\n  #initialised: Promise<unknown>;\n  globalShelter!: Shelter;\n  version: string = WEBR_VERSION;\n\n  RObject!: ReturnType<typeof newRClassProxy<typeof RWorker.RObject, RObject>>;\n  RLogical!: ReturnType<typeof newRClassProxy<typeof RWorker.RLogical, RLogical>>;\n  RInteger!: ReturnType<typeof newRClassProxy<typeof RWorker.RInteger, RInteger>>;\n  RDouble!: ReturnType<typeof newRClassProxy<typeof RWorker.RDouble, RDouble>>;\n  RCharacter!: ReturnType<typeof newRClassProxy<typeof RWorker.RCharacter, RCharacter>>;\n  RComplex!: ReturnType<typeof newRClassProxy<typeof RWorker.RComplex, RComplex>>;\n  RRaw!: ReturnType<typeof newRClassProxy<typeof RWorker.RRaw, RRaw>>;\n  RList!: ReturnType<typeof newRClassProxy<typeof RWorker.RList, RList>>;\n  RDataFrame!: ReturnType<typeof newRClassProxy<typeof RWorker.RDataFrame, RDataFrame>>;\n  RPairlist!: ReturnType<typeof newRClassProxy<typeof RWorker.RPairlist, RPairlist>>;\n  REnvironment!: ReturnType<typeof newRClassProxy<typeof RWorker.REnvironment, REnvironment>>;\n  RSymbol!: ReturnType<typeof newRClassProxy<typeof RWorker.RSymbol, RSymbol>>;\n  RString!: ReturnType<typeof newRClassProxy<typeof RWorker.RString, RString>>;\n  RCall!: ReturnType<typeof newRClassProxy<typeof RWorker.RCall, RCall>>;\n\n  objs: {\n    baseEnv: REnvironment;\n    globalEnv: REnvironment;\n    null: RNull;\n    true: RLogical;\n    false: RLogical;\n    na: RLogical;\n  };\n\n  Shelter;\n\n  constructor(options: WebROptions = {}) {\n    const config: Required<WebROptions> = {\n      ...defaultOptions,\n      ...options,\n      REnv: {\n        ...defaultOptions.REnv,\n        ...options.REnv,\n      }\n    };\n    this.#chan = newChannelMain(config);\n\n    this.objs = {} as typeof this.objs;\n    this.Shelter = newShelterProxy(this.#chan);\n\n    this.#initialised = this.#chan.initialised.then(async () => {\n      this.globalShelter = await new this.Shelter();\n\n      this.RObject = this.globalShelter.RObject;\n      this.RLogical = this.globalShelter.RLogical;\n      this.RInteger = this.globalShelter.RInteger;\n      this.RDouble = this.globalShelter.RDouble;\n      this.RComplex = this.globalShelter.RComplex;\n      this.RCharacter = this.globalShelter.RCharacter;\n      this.RRaw = this.globalShelter.RRaw;\n      this.RList = this.globalShelter.RList;\n      this.RDataFrame = this.globalShelter.RDataFrame;\n      this.RPairlist = this.globalShelter.RPairlist;\n      this.REnvironment = this.globalShelter.REnvironment;\n      this.RSymbol = this.globalShelter.RSymbol;\n      this.RString = this.globalShelter.RString;\n      this.RCall = this.globalShelter.RCall;\n\n      this.objs = {\n        baseEnv: (await this.RObject.getPersistentObject('baseEnv')) as REnvironment,\n        globalEnv: (await this.RObject.getPersistentObject('globalEnv')) as REnvironment,\n        null: (await this.RObject.getPersistentObject('null')) as RNull,\n        true: (await this.RObject.getPersistentObject('true')) as RLogical,\n        false: (await this.RObject.getPersistentObject('false')) as RLogical,\n        na: (await this.RObject.getPersistentObject('na')) as RLogical,\n      };\n\n      void this.#handleSystemMessages();\n    });\n  }\n\n  /**\n   * @returns {Promise<void>} A promise that resolves once webR has been\n   * initialised.\n   */\n  async init() {\n    return this.#initialised;\n  }\n\n  async #handleSystemMessages() {\n    for (; ;) {\n      const msg = await this.#chan.readSystem();\n      switch (msg.type) {\n        case 'setTimeoutWasm':\n          /* Handle messages requesting a delayed invocation of a wasm function.\n          * TODO: Reimplement without using the main thread once it is possible\n          *       to yield in the worker thread.\n          */\n          setTimeout(\n            (ptr: EmPtr, args: number[]) => {\n              void this.invokeWasmFunction(ptr, ...args);\n            },\n            msg.data.delay as number,\n            msg.data.ptr,\n            msg.data.args\n          );\n          break;\n        case 'console.log':\n          console.log(msg.data);\n          break;\n        case 'console.warn':\n          console.warn(msg.data);\n          break;\n        case 'console.error':\n          console.error(msg.data);\n          break;\n        case 'close':\n          this.#chan.close();\n          break;\n        default:\n          throw new WebRError('Unknown system message type `' + msg.type + '`');\n      }\n    }\n  }\n\n  /**\n   * Close the communication channel between the main thread and the worker\n   * thread cleanly. Once this has been executed, webR will be unable to\n   * continue.\n   */\n  close() {\n    this.#chan.close();\n  }\n\n  /**\n   * Read from the communication channel and return an output message.\n   * @returns {Promise<Message>} The output message\n   */\n  async read(): Promise<Message> {\n    return await this.#chan.read();\n  }\n\n  /**\n   * Flush the output queue in the communication channel and return all output\n   * messages.\n   * @returns {Promise<Message[]>} The output messages\n   */\n  async flush(): Promise<Message[]> {\n    return await this.#chan.flush();\n  }\n\n  /**\n   * Send a message to the communication channel input queue.\n   * @param {Message} msg Message to be added to the input queue.\n   */\n  write(msg: Message) {\n    this.#chan.write(msg);\n  }\n\n  /**\n   * Send a line of standard input to the communication channel input queue.\n   * @param {string} input Message to be added to the input queue.\n   */\n  writeConsole(input: string) {\n    this.write({ type: 'stdin', data: input + '\\n' });\n  }\n\n  /** Attempt to interrupt a running R computation. */\n  interrupt() {\n    this.#chan.interrupt();\n  }\n\n  /**\n   * Install a list of R packages from Wasm binary package repositories.\n   * @param {string | string[]} packages An string or array of strings\n   *   containing R package names.\n   * @param {InstallPackagesOptions} [options] Options to be used when\n   *   installing webR packages.\n   */\n  async installPackages(packages: string | string[], options?: InstallPackagesOptions) {\n    const op = Object.assign({\n      quiet: false,\n      mount: true\n    }, options);\n\n    const msg = { type: 'installPackages', data: { name: packages, options: op } };\n    await this.#chan.request(msg);\n  }\n\n  /**\n   * Destroy an R object reference.\n   * @param {RObject} x An R object reference.\n   */\n  async destroy(x: RObject) {\n    await this.globalShelter.destroy(x);\n  }\n\n  /**\n   * Evaluate the given R code.\n   *\n   * Stream outputs and any conditions raised during execution are written to\n   * the JavaScript console.\n   * @param {string} code The R code to evaluate.\n   * @param {EvalROptions} [options] Options for the execution environment.\n   * @returns {Promise<RObject>} The result of the computation.\n   */\n  async evalR(code: string, options?: EvalROptions): Promise<RObject> {\n    return this.globalShelter.evalR(code, options);\n  }\n\n  async evalRVoid(code: string, options?: EvalROptions) {\n    return this.evalRRaw(code, 'void', options);\n  }\n\n  async evalRBoolean(code: string, options?: EvalROptions) {\n    return this.evalRRaw(code, 'boolean', options);\n  }\n\n  async evalRNumber(code: string, options?: EvalROptions) {\n    return this.evalRRaw(code, 'number', options);\n  }\n\n  async evalRString(code: string, options?: EvalROptions) {\n    return this.evalRRaw(code, 'string', options);\n  }\n\n  /**\n   * Evaluate the given R code, returning the result as a raw JavaScript object.\n   * @param {string} code The R code to evaluate.\n   * @param {EvalRMessageOutputType} outputType JavaScript type to return the result as.\n   * @param {EvalROptions} [options] Options for the execution environment.\n   * @returns {Promise<unknown>} The result of the computation.\n   */\n  async evalRRaw(code: string, outputType: 'void', options?: EvalROptions): Promise<void>;\n  async evalRRaw(code: string, outputType: 'boolean', options?: EvalROptions): Promise<boolean>;\n  async evalRRaw(code: string, outputType: 'boolean[]', options?: EvalROptions): Promise<boolean[]>;\n  async evalRRaw(code: string, outputType: 'number', options?: EvalROptions): Promise<number>;\n  async evalRRaw(code: string, outputType: 'number[]', options?: EvalROptions): Promise<number[]>;\n  async evalRRaw(code: string, outputType: 'string', options?: EvalROptions): Promise<string>;\n  async evalRRaw(code: string, outputType: 'string[]', options?: EvalROptions): Promise<string[]>;\n  async evalRRaw(code: string, outputType: EvalRMessageOutputType, options: EvalROptions = {}) {\n    const opts = replaceInObject(options, isRObject, (obj: RObject) => obj._payload);\n    const msg: EvalRMessageRaw = {\n      type: 'evalRRaw',\n      data: { code: code, options: opts as EvalROptions, outputType: outputType },\n    };\n    const payload = await this.#chan.request(msg);\n\n    switch (payload.payloadType) {\n      case 'raw':\n        return payload.obj;\n      case 'ptr':\n        throw new WebRPayloadError('Unexpected ptr payload type returned from evalRVoid');\n    }\n  }\n\n  async invokeWasmFunction(ptr: EmPtr, ...args: number[]): Promise<EmPtr> {\n    const msg = {\n      type: 'invokeWasmFunction',\n      data: { ptr, args },\n    } as InvokeWasmFunctionMessage;\n    const resp = await this.#chan.request(msg);\n    return resp.obj as EmPtr;\n  }\n\n  FS = {\n    lookupPath: async (path: string): Promise<FSNode> => {\n      const msg: FSMessage = { type: 'lookupPath', data: { path } };\n      const payload = await this.#chan.request(msg);\n      return payload.obj as FSNode;\n    },\n    mkdir: async (path: string): Promise<FSNode> => {\n      const msg: FSMessage = { type: 'mkdir', data: { path } };\n      const payload = await this.#chan.request(msg);\n      return payload.obj as FSNode;\n    },\n    mount: async <T extends FSType>(\n      type: T,\n      options: FSMountOptions<T>,\n      mountpoint: string\n    ): Promise<void> => {\n      // Convert blobs to ArrayBuffer for transfer over the communication channel\n      // FIXME: Use a replacer + reviver to transfer `Blob`s\n      let promises: Promise<void>[] = [];\n      if ('blobs' in options && options.blobs) {\n        promises = [...promises, ...options.blobs.map((item) => {\n          if (item.data instanceof Blob) {\n            return item.data.arrayBuffer().then((data) => {\n              item.data = new Uint8Array(data);\n            });\n          } else {\n            return Promise.resolve();\n          }\n        })];\n      }\n      if ('packages' in options && options.packages) {\n        promises = [...promises, ...options.packages.map((pkg) => {\n          if (pkg.blob instanceof Blob) {\n            return pkg.blob.arrayBuffer().then((data) => {\n              pkg.blob = new Uint8Array(data);\n            });\n          } else {\n            return Promise.resolve();\n          }\n        })];\n      }\n      await Promise.all(promises);\n\n      const msg: FSMountMessage = { type: 'mount', data: { type, options, mountpoint } };\n      await this.#chan.request(msg);\n    },\n    syncfs: async (populate: boolean): Promise<void> => {\n      const msg: FSSyncfsMessage = { type: 'syncfs', data: { populate } };\n      await this.#chan.request(msg);\n    },\n    readFile: async (path: string, flags?: string): Promise<Uint8Array> => {\n      const msg: FSReadFileMessage = { type: 'readFile', data: { path, flags } };\n      const payload = await this.#chan.request(msg);\n      return payload.obj as Uint8Array;\n    },\n    rmdir: async (path: string): Promise<void> => {\n      const msg: FSMessage = { type: 'rmdir', data: { path } };\n      await this.#chan.request(msg);\n    },\n    writeFile: async (path: string, data: ArrayBufferView, flags?: string): Promise<void> => {\n      const msg: FSWriteFileMessage = { type: 'writeFile', data: { path, data, flags } };\n      await this.#chan.request(msg);\n    },\n    unlink: async (path: string): Promise<void> => {\n      const msg: FSMessage = { type: 'unlink', data: { path } };\n      await this.#chan.request(msg);\n    },\n    unmount: async (mountpoint: string): Promise<void> => {\n      const msg: FSMessage = { type: 'unmount', data: { path: mountpoint } };\n      await this.#chan.request(msg);\n    },\n  };\n}\n\n/** WebR shelters provide fine-grained control over the lifetime of R objects. */\nexport class Shelter {\n  #id = '';\n  #chan: ChannelMain;\n  #initialised = false;\n\n  RObject!: ReturnType<typeof newRClassProxy<typeof RWorker.RObject, RObject>>;\n  RLogical!: ReturnType<typeof newRClassProxy<typeof RWorker.RLogical, RLogical>>;\n  RInteger!: ReturnType<typeof newRClassProxy<typeof RWorker.RInteger, RInteger>>;\n  RDouble!: ReturnType<typeof newRClassProxy<typeof RWorker.RDouble, RDouble>>;\n  RCharacter!: ReturnType<typeof newRClassProxy<typeof RWorker.RCharacter, RCharacter>>;\n  RComplex!: ReturnType<typeof newRClassProxy<typeof RWorker.RComplex, RComplex>>;\n  RRaw!: ReturnType<typeof newRClassProxy<typeof RWorker.RRaw, RRaw>>;\n  RList!: ReturnType<typeof newRClassProxy<typeof RWorker.RList, RList>>;\n  RDataFrame!: ReturnType<typeof newRClassProxy<typeof RWorker.RDataFrame, RDataFrame>>;\n  RPairlist!: ReturnType<typeof newRClassProxy<typeof RWorker.RPairlist, RPairlist>>;\n  REnvironment!: ReturnType<typeof newRClassProxy<typeof RWorker.REnvironment, REnvironment>>;\n  RSymbol!: ReturnType<typeof newRClassProxy<typeof RWorker.RSymbol, RSymbol>>;\n  RString!: ReturnType<typeof newRClassProxy<typeof RWorker.RString, RString>>;\n  RCall!: ReturnType<typeof newRClassProxy<typeof RWorker.RCall, RCall>>;\n\n  /** @internal */\n  constructor(chan: ChannelMain) {\n    this.#chan = chan;\n  }\n\n  /** @internal */\n  async init() {\n    if (this.#initialised) {\n      return;\n    }\n\n    const msg = { type: 'newShelter' } as NewShelterMessage;\n    const payload = await this.#chan.request(msg);\n    this.#id = payload.obj as string;\n\n    this.RObject = newRClassProxy<typeof RWorker.RObject, RObject>(this.#chan, this.#id, 'object');\n    this.RLogical = newRClassProxy<typeof RWorker.RLogical, RLogical>(this.#chan, this.#id, 'logical');\n    this.RInteger = newRClassProxy<typeof RWorker.RInteger, RInteger>(this.#chan, this.#id, 'integer');\n    this.RDouble = newRClassProxy<typeof RWorker.RDouble, RDouble>(this.#chan, this.#id, 'double');\n    this.RComplex = newRClassProxy<typeof RWorker.RComplex, RComplex>(this.#chan, this.#id, 'complex');\n    this.RCharacter = newRClassProxy<typeof RWorker.RCharacter, RCharacter>(this.#chan, this.#id, 'character');\n    this.RRaw = newRClassProxy<typeof RWorker.RRaw, RRaw>(this.#chan, this.#id, 'raw');\n    this.RList = newRClassProxy<typeof RWorker.RList, RList>(this.#chan, this.#id, 'list');\n    this.RDataFrame = newRClassProxy<typeof RWorker.RDataFrame, RDataFrame>(this.#chan, this.#id, 'dataframe');\n    this.RPairlist = newRClassProxy<typeof RWorker.RPairlist, RPairlist>(this.#chan, this.#id, 'pairlist');\n    this.REnvironment = newRClassProxy<typeof RWorker.REnvironment, REnvironment>(this.#chan, this.#id, 'environment');\n    this.RSymbol = newRClassProxy<typeof RWorker.RSymbol, RSymbol>(this.#chan, this.#id, 'symbol');\n    this.RString = newRClassProxy<typeof RWorker.RString, RString>(this.#chan, this.#id, 'string');\n    this.RCall = newRClassProxy<typeof RWorker.RCall, RCall>(this.#chan, this.#id, 'call');\n\n    this.#initialised = true;\n  }\n\n  async purge() {\n    const msg: ShelterMessage = {\n      type: 'shelterPurge',\n      data: this.#id,\n    };\n    await this.#chan.request(msg);\n  }\n\n  async destroy(x: RObject) {\n    const msg: ShelterDestroyMessage = {\n      type: 'shelterDestroy',\n      data: { id: this.#id, obj: x._payload },\n    };\n    await this.#chan.request(msg);\n  }\n\n  async size(): Promise<number> {\n    const msg: ShelterMessage = {\n      type: 'shelterSize',\n      data: this.#id,\n    };\n    const payload = await this.#chan.request(msg);\n    return payload.obj as number;\n  }\n\n  /**\n   * Evaluate the given R code.\n   *\n   * Stream outputs and any conditions raised during execution are written to\n   * the JavaScript console. The returned R object is protected by the shelter.\n   * @param {string} code The R code to evaluate.\n   * @param {EvalROptions} [options] Options for the execution environment.\n   * @returns {Promise<RObject>} The result of the computation.\n   */\n  async evalR(code: string, options: EvalROptions = {}): Promise<RObject> {\n    const opts = replaceInObject(options, isRObject, (obj: RObject) => obj._payload);\n    const msg: EvalRMessage = {\n      type: 'evalR',\n      data: { code: code, options: opts as EvalROptions, shelter: this.#id },\n    };\n    const payload = await this.#chan.request(msg);\n\n    switch (payload.payloadType) {\n      case 'raw':\n        throw new WebRPayloadError('Unexpected payload type returned from evalR');\n      default:\n        return newRProxy(this.#chan, payload);\n    }\n  }\n\n  /**\n   * Evaluate the given R code, capturing output.\n   *\n   * Stream outputs and conditions raised during execution are captured and\n   * returned as part of the output of this function. Returned R objects are\n   * protected by the shelter.\n   * @param {string} code The R code to evaluate.\n   * @param {EvalROptions} [options] Options for the execution environment.\n   * @returns {Promise<{\n   *   result: RObject,\n   *   output: { type: string; data: any }[],\n   *   images: ImageBitmap[]\n   * }>} An object containing the result of the computation, an array of output,\n   *   and an array of captured plots.\n   */\n  async captureR(code: string, options: EvalROptions = {}): Promise<{\n    result: RObject;\n    output: { type: string; data: any }[];\n    images: ImageBitmap[];\n  }> {\n    const opts = replaceInObject(options, isRObject, (obj: RObject) => obj._payload);\n    const msg: CaptureRMessage = {\n      type: 'captureR',\n      data: {\n        code: code,\n        options: opts as EvalROptions,\n        shelter: this.#id,\n      },\n    };\n    const payload = await this.#chan.request(msg);\n\n    switch (payload.payloadType) {\n      case 'ptr':\n        throw new WebRPayloadError('Unexpected payload type returned from evalR');\n\n      case 'raw': {\n        const data = payload.obj as {\n          result: WebRPayloadPtr;\n          output: { type: string; data: any }[];\n          images: ImageBitmap[];\n        };\n        const result = newRProxy(this.#chan, data.result);\n        const output = data.output;\n        const images = data.images;\n\n        for (let i = 0; i < output.length; ++i) {\n          if (output[i].type !== 'stdout' && output[i].type !== 'stderr') {\n            output[i].data = newRProxy(this.#chan, output[i].data as WebRPayloadPtr);\n          }\n        }\n\n        return { result, output, images };\n      }\n    }\n  }\n}\n\nfunction newShelterProxy(chan: ChannelMain) {\n  return new Proxy(Shelter, {\n    construct: async () => {\n      const out = new Shelter(chan);\n      await out.init();\n      return out;\n    },\n  }) as unknown as {\n    new(): Promise<Shelter>;\n  };\n}\n", "/**\n * Custom Error classes that shall be raised by webR.\n * @module Error\n */\n\n/**\n * A general error raised by webR.\n */\nexport class WebRError extends Error {\n  constructor(msg: string) {\n    super(msg);\n    this.name = this.constructor.name;\n    Object.setPrototypeOf(this, new.target.prototype);\n  }\n}\n\n/**\n * Exceptions raised on the webR worker thread that have been forwarded to the\n * main thread through the communication channel.\n */\nexport class WebRWorkerError extends WebRError { }\n\n/**\n * Exceptions related to issues with the webR communication channel.\n */\nexport class WebRChannelError extends WebRError { }\n\n/**\n * Exceptions related to issues with webR object payloads.\n */\nexport class WebRPayloadError extends WebRError { }\n", "import { WebRError } from './error';\n\ninterface Process {\n  browser: string | undefined;\n  release: { [key: string]: string };\n}\ndeclare let process: Process;\n\nexport const IN_NODE =\n  typeof process !== 'undefined' &&\n  process.release &&\n  process.release.name === 'node';\n\n// Adapted from https://github.com/pyodide/pyodide/blob/main/src/js/compat.ts\nexport let loadScript: (url: string) => Promise<void>;\nif (globalThis.document) {\n  loadScript = (url) =>\n    new Promise((resolve, reject) => {\n      const script = document.createElement('script');\n      script.src = url;\n      script.onload = () => resolve();\n      script.onerror = reject;\n      document.head.appendChild(script);\n    });\n} else if (globalThis.importScripts) {\n  loadScript = async (url) => {\n    try {\n      globalThis.importScripts(url);\n    } catch (e) {\n      if (e instanceof TypeError) {\n        await import(url);\n      } else {\n        throw e;\n      }\n    }\n  };\n} else if (IN_NODE) {\n  loadScript = async (url: string) => {\n    const nodePathMod = (await import('path')).default;\n    await import(nodePathMod.resolve(url));\n  };\n} else {\n  throw new WebRError('Cannot determine runtime environment');\n}\n", "import type { RPtr, RTypeNumber } from './robj';\nimport type { RObject, RList } from './robj-worker';\nimport type { EvalROptions } from './webr-chan';\nimport type { UnwindProtectException } from './utils-r';\n\nexport interface Module extends EmscriptenModule {\n  /* Add mkdirTree to FS namespace, missing from @types/emscripten at the\n   * time of writing.\n   */\n  FS: typeof FS & {\n    _mount: typeof FS.mount;\n    mkdirTree(path: string): void;\n    filesystems: {\n      [key: string]: Emscripten.FileSystemType;\n    }\n  };\n  ENV: { [key: string]: string };\n  GOT: {\n    [key: string]: { required: boolean; value: number };\n  }\n  createLazyFilesystem: () => void;\n  monitorRunDependencies: (n: number) => void;\n  noImageDecoding: boolean;\n  noAudioDecoding: boolean;\n  noWasmDecoding: boolean;\n  setPrompt: (prompt: string) => void;\n  downloadFileContent: (\n    URL: string,\n    headers?: Array<string>\n  ) => {\n    status: number;\n    response: string | ArrayBuffer;\n  };\n  mountImageUrl: (url: string, mountpoint: string) => void;\n  mountImagePath: (path: string, mountpoint: string) => void;\n  // Exported Emscripten JS API\n  allocateUTF8: typeof allocateUTF8;\n  allocateUTF8OnStack: typeof allocateUTF8OnStack;\n  getValue: typeof getValue;\n  setValue: typeof setValue;\n  UTF8ToString: typeof UTF8ToString;\n  callMain: (args: string[]) => void;\n  getWasmTableEntry: (entry: number) => (...args: any[]) => RPtr;\n  // R symbols from Rinternals.h\n  _ATTRIB: (ptr: RPtr) => RPtr;\n  _CAR: (ptr: RPtr) => RPtr;\n  _CDR: (ptr: RPtr) => RPtr;\n  _CLOENV: (ptr: RPtr) => RPtr;\n  _COMPLEX: (ptr: RPtr) => RPtr;\n  _FRAME: (ptr: RPtr) => RPtr;\n  _INTEGER: (ptr: RPtr) => RPtr;\n  _INTERNAL: (ptr: RPtr) => RPtr;\n  _LENGTH: (ptr: RPtr) => number;\n  _LOGICAL: (ptr: RPtr) => RPtr;\n  _PRINTNAME: (ptr: RPtr) => RPtr;\n  _R_CHAR: (ptr: RPtr) => RPtr;\n  _RAW: (ptr: RPtr) => RPtr;\n  _REAL: (ptr: RPtr) => RPtr;\n  _SETCAR: (x: RPtr, y: RPtr) => void;\n  _STRING_ELT: (ptr: RPtr, idx: number) => RPtr;\n  _STRING_PTR: (ptr: RPtr) => RPtr;\n  _SYMVALUE: (ptr: RPtr) => RPtr;\n  _TAG: (ptr: RPtr) => RPtr;\n  _TYPEOF: (ptr: RPtr) => RPtr;\n  _VECTOR_ELT: (ptr: RPtr, idx: number) => RPtr;\n  _R_lsInternal3: (env: RPtr, all: number, sorted: number) => RPtr;\n  _R_MakeExternalPtr: (p: number, tag: RPtr, prot: RPtr) => RPtr;\n  _R_NewEnv: (enclos: RPtr, hash: number, size: number) => RPtr;\n  _R_ParseEvalString: (code: number, env: RPtr) => RPtr;\n  _R_PreserveObject: (ptr: RPtr) => void;\n  _R_ReleaseObject: (ptr: RPtr) => void;\n  _R_ReplDLLinit: () => void;\n  _R_ReplDLLdo1: () => number;\n  _Rf_ScalarReal: (n: number) => RPtr;\n  _Rf_ScalarLogical: (l: number) => RPtr;\n  _Rf_ScalarInteger: (n: number) => RPtr;\n  _Rf_ScalarString: (s: string) => RPtr;\n  _Rf_allocList: (len: number) => RPtr;\n  _Rf_allocVector: (type: RTypeNumber, len: number) => RPtr;\n  _Rf_defineVar: (symbol: RPtr, value: RPtr, env: RPtr) => void;\n  _Rf_error: (msg: EmPtr) => void;\n  _Rf_eval: (call: RPtr, env: RPtr) => RPtr;\n  _Rf_findVarInFrame: (rho: RPtr, symbol: RPtr) => RPtr;\n  _Rf_listAppend: (source: RPtr, target: RPtr) => RPtr;\n  _Rf_getAttrib: (ptr1: RPtr, ptr2: RPtr) => RPtr;\n  _Rf_initialize_R: (argc: number, argv: RPtr) => void;\n  _Rf_install: (ptr: number) => RPtr;\n  _Rf_installTrChar: (name: RPtr) => RPtr;\n  _Rf_lang1: (ptr1: RPtr) => RPtr;\n  _Rf_lang2: (ptr1: RPtr, ptr2: RPtr) => RPtr;\n  _Rf_lang3: (ptr1: RPtr, ptr2: RPtr, ptr3: RPtr) => RPtr;\n  _Rf_lang4: (ptr1: RPtr, ptr2: RPtr, ptr3: RPtr, ptr4: RPtr) => RPtr;\n  _Rf_lang5: (ptr1: RPtr, ptr2: RPtr, ptr3: RPtr, ptr4: RPtr, ptr5: RPtr) => RPtr;\n  _Rf_lang6: (ptr1: RPtr, ptr2: RPtr, ptr3: RPtr, ptr4: RPtr, ptr5: RPtr, ptr6: RPtr) => RPtr;\n  _Rf_mkChar: (ptr: number) => RPtr;\n  _Rf_mkString: (ptr: number) => RPtr;\n  _Rf_onintr: () => void;\n  _Rf_protect: (ptr: RPtr) => RPtr;\n  _R_ContinueUnwind: (cont: RPtr) => never;\n  _R_ProtectWithIndex: (ptr1: RPtr, ptr2: RPtr) => void;\n  _R_Reprotect: (ptr1: RPtr, ptr2: RPtr) => void;\n  _Rf_setAttrib: (ptr1: RPtr, ptr2: RPtr, ptr3: RPtr) => RPtr;\n  _Rf_unprotect: (n: number) => void;\n  _Rf_unprotect_ptr: (ptr: RPtr) => void;\n  _DLLbuf: RPtr;\n  _DLLbufp: RPtr;\n  _R_BaseEnv: RPtr;\n  _R_BracketSymbol: RPtr;\n  _R_Bracket2Symbol: RPtr;\n  _R_DollarSymbol: RPtr;\n  _R_EmptyEnv: RPtr;\n  _R_FalseValue: RPtr;\n  _R_GlobalEnv: RPtr;\n  _R_Interactive: RPtr;\n  _R_NaInt: RPtr;\n  _R_NaReal: RPtr;\n  _R_NaString: RPtr;\n  _R_LogicalNAValue: RPtr;\n  _R_NilValue: RPtr;\n  _R_TrueValue: RPtr;\n  _R_NamesSymbol: RPtr;\n  _R_UnboundValue: RPtr;\n  _SET_STRING_ELT: (ptr: RPtr, idx: number, val: RPtr) => void;\n  _SET_VECTOR_ELT: (ptr: RPtr, idx: number, val: RPtr) => void;\n  _setup_Rmainloop: () => void;\n  _strcpy: (dest: RPtr, src: RPtr) => number;\n  // TODO: Namespace all webR properties\n  webr: {\n    UnwindProtectException: typeof UnwindProtectException;\n    canvas: {\n      [key: number]: {\n        ctx: OffscreenCanvasRenderingContext2D;\n        offscreen: OffscreenCanvas;\n        transmit: boolean;\n      };\n    };\n    readConsole: () => number;\n    resolveInit: () => void;\n    handleEvents: () => void;\n    dataViewer: (data: RPtr, title: string) => void;\n    evalJs: (code: RPtr) => unknown;\n    evalR: (expr: string | RObject, options?: EvalROptions) => RObject;\n    captureR: (expr: string | RObject, options: EvalROptions) => {\n      result: RObject,\n      output: RList,\n      images: ImageBitmap[],\n    };\n    setTimeoutWasm: (ptr: EmPtr, data: EmPtr, delay: number) => void;\n  };\n}\n\nexport const Module = {} as Module;\n\nexport type EmPtr = ReturnType<typeof Module.allocateUTF8>;\n\nexport interface DictEmPtrs {\n  [key: string]: EmPtr;\n}\n\nexport function dictEmFree(dict: { [key: string | number]: EmPtr }) {\n  Object.keys(dict).forEach((key) => Module._free(dict[key]));\n}\n", "/**\n * Common module for working with R objects.\n * @module RObject\n */\nimport * as RMain from './robj-main';\nimport * as RWorker from './robj-worker';\n\nexport type RPtr = number;\n\nexport const RTypeMap = {\n  null: 0,\n  symbol: 1,\n  pairlist: 2,\n  closure: 3,\n  environment: 4,\n  promise: 5,\n  call: 6,\n  special: 7,\n  builtin: 8,\n  string: 9,\n  logical: 10,\n  integer: 13,\n  double: 14,\n  complex: 15,\n  character: 16,\n  dots: 17,\n  any: 18,\n  list: 19,\n  expression: 20,\n  bytecode: 21,\n  pointer: 22,\n  weakref: 23,\n  raw: 24,\n  s4: 25,\n  new: 30,\n  free: 31,\n  function: 99,\n} as const;\nexport type RType = keyof typeof RTypeMap;\nexport type RTypeNumber = typeof RTypeMap[RType];\n\n/** @internal */\nexport type RCtor = 'object' | 'dataframe';\n\nexport type Complex = {\n  re: number;\n  im: number;\n};\n\nexport type WebRDataRaw =\n  | number\n  | string\n  | boolean\n  | undefined\n  | null\n  | void\n  | Complex\n  | Error\n  | ArrayBuffer\n  | ArrayBufferView\n  | ImageBitmap\n  | Array<WebRDataRaw>\n  | Map<WebRDataRaw, WebRDataRaw>\n  | Set<WebRDataRaw>\n  | { [key: string]: WebRDataRaw };\n\nexport type NamedEntries<T> = [string | null, T][];\nexport type NamedObject<T> = { [key: string]: T };\n\n/**\n * A union of JavaScript types that are able to be converted into an R object.\n *\n * `WebRData` is used both as a general input argument for R object construction\n * and also as a general return type when converting R objects into JavaScript.\n *\n */\nexport type WebRData =\n  | RMain.RObject\n  | RWorker.RObjectBase\n  | RWorker.RObject\n  | WebRDataRaw\n  | WebRDataJs\n  | WebRData[]\n  | ArrayBuffer\n  | ArrayBufferView\n  | { [key: string]: WebRData };\n\n/**\n * A subset of {@link WebRData} for JavaScript objects that can be converted\n * into R atomic vectors.\n * @typeParam T The JavaScript scalar type associated with the atomic vector.\n */\nexport type WebRDataAtomic<T> =\n  | WebRDataScalar<T>\n  | WebRDataJsAtomic<T>\n  | NamedObject<T | null>\n  | ([T] extends [number] ? ArrayBuffer | ArrayBufferView | (number | null)[] : (T | null)[]);\n\n/**\n * `WebRDataJs` objects form a tree structure, used when serialising R objects\n * into a JavaScript representation.\n *\n * Nested R objects are serialised using the {@link WebRDataJsNode} type,\n * forming branches in the resulting tree structure, with leaves formed by the\n * remaining types.\n */\nexport type WebRDataJs =\n  | WebRDataJsNull\n  | WebRDataJsString\n  | WebRDataJsSymbol\n  | WebRDataJsNode\n  | WebRDataJsAtomic<RWorker.atomicType>;\n\nexport type WebRDataJsNull = {\n  type: 'null';\n};\n\nexport type WebRDataJsString = {\n  type: 'string';\n  value: string;\n};\n\nexport type WebRDataJsSymbol = {\n  type: 'symbol';\n  printname: string | null;\n  symvalue: RPtr | null;\n  internal: RPtr | null;\n};\n\nexport type WebRDataJsNode = {\n  type: 'list' | 'pairlist' | 'environment';\n  names: (string | null)[] | null;\n  values: (WebRDataRaw | RWorker.RObject | RMain.RObject | WebRDataJs)[];\n};\n\nexport type WebRDataJsAtomic<T> = {\n  type: 'logical' | 'integer' | 'double' | 'complex' | 'character' | 'raw';\n  names: (string | null)[] | null;\n  values: (T | null)[];\n};\n\n/**\n * Test for a {@link WebRDataJs} instance.\n * @param {any} value The object to test.\n * @returns {boolean} True if the object is an instance of a {@link WebRDataJs}.\n */\nexport function isWebRDataJs(value: any): value is WebRDataJs {\n  return !!value && typeof value === 'object'\n    && Object.keys(RTypeMap).includes(value.type as string);\n}\n\n/**\n * A subset of WebRData for scalar JavaScript objects.\n */\nexport type WebRDataScalar<T> = T | RMain.RObject | RWorker.RObjectBase;\n\n/**\n * Test if an object is of type {@link Complex}.\n * @param {any} value The object to test.\n * @returns {boolean} True if the object is of type {@link Complex}.\n */\nexport function isComplex(value: any): value is Complex {\n  return !!value && typeof value === 'object' && 're' in value && 'im' in value;\n}\n", "import { Module, DictEmPtrs, dictEmFree } from './emscripten';\nimport { WebRData, RPtr } from './robj';\nimport { RObject, REnvironment, RHandle, handlePtr } from './robj-worker';\n\nexport function protect<T extends RHandle>(x: T): T {\n  Module._Rf_protect(handlePtr(x));\n  return x;\n}\n\nexport function protectInc<T extends RHandle>(x: T, prot: { n: number }): T {\n  Module._Rf_protect(handlePtr(x));\n  ++prot.n;\n  return x;\n}\n\nexport function protectWithIndex(x: RHandle): { loc: number; ptr: RPtr } {\n  // Integer size hardcoded to 4 bytes. This is fine but is there a\n  // way to call sizeof?\n  const pLoc = Module._malloc(4);\n\n  Module._R_ProtectWithIndex(handlePtr(x), pLoc);\n  const loc = Module.getValue(pLoc, 'i32');\n\n  return { loc: loc, ptr: pLoc };\n}\n\nexport function unprotectIndex(index: { ptr: RPtr }): void {\n  Module._Rf_unprotect(1);\n  Module._free(index.ptr);\n}\n\nexport function reprotect<T extends RHandle>(x: T, index: { loc: number; ptr: RPtr }): T {\n  Module._R_Reprotect(handlePtr(x), index.loc);\n  return x;\n}\n\nexport function unprotect(n: number) {\n  Module._Rf_unprotect(n);\n}\n\n// rlang convention: `env`-prefixed functions consistently take `env`\n// as first argument\nexport function envPoke(env: RHandle, sym: RHandle, value: RHandle) {\n  Module._Rf_defineVar(handlePtr(sym), handlePtr(value), handlePtr(env));\n}\n\nexport function parseEvalBare(code: string, env: WebRData): RObject {\n  const strings: DictEmPtrs = {};\n  const prot = { n: 0 };\n\n  try {\n    const envObj = new REnvironment(env);\n    protectInc(envObj, prot);\n\n    strings.code = Module.allocateUTF8(code);\n\n    const out = Module._R_ParseEvalString(strings.code, envObj.ptr);\n    return RObject.wrap(out);\n  } finally {\n    dictEmFree(strings);\n    unprotect(prot.n);\n  }\n}\n\nexport class UnwindProtectException extends Error {\n  cont: RPtr;\n  constructor(message: string, cont: RPtr) {\n    super(message);\n    this.name = 'UnwindProtectException';\n    this.cont = cont;\n  }\n}\n\nexport function safeEval(call: RHandle, env: RHandle): RPtr {\n  return Module.getWasmTableEntry(Module.GOT.ffi_safe_eval.value)(\n    handlePtr(call),\n    handlePtr(env)\n  );\n}\n", "// Original code from Synclink and Comlink. Released under Apache 2.0.\n\nexport const SZ_BUF_DOESNT_FIT = 0;\nexport const SZ_BUF_FITS_IDX = 1;\nexport const SZ_BUF_SIZE_IDX = 0;\n\nexport interface Endpoint extends EventSource {\n  postMessage(message: any, transfer?: Transferable[]): void;\n  start?: () => void;\n}\n\nexport interface EventSource {\n  addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: object): void;\n\n  removeEventListener(\n    type: string,\n    listener: EventListenerOrEventListenerObject,\n    options?: object,\n  ): void;\n}\n\nexport function toWireValue(value: any): [any, Transferable[]] {\n  return [value, transferCache.get(value) || []];\n}\n\nconst transferCache = new WeakMap<any, Transferable[]>();\nexport function transfer<T>(obj: T, transfers: Transferable[]): T {\n  transferCache.set(obj, transfers);\n  return obj;\n}\n\nexport type UUID = string;\n\nexport function isUUID(x: any): x is UUID {\n  return typeof x === 'string' && x.length === UUID_LENGTH;\n}\n\nexport const UUID_LENGTH = 63;\n\nexport function generateUUID(): UUID {\n  const result = Array.from({ length: 4 }, randomSegment).join('-');\n  if (result.length !== UUID_LENGTH) {\n    throw new Error('comlink internal error: UUID has the wrong length');\n  }\n  return result;\n}\n\nfunction randomSegment() {\n  let result = Math.floor(Math.random() * Number.MAX_SAFE_INTEGER).toString(16);\n  const pad = 15 - result.length;\n  if (pad > 0) {\n    result = Array.from({ length: pad }, () => 0).join('') + result;\n  }\n  return result;\n}\n", "/**\n * Module for working with R objects on the worker thead.\n * @module RWorker\n */\nimport { Module } from './emscripten';\nimport { Complex, isComplex, NamedEntries, NamedObject, WebRDataRaw, WebRDataScalar } from './robj';\nimport { WebRData, WebRDataAtomic, RPtr, RType, RTypeMap, RTypeNumber, RCtor } from './robj';\nimport { isWebRDataJs, WebRDataJs, WebRDataJsAtomic, WebRDataJsNode } from './robj';\nimport { WebRDataJsNull, WebRDataJsString, WebRDataJsSymbol } from './robj';\nimport { envPoke, parseEvalBare, protect, protectInc, unprotect } from './utils-r';\nimport { protectWithIndex, reprotect, unprotectIndex, safeEval } from './utils-r';\nimport { EvalROptions, ShelterID, isShelterID } from './webr-chan';\n\nexport type RHandle = RObject | RPtr;\n\nexport function handlePtr(x: RHandle): RPtr {\n  if (isRObject(x)) {\n    return x.ptr;\n  } else {\n    return x;\n  }\n}\n\n// Throw if an R object does not match a certain R type\nfunction assertRType(obj: RObjectBase, type: RType) {\n  if (Module._TYPEOF(obj.ptr) !== RTypeMap[type]) {\n    throw new Error(`Unexpected object type \"${obj.type()}\" when expecting type \"${type}\"`);\n  }\n}\n\n// TODO: Shelter should be a dictionary not an array\nexport const shelters = new Map<ShelterID, RPtr[]>();\n\n// Use this for implicit protection of objects sent to the main\n// thread. Currently uses the precious list but could use a different\n// mechanism in the future. Unprotection is explicit through\n// `Shelter.destroy()`.\nexport function keep(shelter: ShelterID, x: RHandle) {\n  const ptr = handlePtr(x);\n  Module._R_PreserveObject(ptr);\n\n  // TODO: Remove when shelter transition is complete\n  if (shelter === undefined) {\n    return;\n  }\n\n  if (isShelterID(shelter)) {\n    shelters.get(shelter)!.push(ptr);\n    return;\n  }\n\n  throw new Error('Unexpected shelter type ' + typeof shelter);\n}\n\n// Frees objects preserved with `keep()`. This method is called by\n// users in the main thread to release objects that were automatically\n// protected before being sent away.\nexport function destroy(shelter: ShelterID, x: RHandle) {\n  const ptr = handlePtr(x);\n  Module._R_ReleaseObject(ptr);\n\n  const objs: RPtr[] = shelters.get(shelter)!;\n  const loc = objs.indexOf(ptr);\n\n  if (loc < 0) {\n    throw new Error(\"Can't find object in shelter.\");\n  }\n\n  objs.splice(loc, 1);\n}\n\nexport function purge(shelter: ShelterID) {\n  const ptrs: RPtr[] = shelters.get(shelter)!;\n\n  for (const ptr of ptrs) {\n    try {\n      Module._R_ReleaseObject(ptr);\n    } catch (e) {\n      console.error(e);\n    }\n  }\n\n  shelters.set(shelter, []);\n}\n\nexport interface ToJsOptions {\n  depth: number;\n}\n\nexport type Nullable<T> = T | RNull;\n\nfunction newObjectFromData(obj: WebRData): RObject {\n  // Conversion of WebRDataJs type JS objects\n  if (isWebRDataJs(obj)) {\n    return new (getRWorkerClass(obj.type))(obj);\n  }\n\n  // Conversion of explicit R NULL value\n  if (obj && typeof obj === 'object' && 'type' in obj && obj.type === 'null') {\n    return new RNull();\n  }\n\n  // Direct conversion of scalar JS values\n  if (obj === null) {\n    return new RLogical({ type: 'logical', names: null, values: [null] });\n  }\n  if (typeof obj === 'boolean') {\n    return new RLogical(obj);\n  }\n  if (typeof obj === 'number') {\n    return new RDouble(obj);\n  }\n  if (typeof obj === 'string') {\n    return new RCharacter(obj);\n  }\n  if (isComplex(obj)) {\n    return new RComplex(obj);\n  }\n\n  // Conversion of composite JS objects\n  if (ArrayBuffer.isView(obj) || obj instanceof ArrayBuffer) {\n    return new RRaw(obj);\n  }\n  if (Array.isArray(obj)) {\n    return newObjectFromArray(obj);\n  }\n  // Any other JS object shape is reserved for creating an R `data.frame`\n  if (typeof obj === 'object') {\n    return RDataFrame.fromObject(obj);\n  }\n\n  throw new Error('Robj construction for this JS object is not yet supported');\n}\n\nfunction newObjectFromArray(arr: WebRData[]): RObject {\n  const prot = { n: 0 };\n\n  // Is this a D3 formatted data frame?\n  const hasObjects = arr.every((v) => v && typeof v === 'object' && !isRObject(v) && !isComplex(v));\n  if (hasObjects) {\n    const _arr = arr as { [key: string]: WebRData }[];\n    const isConsistent = _arr.every((a) => {\n      return Object.keys(a).filter((k) => !Object.keys(_arr[0]).includes(k)).length === 0 &&\n        Object.keys(_arr[0]).filter((k) => !Object.keys(a).includes(k)).length === 0;\n    });\n    const isAtomic = _arr.every((a) => Object.values(a).every((v) => {\n      return isAtomicType(v) || isRVectorAtomic(v);\n    }));\n    if (isConsistent && isAtomic) {\n      return RDataFrame.fromD3(_arr);\n    }\n  }\n\n  // Not D3 formatted - Can we shortcut and convert directly?\n  if (arr.every((v) => typeof v === 'boolean' || v === null)) {\n    return new RLogical(arr as (boolean | null)[]);\n  }\n  if (arr.every((v) => typeof v === 'number' || v === null)) {\n    return new RDouble(arr as (number | null)[]);\n  }\n  if (arr.every((v) => typeof v === 'string' || v === null)) {\n    return new RCharacter(arr as (string | null)[]);\n  }\n\n  // Not D3 & mixed types: use R's built in object coercion with c() so as to\n  // match R's built in coercion rules\n  try {\n    const call = new RCall([new RSymbol('c'), ...arr]);\n    protectInc(call, prot);\n    return call.eval();\n  } finally {\n    unprotect(prot.n);\n  }\n}\n\nexport class RObjectBase {\n  ptr: RPtr;\n  constructor(ptr: RPtr) {\n    this.ptr = ptr;\n  }\n\n  type(): RType {\n    const typeNumber = Module._TYPEOF(this.ptr) as RTypeNumber;\n    const type = Object.keys(RTypeMap).find(\n      (typeName) => RTypeMap[typeName as RType] === typeNumber\n    );\n    return type as RType;\n  }\n}\n\nexport class RObject extends RObjectBase {\n  constructor(data: WebRData) {\n    if (!(data instanceof RObjectBase)) {\n      return newObjectFromData(data);\n    }\n\n    super(data.ptr);\n  }\n\n  static wrap<T extends typeof RObject>(this: T, ptr: RPtr): InstanceType<T> {\n    const typeNumber = Module._TYPEOF(ptr) as RTypeNumber;\n    const type = Object.keys(RTypeMap)[Object.values(RTypeMap).indexOf(typeNumber)];\n    return new (getRWorkerClass(type as RType))(new RObjectBase(ptr)) as InstanceType<T>;\n  }\n\n  get [Symbol.toStringTag](): string {\n    return `RObject:${this.type()}`;\n  }\n\n  /** @internal */\n  static getPersistentObject(prop: keyof typeof objs): unknown {\n    return objs[prop];\n  }\n\n  /** @internal */\n  getPropertyValue(prop: keyof this): unknown {\n    return this[prop];\n  }\n\n  inspect(): void {\n    parseEvalBare('.Internal(inspect(x))', { x: this });\n  }\n\n  isNull(): this is RNull {\n    return Module._TYPEOF(this.ptr) === RTypeMap.null;\n  }\n\n  isNa(): boolean {\n    try {\n      const result = parseEvalBare('is.na(x)', { x: this }) as RLogical;\n      protect(result);\n      return result.toBoolean();\n    } finally {\n      unprotect(1);\n    }\n  }\n\n  isUnbound(): boolean {\n    return this.ptr === objs.unboundValue.ptr;\n  }\n\n  attrs(): Nullable<RPairlist> {\n    return RPairlist.wrap(Module._ATTRIB(this.ptr));\n  }\n\n  class(): RCharacter {\n    const prot = { n: 0 };\n    const classCall = new RCall([new RSymbol('class'), this]);\n    protectInc(classCall, prot);\n    try {\n      return classCall.eval() as RCharacter;\n    } finally {\n      unprotect(prot.n);\n    }\n  }\n\n  setNames(values: (string | null)[] | null): this {\n    let namesObj: RObject;\n\n    if (values === null) {\n      namesObj = objs.null;\n    } else if (Array.isArray(values) && values.every((v) => typeof v === 'string' || v === null)) {\n      namesObj = new RCharacter(values);\n    } else {\n      throw new Error('Argument to setNames must be null or an Array of strings or null');\n    }\n\n    // `setAttrib()` protects its inputs\n    Module._Rf_setAttrib(this.ptr, objs.namesSymbol.ptr, namesObj.ptr);\n    return this;\n  }\n\n  names(): (string | null)[] | null {\n    const names = RCharacter.wrap(Module._Rf_getAttrib(this.ptr, objs.namesSymbol.ptr));\n    if (names.isNull()) {\n      return null;\n    } else {\n      return names.toArray();\n    }\n  }\n\n  includes(name: string) {\n    const names = this.names();\n    return names && names.includes(name);\n  }\n\n  // eslint-disable-next-line @typescript-eslint/no-unused-vars\n  toJs(options: ToJsOptions = { depth: 0 }, depth = 1): WebRDataJs {\n    throw new Error('This R object cannot be converted to JS');\n  }\n\n  subset(prop: number | string): RObject {\n    return this.#slice(prop, objs.bracketSymbol.ptr);\n  }\n\n  get(prop: number | string): RObject {\n    return this.#slice(prop, objs.bracket2Symbol.ptr);\n  }\n\n  getDollar(prop: string): RObject {\n    return this.#slice(prop, objs.dollarSymbol.ptr);\n  }\n\n  #slice(prop: number | string, op: RPtr): RObject {\n    const prot = { n: 0 };\n\n    try {\n      const idx = new RObject(prop);\n      protectInc(idx, prot);\n\n      const call = Module._Rf_lang3(op, this.ptr, idx.ptr);\n      protectInc(call, prot);\n\n      return RObject.wrap(safeEval(call, objs.baseEnv));\n    } finally {\n      unprotect(prot.n);\n    }\n  }\n\n  pluck(...path: (string | number)[]): RObject | undefined {\n    const index = protectWithIndex(objs.null);\n\n    try {\n      const getter = (obj: RObject, prop: string | number): RObject => {\n        const out = obj.get(prop);\n        return reprotect(out, index);\n      };\n      const result = path.reduce(getter, this);\n\n      return result.isNull() ? undefined : result;\n    } finally {\n      unprotectIndex(index);\n    }\n  }\n\n  set(prop: string | number, value: RObject | WebRDataRaw): RObject {\n    const prot = { n: 0 };\n\n    try {\n      const idx = new RObject(prop);\n      protectInc(idx, prot);\n\n      const valueObj = new RObject(value);\n      protectInc(valueObj, prot);\n\n      const assign = new RSymbol('[[<-');\n      const call = Module._Rf_lang4(assign.ptr, this.ptr, idx.ptr, valueObj.ptr);\n      protectInc(call, prot);\n\n      return RObject.wrap(safeEval(call, objs.baseEnv));\n    } finally {\n      unprotect(prot.n);\n    }\n  }\n\n  /** @internal */\n  static getMethods(obj: RObject) {\n    const props = new Set<string>();\n    let cur: unknown = obj;\n    do {\n      Object.getOwnPropertyNames(cur).map((p) => props.add(p));\n    } while ((cur = Object.getPrototypeOf(cur)));\n    return [...props.keys()].filter((i) => typeof obj[i as keyof typeof obj] === 'function');\n  }\n}\n\nexport class RNull extends RObject {\n  constructor() {\n    super(new RObjectBase(Module.getValue(Module._R_NilValue, '*')));\n    return this;\n  }\n\n  toJs(): WebRDataJsNull {\n    return { type: 'null' };\n  }\n}\n\nexport class RSymbol extends RObject {\n  // Note that symbols don't need to be protected. This also means\n  // that allocating symbols in loops with random data is probably a\n  // bad idea because this leaks memory.\n  constructor(x: WebRDataScalar<string>) {\n    if (x instanceof RObjectBase) {\n      assertRType(x, 'symbol');\n      super(x);\n      return;\n    }\n    const name = Module.allocateUTF8(x as string);\n    try {\n      super(new RObjectBase(Module._Rf_install(name)));\n    } finally {\n      Module._free(name);\n    }\n  }\n\n  toJs(): WebRDataJsSymbol {\n    const obj = this.toObject();\n    return {\n      type: 'symbol',\n      printname: obj.printname,\n      symvalue: obj.symvalue,\n      internal: obj.internal,\n    };\n  }\n\n  toObject(): {\n    printname: string | null;\n    symvalue: RPtr | null;\n    internal: RPtr | null;\n  } {\n    return {\n      printname: this.printname().isUnbound() ? null : this.printname().toString(),\n      symvalue: this.symvalue().isUnbound() ? null : this.symvalue().ptr,\n      internal: this.internal().isNull() ? null : this.internal().ptr,\n    };\n  }\n\n  toString(): string {\n    return this.printname().toString();\n  }\n\n  printname(): RString {\n    return RString.wrap(Module._PRINTNAME(this.ptr));\n  }\n  symvalue(): RObject {\n    return RObject.wrap(Module._SYMVALUE(this.ptr));\n  }\n  internal(): RObject {\n    return RObject.wrap(Module._INTERNAL(this.ptr));\n  }\n}\n\nexport class RPairlist extends RObject {\n  constructor(val: WebRData) {\n    if (val instanceof RObjectBase) {\n      assertRType(val, 'pairlist');\n      super(val);\n      return this;\n    }\n\n    const prot = { n: 0 };\n\n    try {\n      const { names, values } = toWebRData(val);\n\n      const list = RPairlist.wrap(Module._Rf_allocList(values.length));\n      protectInc(list, prot);\n\n      for (\n        let [i, next] = [0, list as Nullable<RPairlist>];\n        !next.isNull();\n        [i, next] = [i + 1, next.cdr()]\n      ) {\n        next.setcar(new RObject(values[i]));\n      }\n\n      list.setNames(names);\n      super(list);\n    } finally {\n      unprotect(prot.n);\n    }\n  }\n\n  get length(): number {\n    return this.toArray().length;\n  }\n\n  toArray(options: ToJsOptions = { depth: 1 }): WebRData[] {\n    return this.toJs(options).values;\n  }\n\n  toObject({\n    allowDuplicateKey = true,\n    allowEmptyKey = false,\n    depth = -1,\n  } = {}): NamedObject<WebRData> {\n    const entries = this.entries({ depth });\n    const keys = entries.map(([k,]) => k);\n    if (!allowDuplicateKey && new Set(keys).size !== keys.length) {\n      throw new Error('Duplicate key when converting pairlist without allowDuplicateKey enabled');\n    }\n    if (!allowEmptyKey && keys.some((k) => !k)) {\n      throw new Error('Empty or null key when converting pairlist without allowEmptyKey enabled');\n    }\n    return Object.fromEntries(\n      entries.filter((u, idx) => entries.findIndex((v) => v[0] === u[0]) === idx)\n    ) as NamedObject<WebRData>;\n  }\n\n  entries(options: ToJsOptions = { depth: 1 }): NamedEntries<WebRData> {\n    const obj = this.toJs(options);\n    return obj.values.map((v, i) => [obj.names ? obj.names[i] : null, v]);\n  }\n\n  toJs(options: ToJsOptions = { depth: 0 }, depth = 1): WebRDataJsNode {\n    const namesArray: string[] = [];\n    let hasNames = false;\n    const values: WebRDataJsNode['values'] = [];\n\n    for (let next = this as Nullable<RPairlist>; !next.isNull(); next = next.cdr()) {\n      const symbol = next.tag();\n      if (symbol.isNull()) {\n        namesArray.push('');\n      } else {\n        hasNames = true;\n        namesArray.push(symbol.toString());\n      }\n      if (options.depth && depth >= options.depth) {\n        values.push(next.car());\n      } else {\n        values.push(next.car().toJs(options, depth + 1));\n      }\n    }\n    const names = hasNames ? namesArray : null;\n    return { type: 'pairlist', names, values };\n  }\n\n  includes(name: string): boolean {\n    return name in this.toObject();\n  }\n\n  setcar(obj: RObject): void {\n    Module._SETCAR(this.ptr, obj.ptr);\n  }\n\n  car(): RObject {\n    return RObject.wrap(Module._CAR(this.ptr));\n  }\n\n  cdr(): Nullable<RPairlist> {\n    return RObject.wrap(Module._CDR(this.ptr)) as Nullable<RPairlist>;\n  }\n\n  tag(): Nullable<RSymbol> {\n    return RObject.wrap(Module._TAG(this.ptr)) as Nullable<RSymbol>;\n  }\n}\n\nexport class RCall extends RObject {\n  constructor(val: WebRData) {\n    if (val instanceof RObjectBase) {\n      assertRType(val, 'call');\n      super(val);\n      return this;\n    }\n    const prot = { n: 0 };\n\n    try {\n      const { values } = toWebRData(val);\n      const objs = values.map((value) => protectInc(new RObject(value), prot));\n      const call = RCall.wrap(Module._Rf_allocVector(RTypeMap.call, values.length));\n      protectInc(call, prot);\n\n      for (\n        let [i, next] = [0, call as Nullable<RPairlist>];\n        !next.isNull();\n        [i, next] = [i + 1, next.cdr()]\n      ) {\n        next.setcar(objs[i]);\n      }\n      super(call);\n    } finally {\n      unprotect(prot.n);\n    }\n  }\n\n  setcar(obj: RObject): void {\n    Module._SETCAR(this.ptr, obj.ptr);\n  }\n\n  car(): RObject {\n    return RObject.wrap(Module._CAR(this.ptr));\n  }\n\n  cdr(): Nullable<RPairlist> {\n    return RObject.wrap(Module._CDR(this.ptr)) as Nullable<RPairlist>;\n  }\n\n  eval(): RObject {\n    return Module.webr.evalR(this, { env: objs.baseEnv });\n  }\n\n  capture(options: EvalROptions = {}) {\n    return Module.webr.captureR(this, options);\n  }\n\n  deparse(): string {\n    const prot = { n: 0 };\n    try {\n      const call = Module._Rf_lang2(\n        new RSymbol('deparse1').ptr,\n        Module._Rf_lang2(new RSymbol('quote').ptr, this.ptr)\n      );\n      protectInc(call, prot);\n\n      const val = RCharacter.wrap(safeEval(call, objs.baseEnv));\n      protectInc(val, prot);\n\n      return val.toString();\n    } finally {\n      unprotect(prot.n);\n    }\n  }\n}\n\nexport class RList extends RObject {\n  constructor(val: WebRData, names: (string | null)[] | null = null) {\n    if (val instanceof RObjectBase) {\n      assertRType(val, 'list');\n      super(val);\n      if (names) {\n        if (names.length !== this.length) {\n          throw new Error(\n            \"Can't construct named `RList`. Supplied `names` must be the same length as the list.\"\n          );\n        }\n        this.setNames(names);\n      }\n      return this;\n    }\n\n    const prot = { n: 0 };\n\n    try {\n      const data = toWebRData(val);\n      const ptr = Module._Rf_allocVector(RTypeMap.list, data.values.length);\n      protectInc(ptr, prot);\n\n      data.values.forEach((v, i) => {\n        Module._SET_VECTOR_ELT(ptr, i, new RObject(v).ptr);\n      });\n\n      const _names = names ? names : data.names;\n      if (_names && _names.length !== data.values.length) {\n        throw new Error(\n          \"Can't construct named `RList`. Supplied `names` must be the same length as the list.\"\n        );\n      }\n      RObject.wrap(ptr).setNames(_names);\n\n      super(new RObjectBase(ptr));\n    } finally {\n      unprotect(prot.n);\n    }\n  }\n\n  get length(): number {\n    return Module._LENGTH(this.ptr);\n  }\n\n  isDataFrame(): boolean {\n    const classes = RPairlist.wrap(Module._ATTRIB(this.ptr)).get('class') as RNull | RCharacter;\n    return !classes.isNull() && classes.toArray().includes('data.frame');\n  }\n\n  toArray(options: { depth: number } = { depth: 1 }): WebRData[] {\n    return this.toJs(options).values;\n  }\n\n  toObject({\n    allowDuplicateKey = true,\n    allowEmptyKey = false,\n    depth = -1,\n  } = {}): NamedObject<WebRData> {\n    const entries = this.entries({ depth });\n    const keys = entries.map(([k,]) => k);\n    if (!allowDuplicateKey && new Set(keys).size !== keys.length) {\n      throw new Error('Duplicate key when converting list without allowDuplicateKey enabled');\n    }\n    if (!allowEmptyKey && keys.some((k) => !k)) {\n      throw new Error('Empty or null key when converting list without allowEmptyKey enabled');\n    }\n    return Object.fromEntries(\n      entries.filter((u, idx) => entries.findIndex((v) => v[0] === u[0]) === idx)\n    ) as NamedObject<WebRData>;\n  }\n\n  toD3(): NamedObject<WebRData>[] {\n    if (!this.isDataFrame()) {\n      throw new Error(\n        \"Can't convert R list object to D3 format. Object must be of class 'data.frame'.\"\n      );\n    }\n    const entries = this.entries() as Array<[string, atomicType[]]>;\n    return entries.reduce((a, entry) => {\n      entry[1].forEach((v, j) => a[j] = Object.assign(a[j] || {}, { [entry[0]!]: v }));\n      return a;\n    }, []);\n  }\n\n  entries(options: { depth: number } = { depth: -1 }): NamedEntries<WebRData> {\n    const obj = this.toJs(options);\n\n    // If this is a data frame, assume we have atomic vector columns and can\n    // convert directly to array values by default.\n    if (this.isDataFrame() && options.depth < 0) {\n      obj.values = (obj.values as RVectorAtomic<atomicType>[]).map((v) => v.toArray());\n    }\n    return obj.values.map((v, i) => [obj.names ? obj.names[i] : null, v]);\n  }\n\n  toJs(options: { depth: number } = { depth: 0 }, depth = 1): WebRDataJsNode {\n    return {\n      type: 'list',\n      names: this.names(),\n      values: [...Array(this.length).keys()].map((i) => {\n        if (options.depth && depth >= options.depth) {\n          return this.get(i + 1);\n        } else {\n          return this.get(i + 1).toJs(options, depth + 1);\n        }\n      }),\n    };\n  }\n}\n\nexport class RDataFrame extends RList {\n  constructor(val: WebRData) {\n    if (val instanceof RObjectBase) {\n      super(val);\n      if (!this.isDataFrame()) {\n        throw new Error(\"Can't construct `RDataFrame`. Supplied R object is not a `data.frame`.\");\n      }\n      return this;\n    }\n    return RDataFrame.fromObject(val);\n  }\n\n  static fromObject(obj: WebRData) {\n    const { names, values } = toWebRData(obj);\n    const prot = { n: 0 };\n\n    // Do we have consistent columns of atomic type? If so, make a `data.frame`.\n    try {\n      const hasNames = !!names && names.length > 0 && names.every((v) => v);\n      const hasArrays = values.length > 0 && values.every((v) => {\n        return Array.isArray(v) || ArrayBuffer.isView(v) || v instanceof ArrayBuffer;\n      });\n\n      if (hasNames && hasArrays) {\n        const _values = values as WebRData[][];\n        const isConsistentLength = _values.every((a) => a.length === _values[0].length);\n        const isAtomic = _values.every((a) => {\n          return isAtomicType(a[0]) || isRVectorAtomic(a[0]);\n        });\n\n        if (isConsistentLength && isAtomic) {\n          const listObj = new RList({\n            type: 'list',\n            names: names,\n            values: _values.map((a) => newObjectFromData(a))\n          });\n          protectInc(listObj, prot);\n\n          const asDataFrame = new RCall([new RSymbol('as.data.frame'), listObj]);\n          protectInc(asDataFrame, prot);\n\n          return new RDataFrame(asDataFrame.eval());\n        }\n      }\n    } finally {\n      unprotect(prot.n);\n    }\n\n    // Not eligible as a `data.frame`, throw an error.\n    throw new Error(\"Can't construct `data.frame`. Source object is not eligible.\");\n  }\n\n  static fromD3(arr: { [key: string]: WebRData }[]) {\n    return this.fromObject(\n      Object.fromEntries(Object.keys(arr[0]).map((k) => [k, arr.map((v) => v[k])]))\n    );\n  }\n}\n\nexport class RFunction extends RObject {\n  exec(...args: (WebRDataRaw | RObject)[]): RObject {\n    const prot = { n: 0 };\n\n    try {\n      const call = new RCall([this, ...args]);\n      protectInc(call, prot);\n      return call.eval();\n    } finally {\n      unprotect(prot.n);\n    }\n  }\n\n  capture(options: EvalROptions = {}, ...args: (WebRDataRaw | RObject)[]) {\n    const prot = { n: 0 };\n\n    try {\n      const call = new RCall([this, ...args]);\n      protectInc(call, prot);\n      return call.capture(options);\n    } finally {\n      unprotect(prot.n);\n    }\n  }\n}\n\nexport class RString extends RObject {\n  // Unlike symbols, strings are not cached and must thus be protected\n  constructor(x: WebRDataScalar<string>) {\n    if (x instanceof RObjectBase) {\n      assertRType(x, 'string');\n      super(x);\n      return;\n    }\n\n    const name = Module.allocateUTF8(x as string);\n\n    try {\n      super(new RObjectBase(Module._Rf_mkChar(name)));\n    } finally {\n      Module._free(name);\n    }\n  }\n\n  toString(): string {\n    return Module.UTF8ToString(Module._R_CHAR(this.ptr));\n  }\n\n  toJs(): WebRDataJsString {\n    return {\n      type: 'string',\n      value: this.toString(),\n    };\n  }\n}\n\nexport class REnvironment extends RObject {\n  constructor(val: WebRData = {}) {\n    if (val instanceof RObjectBase) {\n      assertRType(val, 'environment');\n      super(val);\n      return this;\n    }\n    let nProt = 0;\n\n    try {\n      const { names, values } = toWebRData(val);\n\n      const ptr = protect(Module._R_NewEnv(objs.globalEnv.ptr, 0, 0));\n      ++nProt;\n\n      values.forEach((v, i) => {\n        const name = names ? names[i] : null;\n        if (!name) {\n          throw new Error(\"Can't create object in new environment with empty symbol name\");\n        }\n\n        const sym = new RSymbol(name);\n        const vObj = protect(new RObject(v));\n        try {\n          envPoke(ptr, sym, vObj);\n        } finally {\n          unprotect(1);\n        }\n      });\n\n      super(new RObjectBase(ptr));\n    } finally {\n      unprotect(nProt);\n    }\n  }\n\n  ls(all = false, sorted = true): string[] {\n    const ls = RCharacter.wrap(Module._R_lsInternal3(this.ptr, Number(all), Number(sorted)));\n    return ls.toArray() as string[];\n  }\n\n  bind(name: string, value: WebRData): void {\n    const sym = new RSymbol(name);\n    const valueObj = protect(new RObject(value));\n\n    try {\n      envPoke(this, sym, valueObj);\n    } finally {\n      unprotect(1);\n    }\n  }\n\n  names(): string[] {\n    return this.ls(true, true);\n  }\n\n  frame(): RObject {\n    return RObject.wrap(Module._FRAME(this.ptr));\n  }\n\n  subset(prop: number | string): RObject {\n    if (typeof prop === 'number') {\n      throw new Error('Object of type environment is not subsettable');\n    }\n    return this.getDollar(prop);\n  }\n\n  toObject({ depth = -1 } = {}): NamedObject<WebRData> {\n    const symbols = this.names();\n    return Object.fromEntries(\n      [...Array(symbols.length).keys()].map((i) => {\n        const value = this.getDollar(symbols[i]);\n        return [symbols[i], depth < 0 ? value : value.toJs({ depth })];\n      })\n    );\n  }\n\n  toJs(options: { depth: number } = { depth: 0 }, depth = 1): WebRDataJsNode {\n    const names = this.names();\n    const values = [...Array(names.length).keys()].map((i) => {\n      if (options.depth && depth >= options.depth) {\n        return this.getDollar(names[i]);\n      } else {\n        return this.getDollar(names[i]).toJs(options, depth + 1);\n      }\n    });\n\n    return {\n      type: 'environment',\n      names,\n      values,\n    };\n  }\n}\n\ntype TypedArray =\n  | Int8Array\n  | Uint8Array\n  | Int16Array\n  | Uint16Array\n  | Int32Array\n  | Uint32Array\n  | Float32Array\n  | Float64Array;\n\nexport type atomicType = number | boolean | Complex | string;\n\nabstract class RVectorAtomic<T extends atomicType> extends RObject {\n  constructor(\n    val: WebRDataAtomic<T>,\n    kind: RType,\n    newSetter: (ptr: RPtr) => (v: any, i: number) => void\n  ) {\n    if (val instanceof RObjectBase) {\n      assertRType(val, kind);\n      super(val);\n      return this;\n    }\n\n    const prot = { n: 0 };\n\n    try {\n      const { names, values } = toWebRData(val);\n\n      const ptr = Module._Rf_allocVector(RTypeMap[kind], values.length);\n      protectInc(ptr, prot);\n\n      values.forEach(newSetter(ptr));\n      RObject.wrap(ptr).setNames(names);\n\n      super(new RObjectBase(ptr));\n    } finally {\n      unprotect(prot.n);\n    }\n  }\n\n  get length(): number {\n    return Module._LENGTH(this.ptr);\n  }\n\n  get(prop: number | string): this {\n    return super.get(prop) as this;\n  }\n\n  subset(prop: number | string): this {\n    return super.subset(prop) as this;\n  }\n\n  getDollar(): RObject {\n    throw new Error('$ operator is invalid for atomic vectors');\n  }\n\n  detectMissing(): boolean[] {\n    const prot = { n: 0 };\n\n    try {\n      const call = Module._Rf_lang2(new RSymbol('is.na').ptr, this.ptr);\n      protectInc(call, prot);\n\n      const val = RLogical.wrap(safeEval(call, objs.baseEnv));\n      protectInc(val, prot);\n\n      const ret = val.toTypedArray();\n      return Array.from(ret).map((elt) => Boolean(elt));\n    } finally {\n      unprotect(prot.n);\n    }\n  }\n\n  abstract toTypedArray(): TypedArray;\n\n  toArray(): (T | null)[] {\n    const arr = this.toTypedArray();\n    return this.detectMissing().map((m, idx) => (m ? null : (arr[idx] as T)));\n  }\n\n  toObject({ allowDuplicateKey = true, allowEmptyKey = false } = {}): NamedObject<T | null> {\n    const entries = this.entries();\n    const keys = entries.map(([k,]) => k);\n    if (!allowDuplicateKey && new Set(keys).size !== keys.length) {\n      throw new Error(\n        'Duplicate key when converting atomic vector without allowDuplicateKey enabled'\n      );\n    }\n    if (!allowEmptyKey && keys.some((k) => !k)) {\n      throw new Error(\n        'Empty or null key when converting atomic vector without allowEmptyKey enabled'\n      );\n    }\n    return Object.fromEntries(\n      entries.filter((u, idx) => entries.findIndex((v) => v[0] === u[0]) === idx)\n    ) as NamedObject<T | null>;\n  }\n\n  entries(): NamedEntries<T | null> {\n    const values = this.toArray();\n    const names = this.names();\n    return values.map((v, i) => [names ? names[i] : null, v]);\n  }\n\n  toJs(): WebRDataJsAtomic<T> {\n    return {\n      type: this.type() as 'logical' | 'integer' | 'double' | 'complex' | 'character' | 'raw',\n      names: this.names(),\n      values: this.toArray(),\n    };\n  }\n}\n\nexport class RLogical extends RVectorAtomic<boolean> {\n  constructor(val: WebRDataAtomic<boolean>) {\n    super(val, 'logical', RLogical.#newSetter);\n  }\n\n  static #newSetter = (ptr: RPtr) => {\n    const data = Module._LOGICAL(ptr);\n    const naLogical = Module.getValue(Module._R_NaInt, 'i32');\n    return (v: null | boolean, i: number) => {\n      Module.setValue(data + 4 * i, v === null ? naLogical : Boolean(v), 'i32');\n    };\n  };\n\n  getBoolean(idx: number): boolean | null {\n    return this.get(idx).toArray()[0];\n  }\n\n  toBoolean(): boolean {\n    if (this.length !== 1) {\n      throw new Error(\"Can't convert atomic vector of length > 1 to a scalar JS value\");\n    }\n    const val = this.getBoolean(1);\n    if (val === null) {\n      throw new Error(\"Can't convert missing value `NA` to a JS boolean\");\n    }\n    return val;\n  }\n\n  toTypedArray(): Int32Array {\n    return new Int32Array(\n      Module.HEAP32.subarray(\n        Module._LOGICAL(this.ptr) / 4,\n        Module._LOGICAL(this.ptr) / 4 + this.length\n      )\n    );\n  }\n\n  toArray(): (boolean | null)[] {\n    const arr = this.toTypedArray();\n    return this.detectMissing().map((m, idx) => (m ? null : Boolean(arr[idx])));\n  }\n}\n\nexport class RInteger extends RVectorAtomic<number> {\n  constructor(val: WebRDataAtomic<number>) {\n    super(val, 'integer', RInteger.#newSetter);\n  }\n\n  static #newSetter = (ptr: RPtr) => {\n    const data = Module._INTEGER(ptr);\n    const naInteger = Module.getValue(Module._R_NaInt, 'i32');\n\n    return (v: null | number, i: number) => {\n      Module.setValue(data + 4 * i, v === null ? naInteger : Math.round(Number(v)), 'i32');\n    };\n  };\n\n  getNumber(idx: number): number | null {\n    return this.get(idx).toArray()[0];\n  }\n\n  toNumber(): number {\n    if (this.length !== 1) {\n      throw new Error(\"Can't convert atomic vector of length > 1 to a scalar JS value\");\n    }\n    const val = this.getNumber(1);\n    if (val === null) {\n      throw new Error(\"Can't convert missing value `NA` to a JS number\");\n    }\n    return val;\n  }\n\n  toTypedArray(): Int32Array {\n    return new Int32Array(\n      Module.HEAP32.subarray(\n        Module._INTEGER(this.ptr) / 4,\n        Module._INTEGER(this.ptr) / 4 + this.length\n      )\n    );\n  }\n}\n\nexport class RDouble extends RVectorAtomic<number> {\n  constructor(val: WebRDataAtomic<number>) {\n    super(val, 'double', RDouble.#newSetter);\n  }\n\n  static #newSetter = (ptr: RPtr) => {\n    const data = Module._REAL(ptr);\n    const naDouble = Module.getValue(Module._R_NaReal, 'double');\n\n    return (v: null | number, i: number) => {\n      Module.setValue(data + 8 * i, v === null ? naDouble : v, 'double');\n    };\n  };\n\n  getNumber(idx: number): number | null {\n    return this.get(idx).toArray()[0];\n  }\n\n  toNumber(): number {\n    if (this.length !== 1) {\n      throw new Error(\"Can't convert atomic vector of length > 1 to a scalar JS value\");\n    }\n    const val = this.getNumber(1);\n    if (val === null) {\n      throw new Error(\"Can't convert missing value `NA` to a JS number\");\n    }\n    return val;\n  }\n\n  toTypedArray(): Float64Array {\n    return new Float64Array(\n      Module.HEAPF64.subarray(Module._REAL(this.ptr) / 8, Module._REAL(this.ptr) / 8 + this.length)\n    );\n  }\n}\n\nexport class RComplex extends RVectorAtomic<Complex> {\n  constructor(val: WebRDataAtomic<Complex>) {\n    super(val, 'complex', RComplex.#newSetter);\n  }\n\n  static #newSetter = (ptr: RPtr) => {\n    const data = Module._COMPLEX(ptr);\n    const naDouble = Module.getValue(Module._R_NaReal, 'double');\n\n    return (v: null | Complex, i: number) => {\n      Module.setValue(data + 8 * (2 * i), v === null ? naDouble : v.re, 'double');\n      Module.setValue(data + 8 * (2 * i + 1), v === null ? naDouble : v.im, 'double');\n    };\n  };\n\n  getComplex(idx: number): Complex | null {\n    return this.get(idx).toArray()[0];\n  }\n\n  toComplex(): Complex {\n    if (this.length !== 1) {\n      throw new Error(\"Can't convert atomic vector of length > 1 to a scalar JS value\");\n    }\n    const val = this.getComplex(1);\n    if (val === null) {\n      throw new Error(\"Can't convert missing value `NA` to a JS object\");\n    }\n    return val;\n  }\n\n  toTypedArray(): Float64Array {\n    return new Float64Array(\n      Module.HEAPF64.subarray(\n        Module._COMPLEX(this.ptr) / 8,\n        Module._COMPLEX(this.ptr) / 8 + 2 * this.length\n      )\n    );\n  }\n\n  toArray(): (Complex | null)[] {\n    const arr = this.toTypedArray();\n    return this.detectMissing().map((m, idx) =>\n      m ? null : { re: arr[2 * idx], im: arr[2 * idx + 1] }\n    );\n  }\n}\n\nexport class RCharacter extends RVectorAtomic<string> {\n  constructor(val: WebRDataAtomic<string>) {\n    super(val, 'character', RCharacter.#newSetter);\n  }\n\n  static #newSetter = (ptr: RPtr) => {\n    return (v: null | string, i: number) => {\n      if (v === null) {\n        Module._SET_STRING_ELT(ptr, i, objs.naString.ptr);\n      } else {\n        Module._SET_STRING_ELT(ptr, i, new RString(v).ptr);\n      }\n    };\n  };\n\n  getString(idx: number): string | null {\n    return this.get(idx).toArray()[0];\n  }\n\n  toString(): string {\n    if (this.length !== 1) {\n      throw new Error(\"Can't convert atomic vector of length > 1 to a scalar JS value\");\n    }\n    const val = this.getString(1);\n    if (val === null) {\n      throw new Error(\"Can't convert missing value `NA` to a JS string\");\n    }\n    return val;\n  }\n\n  toTypedArray(): Uint32Array {\n    return new Uint32Array(\n      Module.HEAPU32.subarray(\n        Module._STRING_PTR(this.ptr) / 4,\n        Module._STRING_PTR(this.ptr) / 4 + this.length\n      )\n    );\n  }\n\n  toArray(): (string | null)[] {\n    return this.detectMissing().map((m, idx) =>\n      m ? null : Module.UTF8ToString(Module._R_CHAR(Module._STRING_ELT(this.ptr, idx)))\n    );\n  }\n}\n\nexport class RRaw extends RVectorAtomic<number> {\n  constructor(val: WebRDataAtomic<number>) {\n    if (val instanceof ArrayBuffer) {\n      val = new Uint8Array(val);\n    }\n    super(val, 'raw', RRaw.#newSetter);\n  }\n\n  static #newSetter = (ptr: RPtr) => {\n    const data = Module._RAW(ptr);\n\n    return (v: number, i: number) => {\n      Module.setValue(data + i, Number(v), 'i8');\n    };\n  };\n\n  getNumber(idx: number): number | null {\n    return this.get(idx).toArray()[0];\n  }\n\n  toNumber(): number {\n    if (this.length !== 1) {\n      throw new Error(\"Can't convert atomic vector of length > 1 to a scalar JS value\");\n    }\n    const val = this.getNumber(1);\n    if (val === null) {\n      throw new Error(\"Can't convert missing value `NA` to a JS number\");\n    }\n    return val;\n  }\n\n  toTypedArray(): Uint8Array {\n    return new Uint8Array(\n      Module.HEAPU8.subarray(Module._RAW(this.ptr), Module._RAW(this.ptr) + this.length)\n    );\n  }\n}\n\n/*\n * Convert the various types possible in the type union WebRData into\n * consistently typed arrays of names and values.\n */\nfunction toWebRData<T>(jsObj: WebRDataAtomic<T>): {\n  names: (string | null)[] | null;\n  values: (T | null)[];\n};\nfunction toWebRData(jsObj: WebRData): WebRData;\nfunction toWebRData(jsObj: WebRData): WebRData {\n  if (isWebRDataJs(jsObj)) {\n    return jsObj;\n  } else if (Array.isArray(jsObj) || ArrayBuffer.isView(jsObj)) {\n    return { names: null, values: jsObj };\n  } else if (jsObj && typeof jsObj === 'object' && !isComplex(jsObj)) {\n    return {\n      names: Object.keys(jsObj),\n      values: Object.values(jsObj),\n    };\n  }\n  return { names: null, values: [jsObj] };\n}\n\nexport function getRWorkerClass(type: RType | RCtor): typeof RObject {\n  const typeClasses: { [key: string]: typeof RObject } = {\n    object: RObject,\n    null: RNull,\n    symbol: RSymbol,\n    pairlist: RPairlist,\n    closure: RFunction,\n    environment: REnvironment,\n    call: RCall,\n    special: RFunction,\n    builtin: RFunction,\n    string: RString,\n    logical: RLogical,\n    integer: RInteger,\n    double: RDouble,\n    complex: RComplex,\n    character: RCharacter,\n    list: RList,\n    raw: RRaw,\n    function: RFunction,\n    dataframe: RDataFrame,\n  };\n  if (type in typeClasses) {\n    return typeClasses[type];\n  }\n  return RObject;\n}\n\n/**\n * Test for an RWorker.RObject instance.\n *\n * RWorker.RObject is the internal interface to R objects, intended to be used\n * on the worker thread.\n *\n * @private\n * @param {any} value The object to test.\n * @return {boolean} True if the object is an instance of an RObject.\n */\nexport function isRObject(value: any): value is RObject {\n  return value instanceof RObject;\n}\n\n/**\n * Test for an RWorker.RVectorAtomic instance.\n *\n * @private\n * @param {any} value The object to test.\n * @return {boolean} True if the object is an instance of an RVectorAtomic.\n */\nexport function isRVectorAtomic(value: any): value is RVectorAtomic<atomicType> {\n  const atomicRTypes = ['logical', 'integer', 'double', 'complex', 'character'];\n\n  return (\n    (isRObject(value) && atomicRTypes.includes(value.type()))\n    || (isRObject(value) && value.isNa())\n  );\n}\n\n/**\n * Test for an atomicType, including missing `null` values.\n *\n * @private\n * @param {any} value The object to test.\n * @return {boolean} True if the object is of type atomicType.\n */\nexport function isAtomicType(value: any): value is atomicType | null {\n  return (\n    value === null\n    || typeof value === 'number'\n    || typeof value === 'boolean'\n    || typeof value === 'string'\n    || isComplex(value)\n  );\n}\n\n/**\n * A store for persistent R objects, initialised at R startup.\n */\nexport let objs: {\n  baseEnv: REnvironment,\n  bracket2Symbol: RSymbol,\n  bracketSymbol: RSymbol,\n  dollarSymbol: RSymbol,\n  emptyEnv: REnvironment,\n  false: RLogical,\n  globalEnv: REnvironment,\n  na: RLogical,\n  namesSymbol: RSymbol,\n  naString: RObject,\n  null: RNull,\n  true: RLogical,\n  unboundValue: RObject,\n};\n\n/**\n * Populate the persistent R object store.\n * @internal\n */\nexport function initPersistentObjects() {\n  objs = {\n    baseEnv: REnvironment.wrap(Module.getValue(Module._R_BaseEnv, '*')),\n    bracket2Symbol: RSymbol.wrap(Module.getValue(Module._R_Bracket2Symbol, '*')),\n    bracketSymbol: RSymbol.wrap(Module.getValue(Module._R_BracketSymbol, '*')),\n    dollarSymbol: RSymbol.wrap(Module.getValue(Module._R_DollarSymbol, '*')),\n    emptyEnv: REnvironment.wrap(Module.getValue(Module._R_EmptyEnv, '*')),\n    false: RLogical.wrap(Module.getValue(Module._R_FalseValue, '*')),\n    globalEnv: REnvironment.wrap(Module.getValue(Module._R_GlobalEnv, '*')),\n    na: RLogical.wrap(Module.getValue(Module._R_LogicalNAValue, '*')),\n    namesSymbol: RSymbol.wrap(Module.getValue(Module._R_NamesSymbol, '*')),\n    naString: RObject.wrap(Module.getValue(Module._R_NaString, '*')),\n    null: RNull.wrap(Module.getValue(Module._R_NilValue, '*')),\n    true: RLogical.wrap(Module.getValue(Module._R_TrueValue, '*')),\n    unboundValue: RObject.wrap(Module.getValue(Module._R_UnboundValue, '*')),\n  };\n}\n", "import { IN_NODE } from './compat';\nimport { WebRError } from './error';\nimport { RObjectBase } from './robj-worker';\n\nexport type ResolveFn = (_value?: unknown) => void;\nexport type RejectFn = (_reason?: any) => void;\n\nexport function promiseHandles() {\n  const out = {\n    resolve: () => { return; },\n    reject: () => { return; },\n    promise: Promise.resolve(),\n  } as {\n    resolve: ResolveFn,\n    reject: RejectFn,\n    promise: Promise<unknown>,\n  };\n\n  const promise = new Promise((resolve, reject) => {\n    out.resolve = resolve;\n    out.reject = reject;\n  });\n  out.promise = promise;\n\n  return out;\n}\n\nexport function sleep(ms: number) {\n  return new Promise((resolve) => setTimeout(resolve, ms));\n}\n\nexport function replaceInObject<T>(\n  obj: T | T[],\n  test: (obj: any) => boolean,\n  replacer: (obj: any, ...replacerArgs: any[]) => unknown,\n  ...replacerArgs: unknown[]\n): T | T[] {\n  if (obj === null || obj === undefined || isImageBitmap(obj)) {\n    return obj;\n  }\n  if (obj instanceof ArrayBuffer) {\n    return new Uint8Array(obj) as T;\n  }\n  if (test(obj)) {\n    return replacer(obj, ...replacerArgs) as T;\n  }\n  if (Array.isArray(obj) || ArrayBuffer.isView(obj)) {\n    return (obj as unknown[]).map((v) =>\n      replaceInObject(v, test, replacer, ...replacerArgs)\n    ) as T[];\n  }\n  if (obj instanceof RObjectBase) {\n    return obj;\n  }\n  if (typeof obj === 'object') {\n    return Object.fromEntries(\n      Object.entries(obj).map(([k, v]) => [k, replaceInObject(v, test, replacer, ...replacerArgs)])\n    ) as T;\n  }\n  return obj;\n}\n\n/* Workaround for loading a cross-origin script.\n *\n * When fetching a worker script, the fetch is required by the spec to\n * use \"same-origin\" mode. This is to avoid loading a worker with a\n * cross-origin global scope, which can allow for a cross-origin\n * restriction bypass.\n *\n * When the fetch URL begins with 'http', we assume the request is\n * cross-origin. We download the content of the URL using a XHR first,\n * create a blob URL containing the requested content, then load the\n * blob URL as a script.\n *\n * The origin of a blob URL is the same as that of the environment that\n * created the URL, and so the global scope of the resulting worker is\n * no longer cross-origin. In that case, the cross-origin restriction\n * bypass is not possible, and the script is permitted to be loaded.\n */\nexport function newCrossOriginWorker(url: string, cb: (worker: Worker) => void): void {\n  const req = new XMLHttpRequest();\n  req.open('get', url, true);\n  req.onload = () => {\n    const worker = new Worker(URL.createObjectURL(new Blob([req.responseText])));\n    cb(worker);\n  };\n  req.send();\n}\n\nexport function isCrossOrigin(urlString: string) {\n  if (IN_NODE) return false;\n  const url1 = new URL(location.href);\n  const url2 = new URL(urlString, location.origin);\n  if (url1.host === url2.host && url1.port === url2.port && url1.protocol === url2.protocol) {\n    return false;\n  }\n  return true;\n}\n\nexport function isImageBitmap(value: any): value is ImageBitmap {\n  return (typeof ImageBitmap !== 'undefined' && value instanceof ImageBitmap);\n}\n\nexport function throwUnreachable(context?: string) {\n  let msg = 'Reached the unreachable';\n  msg = msg + (context ? ': ' + context : '.');\n\n  throw new WebRError(msg);\n}\n\n// From https://stackoverflow.com/a/9458996\nexport function bufferToBase64(buffer: ArrayBuffer) {\n  let binary = '';\n  const bytes = new Uint8Array(buffer);\n  const len = bytes.byteLength;\n  for (let i = 0; i < len; i++) {\n    binary += String.fromCharCode(bytes[i]);\n  }\n  return window.btoa(binary);\n}\n", "// Original code from Synclink and Comlink. Released under Apache 2.0.\n\nimport { Endpoint, SZ_BUF_FITS_IDX, SZ_BUF_SIZE_IDX, generateUUID } from './task-common';\n\nimport { sleep } from '../utils';\nimport { SyncRequestData } from './message';\nimport { encode } from '@msgpack/msgpack';\n\nimport { IN_NODE } from '../compat';\nimport type { Worker as NodeWorker } from 'worker_threads';\n\nconst encoder = new TextEncoder();\n\n/**\n * Respond to a blocking request. Most of the work has already been done in\n * asynclink, we are just responsible here for getting the return value back to\n * the requester through this slightly convoluted Atomics protocol.\n * @param {Endpoint} endpoint  A message port to receive messages from. Other\n *        thread is blocked, so we can't send messages back.\n * @param {SyncRequestData} data The message that was recieved. We will use it\n *        to read out the buffers to write the answer into. NOTE: requester\n *        owns buffers.\n * @param {any} response The value we want to send back to the requester. We\n *        have to encode it into data_buffer.\n */\nexport async function syncResponse(endpoint: Endpoint, data: SyncRequestData, response: any) {\n  try {\n    // eslint-disable-next-line prefer-const\n    let { taskId, sizeBuffer, dataBuffer, signalBuffer } = data;\n    // console.warn(msg);\n\n    const bytes = encode(response);\n    const fits = bytes.length <= dataBuffer.length;\n\n    Atomics.store(sizeBuffer, SZ_BUF_SIZE_IDX, bytes.length);\n    Atomics.store(sizeBuffer, SZ_BUF_FITS_IDX, +fits);\n    if (!fits) {\n      // console.log(\"      need larger buffer\", taskId)\n      // Request larger buffer\n      const [uuid, dataPromise] = requestResponseMessage(endpoint);\n\n      // Write UUID into dataBuffer so syncRequest knows where to respond to.\n      dataBuffer.set(encoder.encode(uuid));\n      await signalRequester(signalBuffer, taskId!);\n\n      // Wait for response with new bigger dataBuffer\n      dataBuffer = (await dataPromise).dataBuffer as Uint8Array;\n    }\n\n    // Encode result into dataBuffer\n    dataBuffer.set(bytes);\n    Atomics.store(sizeBuffer, SZ_BUF_FITS_IDX, +true);\n\n    // console.log(\"       signaling completion\", taskId)\n    await signalRequester(signalBuffer, taskId as number);\n  } catch (e) {\n    console.warn(e);\n  }\n}\n\nfunction requestResponseMessage(ep: Endpoint): [string, Promise<any>] {\n  const id = generateUUID();\n  return [\n    id,\n    new Promise((resolve) => {\n      if (IN_NODE) {\n        (ep as unknown as NodeWorker).once('message', (message: any) => {\n          if (!message.id || message.id !== id) {\n            return;\n          }\n          resolve(message);\n        });\n      } else {\n        ep.addEventListener('message', function l(ev: MessageEvent) {\n          if (!ev.data || !ev.data.id || ev.data.id !== id) {\n            return;\n          }\n          ep.removeEventListener('message', l as EventListenerOrEventListenerObject);\n          resolve(ev.data);\n        } as EventListenerOrEventListenerObject);\n      }\n      if (ep.start) {\n        ep.start();\n      }\n    }),\n  ];\n}\n\nasync function signalRequester(signalBuffer: Int32Array, taskId: number) {\n  const index = (taskId >> 1) % 32;\n  let sleepTime = 1;\n  while (Atomics.compareExchange(signalBuffer, index + 1, 0, taskId) !== 0) {\n    // No Atomics.asyncWait except on Chrome =(\n    await sleep(sleepTime);\n    if (sleepTime < 32) {\n      // exponential backoff\n      sleepTime *= 2;\n    }\n  }\n  Atomics.or(signalBuffer, 0, 1 << index);\n  Atomics.notify(signalBuffer, 0);\n}\n", "// From https://stackoverflow.com/questions/47157428/how-to-implement-a-pseudo-blocking-async-queue-in-js-ts\n/**\n * @module Queue\n */\n\n/**\n * Asynchronous queue mechanism to be used by the communication channels.\n * @typeParam T The type of item to be stored in the queue.\n */\nexport class AsyncQueue<T> {\n  #promises: Promise<T>[];\n  #resolvers: ((t: T) => void)[];\n\n  constructor() {\n    this.#resolvers = [];\n    this.#promises = [];\n  }\n\n  reset() {\n    this.#resolvers = [];\n    this.#promises = [];\n  }\n\n  put(t: T) {\n    if (!this.#resolvers.length) {\n      this.#add();\n    }\n    const resolve = this.#resolvers.shift()!;\n    resolve(t);\n  }\n\n  async get() {\n    if (!this.#promises.length) {\n      this.#add();\n    }\n    const promise = this.#promises.shift()!;\n    return promise;\n  }\n\n  isEmpty() {\n    return !this.#promises.length;\n  }\n\n  isBlocked() {\n    return !!this.#resolvers.length;\n  }\n\n  get length() {\n    return this.#promises.length - this.#resolvers.length;\n  }\n\n  #add() {\n    this.#promises.push(\n      new Promise((resolve) => {\n        this.#resolvers.push(resolve);\n      })\n    );\n  }\n}\n", "/**\n * WebR communication channel messaging and request types.\n * @module Message\n */\nimport { generateUUID, transfer, UUID } from './task-common';\n\n/** A webR communication channel message. */\nexport interface Message {\n  type: string;\n  data?: any;\n}\n\n/** A webR communication channel request. */\nexport interface Request {\n  type: 'request';\n  data: {\n    uuid: UUID;\n    msg: Message;\n  };\n}\n\n/** A webR communication channel response. */\nexport interface Response {\n  type: 'response';\n  data: {\n    uuid: UUID;\n    resp: unknown;\n  };\n}\n\n/** @internal */\nexport function newRequest(msg: Message, transferables?: [Transferable]): Request {\n  return newRequestResponseMessage(\n    {\n      type: 'request',\n      data: {\n        uuid: generateUUID(),\n        msg: msg,\n      },\n    },\n    transferables\n  );\n}\n\n/** @internal */\nexport function newResponse(uuid: UUID, resp: unknown, transferables?: [Transferable]): Response {\n  return newRequestResponseMessage(\n    {\n      type: 'response',\n      data: {\n        uuid,\n        resp,\n      },\n    },\n    transferables\n  );\n}\n\n/** @internal */\nfunction newRequestResponseMessage<T>(msg: T, transferables?: [Transferable]): T {\n  // Signal to Synclink that the data contains objects we wish to\n  // transfer, as in `postMessage()`\n  if (transferables) {\n    transfer(msg, transferables);\n  }\n  return msg;\n}\n\n/** A webR communication channel sync-request.\n * @internal\n */\nexport interface SyncRequest {\n  type: 'sync-request';\n  data: {\n    msg: Message;\n    reqData: SyncRequestData;\n  };\n}\n\n/** Transfer data required when using sync-request with SharedArrayBuffer.\n * @internal */\nexport interface SyncRequestData {\n  taskId?: number;\n  sizeBuffer: Int32Array;\n  signalBuffer: Int32Array;\n  dataBuffer: Uint8Array;\n}\n\n/** @internal */\nexport function newSyncRequest(msg: Message, data: SyncRequestData): SyncRequest {\n  return {\n    type: 'sync-request',\n    data: { msg, reqData: data },\n  };\n}\n", "/**\n * Types containing references to R objects, raw data or errors over the webR\n * communication channel.\n * @module Payload\n */\nimport { WebRDataRaw, RPtr, RType } from './robj';\nimport { WebRWorkerError } from './error';\n\nexport type WebRPayloadRaw = {\n  obj: WebRDataRaw;\n  payloadType: 'raw';\n};\n\nexport type WebRPayloadPtr = {\n  obj: {\n    type?: RType;\n    ptr: RPtr;\n    methods?: string[];\n  };\n  payloadType: 'ptr';\n};\n\nexport type WebRPayloadErr = {\n  obj: {\n    message: string;\n    name: string;\n    stack?: string;\n  };\n  payloadType: 'err';\n};\n\n// On the main side we shouldn't see any error payload as these are\n// rethrown as JS exceptions\nexport type WebRPayload = WebRPayloadRaw | WebRPayloadPtr;\nexport type WebRPayloadWorker = WebRPayloadRaw | WebRPayloadPtr | WebRPayloadErr;\n\n/* @internal */\nexport function webRPayloadAsError(payload: WebRPayloadErr): Error {\n  const e = new WebRWorkerError(payload.obj.message);\n  // Forward the error name to the main thread, if more specific than a general `Error`\n  if (payload.obj.name !== 'Error') {\n    e.name = payload.obj.name;\n  }\n  e.stack = payload.obj.stack;\n  return e;\n}\n\n/**\n * Test for an WebRPayload instance.\n * @param {any} value The object to test.\n * @returns {boolean} True if the object is an instance of an WebRPayload.\n */\nexport function isWebRPayload(value: any): value is WebRPayload {\n  return !!value && typeof value === 'object' && 'payloadType' in value && 'obj' in value;\n}\n\n/**\n * Test for an WebRPayloadPtr instance.\n * @param {any} value The object to test.\n * @returns {boolean} True if the object is an instance of an WebRPayloadPtr.\n */\nexport function isWebRPayloadPtr(value: any): value is WebRPayloadPtr {\n  return isWebRPayload(value) && value.payloadType === 'ptr';\n}\n\n/**\n * Test for an WebRPayloadRaw instance.\n * @param {any} value The object to test.\n * @returns {boolean} True if the object is an instance of an WebRPayloadRaw.\n */\nexport function isWebRPayloadRaw(value: any): value is WebRPayloadRaw {\n  return isWebRPayload(value) && value.payloadType === 'raw';\n}\n", "/**\n * Interfaces for the webR main and worker thread communication channels.\n * @module Channel\n */\n\nimport { promiseHandles, ResolveFn, RejectFn } from '../utils';\nimport { AsyncQueue } from './queue';\nimport { Message, newRequest, Response } from './message';\nimport { WebRPayload, WebRPayloadWorker, webRPayloadAsError } from '../payload';\nimport { WebRChannelError } from '../error';\n\n// The channel structure is asymmetric:\n//\n// - The main thread maintains the input and output queues. All\n//   messages sent from main are stored in the input queue. The input\n//   queue is pull-based, it's the worker that initiates a transfer\n//   via a sync-request.\n//\n//   The output queue is filled at the initiative of the worker. The\n//   main thread asynchronously reads from this queue, typically in an\n//   async infloop.\n//\n// - The worker synchronously reads from the input queue. Reading a\n//   message blocks until an input is available. Writing a message to\n//   the output queue is equivalent to calling `postMessage()` and\n//   returns immediately.\n//\n//   Note that the messages sent from main to worker need to be\n//   serialised. There is no structured cloning involved, and\n//   ArrayBuffers can't be transferred, only copied.\n\nexport abstract class ChannelMain {\n  inputQueue = new AsyncQueue<Message>();\n  outputQueue = new AsyncQueue<Message>();\n  systemQueue = new AsyncQueue<Message>();\n\n  #parked = new Map<string, { resolve: ResolveFn; reject: RejectFn }>();\n  #closed = false;\n\n  abstract initialised: Promise<unknown>;\n  abstract close(): void;\n  abstract interrupt(): void;\n\n  async read(): Promise<Message> {\n    return await this.outputQueue.get();\n  }\n\n  async flush(): Promise<Message[]> {\n    const msg: Message[] = [];\n    while (!this.outputQueue.isEmpty()) {\n      msg.push(await this.read());\n    }\n    return msg;\n  }\n\n  async readSystem(): Promise<Message> {\n    return await this.systemQueue.get();\n  }\n\n  write(msg: Message): void {\n    if (this.#closed) {\n      throw new WebRChannelError(\"The webR communication channel has been closed.\");\n    }\n    this.inputQueue.put(msg);\n  }\n\n  async request(msg: Message, transferables?: [Transferable]): Promise<WebRPayload> {\n    const req = newRequest(msg, transferables);\n\n    const { resolve, reject, promise } = promiseHandles();\n    this.#parked.set(req.data.uuid, { resolve, reject });\n\n    this.write(req);\n    return promise as Promise<WebRPayload>;\n  }\n\n  protected putClosedMessage(): void {\n    this.#closed = true;\n    this.outputQueue.put({ type: 'closed' });\n  }\n\n  protected resolveResponse(msg: Response) {\n    const uuid = msg.data.uuid;\n    const handles = this.#parked.get(uuid);\n\n    if (handles) {\n      const payload = msg.data.resp as WebRPayloadWorker;\n      this.#parked.delete(uuid);\n\n      if (payload.payloadType === 'err') {\n        handles.reject(webRPayloadAsError(payload));\n      } else {\n        handles.resolve(payload);\n      }\n    } else {\n      console.warn(\"Can't find request.\");\n    }\n  }\n}\n\nexport interface ChannelWorker {\n  resolve(): void;\n  write(msg: Message, transfer?: [Transferable]): void;\n  writeSystem(msg: Message, transfer?: [Transferable]): void;\n  read(): Message;\n  handleInterrupt(): void;\n  setInterrupt(interrupt: () => void): void;\n  run(args: string[]): void;\n  inputOrDispatch: () => number;\n  setDispatchHandler: (dispatch: (msg: Message) => void) => void;\n  onMessageFromMainThread: (msg: Message) => void;\n}\n\n/**\n * Handler functions dealing with setup and communication over a Service Worker.\n */\nexport interface ServiceWorkerHandlers {\n  handleActivate: (this: ServiceWorkerGlobalScope, ev: ExtendableEvent) => any;\n  handleFetch: (this: ServiceWorkerGlobalScope, ev: FetchEvent) => any;\n  handleInstall: (this: ServiceWorkerGlobalScope, ev: ExtendableEvent) => any;\n  handleMessage: (this: ServiceWorkerGlobalScope, ev: ExtendableMessageEvent) => any;\n}\n", "// Original code from Synclink and Comlink. Released under Apache 2.0.\n\nimport {\n  Endpoint,\n  SZ_BUF_DOESNT_FIT,\n  SZ_BUF_FITS_IDX,\n  SZ_BUF_SIZE_IDX,\n  UUID_LENGTH,\n} from './task-common';\n\nimport { newSyncRequest, Message } from './message';\nimport { decode } from '@msgpack/msgpack';\n\nconst decoder = new TextDecoder('utf-8');\n\nexport class SyncTask {\n  endpoint: Endpoint;\n  msg: Message;\n  transfers: Transferable[];\n\n  #scheduled = false;\n  #resolved: boolean;\n  #result?: any;\n  #exception?: any;\n\n  // sync only\n  taskId?: number;\n  #syncGen?: Generator<void, unknown, void>;\n  sizeBuffer?: Int32Array;\n  signalBuffer?: Int32Array;\n  syncifier = new _Syncifier();\n\n  constructor(endpoint: Endpoint, msg: Message, transfers: Transferable[] = []) {\n    this.endpoint = endpoint;\n    this.msg = msg;\n    this.transfers = transfers;\n    this.#resolved = false;\n  }\n\n  scheduleSync() {\n    if (this.#scheduled) {\n      return;\n    }\n    this.#scheduled = true;\n\n    this.syncifier.scheduleTask(this);\n    this.#syncGen = this.doSync();\n    this.#syncGen.next();\n    return this;\n  }\n\n  poll() {\n    if (!this.#scheduled) {\n      throw new Error('Task not synchronously scheduled');\n    }\n\n    const { done, value } = this.#syncGen!.next();\n    if (!done) {\n      return false;\n    }\n\n    this.#resolved = true;\n    this.#result = value;\n\n    return true;\n  }\n\n  *doSync() {\n    // just use syncRequest.\n    const { endpoint, msg, transfers } = this;\n    const sizeBuffer = new Int32Array(new SharedArrayBuffer(8));\n    const signalBuffer = this.signalBuffer!;\n    const taskId = this.taskId;\n\n    // Ensure status is cleared. We will notify\n    let dataBuffer = acquireDataBuffer(UUID_LENGTH);\n    // console.log(\"===requesting\", taskId);\n\n    const syncMsg = newSyncRequest(msg, {\n      sizeBuffer,\n      dataBuffer,\n      signalBuffer,\n      taskId,\n    });\n\n    endpoint.postMessage(syncMsg, transfers);\n    yield;\n\n    if (Atomics.load(sizeBuffer, SZ_BUF_FITS_IDX) === SZ_BUF_DOESNT_FIT) {\n      // There wasn't enough space, make a bigger dataBuffer.\n      // First read uuid for response out of current dataBuffer\n      const id = decoder.decode(dataBuffer.slice(0, UUID_LENGTH));\n      releaseDataBuffer(dataBuffer);\n      const size = Atomics.load(sizeBuffer, SZ_BUF_SIZE_IDX);\n      dataBuffer = acquireDataBuffer(size);\n      // console.log(\"===bigger data buffer\", taskId);\n      endpoint.postMessage({ id, dataBuffer });\n      yield;\n    }\n\n    const size = Atomics.load(sizeBuffer, SZ_BUF_SIZE_IDX);\n    // console.log(\"===completing\", taskId);\n    return decode(dataBuffer.slice(0, size));\n  }\n\n  get result() {\n    if (this.#exception) {\n      throw this.#exception;\n    }\n    // console.log(this.#resolved);\n    if (this.#resolved) {\n      return this.#result as unknown;\n    }\n    throw new Error('Not ready.');\n  }\n\n  syncify(): any {\n    this.scheduleSync();\n    this.syncifier.syncifyTask(this);\n    return this.result;\n  }\n}\n\nclass _Syncifier {\n  nextTaskId: Int32Array;\n  signalBuffer: Int32Array;\n  tasks: Map<number, SyncTask>;\n\n  constructor() {\n    this.nextTaskId = new Int32Array([1]);\n    this.signalBuffer = new Int32Array(new SharedArrayBuffer(32 * 4 + 4));\n    this.tasks = new Map();\n  }\n\n  scheduleTask(task: SyncTask) {\n    task.taskId = this.nextTaskId[0];\n    this.nextTaskId[0] += 2;\n    task.signalBuffer = this.signalBuffer;\n    this.tasks.set(task.taskId, task);\n  }\n\n  waitOnSignalBuffer() {\n    const timeout = 50;\n    for (; ;) {\n      const status = Atomics.wait(this.signalBuffer, 0, 0, timeout);\n      switch (status) {\n        case 'ok':\n        case 'not-equal':\n          return;\n        case 'timed-out':\n          if (interruptBuffer[0] !== 0) {\n            handleInterrupt();\n          }\n          break;\n        default:\n          throw new Error('Unreachable');\n      }\n    }\n  }\n\n  *tasksIdsToWakeup() {\n    const flag = Atomics.load(this.signalBuffer, 0);\n    for (let i = 0; i < 32; i++) {\n      const bit = 1 << i;\n      if (flag & bit) {\n        Atomics.and(this.signalBuffer, 0, ~bit);\n        const wokenTask = Atomics.exchange(this.signalBuffer, i + 1, 0);\n        yield wokenTask;\n      }\n    }\n  }\n\n  pollTasks(task?: SyncTask) {\n    let result = false;\n    for (const wokenTaskId of this.tasksIdsToWakeup()) {\n      // console.log(\"poll task\", wokenTaskId, \"looking for\",task);\n      const wokenTask = this.tasks.get(wokenTaskId);\n      if (!wokenTask) {\n        throw new Error(`Assertion error: unknown taskId ${wokenTaskId}.`);\n      }\n      if (wokenTask.poll()) {\n        // console.log(\"completed task \", wokenTaskId, wokenTask, wokenTask._result);\n        this.tasks.delete(wokenTaskId);\n        if (wokenTask === task) {\n          result = true;\n        }\n      }\n    }\n    return result;\n  }\n\n  syncifyTask(task: SyncTask) {\n    for (; ;) {\n      this.waitOnSignalBuffer();\n      // console.log(\"syncifyTask:: woke\");\n      if (this.pollTasks(task)) {\n        return;\n      }\n    }\n  }\n}\n\nconst dataBuffers: Uint8Array[][] = [];\n\nfunction acquireDataBuffer(size: number): Uint8Array {\n  const powerof2 = Math.ceil(Math.log2(size));\n  if (!dataBuffers[powerof2]) {\n    dataBuffers[powerof2] = [];\n  }\n  const result = dataBuffers[powerof2].pop();\n  if (result) {\n    result.fill(0);\n    return result;\n  }\n  return new Uint8Array(new SharedArrayBuffer(2 ** powerof2));\n}\n\nfunction releaseDataBuffer(buffer: Uint8Array) {\n  const powerof2 = Math.ceil(Math.log2(buffer.byteLength));\n  dataBuffers[powerof2].push(buffer);\n}\n\nlet interruptBuffer = new Int32Array(new ArrayBuffer(4));\n\nlet handleInterrupt = (): void => {\n  interruptBuffer[0] = 0;\n  throw new Error('Interrupted!');\n};\n\n/**\n * Sets the interrupt handler. This is called when the computation is\n * interrupted. Should zero the interrupt buffer and throw an exception.\n * @internal\n */\nexport function setInterruptHandler(handler: () => void) {\n  handleInterrupt = handler;\n}\n\n/**\n * Sets the interrupt buffer. Should be a shared array buffer. When element 0\n * is set non-zero it signals an interrupt.\n * @internal\n */\nexport function setInterruptBuffer(buffer: ArrayBufferLike) {\n  interruptBuffer = new Int32Array(buffer);\n}\n", "import { promiseHandles, newCrossOriginWorker, isCrossOrigin } from '../utils';\nimport { Message, Response, SyncRequest } from './message';\nimport { Endpoint } from './task-common';\nimport { syncResponse } from './task-main';\nimport { ChannelMain, ChannelWorker } from './channel';\nimport { ChannelType } from './channel-common';\nimport { WebROptions } from '../webr-main';\nimport { WebRChannelError, WebRWorkerError } from '../error';\n\nimport { IN_NODE } from '../compat';\nimport type { Worker as NodeWorker } from 'worker_threads';\nif (IN_NODE) {\n  (globalThis as any).Worker = require('worker_threads').Worker as NodeWorker;\n}\n\n// Main ----------------------------------------------------------------\n\nexport class SharedBufferChannelMain extends ChannelMain {\n  #interruptBuffer?: Int32Array;\n\n  initialised: Promise<unknown>;\n  resolve: (_?: unknown) => void;\n  reject: (message: string | Error) => void;\n  close = () => { return; };\n\n  constructor(config: Required<WebROptions>) {\n    super();\n    ({ resolve: this.resolve, reject: this.reject, promise: this.initialised } = promiseHandles());\n\n    const initWorker = (worker: Worker) => {\n      this.#handleEventsFromWorker(worker);\n      this.close = () => {\n        worker.terminate();\n        this.putClosedMessage();\n      };\n      const msg = {\n        type: 'init',\n        data: { config, channelType: ChannelType.SharedArrayBuffer },\n      } as Message;\n      worker.postMessage(msg);\n    };\n\n    if (isCrossOrigin(config.baseUrl)) {\n      newCrossOriginWorker(`${config.baseUrl}webr-worker.js`, (worker: Worker) =>\n        initWorker(worker)\n      );\n    } else {\n      const worker = new Worker(`${config.baseUrl}webr-worker.js`);\n      initWorker(worker);\n    }\n  }\n\n  interrupt() {\n    if (!this.#interruptBuffer) {\n      throw new WebRChannelError('Failed attempt to interrupt before initialising interruptBuffer');\n    }\n    this.inputQueue.reset();\n    this.#interruptBuffer[0] = 1;\n  }\n\n  #handleEventsFromWorker(worker: Worker) {\n    if (IN_NODE) {\n      (worker as unknown as NodeWorker).on('message', (message: Message) => {\n        void this.#onMessageFromWorker(worker, message);\n      });\n      (worker as unknown as NodeWorker).on('error', (ev: Event) => {\n        console.error(ev);\n        this.reject(new WebRWorkerError(\n          \"An error occurred initialising the webR SharedBufferChannel worker.\"\n        ));\n      });\n    } else {\n      worker.onmessage = (ev: MessageEvent) =>\n        this.#onMessageFromWorker(worker, ev.data as Message);\n      worker.onerror = (ev) => {\n        console.error(ev);\n        this.reject(new WebRWorkerError(\n          \"An error occurred initialising the webR SharedBufferChannel worker.\"\n        ));\n      };\n    }\n  }\n\n  #onMessageFromWorker = async (worker: Worker, message: Message) => {\n    if (!message || !message.type) {\n      return;\n    }\n\n    switch (message.type) {\n      case 'resolve':\n        this.#interruptBuffer = new Int32Array(message.data as SharedArrayBuffer);\n        this.resolve();\n        return;\n\n      case 'response':\n        this.resolveResponse(message as Response);\n        return;\n\n      case 'system':\n        this.systemQueue.put(message.data as Message);\n        return;\n\n      default:\n        this.outputQueue.put(message);\n        return;\n\n      case 'sync-request': {\n        const msg = message as SyncRequest;\n        const payload = msg.data.msg;\n        const reqData = msg.data.reqData;\n\n        switch (payload.type) {\n          case 'read': {\n            const response = await this.inputQueue.get();\n            await syncResponse(worker, reqData, response);\n            break;\n          }\n          default:\n            throw new WebRChannelError(`Unsupported request type '${payload.type}'.`);\n        }\n        return;\n      }\n      case 'request':\n        throw new WebRChannelError(\n          \"Can't send messages of type 'request' from a worker. Please Use 'sync-request' instead.\"\n        );\n    }\n  };\n}\n\n// Worker --------------------------------------------------------------\n\nimport { SyncTask, setInterruptHandler, setInterruptBuffer } from './task-worker';\nimport { Module } from '../emscripten';\n\nexport class SharedBufferChannelWorker implements ChannelWorker {\n  #ep: Endpoint;\n  #dispatch: (msg: Message) => void = () => 0;\n  #interruptBuffer = new Int32Array(new SharedArrayBuffer(4));\n  #interrupt = () => { return; };\n  onMessageFromMainThread: (msg: Message) => void = () => { return; };\n\n  constructor() {\n    this.#ep = (IN_NODE ? require('worker_threads').parentPort : globalThis) as Endpoint;\n    setInterruptBuffer(this.#interruptBuffer.buffer);\n    setInterruptHandler(() => this.handleInterrupt());\n  }\n\n  resolve() {\n    this.write({ type: 'resolve', data: this.#interruptBuffer.buffer });\n  }\n\n  write(msg: Message, transfer?: [Transferable]) {\n    this.#ep.postMessage(msg, transfer);\n  }\n\n  writeSystem(msg: Message, transfer?: [Transferable]) {\n    this.#ep.postMessage({ type: 'system', data: msg }, transfer);\n  }\n\n  read(): Message {\n    const msg = { type: 'read' } as Message;\n    const task = new SyncTask(this.#ep, msg);\n    return task.syncify() as Message;\n  }\n\n  inputOrDispatch(): number {\n    for (; ;) {\n      const msg = this.read();\n      if (msg.type === 'stdin') {\n        return Module.allocateUTF8(msg.data as string);\n      }\n      this.#dispatch(msg);\n    }\n  }\n\n  run(args: string[]) {\n    try{\n      Module.callMain(args);\n    } catch (e) {\n      if (e instanceof WebAssembly.RuntimeError) {\n        this.writeSystem({ type: 'console.error', data: e.message });\n        this.writeSystem({\n          type: 'console.error',\n          data: \"An unrecoverable WebAssembly error has occurred, the webR worker will be closed.\",\n        });\n        this.writeSystem({ type: 'close' });\n      }\n      throw e;\n    }\n  }\n\n  setInterrupt(interrupt: () => void) {\n    this.#interrupt = interrupt;\n  }\n\n  handleInterrupt() {\n    if (this.#interruptBuffer[0] !== 0) {\n      this.#interruptBuffer[0] = 0;\n      this.#interrupt();\n    }\n  }\n\n  setDispatchHandler(dispatch: (msg: Message) => void) {\n    this.#dispatch = dispatch;\n  }\n}\n", "import { promiseHandles, newCrossOriginWorker, isCrossOrigin } from '../utils';\nimport {\n  Message,\n  newRequest,\n  Response,\n  Request,\n  newResponse,\n} from './message';\nimport { encode, decode } from '@msgpack/msgpack';\nimport { Endpoint } from './task-common';\nimport { ChannelMain, ChannelWorker } from './channel';\nimport { ChannelType } from './channel-common';\nimport { WebROptions } from '../webr-main';\nimport { WebRChannelError, WebRWorkerError } from '../error';\n\nimport { IN_NODE } from '../compat';\nimport type { Worker as NodeWorker } from 'worker_threads';\nif (IN_NODE) {\n  (globalThis as any).Worker = require('worker_threads').Worker as NodeWorker;\n}\n\n// Main ----------------------------------------------------------------\n\nexport class ServiceWorkerChannelMain extends ChannelMain {\n  initialised: Promise<unknown>;\n\n  resolve: (_?: unknown) => void;\n  reject: (message: string | Error) => void;\n  close = () => { return; };\n\n  #syncMessageCache = new Map<string, Message>();\n  #registration?: ServiceWorkerRegistration;\n  #interrupted = false;\n\n  constructor(config: Required<WebROptions>) {\n    super();\n    ({ resolve: this.resolve, reject: this.reject, promise: this.initialised } = promiseHandles());\n\n    console.warn(\n      \"The ServiceWorker communication channel is deprecated and will be removed in a future version of webR. \" +\n      \"Consider using the PostMessage channel instead. If blocking input is required (for example, `browser()`) \" +\n      \"the SharedArrayBuffer channel should be used. See https://docs.r-wasm.org/webr/latest/serving.html for further information.\"\n    );\n    const initWorker = (worker: Worker) => {\n      this.#handleEventsFromWorker(worker);\n      this.close = () => {\n        worker.terminate();\n        this.putClosedMessage();\n      };\n      void this.#registerServiceWorker(`${config.serviceWorkerUrl}webr-serviceworker.js`)\n        .then(\n          (clientId) => {\n            const msg = {\n              type: 'init',\n              data: {\n                config,\n                channelType: ChannelType.ServiceWorker,\n                clientId,\n                location: window.location.href,\n              },\n            } as Message;\n            worker.postMessage(msg);\n          }\n        );\n    };\n\n    if (isCrossOrigin(config.serviceWorkerUrl)) {\n      newCrossOriginWorker(`${config.serviceWorkerUrl}webr-worker.js`, (worker: Worker) =>\n        initWorker(worker)\n      );\n    } else {\n      const worker = new Worker(`${config.serviceWorkerUrl}webr-worker.js`);\n      initWorker(worker);\n    }\n  }\n\n  activeRegistration(): ServiceWorker {\n    if (!this.#registration?.active) {\n      throw new WebRChannelError('Attempted to obtain a non-existent active registration.');\n    }\n    return this.#registration.active;\n  }\n\n  interrupt() {\n    this.#interrupted = true;\n  }\n\n  async #registerServiceWorker(url: string): Promise<string> {\n    // Register service worker\n    this.#registration = await navigator.serviceWorker.register(url);\n    await navigator.serviceWorker.ready;\n    window.addEventListener('beforeunload', () => {\n      void this.#registration?.unregister();\n    });\n\n    // Ensure we can communicate with service worker and we have a client ID\n    const clientId = await new Promise<string>((resolve) => {\n      navigator.serviceWorker.addEventListener(\n        'message',\n        function listener(event: MessageEvent<{ type: string; clientId: string }>) {\n          if (event.data.type === 'registration-successful') {\n            navigator.serviceWorker.removeEventListener('message', listener);\n            resolve(event.data.clientId);\n          }\n        }\n      );\n      this.activeRegistration().postMessage({ type: 'register-client-main' });\n    });\n\n    // Setup listener for service worker messages\n    navigator.serviceWorker.addEventListener('message', (event: MessageEvent<Request>) => {\n      void this.#onMessageFromServiceWorker(event);\n    });\n    return clientId;\n  }\n\n  async #onMessageFromServiceWorker(event: MessageEvent<Message>) {\n    if (event.data.type === 'request') {\n      const uuid = event.data.data as string;\n      const message = this.#syncMessageCache.get(uuid);\n      if (!message) {\n        throw new WebRChannelError('Request not found during service worker XHR request');\n      }\n      this.#syncMessageCache.delete(uuid);\n      switch (message.type) {\n        case 'read': {\n          const response = await this.inputQueue.get();\n          this.activeRegistration().postMessage({\n            type: 'wasm-webr-fetch-response',\n            uuid: uuid,\n            response: newResponse(uuid, response),\n          });\n          break;\n        }\n        case 'interrupt': {\n          const response = this.#interrupted;\n          this.activeRegistration().postMessage({\n            type: 'wasm-webr-fetch-response',\n            uuid: uuid,\n            response: newResponse(uuid, response),\n          });\n          this.inputQueue.reset();\n          this.#interrupted = false;\n          break;\n        }\n        default:\n          throw new WebRChannelError(`Unsupported request type '${message.type}'.`);\n      }\n      return;\n    }\n  }\n\n  #handleEventsFromWorker(worker: Worker) {\n    if (IN_NODE) {\n      (worker as unknown as NodeWorker).on('message', (message: Message) => {\n        this.#onMessageFromWorker(worker, message);\n      });\n      (worker as unknown as NodeWorker).on('error', (ev: Event) => {\n        console.error(ev);\n        this.reject(new WebRWorkerError(\n          \"An error occurred initialising the webR ServiceWorkerChannel worker.\"\n        ));\n      });\n    } else {\n      worker.onmessage = (ev: MessageEvent) =>\n        this.#onMessageFromWorker(worker, ev.data as Message);\n      worker.onerror = (ev) => {\n        console.error(ev);\n        this.reject(new WebRWorkerError(\n          \"An error occurred initialising the webR ServiceWorkerChannel worker.\"\n        ));\n      };\n    }\n  }\n\n  #onMessageFromWorker = (worker: Worker, message: Message) => {\n    if (!message || !message.type) {\n      return;\n    }\n\n    switch (message.type) {\n      case 'resolve':\n        this.resolve();\n        return;\n\n      case 'response':\n        this.resolveResponse(message as Response);\n        return;\n\n      case 'system':\n        this.systemQueue.put(message.data as Message);\n        return;\n\n      default:\n        this.outputQueue.put(message);\n        return;\n\n      case 'sync-request': {\n        const request = message.data as Request;\n        this.#syncMessageCache.set(request.data.uuid, request.data.msg);\n        return;\n      }\n\n      case 'request':\n        throw new WebRChannelError(\n          \"Can't send messages of type 'request' from a worker.\" +\n          'Use service worker fetch request instead.'\n        );\n    }\n  };\n}\n\n// Worker --------------------------------------------------------------\n\nimport { Module } from '../emscripten';\n\nexport class ServiceWorkerChannelWorker implements ChannelWorker {\n  #ep: Endpoint;\n  #mainThreadId: string;\n  #location: string;\n  #lastInterruptReq = Date.now();\n  #dispatch: (msg: Message) => void = () => 0;\n  #interrupt = () => { return; };\n  onMessageFromMainThread: (msg: Message) => void = () => { return; };\n\n  constructor(data: { clientId?: string; location?: string }) {\n    if (!data.clientId || !data.location) {\n      throw new WebRChannelError(\"Can't start service worker channel\");\n    }\n    this.#mainThreadId = data.clientId;\n    this.#location = data.location;\n    this.#ep = (IN_NODE ? require('worker_threads').parentPort : globalThis) as Endpoint;\n  }\n\n  resolve() {\n    this.write({ type: 'resolve' });\n  }\n\n  write(msg: Message, transfer?: [Transferable]) {\n    this.#ep.postMessage(msg, transfer);\n  }\n\n  writeSystem(msg: Message, transfer?: [Transferable]) {\n    this.#ep.postMessage({ type: 'system', data: msg }, transfer);\n  }\n\n  syncRequest(message: Message): Response {\n    /*\n     * Browsers timeout service workers after about 5 minutes on inactivity.\n     * See e.g. service_worker_version.cc in Chromium.\n     *\n     * To avoid the service worker being shut down, we timeout our XHR after\n     * 1 minute and then resend the request as a keep-alive. The service worker\n     * uses the message UUID to identify the request and continue waiting for a\n     * response from where it left off.\n     */\n    const request = newRequest(message);\n    this.write({ type: 'sync-request', data: request });\n\n    let retryCount = 0;\n    for (; ;) {\n      try {\n        const url = new URL('__wasm__/webr-fetch-request/', this.#location);\n        const xhr = new XMLHttpRequest();\n        xhr.timeout = 60000;\n        xhr.responseType = 'arraybuffer';\n        xhr.open('POST', url, false);\n        const fetchReqBody = {\n          clientId: this.#mainThreadId,\n          uuid: request.data.uuid,\n        };\n        xhr.send(encode(fetchReqBody));\n        return decode(xhr.response as ArrayBuffer) as Response;\n      } catch (e: any) {\n        if (e instanceof DOMException && retryCount++ < 1000) {\n          console.log('Service worker request failed - resending request');\n        } else {\n          throw e;\n        }\n      }\n    }\n  }\n\n  read(): Message {\n    const response = this.syncRequest({ type: 'read' });\n    return response.data.resp as Message;\n  }\n\n  inputOrDispatch(): number {\n    for (; ;) {\n      const msg = this.read();\n      if (msg.type === 'stdin') {\n        return Module.allocateUTF8(msg.data as string);\n      }\n      this.#dispatch(msg);\n    }\n  }\n\n  run(args: string[]) {\n    try{\n      Module.callMain(args);\n    } catch (e) {\n      if (e instanceof WebAssembly.RuntimeError) {\n        this.writeSystem({ type: 'console.error', data: e.message });\n        this.writeSystem({\n          type: 'console.error',\n          data: \"An unrecoverable WebAssembly error has occurred, the webR worker will be closed.\",\n        });\n        this.writeSystem({ type: 'close' });\n      }\n      throw e;\n    }\n  }\n\n  setInterrupt(interrupt: () => void) {\n    this.#interrupt = interrupt;\n  }\n\n  handleInterrupt() {\n    /* During R computation we have no way to directly interrupt the worker\n     * thread. Instead, we hook into R's PolledEvents. Since we are not using\n     * SharedArrayBuffer as a signal method, we instead send a message to the\n     * main thread to ask if we should interrupt R.\n     *\n     * The rate of requests is limited to once per second. This stops the\n     * browser being overloaded with XHR sync requests while R is working.\n     */\n    if (Date.now() > this.#lastInterruptReq + 1000) {\n      this.#lastInterruptReq = Date.now();\n      const response = this.syncRequest({ type: 'interrupt' });\n      const interrupted = response.data.resp as boolean;\n      if (interrupted) {\n        this.#interrupt();\n      }\n    }\n  }\n\n  setDispatchHandler(dispatch: (msg: Message) => void) {\n    this.#dispatch = dispatch;\n  }\n}\n", "import { promiseHandles, ResolveFn, newCrossOriginWorker, isCrossOrigin } from '../utils';\nimport { Message, newRequest, Response, Request, newResponse } from './message';\nimport { Endpoint } from './task-common';\nimport { ChannelType } from './channel-common';\nimport { WebROptions } from '../webr-main';\nimport { ChannelMain } from './channel';\nimport { WebRChannelError, WebRWorkerError } from '../error';\n\nimport { IN_NODE } from '../compat';\nimport type { Worker as NodeWorker } from 'worker_threads';\nif (IN_NODE) {\n  (globalThis as any).Worker = require('worker_threads').Worker as NodeWorker;\n}\n\n// Main ----------------------------------------------------------------\n\nexport class PostMessageChannelMain extends ChannelMain {\n\n  initialised: Promise<unknown>;\n  resolve: (_?: unknown) => void;\n  reject: (message: string | Error) => void;\n  close: () => void = () => { return; };\n  #worker?: Worker;\n\n  constructor(config: Required<WebROptions>) {\n    super();\n    ({ resolve: this.resolve, reject: this.reject, promise: this.initialised } = promiseHandles());\n\n    const initWorker = (worker: Worker) => {\n      this.#worker = worker;\n      this.#handleEventsFromWorker(worker);\n      this.close = () => {\n        worker.terminate();\n        this.putClosedMessage();\n      };\n      const msg = {\n        type: 'init',\n        data: { config, channelType: ChannelType.PostMessage },\n      } as Message;\n      worker.postMessage(msg);\n    };\n\n    if (isCrossOrigin(config.baseUrl)) {\n      newCrossOriginWorker(`${config.baseUrl}webr-worker.js`, (worker: Worker) =>\n        initWorker(worker)\n      );\n    } else {\n      const worker = new Worker(`${config.baseUrl}webr-worker.js`);\n      initWorker(worker);\n    }\n  }\n\n  interrupt() {\n    console.error('Interrupting R execution is not available when using the PostMessage channel');\n  }\n\n  #handleEventsFromWorker(worker: Worker) {\n    if (IN_NODE) {\n      (worker as unknown as NodeWorker).on('message', (message: Message) => {\n        void this.#onMessageFromWorker(worker, message);\n      });\n      (worker as unknown as NodeWorker).on('error', (ev: Event) => {\n        console.error(ev);\n        this.reject(new WebRWorkerError(\n          \"An error occurred initialising the webR PostMessageChannel worker.\"\n        ));\n      });\n    } else {\n      worker.onmessage = (ev: MessageEvent) =>\n        this.#onMessageFromWorker(worker, ev.data as Message);\n      worker.onerror = (ev) => {\n        console.error(ev);\n        this.reject(new WebRWorkerError(\n          \"An error occurred initialising the webR PostMessageChannel worker.\"\n        ));\n      };\n    }\n  }\n\n  #onMessageFromWorker = async (worker: Worker, message: Message) => {\n    if (!message || !message.type) {\n      return;\n    }\n\n    switch (message.type) {\n      case 'resolve':\n        this.resolve();\n        return;\n\n      case 'response':\n        this.resolveResponse(message as Response);\n        return;\n\n      case 'system':\n        this.systemQueue.put(message.data as Message);\n        return;\n\n      default:\n        this.outputQueue.put(message);\n        return;\n\n      case 'request': {\n        const msg = message as Request;\n        const payload = msg.data.msg;\n\n        switch (payload.type) {\n          case 'read': {\n            const input = await this.inputQueue.get();\n            if (this.#worker) {\n              const response = newResponse(msg.data.uuid, input);\n              this.#worker.postMessage(response);\n            }\n            break;\n          }\n          default:\n            throw new WebRChannelError(`Unsupported request type '${payload.type}'.`);\n        }\n        return;\n      }\n\n      case 'sync-request':\n        throw new WebRChannelError(\n          \"Can't send messages of type 'sync-request' in PostMessage mode. Use 'request' instead.\"\n        );\n    }\n  };\n}\n\n// Worker --------------------------------------------------------------\n\nimport { Module as _Module } from '../emscripten';\n\ndeclare let Module: _Module;\n\nexport class PostMessageChannelWorker {\n  #ep: Endpoint;\n  #parked = new Map<string, ResolveFn>();\n  #dispatch: (msg: Message) => void = () => 0;\n  #promptDepth = 0;\n\n  constructor() {\n    this.#ep = (IN_NODE ? require('worker_threads').parentPort : globalThis) as Endpoint;\n  }\n\n  resolve() {\n    this.write({ type: 'resolve' });\n  }\n\n  write(msg: Message, transfer?: [Transferable]) {\n    this.#ep.postMessage(msg, transfer);\n  }\n\n  writeSystem(msg: Message, transfer?: [Transferable]) {\n    this.#ep.postMessage({ type: 'system', data: msg }, transfer);\n  }\n\n  read(): Message {\n    throw new WebRChannelError(\n      'Unable to synchronously read when using the `PostMessage` channel.'\n    );\n  }\n\n  inputOrDispatch(): number {\n    if (this.#promptDepth > 0) {\n      this.#promptDepth = 0;\n      const msg = Module.allocateUTF8OnStack(\n        \"Can't block for input when using the PostMessage communication channel.\"\n      );\n      Module._Rf_error(msg);\n    }\n    this.#promptDepth++;\n    // Unable to block, so just return a NULL\n    return 0;\n  }\n\n  run(_args: string[]) {\n    const args: string[] = _args || [];\n    args.unshift('R');\n    const argc = args.length;\n    const argv = Module._malloc(4 * (argc + 1));\n    args.forEach((arg, idx) => {\n      const argvPtr = argv + 4 * idx;\n      const argPtr = Module.allocateUTF8(arg);\n      Module.setValue(argvPtr, argPtr, '*');\n    });\n\n    this.writeSystem({\n      type: 'console.warn',\n      data: 'WebR is using `PostMessage` communication channel, nested R REPLs are not available.',\n    });\n\n    Module._Rf_initialize_R(argc, argv);\n    Module._setup_Rmainloop();\n    Module._R_ReplDLLinit();\n    Module._R_ReplDLLdo1();\n    void this.#asyncREPL();\n  }\n\n  setDispatchHandler(dispatch: (msg: Message) => void) {\n    this.#dispatch = dispatch;\n  }\n\n  async request(msg: Message, transferables?: [Transferable]): Promise<any> {\n    const req = newRequest(msg, transferables);\n\n    const { resolve: resolve, promise: prom } = promiseHandles();\n    this.#parked.set(req.data.uuid, resolve);\n\n    this.write(req);\n    return prom;\n  }\n\n  setInterrupt() { return; }\n  handleInterrupt() { return; }\n\n  onMessageFromMainThread(message: Message) {\n    const msg = message as Response;\n    const uuid = msg.data.uuid;\n    const resolve = this.#parked.get(uuid);\n\n    if (resolve) {\n      this.#parked.delete(uuid);\n      resolve(msg.data.resp);\n    } else {\n      console.warn(\"Can't find request.\");\n    }\n  }\n\n  /*\n   * This is a fallback REPL for webR running in PostMessage mode. The prompt\n   * section of R's R_ReplDLLdo1 returns empty with -1, which allows this\n   * fallback REPL to yield to the event loop with await.\n   *\n   * The drawback of this approach is that nested REPLs do not work, such as\n   * readline, browser or menu. Attempting to use a nested REPL prints an error\n   * to the JS console.\n   *\n   * R/Wasm errors during execution are caught and the REPL is restarted at the\n   * top level. Any other JS errors are re-thrown.\n   */\n  #asyncREPL = async () => {\n    for (; ;) {\n      try {\n        this.#promptDepth = 0;\n        const msg = (await this.request({ type: 'read' })) as Message;\n        if (msg.type === 'stdin') {\n          // Copy the new input into WASM memory\n          const str = Module.allocateUTF8(msg.data as string);\n          Module._strcpy(Module._DLLbuf, str);\n          Module.setValue(Module._DLLbufp, Module._DLLbuf, '*');\n          Module._free(str);\n\n          // Execute the R code using a single step of R's built in REPL\n          try {\n            while (Module._R_ReplDLLdo1() > 0);\n          } catch (e: any) {\n            if (e instanceof (WebAssembly as any).Exception) {\n              // R error: clear command buffer and reproduce prompt\n              Module._R_ReplDLLinit();\n              Module._R_ReplDLLdo1();\n            } else {\n              throw e;\n            }\n          }\n        } else {\n          this.#dispatch(msg);\n        }\n      } catch (e) {\n        // Close on unrecoverable error\n        if (e instanceof WebAssembly.RuntimeError) {\n          this.writeSystem({ type: 'console.error', data: e.message });\n          this.writeSystem({\n            type: 'console.error',\n            data: \"An unrecoverable WebAssembly error has occurred, the webR worker will be closed.\",\n          });\n          this.writeSystem({ type: 'close' });\n        }\n        // Don't break the REPL loop on other Wasm `Exception` errors\n        if (!(e instanceof (WebAssembly as any).Exception)) {\n          throw e;\n        }\n      }\n    }\n  };\n}\n", "import { SharedBufferChannelMain, SharedBufferChannelWorker } from './channel-shared';\nimport { ServiceWorkerChannelMain, ServiceWorkerChannelWorker } from './channel-service';\nimport { PostMessageChannelMain, PostMessageChannelWorker } from './channel-postmessage';\nimport { WebROptions } from '../webr-main';\nimport { WebRChannelError } from '../error';\n\n// This file refers to objects imported from `./channel-shared` and\n// `./channel-service.` These can't be included in `./channel` as this\n// causes a circular dependency issue.\n\nexport const ChannelType = {\n  Automatic: 0,\n  SharedArrayBuffer: 1,\n  ServiceWorker: 2,\n  PostMessage: 3,\n} as const;\n\nexport type ChannelInitMessage = {\n  type: string;\n  data: {\n    config: Required<WebROptions>;\n    channelType: Exclude<\n      (typeof ChannelType)[keyof typeof ChannelType],\n      typeof ChannelType.Automatic\n    >;\n    clientId?: string;\n    location?: string;\n  };\n};\n\nexport function newChannelMain(data: Required<WebROptions>) {\n  switch (data.channelType) {\n    case ChannelType.SharedArrayBuffer:\n      return new SharedBufferChannelMain(data);\n    case ChannelType.ServiceWorker:\n      return new ServiceWorkerChannelMain(data);\n    case ChannelType.PostMessage:\n      return new PostMessageChannelMain(data);\n    case ChannelType.Automatic:\n    default:\n      if (typeof SharedArrayBuffer !== 'undefined') {\n        return new SharedBufferChannelMain(data);\n      } else {\n        return new PostMessageChannelMain(data);\n      }\n  }\n}\n\nexport function newChannelWorker(msg: ChannelInitMessage) {\n  switch (msg.data.channelType) {\n    case ChannelType.SharedArrayBuffer:\n      return new SharedBufferChannelWorker();\n    case ChannelType.ServiceWorker:\n      return new ServiceWorkerChannelWorker(msg.data);\n    case ChannelType.PostMessage:\n      return new PostMessageChannelWorker();\n    default:\n      throw new WebRChannelError('Unknown worker channel type received');\n  }\n}\n", "import { IN_NODE } from './compat';\n\nexport const BASE_URL = IN_NODE ? __dirname + '/' : './';\nexport const PKG_BASE_URL = 'https://repo.r-wasm.org';\nexport const WEBR_VERSION = '2024.09.16';\n", "/**\n * Module for working with R objects on the main thead through\n * JavaScript proxies. The `RObject` types in `RMain` are aliases for\n * proxies to the corresponding types in `RWorker`. For instance,\n * `RMain.RCharacter` is an alias for `RMain.RProxy<RWorker.RCharacter>`.\n * The proxies automatically and asynchronously forward method and\n * getter calls to the implementations on the R worker side.\n * @module RMain\n */\nimport type { RProxy } from './proxy';\nimport { isWebRPayloadPtr } from './payload';\nimport * as RWorker from './robj-worker';\n\n// RProxy<RWorker.RObject> type aliases\nexport type RObject = RProxy<RWorker.RObject>;\nexport type RNull = RProxy<RWorker.RNull>;\nexport type RSymbol = RProxy<RWorker.RSymbol>;\nexport type RPairlist = RProxy<RWorker.RPairlist>;\nexport type REnvironment = RProxy<RWorker.REnvironment>;\nexport type RString = RProxy<RWorker.RString>;\nexport type RLogical = RProxy<RWorker.RLogical>;\nexport type RInteger = RProxy<RWorker.RInteger>;\nexport type RDouble = RProxy<RWorker.RDouble>;\nexport type RComplex = RProxy<RWorker.RComplex>;\nexport type RCharacter = RProxy<RWorker.RCharacter>;\nexport type RList = RProxy<RWorker.RList>;\nexport type RDataFrame = RProxy<RWorker.RDataFrame>;\nexport type RRaw = RProxy<RWorker.RRaw>;\nexport type RCall = RProxy<RWorker.RCall>;\n// RFunction proxies are callable\nexport type RFunction = RProxy<RWorker.RFunction> & ((...args: unknown[]) => Promise<unknown>);\n\n/**\n * Test for an RObject instance\n *\n * RObject is the user facing interface to R objects.\n * @param {any} value The object to test.\n * @returns {boolean} True if the object is an instance of an RObject.\n */\nexport function isRObject(value: any): value is RObject {\n  return (\n    !!value &&\n    (typeof value === 'object' || typeof value === 'function') &&\n    'payloadType' in value &&\n    isWebRPayloadPtr(value._payload)\n  );\n}\n\n/**\n * Test for an RNull instance\n * @param {any} value The object to test.\n * @returns {boolean} True if the object is an instance of an RNull.\n */\nexport function isRNull(value: any): value is RNull {\n  return isRObject(value) && value._payload.obj.type === 'null';\n}\n\n/**\n * Test for an RSymbol instance\n * @param {any} value The object to test.\n * @returns {boolean} True if the object is an instance of an RSymbol.\n */\nexport function isRSymbol(value: any): value is RSymbol {\n  return isRObject(value) && value._payload.obj.type === 'symbol';\n}\n\n/**\n * Test for an RPairlist instance\n * @param {any} value The object to test.\n * @returns {boolean} True if the object is an instance of an RPairlist.\n */\nexport function isRPairlist(value: any): value is RPairlist {\n  return isRObject(value) && value._payload.obj.type === 'pairlist';\n}\n\n/**\n * Test for an REnvironment instance\n * @param {any} value The object to test.\n * @returns {boolean} True if the object is an instance of an REnvironment.\n */\nexport function isREnvironment(value: any): value is REnvironment {\n  return isRObject(value) && value._payload.obj.type === 'environment';\n}\n\n/**\n * Test for an RLogical instance\n * @param {any} value The object to test.\n * @returns {boolean} True if the object is an instance of an RLogical.\n */\nexport function isRLogical(value: any): value is RLogical {\n  return isRObject(value) && value._payload.obj.type === 'logical';\n}\n\n/**\n * Test for an RInteger instance\n * @param {any} value The object to test.\n * @returns {boolean} True if the object is an instance of an RInteger.\n */\nexport function isRInteger(value: any): value is RInteger {\n  return isRObject(value) && value._payload.obj.type === 'integer';\n}\n\n/**\n * Test for an RDouble instance\n * @param {any} value The object to test.\n * @returns {boolean} True if the object is an instance of an RDouble.\n */\nexport function isRDouble(value: any): value is RDouble {\n  return isRObject(value) && value._payload.obj.type === 'double';\n}\n\n/**\n * Test for an RComplex instance\n * @param {any} value The object to test.\n * @returns {boolean} True if the object is an instance of an RComplex.\n */\nexport function isRComplex(value: any): value is RComplex {\n  return isRObject(value) && value._payload.obj.type === 'complex';\n}\n\n/**\n * Test for an RCharacter instance\n * @param {any} value The object to test.\n * @returns {boolean} True if the object is an instance of an RCharacter.\n */\nexport function isRCharacter(value: any): value is RCharacter {\n  return isRObject(value) && value._payload.obj.type === 'character';\n}\n\n/**\n * Test for an RList instance\n * @param {any} value The object to test.\n * @returns {boolean} True if the object is an instance of an RList.\n */\nexport function isRList(value: any): value is RList {\n  return isRObject(value) && value._payload.obj.type === 'list';\n}\n\n/**\n * Test for an RRaw instance\n * @param {any} value The object to test.\n * @returns {boolean} True if the object is an instance of an RRaw.\n */\nexport function isRRaw(value: any): value is RRaw {\n  return isRObject(value) && value._payload.obj.type === 'raw';\n}\n\n/**\n * Test for an RCall instance\n * @param {any} value The object to test.\n * @returns {boolean} True if the object is an instance of an RCall.\n */\nexport function isRCall(value: any): value is RCall {\n  return isRObject(value) && value._payload.obj.type === 'call';\n}\n\n/**\n * Test for an RFunction instance\n * @param {any} value The object to test.\n * @returns {boolean} True if the object is an instance of an RFunction.\n */\nexport function isRFunction(value: any): value is RFunction {\n  return Boolean(isRObject(value) && value._payload.obj.methods?.includes('exec'));\n}\n", "/**\n * Proxy R objects on the webR worker thread so that they can be accessed from\n * the main thread.\n * @module Proxy\n */\nimport { ChannelMain } from './chan/channel';\nimport { replaceInObject } from './utils';\nimport { isWebRPayloadPtr, WebRPayloadPtr, WebRPayload } from './payload';\nimport { RType, RCtor, WebRData, WebRDataRaw } from './robj';\nimport { isRObject, RObject, isRFunction } from './robj-main';\nimport * as RWorker from './robj-worker';\nimport { ShelterID, CallRObjectMethodMessage, NewRObjectMessage } from './webr-chan';\nimport type * as Payload from './payload';\nimport { WebRError, WebRPayloadError } from './error';\n\n/**\n * Obtain a union of the keys corresponding to methods of a given class `T`.\n * @typeParam T The type to provide the methods for.\n */\nexport type Methods<T> = {\n  [P in keyof T]: T[P] extends (...args: any) => any ? P : never;\n}[keyof T];\n\n/**\n * Distributive conditional type for {@link RProxy}.\n *\n * Distributes {@link RProxy} over any {@link RWorker.RObject} in the given\n * union type U.\n * @typeParam U The type union to distribute {@link RProxy} over.\n */\nexport type DistProxy<U> = U extends RWorker.RObject ? RProxy<U> : U;\n\n/**\n * Convert {@link RWorker.RObject} properties for use with an {@link RProxy}.\n *\n * Properties in the type parameter `T` are mapped so that {@link RProxy} is\n * distributed over any {@link RWorker.RObject} types, then wrapped in a\n * Promise.\n *\n * Function signatures are mapped so that arguments with {@link RWorker.RObject}\n * type instead take {@link RProxy}<{@link RWorker.RObject}> type. Other\n * function arguments remain as they are. The function return type is also\n * converted to a corresponding type using `RProxify` recursively.\n * @typeParam T The type to convert.\n */\nexport type RProxify<T> = T extends Array<any> // [RObject, RObject, ...]\n  ? Promise<DistProxy<T[0]>[]>\n  : T extends (...args: infer U) => any // (...args) => <RObject>\n  ? (\n    ...args: {\n      [V in keyof U]: DistProxy<U[V]>;\n    }\n  ) => RProxify<ReturnType<T>>\n  : T extends { result: RWorker.RObject, output: RWorker.RObject } // Return type of .capture()\n  ? Promise<{\n    [U in keyof T]: DistProxy<T[U]>\n  }>\n  : Promise<DistProxy<T>>; // RObject, any other types\n\n/**\n * Create an {@link RProxy} based on an {@link RWorker.RObject} type parameter.\n *\n * R objects created via an {@link RProxy} are intended to be used in place of\n * {@link RWorker.RObject} on the main thread. An {@link RProxy} object has the\n * same instance methods as the given {@link RWorker.RObject} parameter, with\n * the following differences:\n * - Method arguments take `RProxy` in place of {@link RWorker.RObject}.\n *\n * - Where an {@link RWorker.RObject} would be returned, an `RProxy` is\n *   returned instead.\n *\n * - All return types are wrapped in a Promise.\n *\n * If required, the {@link Payload.WebRPayloadPtr} object associated with the\n * proxy can be accessed directly through the `_payload` property.\n * @typeParam T The {@link RWorker.RObject} type to convert into `RProxy` type.\n */\nexport type RProxy<T extends RWorker.RObject> = { [P in Methods<T>]: RProxify<T[P]> } & {\n  _payload: WebRPayloadPtr;\n  [Symbol.asyncIterator](): AsyncGenerator<RProxy<RWorker.RObject>, void, unknown>;\n};\n\n/**\n * Create a proxy constructor based on a {@link RWorker.RObject} class.\n *\n * The class constructors and static methods of the given subclass of\n * {@link RWorker.RObject} are proxied, and the proxied constructor returns a\n * promise to an R object of a given {@link RProxy} type.\n * @typeParam T The type of the {@link RWorker.RObject} class to be proxied.\n * @typeParam R The type to be returned from the proxied class constructor.\n */\nexport type ProxyConstructor<T, R> = (T extends abstract new (...args: infer U) => any\n  ? {\n    new(\n      ...args: {\n        [V in keyof U]: U[V];\n      }\n    ): Promise<R>;\n  }\n  : never) & {\n    [P in Methods<typeof RWorker.RObject>]: RProxify<(typeof RWorker.RObject)[P]>;\n  };\n\n/* The empty function is used as base when we are proxying RFunction objects.\n * This enables function call semantics on the proxy using the apply hook.\n */\nfunction empty() { return; }\n\n/* Proxy the asyncIterator property for R objects with a length. This allows us\n * to use the `for await (i of obj){}` JavaScript syntax.\n */\nfunction targetAsyncIterator(chan: ChannelMain, proxy: RProxy<RWorker.RObject>) {\n  return async function* () {\n    // Get the R object's length\n    const msg: CallRObjectMethodMessage = {\n      type: 'callRObjectMethod',\n      data: {\n        payload: proxy._payload,\n        prop: 'getPropertyValue',\n        args: [{ payloadType: 'raw', obj: 'length' }],\n        shelter: undefined, // TODO\n      },\n    };\n    const reply = await chan.request(msg);\n\n    // Throw an error if there was some problem accessing the object length\n    if (typeof reply.obj !== 'number') {\n      throw new WebRError('Cannot iterate over object, unexpected type for length property.');\n    }\n\n    // Loop through the object and yield values\n    for (let i = 1; i <= reply.obj; i++) {\n      yield proxy.get(i);\n    }\n  };\n}\n\n/**\n * Proxy an R object method by providing an async function that requests that\n * the worker thread calls the method and then returns the result.\n *\n * When the optional payload argument has not been provided, an\n * {@link RWorker.RObject} static method is called.\n * @internal\n */\nexport function targetMethod(chan: ChannelMain, prop: string): unknown;\nexport function targetMethod(chan: ChannelMain, prop: string, payload: WebRPayloadPtr): unknown;\nexport function targetMethod(chan: ChannelMain, prop: string, payload?: WebRPayloadPtr): unknown {\n  return async (..._args: WebRData[]) => {\n    const args = _args.map((arg) => {\n      if (isRObject(arg)) {\n        return arg._payload;\n      }\n      return {\n        obj: replaceInObject(arg, isRObject, (obj: RObject) => obj._payload),\n        payloadType: 'raw',\n      } as WebRPayload;\n    });\n\n    const msg: CallRObjectMethodMessage = {\n      type: 'callRObjectMethod',\n      data: { payload, prop, args: args },\n    };\n    const reply = await chan.request(msg);\n\n    switch (reply.payloadType) {\n      case 'ptr':\n        return newRProxy(chan, reply);\n      case 'raw': {\n        const proxyReply = replaceInObject(\n          reply,\n          isWebRPayloadPtr,\n          (obj: WebRPayloadPtr, chan: ChannelMain) => newRProxy(chan, obj),\n          chan\n        ) as WebRPayload;\n        return proxyReply.obj;\n      }\n    }\n  };\n}\n\n/* Proxy the `RWorker` class constructors. This allows us to create a new R\n * object on the worker thread from a given JS object.\n */\nasync function newRObject(\n  chan: ChannelMain,\n  objType: RType | RCtor,\n  shelter: ShelterID,\n  ...args: WebRData[]\n) {\n  const msg: NewRObjectMessage = {\n    type: 'newRObject',\n    data: {\n      objType,\n      args: replaceInObject<WebRData[]>(args, isRObject, (obj: RObject) => obj._payload),\n      shelter: shelter,\n    },\n  };\n  const payload = await chan.request(msg);\n  switch (payload.payloadType) {\n    case 'raw':\n      throw new WebRPayloadError('Unexpected raw payload type returned from newRObject');\n    case 'ptr':\n      return newRProxy(chan, payload);\n  }\n}\n\n/**\n * Proxy an R object.\n *\n * The proxy targets a particular R object in WebAssembly memory. Methods of the\n * relevant subclass of {@link RWorker.RObject} are proxied, enabling\n * structured manipulation of R objects from the main thread.\n * @param {ChannelMain} chan The current main thread communication channel.\n * @param {WebRPayloadPtr} payload A webR payload referencing an R object.\n * @returns {RProxy<RWorker.RObject>} An {@link RObject} corresponding to the\n * referenced R object.\n */\nexport function newRProxy(chan: ChannelMain, payload: WebRPayloadPtr): RProxy<RWorker.RObject> {\n  const proxy = new Proxy(\n    // Assume we are proxying an RFunction if the methods list contains 'exec'.\n    payload.obj.methods?.includes('exec') ? Object.assign(empty, { ...payload }) : payload,\n    {\n      get: (_: WebRPayload, prop: string | number | symbol) => {\n        if (prop === '_payload') {\n          return payload;\n        } else if (prop === Symbol.asyncIterator) {\n          return targetAsyncIterator(chan, proxy);\n        } else if (payload.obj.methods?.includes(prop.toString())) {\n          return targetMethod(chan, prop.toString(), payload);\n        }\n      },\n      apply: async (_: WebRPayload, _thisArg, args: (WebRDataRaw | RProxy<RWorker.RObject>)[]) => {\n        const res = await (newRProxy(chan, payload) as RProxy<RWorker.RFunction>).exec(...args);\n        return isRFunction(res) ? res : res.toJs();\n      },\n    }\n  ) as unknown as RProxy<RWorker.RObject>;\n  return proxy;\n}\n\n/**\n * Proxy an {@link RWorker.RObject} class.s\n * @param {ChannelMain} chan The current main thread communication channel.\n * @param {ShelterID} shelter The shelter ID to protect returned objects with.\n * @param {(RType | RCtor)} objType The R object type or class, `'object'` for\n * the generic {@link RWorker.RObject} class.\n * @returns {ProxyConstructor} A proxy to the R object subclass corresponding to\n * the given value of the `objType` argument.\n * @typeParam T The type of the {@link RWorker.RObject} class to be proxied.\n * @typeParam R The type to be returned from the proxied class constructor.\n */\nexport function newRClassProxy<T, R>(\n  chan: ChannelMain,\n  shelter: ShelterID,\n  objType: RType | RCtor\n) {\n  return new Proxy(RWorker.RObject, {\n    construct: (_, args: WebRData[]) => newRObject(chan, objType, shelter, ...args),\n    get: (_, prop: string | number | symbol) => {\n      return targetMethod(chan, prop.toString());\n    },\n  }) as unknown as ProxyConstructor<T, R>;\n}\n", "import { IN_NODE } from './compat';\nimport { WebR, WebROptions } from './webr-main';\n\nexport interface ConsoleCallbacks {\n  stdout?: (line: string) => void;\n  stderr?: (line: string) => void;\n  prompt?: (line: string) => void;\n  canvasImage?: (image: ImageBitmap) => void;\n  canvasNewPage?: () => void;\n}\n\n/**\n * Text-based Interactive Console for WebR\n *\n * A helper application to assist in creating an interactive R REPL based on\n * JavaScript callbacks.\n *\n * Callback functions ``stdout`` and ``stderr`` are called with a single line\n * of output as the first argument. The default implementation of `stdout` and\n * `stderr` writes to the console using `console.log` and `console.error`.\n *\n * R code can be sent as input by calling the ``stdin`` method with a single\n * line of textual input.\n *\n * A long running R computation can be interrupted by calling the `interrupt`\n * method.\n *\n * The ``prompt`` callback function is called when webR produces a prompt at\n * the REPL console and is therefore awaiting user input. The prompt character\n * (usually ``>`` or ``+``) is given as the first argument to the callback\n * function. The default implementation of `prompt` shows a JavaScript prompt\n * asking the user for input, and then sends the user input to `stdin`.\n *\n * The ``canvasImage`` callback function is called when webR writes plots to\n * the built-in HTML canvas graphics device.\n *\n * The ``canvasNewPage`` callback function is called when webR creates a new\n * plot.\n *\n * Once constructed, start the Console using the ``run`` method. The `run`\n * method starts an asynchronous infinite loop that waits for output from the\n * webR worker and then calls the relevant callbacks.\n */\nexport class Console {\n  /** The supporting instance of webR */\n  webR: WebR;\n  /**\n   * A HTML canvas element\n   *\n   * The canvas graphics device writes to this element by default. Undefined\n   * when HTML canvas is unsupported.\n   */\n  canvas: HTMLCanvasElement | undefined;\n  /** Called when webR outputs to ``stdout`` */\n  #stdout: (line: string) => void;\n  /** Called when webR outputs to ``stderr`` */\n  #stderr: (line: string) => void;\n  /** Called when webR prompts for input */\n  #prompt: (line: string) => void;\n  /** Called when webR writes to the HTML canvas element */\n  #canvasImage: (image: ImageBitmap) => void;\n  /** Called when webR creates a new plot */\n  #canvasNewPage: () => void;\n\n  /**\n   * @param {ConsoleCallbacks} callbacks A list of webR Console callbacks to\n   * be used for this console.\n   * @param {WebROptions} options The options to use for the new instance of\n   * webR started to support this console.\n   */\n  constructor(\n    callbacks: ConsoleCallbacks = {},\n    options: WebROptions = {\n      REnv: {\n        R_HOME: '/usr/lib/R',\n        FONTCONFIG_PATH: '/etc/fonts',\n        R_ENABLE_JIT: '0',\n      },\n    }\n  ) {\n    this.webR = new WebR(options);\n    if (!IN_NODE) {\n      this.canvas = document.createElement('canvas');\n      this.canvas.setAttribute('width', '1008');\n      this.canvas.setAttribute('height', '1008');\n    }\n    this.#stdout = callbacks.stdout || this.#defaultStdout;\n    this.#stderr = callbacks.stderr || this.#defaultStderr;\n    this.#prompt = callbacks.prompt || this.#defaultPrompt;\n    this.#canvasImage = callbacks.canvasImage || this.#defaultCanvasImage;\n    this.#canvasNewPage = callbacks.canvasNewPage || this.#defaultCanvasNewPage;\n    void this.webR.evalRVoid('options(device=webr::canvas)');\n  }\n\n  /**\n   * Write a line of input to webR's REPL through ``stdin``\n   * @param {string} input A line of input text.\n   */\n  stdin(input: string) {\n    this.webR.writeConsole(input);\n  }\n\n  /**\n   * Interrupt a long running R computation and return to the prompt\n   */\n  interrupt() {\n    this.webR.interrupt();\n  }\n\n  /**\n   * The default function called when webR outputs to ``stdout``\n   * @param {string} text The line sent to stdout by webR.\n   */\n  #defaultStdout = (text: string) => {\n    console.log(text);\n  };\n\n  /**\n   * The default function called when webR outputs to ``stderr``\n   * @param {string} text The line sent to stderr by webR.\n   */\n  #defaultStderr = (text: string) => {\n    console.error(text);\n  };\n\n  /**\n   * The default function called when webR writes out a prompt\n   * @param {string} text The text content of the prompt.\n   */\n  #defaultPrompt = (text: string) => {\n    const input = prompt(text);\n    if (input) this.stdin(`${input}\\n`);\n  };\n\n  /**\n   * The default function called when webR writes to HTML canvas\n   * @param {ImageBitmap} image An ImageBitmap containing the image data.\n   */\n  #defaultCanvasImage = (image: ImageBitmap) => {\n    if (IN_NODE) {\n      throw new Error('Plotting with HTML canvas is not yet supported under Node');\n    }\n    this.canvas!.getContext('2d')!.drawImage(image, 0, 0);\n  };\n\n  /**\n   * The default function called when webR creates a new plot\n   */\n  #defaultCanvasNewPage = () => {\n    if (IN_NODE) {\n      throw new Error('Plotting with HTML canvas is not yet supported under Node');\n    }\n    this.canvas!.getContext('2d')!.clearRect(0, 0, this.canvas!.width, this.canvas!.height);\n  };\n\n  /**\n   * Start the webR console\n   */\n  run() {\n    void this.#run();\n  }\n\n  /*\n   * Start the asynchronous infinite loop\n   *\n   * This loop waits for output from webR and dispatches callbacks based on the\n   * message received.\n   *\n   * The promise returned by this asynchronous function resolves only once the\n   * webR communication channel has closed.\n   */\n  async #run() {\n    for (; ;) {\n      const output = await this.webR.read();\n      switch (output.type) {\n        case 'stdout':\n          this.#stdout(output.data as string);\n          break;\n        case 'stderr':\n          this.#stderr(output.data as string);\n          break;\n        case 'prompt':\n          this.#prompt(output.data as string);\n          break;\n        case 'canvas':\n          if (output.data.event === 'canvasImage') {\n            this.#canvasImage(output.data.image as ImageBitmap);\n          } else if (output.data.event === 'canvasNewPage') {\n            this.#canvasNewPage();\n          }\n          break;\n        case 'closed':\n          return;\n        default:\n          console.warn(`Unhandled output type for webR Console: ${output.type}.`);\n      }\n    }\n  }\n}\n"],
  "mappings": "2tCAEaA,EAAA,WAAa,WAK1B,SAAgBC,GAAUC,EAAgBC,EAAgBC,EAAa,CACrE,IAAMC,EAAOD,EAAQ,WACfE,EAAMF,EACZF,EAAK,UAAUC,EAAQE,CAAI,EAC3BH,EAAK,UAAUC,EAAS,EAAGG,CAAG,CAChC,CALAN,EAAA,UAAAC,GAOA,SAAgBM,GAASL,EAAgBC,EAAgBC,EAAa,CACpE,IAAMC,EAAO,KAAK,MAAMD,EAAQ,UAAa,EACvCE,EAAMF,EACZF,EAAK,UAAUC,EAAQE,CAAI,EAC3BH,EAAK,UAAUC,EAAS,EAAGG,CAAG,CAChC,CALAN,EAAA,SAAAO,GAOA,SAAgBC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,EAAE,KAAOJ,GAAUjC,EAAA,KAAKT,GAAO4C,EAAOE,CAAC,EAAE,IAAsB,GAI3E,MAAO,CAAE,OAAAH,EAAQ,OAAAC,EAAQ,OAAAC,CAAO,CAClC,CACF,CACF,CACF,EA7JEP,EAAA,YACAtC,EAAA,YACAC,GAAA,YA6JF,SAASoB,GAAgBmB,EAAmB,CAC1C,OAAO,IAAI,MAAMD,GAAS,CACxB,UAAW,SAAY,CACrB,IAAMQ,EAAM,IAAIR,GAAQC,CAAI,EAC5B,aAAMO,EAAI,KAAK,EACRA,CACT,CACF,CAAC,CAGH",
  "names": ["exports", "setUint64", "view", "offset", "value", "high", "low", "setInt64", "getInt64", "getUint64", "int_1", "TEXT_ENCODING_AVAILABLE", "_a", "utf8Count", "str", "strLength", "byteLength", "pos", "value", "extra", "exports", "utf8EncodeJs", "output", "outputOffset", "offset", "sharedTextEncoder", "_b", "utf8EncodeTEencode", "utf8EncodeTEencodeInto", "CHUNK_SIZE", "utf8DecodeJs", "bytes", "inputOffset", "end", "units", "result", "byte1", "byte2", "byte3", "byte4", "unit", "sharedTextDecoder", "_c", "utf8DecodeTD", "stringBytes", "ExtData", "type", "data", "exports", "DecodeError", "message", "proto", "exports", "DecodeError_1", "int_1", "exports", "TIMESTAMP32_MAX_SEC", "TIMESTAMP64_MAX_SEC", "encodeTimeSpecToTimestamp", "sec", "nsec", "rv", "secHigh", "secLow", "view", "encodeDateToTimeSpec", "date", "msec", "nsecInSec", "encodeTimestampExtension", "object", "timeSpec", "decodeTimestampToTimeSpec", "data", "nsec30AndSecHigh2", "secLow32", "decodeTimestampExtension", "ExtData_1", "timestamp_1", "ExtensionCodec", "type", "encode", "decode", "index", "object", "context", "i", "encodeExt", "data", "decodeExt", "exports", "ensureUint8Array", "buffer", "exports", "createDataView", "bufferView", "utf8_1", "ExtensionCodec_1", "int_1", "typedArrays_1", "exports", "Encoder", "extensionCodec", "context", "maxDepth", "initialBufferSize", "sortKeys", "forceFloat32", "ignoreUndefined", "forceIntegerToFloat", "object", "depth", "sizeToWrite", "requiredSize", "newSize", "newBuffer", "newBytes", "newView", "byteLength", "ext", "size", "bytes", "item", "keys", "count", "key", "value", "values", "Encoder_1", "defaultEncodeOptions", "encode", "value", "options", "exports", "prettyByte", "byte", "exports", "utf8_1", "DEFAULT_MAX_KEY_LENGTH", "DEFAULT_MAX_LENGTH_PER_KEY", "CachedKeyDecoder", "maxKeyLength", "maxLengthPerKey", "i", "byteLength", "bytes", "inputOffset", "records", "FIND_CHUNK", "record", "recordBytes", "j", "value", "cachedValue", "str", "slicedCopyOfBytes", "exports", "prettyByte_1", "ExtensionCodec_1", "int_1", "utf8_1", "typedArrays_1", "CachedKeyDecoder_1", "DecodeError_1", "isValidMapKeyType", "key", "keyType", "HEAD_BYTE_REQUIRED", "EMPTY_VIEW", "EMPTY_BYTES", "exports", "e", "MORE_DATA", "sharedCachedKeyDecoder", "Decoder", "extensionCodec", "context", "maxStrLength", "maxBinLength", "maxArrayLength", "maxMapLength", "maxExtLength", "keyDecoder", "buffer", "remainingData", "newData", "newBuffer", "size", "posToShow", "view", "pos", "object", "stream", "decoded", "headByte", "totalPos", "isArray", "isArrayHeaderRequired", "arrayItemsLeft", "DECODE", "byteLength", "stack", "state", "headerOffset", "offset", "_a", "headOffset", "extType", "data", "value", "Decoder_1", "exports", "decode", "buffer", "options", "decodeMulti", "isAsyncIterable", "object", "exports", "assertNonNull", "value", "asyncIterableFromStream", "stream", "reader", "done", "ensureAsyncIterable", "streamLike", "Decoder_1", "stream_1", "decode_1", "decodeAsync", "streamLike", "options", "stream", "exports", "decodeArrayStream", "decodeMultiStream", "decodeStream", "encode_1", "exports", "decode_1", "decodeAsync_1", "Decoder_1", "DecodeError_1", "Encoder_1", "ExtensionCodec_1", "ExtData_1", "timestamp_1", "webr_main_exports", "__export", "ChannelType", "Console", "Shelter", "WebR", "WebRChannelError", "WebRError", "WebRPayloadError", "WebRWorkerError", "isRCall", "isRCharacter", "isRComplex", "isRDouble", "isREnvironment", "isRFunction", "isRInteger", "isRList", "isRLogical", "isRNull", "isRObject", "isRPairlist", "isRRaw", "isRSymbol", "isUUID", "__toCommonJS", "WebRError", "msg", "WebRWorkerError", "WebRChannelError", "WebRPayloadError", "IN_NODE", "loadScript", "url", "resolve", "reject", "script", "__toESM", "nodePathMod", "WebRError", "Module", "dictEmFree", "dict", "key", "RTypeMap", "isWebRDataJs", "value", "isComplex", "protect", "x", "Module", "handlePtr", "protectInc", "prot", "protectWithIndex", "pLoc", "unprotectIndex", "index", "reprotect", "unprotect", "n", "envPoke", "env", "sym", "value", "parseEvalBare", "code", "strings", "envObj", "REnvironment", "out", "RObject", "dictEmFree", "safeEval", "call", "env", "Module", "handlePtr", "transferCache", "transfer", "obj", "transfers", "isUUID", "x", "UUID_LENGTH", "generateUUID", "result", "randomSegment", "pad", "handlePtr", "x", "isRObject", "assertRType", "obj", "type", "Module", "RTypeMap", "newObjectFromData", "obj", "isWebRDataJs", "getRWorkerClass", "RNull", "RLogical", "RDouble", "RCharacter", "isComplex", "RComplex", "RRaw", "newObjectFromArray", "RDataFrame", "arr", "prot", "v", "isRObject", "_arr", "isConsistent", "a", "k", "isAtomic", "isAtomicType", "isRVectorAtomic", "call", "RCall", "RSymbol", "protectInc", "unprotect", "RObjectBase", "ptr", "typeNumber", "Module", "RTypeMap", "typeName", "_slice", "slice_fn", "_RObject", "data", "__privateAdd", "type", "prop", "objs", "parseEvalBare", "result", "protect", "RPairlist", "classCall", "values", "namesObj", "names", "name", "options", "depth", "__privateMethod", "path", "index", "protectWithIndex", "getter", "out", "reprotect", "unprotectIndex", "value", "idx", "valueObj", "assign", "safeEval", "props", "cur", "p", "i", "RObject", "op", "x", "assertRType", "RString", "val", "toWebRData", "list", "next", "allowDuplicateKey", "allowEmptyKey", "entries", "keys", "u", "namesArray", "hasNames", "symbol", "RList", "_names", "classes", "entry", "j", "hasArrays", "_values", "isConsistentLength", "listObj", "asDataFrame", "RFunction", "args", "REnvironment", "nProt", "sym", "vObj", "envPoke", "all", "sorted", "symbols", "RVectorAtomic", "kind", "newSetter", "ret", "elt", "m", "_newSetter", "_RLogical", "__privateGet", "naLogical", "_RInteger", "RInteger", "naInteger", "_RDouble", "naDouble", "_RComplex", "_RCharacter", "_RRaw", "jsObj", "typeClasses", "atomicRTypes", "promiseHandles", "out", "promise", "resolve", "reject", "sleep", "ms", "replaceInObject", "obj", "test", "replacer", "replacerArgs", "isImageBitmap", "v", "RObjectBase", "k", "newCrossOriginWorker", "url", "cb", "req", "worker", "isCrossOrigin", "urlString", "IN_NODE", "url1", "url2", "value", "import_msgpack", "encoder", "syncResponse", "endpoint", "data", "response", "taskId", "sizeBuffer", "dataBuffer", "signalBuffer", "bytes", "fits", "uuid", "dataPromise", "requestResponseMessage", "signalRequester", "e", "ep", "id", "generateUUID", "resolve", "IN_NODE", "message", "l", "ev", "index", "sleepTime", "sleep", "_promises", "_resolvers", "_add", "add_fn", "AsyncQueue", "__privateAdd", "__privateSet", "t", "__privateGet", "__privateMethod", "resolve", "newRequest", "msg", "transferables", "newRequestResponseMessage", "generateUUID", "newResponse", "uuid", "resp", "transfer", "newSyncRequest", "data", "webRPayloadAsError", "payload", "WebRWorkerError", "isWebRPayload", "value", "isWebRPayloadPtr", "_parked", "_closed", "ChannelMain", "AsyncQueue", "__privateAdd", "msg", "__privateGet", "WebRChannelError", "transferables", "req", "newRequest", "resolve", "reject", "promise", "promiseHandles", "__privateSet", "uuid", "handles", "payload", "webRPayloadAsError", "import_msgpack", "decoder", "_scheduled", "_resolved", "_result", "_exception", "_syncGen", "SyncTask", "endpoint", "msg", "transfers", "__privateAdd", "_Syncifier", "__privateSet", "__privateGet", "done", "value", "sizeBuffer", "signalBuffer", "taskId", "dataBuffer", "acquireDataBuffer", "UUID_LENGTH", "syncMsg", "newSyncRequest", "id", "releaseDataBuffer", "size", "task", "interruptBuffer", "handleInterrupt", "flag", "i", "bit", "result", "wokenTaskId", "wokenTask", "dataBuffers", "powerof2", "buffer", "setInterruptHandler", "handler", "setInterruptBuffer", "IN_NODE", "_interruptBuffer", "_handleEventsFromWorker", "handleEventsFromWorker_fn", "_onMessageFromWorker", "SharedBufferChannelMain", "ChannelMain", "config", "__privateAdd", "worker", "message", "__privateSet", "msg", "payload", "reqData", "response", "syncResponse", "WebRChannelError", "promiseHandles", "initWorker", "__privateMethod", "ChannelType", "isCrossOrigin", "newCrossOriginWorker", "__privateGet", "ev", "WebRWorkerError", "_ep", "_dispatch", "_interrupt", "SharedBufferChannelWorker", "setInterruptBuffer", "setInterruptHandler", "transfer", "SyncTask", "Module", "args", "e", "interrupt", "dispatch", "import_msgpack", "IN_NODE", "_syncMessageCache", "_registration", "_interrupted", "_registerServiceWorker", "registerServiceWorker_fn", "_onMessageFromServiceWorker", "onMessageFromServiceWorker_fn", "_handleEventsFromWorker", "handleEventsFromWorker_fn", "_onMessageFromWorker", "ServiceWorkerChannelMain", "ChannelMain", "config", "__privateAdd", "worker", "message", "request", "__privateGet", "WebRChannelError", "promiseHandles", "initWorker", "__privateMethod", "clientId", "msg", "ChannelType", "isCrossOrigin", "newCrossOriginWorker", "_a", "__privateSet", "url", "resolve", "listener", "event", "uuid", "response", "newResponse", "ev", "WebRWorkerError", "_ep", "_mainThreadId", "_location", "_lastInterruptReq", "_dispatch", "_interrupt", "ServiceWorkerChannelWorker", "data", "transfer", "newRequest", "retryCount", "xhr", "fetchReqBody", "e", "Module", "args", "interrupt", "dispatch", "IN_NODE", "_worker", "_handleEventsFromWorker", "handleEventsFromWorker_fn", "_onMessageFromWorker", "PostMessageChannelMain", "ChannelMain", "config", "__privateAdd", "worker", "message", "msg", "payload", "input", "__privateGet", "response", "newResponse", "WebRChannelError", "promiseHandles", "initWorker", "__privateSet", "__privateMethod", "ChannelType", "isCrossOrigin", "newCrossOriginWorker", "ev", "WebRWorkerError", "_ep", "_parked", "_dispatch", "_promptDepth", "_asyncREPL", "PostMessageChannelWorker", "str", "e", "transfer", "__privateWrapper", "_args", "args", "argc", "argv", "arg", "idx", "argvPtr", "argPtr", "dispatch", "transferables", "req", "newRequest", "resolve", "prom", "uuid", "ChannelType", "newChannelMain", "data", "SharedBufferChannelMain", "ServiceWorkerChannelMain", "PostMessageChannelMain", "BASE_URL", "IN_NODE", "PKG_BASE_URL", "WEBR_VERSION", "isRObject", "value", "isWebRPayloadPtr", "isRNull", "isRSymbol", "isRPairlist", "isREnvironment", "isRLogical", "isRInteger", "isRDouble", "isRComplex", "isRCharacter", "isRList", "isRRaw", "isRCall", "isRFunction", "_a", "empty", "targetAsyncIterator", "chan", "proxy", "msg", "reply", "WebRError", "i", "targetMethod", "prop", "payload", "_args", "args", "arg", "isRObject", "replaceInObject", "obj", "newRProxy", "isWebRPayloadPtr", "newRObject", "objType", "shelter", "WebRPayloadError", "_a", "_", "_thisArg", "res", "isRFunction", "newRClassProxy", "RObject", "_stdout", "_stderr", "_prompt", "_canvasImage", "_canvasNewPage", "_defaultStdout", "_defaultStderr", "_defaultPrompt", "_defaultCanvasImage", "_defaultCanvasNewPage", "_run", "run_fn", "Console", "callbacks", "options", "__privateAdd", "text", "input", "image", "IN_NODE", "WebR", "__privateSet", "__privateGet", "__privateMethod", "output", "defaultEnv", "WEBR_VERSION", "defaultOptions", "BASE_URL", "PKG_BASE_URL", "ChannelType", "_chan", "_initialised", "_handleSystemMessages", "handleSystemMessages_fn", "WebR", "options", "__privateAdd", "path", "msg", "__privateGet", "type", "mountpoint", "promises", "item", "data", "pkg", "populate", "flags", "config", "__privateSet", "newChannelMain", "newShelterProxy", "__privateMethod", "input", "packages", "op", "x", "code", "outputType", "opts", "replaceInObject", "isRObject", "obj", "payload", "WebRPayloadError", "ptr", "args", "WebRError", "_id", "Shelter", "chan", "newRClassProxy", "newRProxy", "result", "output", "images", "i", "out"]
}
