Skip to content

fix(runtime,codegen): expose the Web Streams globals; resolve instanceof against a built-in held in a variable#6335

Open
proggeramlug wants to merge 2 commits into
PerryTS:mainfrom
proggeramlug:fix/webstream-globals-and-instanceof
Open

fix(runtime,codegen): expose the Web Streams globals; resolve instanceof against a built-in held in a variable#6335
proggeramlug wants to merge 2 commits into
PerryTS:mainfrom
proggeramlug:fix/webstream-globals-and-instanceof

Conversation

@proggeramlug

@proggeramlug proggeramlug commented Jul 13, 2026

Copy link
Copy Markdown
Contributor

Two gaps that both surface the moment a bundler minifies.

1. The Web Streams globals were missing

ReadableStream / WritableStream / TransformStream were absent from globalThis. Perry implements all three — codegen lowers new ReadableStream(…) and x instanceof ReadableStream, and each has a class id — but the NAMES were never registered, so a bare ReadableStream identifier resolved to nothing:

typeof ReadableStream        // perry: "undefined"   node: "function"
"ReadableStream" in globalThis // perry: false       node: true

Libraries feature-detect exactly that (typeof ReadableStream !== "undefined" ? … : …) when deciding how to consume a fetch() body, so they silently took the wrong branch.

2. instanceof failed for a built-in held in a variable

js_instanceof_dynamic returned false for every built-in reached through a variable rather than its bare name:

x instanceof Response        // true
const R = Response;
x instanceof R               // perry: false        node: true

Minifiers alias constructors as a matter of course, so in a bundle this was broadly broken. The dynamic path only understood user class objects; a built-in constructor is a ClosureHeader thunk, which it did not map back to a class id. It now recovers the id from the thunk's recorded name (ReadableStream / WritableStream / TransformStream / Response / Request / Headers / Blob) and defers to js_instanceof.

Validation

node-vs-perry differential — typeof and in globalThis for the three stream constructors, instanceof against both the bare name and an alias, and Response/Headers/Blob through aliases — byte-identical to Node, where 9 of the 10 assertions previously disagreed.

perry-runtime 1264 passed / 0 failed; perry-codegen 159 passed / 0 failed.

Summary by CodeRabbit

  • New Features
    • Added global support for the Web Streams constructors: ReadableStream, WritableStream, and TransformStream.
    • These constructors are now available for feature detection through globalThis.
    • Improved instanceof behavior when built-in constructors such as Web Streams, Request, Response, Headers, and Blob are stored in variables.

…eof against a built-in held in a variable

Two gaps that both surface the moment a bundler minifies.

1. `ReadableStream` / `WritableStream` / `TransformStream` were missing from
   `globalThis`. Perry implements all three — codegen lowers `new ReadableStream(…)`
   and `x instanceof ReadableStream`, and each has a class id — but the NAMES were
   never registered, so a bare `ReadableStream` identifier resolved to nothing:
   `typeof ReadableStream === "undefined"` and `"ReadableStream" in globalThis` was
   false, where Node exposes all three as functions. Libraries feature-detect exactly
   that (`typeof ReadableStream !== "undefined" ? … : …`) when deciding how to consume
   a `fetch()` body, so they silently took the wrong branch.

2. `js_instanceof_dynamic` returned `false` for every built-in reached through a
   *variable* rather than its bare name. `x instanceof Response` worked; the
   equivalent after `const R = Response` did not — and minifiers alias constructors
   as a matter of course, so in a bundle this was broadly broken. The dynamic path
   only understood user class objects; a built-in constructor is a `ClosureHeader`
   thunk, which it did not map back to a class id. It now recovers the id from the
   thunk's recorded name (ReadableStream / WritableStream / TransformStream /
   Response / Request / Headers / Blob) and defers to `js_instanceof`.

Validation: node-vs-perry differential — `typeof` and `in globalThis` for the three
stream constructors, `instanceof` against both the bare name and an alias, and
`Response`/`Headers`/`Blob` through aliases — byte-identical to Node, where 9 of the
10 assertions previously disagreed. perry-runtime 1264 passed / 0 failed;
perry-codegen 159 passed / 0 failed.
@coderabbitai

