← Back to Pull requests

fix(instrumentations): instrument loaded hooked built-ins when dd-trace is bundled #10915

Merged
pabloerhard merged 4 files (222 lines) on Oct 28, 2026 11:15 UTC
View on GitHub
pabloerhard pabloerhard commented on Oct 23, 2026 23:14 UTC
Author

What does this PR do?


When dd-trace is bundled inside the application (bundler-register.js detects a bundled context via !(module instanceof Module)), it now re-requires every enabled hooked Node.js built-in that is already loaded (per process.moduleLoadList; all hooked built-ins if that list is unavailable), instead of only http/https. Disabled instrumentations and serverless exclusions are skipped, Module.syncBuiltinESMExports() runs afterwards so ESM named imports see the patched functions, and failures are logged instead of thrown.

Motivation


In a bundle, built-ins loaded before dd-trace installs its require hooks are cached by the bundler and never pass through ritm. Only http/https were re-required, so built-ins such as dns or fs stayed uninstrumented.

Additional Notes


  • Unit specs cover bundled vs unbundled processes, the loaded-only filter, the moduleLoadList fallback, disabled/serverless filtering, sync running after every re-require, no sync when nothing was patched, and logged require/sync failures. The bundled cases run the real file under its own filename so coverage is attributed to it.

  • End-to-end coverage (esbuild, webpack and Turbopack with dd-trace bundled, CJS and ESM) is in a stacked follow-up PR to keep this review focused on the production change.

  • Checks run locally: bundler-register.spec.js (21 passing) and eslint on the changed files.
  • Diff: 222 lines (+211 / -11) across 4 files Reviewer: rochdev Review duration: 6481m
    All Vouch review confidence checks passed
    Residual risk 0.06 = Change Risk (0.40) × (1 − Review Confidence (0.86)). Review depth and reviewer attention state are adequate.
    Model 1 · Change Risk (XGBoost)
    Score: 0.40 · 222 lines diff across 4 files
    0.40
    Model 2 · Review Depth (DistilBERT)
    Depth Score: 0.80 · 5 substantive comment(s)
    0.80
    Model 3 · Review Timing & Attention
    Session adequacy: 100% · Reviewer familiarity: 50%
    85%
    Bedrock Claude 3 · Risk Narration
    (disconnected)
    Groq
    Groq Risk Narration
    AWS Bedrock is currently disconnected. Generate high-confidence PR triage narration on-demand using Groq.
    Model 1 · Change Risk Attribution
    SHAP Weights
    Diff Size diff_size
    0.323
    Real PR Conversation Timeline
    14 items
    dd-octo-sts[bot] dd-octo-sts[bot] commented on Oct 23, 2026 23:15 UTC
    Bot

    Overall package size

    Self size: 9.71 MB
    Deduped: 10.45 MB
    No deduping: 10.45 MB

    <details><summary>Dependency sizes</summary>
    | name | version | self size | total size |
    |------|---------|-----------|------------|
    | import-in-the-middle | 3.5.1 | 127.66 kB | 528.28 kB |
    | opentracing | 0.14.7 | 194.81 kB | 194.81 kB |
    | dc-polyfill | 0.1.11 | 25.74 kB | 25.74 kB |

    </details>

    <sub>🤖 This report was automatically generated by heaviest-objects-in-the-universe<sub>

    datadog-prod-us1-5[bot] datadog-prod-us1-5[bot] commented on Oct 23, 2026 23:16 UTC
    Bot

    <a target='_blank' href='https://app.datadoghq.com/ci/pipeline-executions?query=ci_level%3Ajob+%40git.commit.sha%3A96c414c0484f34a60dd4a484b5ab727214602eab&referrer=pr-comment&start=1793114878000'><picture><source media="(prefers-color-scheme: dark)" srcset="https://static.datadoghq.com/static/images/pr_comments/software_delivery/badges_header/pipelines-ok.svg"/><img src="https://static.datadoghq.com/static/images/pr_comments/software_delivery/badges_header/pipelines-ok-light.svg" alt="Pipelines" align="center" /></picture></a> &nbsp;<a target='_blank' href='https://app.datadoghq.com/ci/test/runs?query=test_level%3Atest+%40git.commit.sha%3A93672729d9352820f63113595cc90dfac4d2ae5c&referrer=pr-comment&start=1793114878000'><picture><source media="(prefers-color-scheme: dark)" srcset="https://static.datadoghq.com/static/images/pr_comments/software_delivery/badges_header/tests-ok.svg"/><img src="https://static.datadoghq.com/static/images/pr_comments/software_delivery/badges_header/tests-ok-light.svg" alt="Tests" align="center" /></picture></a>

    <details><summary><b>🎉 All green!</b></summary>

    🧪 All tests passed
    ❄️ No new flaky tests detected
    </details>

    🔄 Datadog retried 3 tests - 3 passed on retry <a href="https://app.datadoghq.com/ci/test/runs?query=test_level%3Atest+%40git.commit.sha%3A93672729d9352820f63113595cc90dfac4d2ae5c+%40test.is_retry%3Atrue+AND+%28%40test.retry_reason%3Aauto_test_retry+OR+%28-%40test.retry_reason%3A%2A+AND+-%40test.is_new%3Atrue%29%29&referrer=pr-comment" title="View in Datadog"><img src="https://static.datadoghq.com/static/images/pr_comments/software_delivery/datadog_icon.svg" alt="View in Datadog" align="center" /></a>

    🎯 Code Coverage (<a target='_blank' href='https://app.datadoghq.com/ci/code-coverage/github.com%2Fdatadog%2Fdd-trace-js/pull-requests/10915'>details</a>)<br>• <strong><span title="Percentage of modified executable lines covered by tests in this PR">Patch Coverage</span></strong>: 100.00%<br>• <strong><span title="Percentage of all executable lines covered by tests in the entire codebase">Overall Coverage</span></strong>: 98.37% <span title="Change in overall coverage compared to the base branch">(-0.05%)</span><br>

    <sub>
    This comment will be updated automatically if new data arrives. <br />
    🔗 Commit SHA: 96c414c | <a href="https://docs.datadoghq.com/integrations/guide/source-code-integration/#pr-comments">Docs</a> | <a href="https://app.datadoghq.com/ci/pull-request/Z2l0aHViLmNvbS9kYXRhZG9nL2RkLXRyYWNlLWpzLzEwOTE1?referrer=pr-comment">View more details</a> | Give us <a href="https://dd.enterprise.slack.com/archives/C07E3U2QRMM">feedback</a>!
    </sub>

    codecov[bot] codecov[bot] commented on Oct 23, 2026 23:23 UTC
    Bot

    Codecov Report


    :white_check_mark: All modified and coverable lines are covered by tests.
    :white_check_mark: Project coverage is 98.96%. Comparing base (9e0c95f) to head (96c414c).
    :warning: Report is 25 commits behind head on master.

    <details><summary>Additional details and impacted files</summary>

    @@           Coverage Diff            @@
    ##           master   #10915    +/-   ##
    ========================================
      Coverage   98.96%   98.96%            
    ========================================
      Files        1069     1069            
      Lines      175303   175667   +364     
      Branches       72       72            
    ========================================
    + Hits       173485   173852   +367     
    + Misses       1817     1814     -3     
      Partials        1        1            
    

    | Flag | Coverage Δ | |
    |---|---|---|
    | ai-guard | 63.62% <47.22%> (-0.05%) | :arrow_down: |
    | apm-capabilities | 54.76% <47.22%> (-0.01%) | :arrow_down: |
    | apm-integrations | 80.89% <47.22%> (-0.02%) | :arrow_down: |
    | appsec | 57.27% <47.22%> (-0.01%) | :arrow_down: |
    | debugger | 70.85% <47.22%> (-0.04%) | :arrow_down: |
    | instrumentation | 55.44% <100.00%> (+0.03%) | :arrow_up: |
    | llmobs | 81.35% <47.22%> (-0.06%) | :arrow_down: |
    | master-coverage | 98.96% <100.00%> (?) | |
    | openfeature | 67.34% <47.22%> (-0.03%) | :arrow_down: |
    | platform | 68.39% <47.22%> (-0.01%) | :arrow_down: |
    | profiling | 65.86% <47.22%> (-0.04%) | :arrow_down: |
    | serverless | 64.99% <47.22%> (+0.07%) | :arrow_up: |
    | test-optimization | 82.01% <47.22%> (-0.02%) | :arrow_down: |

    Flags with carried forward coverage won't be shown. Click here to find out more.
    </details>

    :umbrella: View full report in Codecov by Harness.
    :loudspeaker: Have feedback on the report? Share it here.
    <details><summary> :rocket: New features to boost your workflow: </summary>

  • :snowflake: Test Analytics: Detect flaky tests, report on failures, and find test suite problems.

  • :package: JS Bundle Analysis: Save yourself from yourself by tracking and limiting bundle sizes in JS merges.

  • </details>

    pr-commenter[bot] pr-commenter[bot] commented on Oct 23, 2026 23:31 UTC
    Bot

    Benchmarks

    Benchmark execution time: 2026-10-27 16:17:19

    Comparing candidate commit 96c414c0484f34a60dd4a484b5ab727214602eab in PR branch pabloerhard/instrument-loaded-hooked-built-ins-when--8344dc2f with baseline commit 9e0c95fd448f7a6ede4a88185b655ce3fbccaf46 in branch master.

    📊 Benchmarking dashboard

    Found 0 performance improvements and 0 performance regressions! Performance is the same for 2451 metrics, 6 unstable metrics.

    <details>
    <summary><h3>Explanation</h3></summary>

    This is an A/B test comparing a candidate commit's performance against that of a baseline commit. Performance changes are noted in the tables below as:

    🟩 = significantly better candidate vs. baseline
    🟥 = significantly worse candidate vs. baseline

    We compute a confidence interval (CI) over the relative difference of means between metrics from the candidate and baseline commits, considering the baseline as the reference.

    If the CI is entirely outside the configured SIGNIFICANT_IMPACT_THRESHOLD (or the deprecated UNCONFIDENCE_THRESHOLD), the change is considered significant.

    Feel free to reach out to #apm-benchmarking-platform on Slack if you have any questions.

    <details>
    <summary><h4>More details about the CI and significant changes</h4></summary>

    You can imagine this CI as a range of values that is likely to contain the true difference of means between the candidate and baseline commits.

    CIs of the difference of means are often centered around 0%, because often changes are not that big:

    ---------------------------------(------|---^--------)-------------------------------->
                                  -0.6%    0%  0.3%     +1.2%
                                     |          |        |
             lower bound of the CI --'          |        |
    sample mean (center of the CI) -------------'        |
             upper bound of the CI ----------------------'
    

    As described above, a change is considered significant if the CI is entirely outside the configured SIGNIFICANT_IMPACT_THRESHOLD (or the deprecated UNCONFIDENCE_THRESHOLD).

    For instance, for an execution time metric, this confidence interval indicates a significantly worse performance:

    ----------------------------------------|---------|---(---------^---------)---------->
                                           0%        1%  1.3%      2.2%      3.1%
                                                      |   |         |         |
           significant impact threshold --------------'   |         |         |
                          lower bound of CI --------------'         |         |
           sample mean (center of the CI) --------------------------'         |
                          upper bound of CI ----------------------------------'
    

    </details>

    </details>

    <details>
    <summary><h3>Unstable benchmarks</h3></summary>

    These benchmarks have a confidence interval too wide to call a change; treat them as noise rather than signal.

    scenario:appsec-appsec-enabled-20

  • unstable max_rss_usage [-38.288MB; +42.056MB] or [-13.363%; +14.678%]
  • scenario:appsec-iast-no-vulnerability-iast-enabled-default-config-26

  • unstable max_rss_usage [-36.896MB; +13.464MB] or [-13.281%; +4.846%]
  • scenario:appsec-iast-with-vulnerability-iast-enabled-default-config-20

  • unstable max_rss_usage [-32.606MB; +39.256MB] or [-9.087%; +10.941%]
  • scenario:appsec-iast-with-vulnerability-iast-enabled-default-config-24

  • unstable max_rss_usage [-18.619MB; +21.964MB] or [-5.152%; +6.078%]
  • scenario:openfeature-scale-full-24

  • unstable max_rss_usage [-31.191MB; +24.956MB] or [-10.048%; +8.039%]
  • scenario:openfeature-scale-full-26

  • unstable max_rss_usage [-40.066MB; +20.955MB] or [-16.349%; +8.551%]
  • </details>

    chatgpt-codex-connector[bot] chatgpt-codex-connector[bot] commented on Oct 26, 2026 13:58 UTC
    Bot

    <!-- codex-pull-request-review-summary -->
    <!-- codex-review-state:v1 {"code_review":{"commit_sha":"96c414c0484f34a60dd4a484b5ab727214602eab","has_any_findings":false,"has_unresolved_findings":false,"status":"completed"},"security_review":{"commit_sha":"96c414c0484f34a60dd4a484b5ab727214602eab","has_any_findings":false,"has_unresolved_findings":false,"status":"completed"}} -->
    <!-- codex-security-review:v1 {"blockingSeverityThreshold":"P0","headSha":"96c414c0484f34a60dd4a484b5ab727214602eab","mergeGateEnabled":false,"pullRequestNumber":10915,"repository":"DataDog/dd-trace-js","status":"completed"} -->

    Codex Review Summary

    This comment shows the latest Codex review activity on this pull request.

    | Review | Status | Commit | Review trigger |
    | --- | --- | --- | --- |
    | 📝 Code Review | ✅ Completed <relative-time datetime="2026-10-27T16:01:56.409296Z">2026-10-27T16:01:56.409296Z</relative-time> | 96c414c | New commits |
    | 🔒 Security Review | ✅ Completed <relative-time datetime="2026-10-27T16:01:58.968152Z">2026-10-27T16:01:58.968152Z</relative-time> | 96c414c | New commits |

    <details> <summary>ℹ️ About Codex in GitHub</summary>
    <br/>

    Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review

  • Mark a draft as ready

  • Comment "@codex review" or "@codex security review".
  • Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings.

    </details>

    datadog-prod-us1-5[bot] datadog-prod-us1-5[bot] commented on Oct 26, 2026 14:04 UTC
    Reviewer

    <img src="https://img.shields.io/badge/BITS%20CODE%20REVIEW-PASS-1a7f37?labelColor=632CA6&style=for-the-badge&logo=data:image/svg%2Bxml;base64,PHN2ZyB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciIHZpZXdCb3g9IjAgMCAxMjggMTI4Ij48cGF0aCBkPSJNNjMuNTUsNzQuMzJhNTUuMiw1NS4yLDAsMCwxLTEwLTguMzJjLS4zMS0uMjMtLjI2LTEuMjUtLjI2LTEuMjVBNTUuODEsNTUuODEsMCwwLDAsNjguOT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LTEzLjg4LDEwLjMzLDMsOC44OC0xNC44NCwxMC42NSw3LDguMS0xNywyLjg3LDMwLjkxWiIgZmlsbD0iI2ZmZiIvPjwvc3ZnPg%3D%3D" alt="Bits Code Review: PASS" height="36"/>

    <details>
    <summary>More details</summary>

    A standalone Node.js smoke check supported correct built-in re-requires and ESM synchronization. The completed static review identified no reportable defects.

    </details>
    Was this helpful? React 👍 or 👎

    <sub>Open Bits AI session</sub>

    <sub>🤖 Bits Code Review · Commit e86f267</sub>

    <!-- autotest-meta model=gpt-6.1-sol engine=codex reasoning_effort=high verdict=PASS ddrs_bucket=unknown session_id=24de658f-7710-4a71-856f-68e4a4162843 -->

    <!-- datadog-code-review reviewer-id=bad90057-5c12-4101-ad47-d91c9dff0f90 -->
    <!-- datadog-autotest:v1:prod -->
    <!-- datadog-autotest-delivery:v1:prod:91b06f5f5c1d754f64351ec213f810ba2084290da86f365c244a96cece07c1a0:bundle -->

    rochdev rochdev commented on code on Oct 26, 2026 19:39 UTC
    Code Review
    packages/datadog-instrumentations/src/helpers/bundler-register.js:1
    @@ -13,29 +14,52 @@ const {
     } = require('./instrumentation-utils')
     const hooks = require('./hooks')
     const instrumentations = require('./instrumentations')
    +const { isNodeBuiltinModuleName } = require('./shared-utils')
     const { isRewriteActivationEnabled } = require('./rewriter/targets')
     const disabledInstrumentations = getDisabledInstrumentations()
     
     // register.js has now set up ritm (require-in-the-middle). In bundled
    -// environments (webpack, esbuild), Node.js built-in modules required by
    -// dd-trace internal modules (e.g. http from request.js) may have been loaded
    -// before ritm was active. The bundler's module cache then returns those
    -// pre-loaded modules for any subsequent require() calls, bypassing ritm.
    -// Re-requiring them via the real Module.prototype.require ensures ritm applies
    -// their instrumentation hooks.
    +// environments (webpack, esbuild, Turbopack), Node.js built-ins required by the
    +// application or by dd-trace itself may have been loaded and cached by the
    +// bundle before ritm was active, bypassing it. Re-requiring them via the real
    +// Module.prototype.require lets ritm apply their hooks to the shared exports.

    How does this work when the export is a function and its reference is exported directly?

    rochdev rochdev commented on code on Oct 26, 2026 21:00 UTC
    Code Review
    packages/datadog-instrumentations/src/helpers/bundler-register.js:1
    @@ -13,29 +14,52 @@ const {
     } = require('./instrumentation-utils')
     const hooks = require('./hooks')
     const instrumentations = require('./instrumentations')
    +const { isNodeBuiltinModuleName } = require('./shared-utils')
     const { isRewriteActivationEnabled } = require('./rewriter/targets')
     const disabledInstrumentations = getDisabledInstrumentations()
     
     // register.js has now set up ritm (require-in-the-middle). In bundled
    -// environments (webpack, esbuild), Node.js built-in modules required by
    -// dd-trace internal modules (e.g. http from request.js) may have been loaded
    -// before ritm was active. The bundler's module cache then returns those
    -// pre-loaded modules for any subsequent require() calls, bypassing ritm.
    -// Re-requiring them via the real Module.prototype.require ensures ritm applies
    -// their instrumentation hooks.
    +// environments (webpack, esbuild, Turbopack), Node.js built-ins required by the
    +// application or by dd-trace itself may have been loaded and cached by the
    +// bundle before ritm was active, bypassing it. Re-requiring them via the real
    +// Module.prototype.require lets ritm apply their hooks to the shared exports.

    Or is that not something that ever happens with built-ins?

    rochdev rochdev commented on code on Oct 26, 2026 21:00 UTC
    Code Review
    packages/datadog-instrumentations/src/helpers/bundler-register.js:1
    @@ -13,29 +14,52 @@ const {
     } = require('./instrumentation-utils')
     const hooks = require('./hooks')
     const instrumentations = require('./instrumentations')
    +const { isNodeBuiltinModuleName } = require('./shared-utils')
     const { isRewriteActivationEnabled } = require('./rewriter/targets')
     const disabledInstrumentations = getDisabledInstrumentations()
     
     // register.js has now set up ritm (require-in-the-middle). In bundled
    -// environments (webpack, esbuild), Node.js built-in modules required by
    -// dd-trace internal modules (e.g. http from request.js) may have been loaded
    -// before ritm was active. The bundler's module cache then returns those
    -// pre-loaded modules for any subsequent require() calls, bypassing ritm.
    -// Re-requiring them via the real Module.prototype.require ensures ritm applies
    -// their instrumentation hooks.
    +// environments (webpack, esbuild, Turbopack), Node.js built-ins required by the
    +// application or by dd-trace itself may have been loaded and cached by the
    +// bundle before ritm was active, bypassing it. Re-requiring them via the real
    +// Module.prototype.require lets ritm apply their hooks to the shared exports.
     //
     // In regular Node.js, `module` is an instance of Module. In bundlers, the
     // module wrapper object is a plain object (not a Module instance), so we use
     // that to detect a bundled context and avoid unintended side-effects in
     // normal Node.js (e.g. shimmer-wrapping http before ESM modules load).
     if (!(module instanceof Module)) {
    -  for (const name of ['http', 'https']) {
    +  patchLoadedBuiltins()
    +}
    +
    +function patchLoadedBuiltins () {
    +  // A built-in nobody has loaded cannot be cached by the bundle yet, and a later require reaches ritm, so it is
    +  // skipped. moduleLoadList is undocumented: if it ever disappears, every hooked built-in is loaded instead.
    +  // @ts-expect-error - process.moduleLoadList is not typed
    +  const { moduleLoadList } = process
    +  const loadedBuiltins = Array.isArray(moduleLoadList) ? moduleLoadList : undefined
    +
    +  let patched = false
    +  for (const name of Object.keys(hooks)) {
    +    if (!isNodeBuiltinModuleName(name) ||
    +      disabledInstrumentations.has(name) ||
    +      (IS_SERVERLESS && hooks[name].serverless === false) ||

    Any way to centralize this logic somewhere? Why does it have to be handled where it currently is handled plus here?

    pabloerhard pabloerhard commented on code on Oct 26, 2026 21:07 UTC
    Code Review
    packages/datadog-instrumentations/src/helpers/bundler-register.js:1
    @@ -13,29 +14,52 @@ const {
     } = require('./instrumentation-utils')
     const hooks = require('./hooks')
     const instrumentations = require('./instrumentations')
    +const { isNodeBuiltinModuleName } = require('./shared-utils')
     const { isRewriteActivationEnabled } = require('./rewriter/targets')
     const disabledInstrumentations = getDisabledInstrumentations()
     
     // register.js has now set up ritm (require-in-the-middle). In bundled
    -// environments (webpack, esbuild), Node.js built-in modules required by
    -// dd-trace internal modules (e.g. http from request.js) may have been loaded
    -// before ritm was active. The bundler's module cache then returns those
    -// pre-loaded modules for any subsequent require() calls, bypassing ritm.
    -// Re-requiring them via the real Module.prototype.require ensures ritm applies
    -// their instrumentation hooks.
    +// environments (webpack, esbuild, Turbopack), Node.js built-ins required by the
    +// application or by dd-trace itself may have been loaded and cached by the
    +// bundle before ritm was active, bypassing it. Re-requiring them via the real
    +// Module.prototype.require lets ritm apply their hooks to the shared exports.

    It's does not happen with the built-ins we currently instrument.

    pabloerhard pabloerhard commented on code on Oct 26, 2026 21:36 UTC
    Code Review
    packages/datadog-instrumentations/src/helpers/bundler-register.js:1
    @@ -13,29 +14,52 @@ const {
     } = require('./instrumentation-utils')
     const hooks = require('./hooks')
     const instrumentations = require('./instrumentations')
    +const { isNodeBuiltinModuleName } = require('./shared-utils')
     const { isRewriteActivationEnabled } = require('./rewriter/targets')
     const disabledInstrumentations = getDisabledInstrumentations()
     
     // register.js has now set up ritm (require-in-the-middle). In bundled
    -// environments (webpack, esbuild), Node.js built-in modules required by
    -// dd-trace internal modules (e.g. http from request.js) may have been loaded
    -// before ritm was active. The bundler's module cache then returns those
    -// pre-loaded modules for any subsequent require() calls, bypassing ritm.
    -// Re-requiring them via the real Module.prototype.require ensures ritm applies
    -// their instrumentation hooks.
    +// environments (webpack, esbuild, Turbopack), Node.js built-ins required by the
    +// application or by dd-trace itself may have been loaded and cached by the
    +// bundle before ritm was active, bypassing it. Re-requiring them via the real
    +// Module.prototype.require lets ritm apply their hooks to the shared exports.
     //
     // In regular Node.js, `module` is an instance of Module. In bundlers, the
     // module wrapper object is a plain object (not a Module instance), so we use
     // that to detect a bundled context and avoid unintended side-effects in
     // normal Node.js (e.g. shimmer-wrapping http before ESM modules load).
     if (!(module instanceof Module)) {
    -  for (const name of ['http', 'https']) {
    +  patchLoadedBuiltins()
    +}
    +
    +function patchLoadedBuiltins () {
    +  // A built-in nobody has loaded cannot be cached by the bundle yet, and a later require reaches ritm, so it is
    +  // skipped. moduleLoadList is undocumented: if it ever disappears, every hooked built-in is loaded instead.
    +  // @ts-expect-error - process.moduleLoadList is not typed
    +  const { moduleLoadList } = process
    +  const loadedBuiltins = Array.isArray(moduleLoadList) ? moduleLoadList : undefined
    +
    +  let patched = false
    +  for (const name of Object.keys(hooks)) {
    +    if (!isNodeBuiltinModuleName(name) ||
    +      disabledInstrumentations.has(name) ||
    +      (IS_SERVERLESS && hooks[name].serverless === false) ||

    I guess we could indeed reuse some of the logic that register.js is doing. That said, we would still need to add some logic to register.js and additionally add an export to expose what we need to share with bundler-register.js

    rochdev rochdev approved these changes on Oct 27, 2026 22:42 UTC
    Approved Reviewer

    Approved these changes.

    BridgeAR BridgeAR approved these changes on Oct 28, 2026 11:15 UTC
    Approved Reviewer

    LGTM

    Reviewers
    Assignees
    pabloerhard pabloerhard
    Labels
    risk: low confidence: 85.9% reviewed
    Vouch Risk Breakdown
    AI-powered review risk analysis
    Change Risk
    Change Risk · Model 1 (XGBoost)
    Predicted defect probability (0.00–1.00) based on diff churn, modified sensitive files, and author risk history.
    Score: 39.7% (MEDIUM) · Higher = larger blast radius
    39.7%
    Review Confidence
    Review Confidence · Models 2 & 3
    Scrutiny score (0.00–1.00) combining DistilBERT semantic review depth with reviewer familiarity and session dwell time.
    Score: 85.9% · Lower = rushed or shallow review
    85.9%
    Residual Risk
    Residual Risk · Core Equation
    Residual = Change × (1 − Confidence)
    Unmitigated risk surviving review. ≥ 0.65 triggers an automated re-queue to protect production.
    Score: 5.6% · Safe to merge
    5.6%