coderabbitai Bot commented Jul 13, 2026

Copy link
Copy Markdown

Review Change Stack

Warning

Review limit reached

@proggeramlug, you've reached your PR review limit, so we couldn't start this review.

Next review available in: 4 minutes

Enable usage-based reviews in Billing to review now. Otherwise, wait until the next included review is available.
You're only billed for reviews past your plan's rate limits ($0.25/file).

How can I continue?

After more reviews become available, a review can be triggered using the @coderabbitai review command as a PR comment. Alternatively, push new commits to this PR.

To avoid repeated limits, reduce automatic review volume by pausing incremental auto-reviews earlier, using label-based review opt-in, excluding WIP or generated PR titles, or requesting reviews manually when the PR is ready. If your team needs uninterrupted high-volume reviews, an organization admin can enable usage-based reviews.

How do review limits work?

CodeRabbit enforces per-developer PR review limits for each organization. Most developers receive the normal plan review availability.

For paid Pro and Pro+ PR reviews, CodeRabbit uses adaptive limits for sustained high-volume activity. When a developer's recent PR review activity reaches the 95th percentile or higher among CodeRabbit users, additional reviews become available more gradually as earlier reviews age out of the rolling window.

Please refer docs for additional details.

Review details
⚙️ Run configuration

Configuration used: defaults

Review profile: CHILL

Plan: Pro Plus

Run ID: db5704c0-db62-40c2-be8b-1ab6dfe4dbfc

📥 Commits

Reviewing files that changed from the base of the PR and between e377222 and 4393bc9.

📒 Files selected for processing (1)
  • crates/perry-runtime/src/object/instanceof.rs
📝 Walkthrough

Walkthrough

Web Streams constructors are added to Perry’s globalThis builtin name and constructor tables. Dynamic instanceof resolution now recognizes closure-backed builtin constructors, maps supported names to runtime class IDs, and delegates matching to the existing js_instanceof implementation.

Changes

Web Streams builtin support

Layer / File(s) Summary
Register Web Streams constructors
crates/perry-codegen/src/expr/helpers.rs, crates/perry-runtime/src/object/global_this_tables.rs
Adds ReadableStream, WritableStream, and TransformStream to codegen globalThis builtin recognition and runtime constructor registration.
Resolve builtin constructor instanceof
crates/perry-runtime/src/object/instanceof.rs
Maps supported closure-backed builtin constructor names to reserved class IDs and uses those IDs in dynamic instanceof evaluation.

Estimated code review effort: 3 (Moderate) | ~20 minutes

Possibly related PRs

  • PerryTS/perry#5667: Both update the dynamic instanceof resolution path and may affect ordering with Symbol.hasInstance handling.
  • PerryTS/perry#5942: Both add builtin constructor handling to dynamic instanceof resolution.
  • PerryTS/perry#6205: Both modify constructor handling in the js_instanceof_dynamic path.
🚥 Pre-merge checks | ✅ 5
✅ Passed checks (5 passed)
Check name Status Explanation
Title check ✅ Passed The title clearly summarizes the two main fixes: exposing Web Streams globals and fixing instanceof for built-in constructors held in variables.
Description check ✅ Passed The description covers the summary, concrete changes, and validation, but it omits an explicit Related issue entry and uses prose instead of the template's test-plan checklist.
Docstring Coverage ✅ Passed No functions found in the changed files to evaluate docstring coverage. Skipping docstring coverage check.
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.
✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 3

🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Inline comments:
In `@crates/perry-runtime/src/object/instanceof.rs`:
- Line 110: Update the pointer extraction in the instanceof logic to use the
canonical js_nanbox_get_pointer helper instead of JSValue::as_pointer when
decoding the NaN-boxed type_ref value, preserving the existing ClosureHeader
pointer handling.
- Around line 119-120: Update the string conversion flow around
str_bytes_from_jsvalue to check ptr.is_null() before calling
slice::from_raw_parts, returning None for a null pointer (including the
zero-length case); preserve the existing UTF-8 validation for non-null pointers.
- Around line 117-129: Update the constructor-to-class-ID logic around the
closure name lookup to resolve the constructor by identity against the current
globalThis builtins, rather than trusting the closure’s `.name` value. Only map
`ReadableStream`, `WritableStream`, `TransformStream`, `Response`, `Request`,
`Headers`, and `Blob` when the constructor is the corresponding native builtin;
otherwise return None, preserving the existing class-ID mappings.
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: defaults

Review profile: CHILL

Plan: Pro Plus

Run ID: 1f58df21-8a09-42c1-97ea-cd7ca040f57e

📥 Commits

Reviewing files that changed from the base of the PR and between 2c32585 and e377222.

📒 Files selected for processing (3)
  • crates/perry-codegen/src/expr/helpers.rs
  • crates/perry-runtime/src/object/global_this_tables.rs
  • crates/perry-runtime/src/object/instanceof.rs

if !jv.is_pointer() {
return None;
}
let closure = jv.as_pointer::<crate::closure::ClosureHeader>();

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🎯 Functional Correctness | 🟠 Major | ⚡ Quick win

Use the canonical NaN-box pointer extractor.

type_ref is a NaN-boxed value, but Line [110] uses JSValue::as_pointer. Use js_nanbox_get_pointer for pointer payload extraction so this path follows the runtime’s canonical NaN-box decoding contract.

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@crates/perry-runtime/src/object/instanceof.rs` at line 110, Update the
pointer extraction in the instanceof logic to use the canonical
js_nanbox_get_pointer helper instead of JSValue::as_pointer when decoding the
NaN-boxed type_ref value, preserving the existing ClosureHeader pointer
handling.

Source: Coding guidelines

Comment on lines +117 to +129
let name_value = crate::closure::closure_get_dynamic_prop(closure as usize, "name");
let mut scratch = [0u8; crate::value::SHORT_STRING_MAX_LEN];
let (ptr, len) = crate::string::str_bytes_from_jsvalue(name_value, &mut scratch)?;
let name = std::str::from_utf8(unsafe { std::slice::from_raw_parts(ptr, len as usize) }).ok()?;
Some(match name {
"ReadableStream" => 0xFFFF_0060,
"WritableStream" => 0xFFFF_0061,
"TransformStream" => 0xFFFF_0062,
"Response" => 0xFFFF_0028,
"Request" => 0xFFFF_0029,
"Headers" => 0xFFFF_002A,
"Blob" => 0xFFFF_0026,
_ => return None,

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🎯 Functional Correctness | 🟠 Major | ⚡ Quick win

Resolve constructor identity, not only .name.

This treats any closure named Response, ReadableStream, etc. as the native builtin. A user-defined function Response(){} can therefore make actualResponse instanceof Fake return true despite an unrelated prototype. Resolve the constructor by identity against the current globalThis builtin (or an unforgeable builtin marker), then map it to the class ID.

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@crates/perry-runtime/src/object/instanceof.rs` around lines 117 - 129, Update
the constructor-to-class-ID logic around the closure name lookup to resolve the
constructor by identity against the current globalThis builtins, rather than
trusting the closure’s `.name` value. Only map `ReadableStream`,
`WritableStream`, `TransformStream`, `Response`, `Request`, `Headers`, and
`Blob` when the constructor is the corresponding native builtin; otherwise
return None, preserving the existing class-ID mappings.

Comment on lines +119 to +120
let (ptr, len) = crate::string::str_bytes_from_jsvalue(name_value, &mut scratch)?;
let name = std::str::from_utf8(unsafe { std::slice::from_raw_parts(ptr, len as usize) }).ok()?;

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🩺 Stability & Availability | 🟡 Minor | ⚡ Quick win

Guard the nullable string pointer before from_raw_parts.

str_bytes_from_jsvalue explicitly permits Some((null, 0)); Line [120] then creates a slice from that null pointer, which is undefined behavior even for zero length. Return None when ptr.is_null() or change the helper contract.

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@crates/perry-runtime/src/object/instanceof.rs` around lines 119 - 120, Update
the string conversion flow around str_bytes_from_jsvalue to check ptr.is_null()
before calling slice::from_raw_parts, returning None for a null pointer
(including the zero-length case); preserve the existing UTF-8 validation for
non-null pointers.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant