Repository: nodejs/node
Pull request: lib: suppress source map lookup exceptions

#### lib: skip parsing invalid source maps

When the source map data are invalid json strings, skip construct
SourceMap on it. Additionally, suppress exceptions on source map lookups
and fix test runners crash on invalid source maps.

#### lib: optimize prepareStackTrace on builtin frames

Only invalidates source map lookup cache when a new source map is found.
This improves when user codes interleave with builtin functions, like
`array.map`.

```
                                                      confidence improvement accuracy (*)   (**)  (***)
es/error-stack.js n=100000 method='sourcemap'                ***     78.04 %       ±1.27% ±1.70% ±2.24%
es/error-stack.js n=100000 method='without-sourcemap'                 0.27 %       ±1.09% ±1.45% ±1.89%
```

Refs: https://github.com/nodejs/node/issues/56296

Changed files:
filename: benchmark/fixtures/simple-error-stack.js
patch: @@ -1,15 +1,16 @@
 'use strict';
-exports.__esModule = true;
-exports.simpleErrorStack = void 0;
+Object.defineProperty(exports, "__esModule", { value: true });
+exports.simpleErrorStack = simpleErrorStack;
 // Compile with `tsc --inlineSourceMap benchmark/fixtures/simple-error-stack.ts`.
 var lorem = 'Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.';
 function simpleErrorStack() {
-    try {
-        lorem.BANG();
-    }
-    catch (e) {
-        return e.stack;
-    }
+    [1].map(function () {
+        try {
+            lorem.BANG();
+        }
+        catch (e) {
+            return e.stack;
+        }
+    });
 }
-exports.simpleErrorStack = simpleErrorStack;
-//# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJmaWxlIjoic2ltcGxlLWVycm9yLXN0YWNrLmpzIiwic291cmNlUm9vdCI6IiIsInNvdXJjZXMiOlsic2ltcGxlLWVycm9yLXN0YWNrLnRzIl0sIm5hbWVzIjpbXSwibWFwcGluZ3MiOiJBQUFBLFlBQVksQ0FBQzs7O0FBRWIsaUZBQWlGO0FBRWpGLElBQU0sS0FBSyxHQUFHLCtiQUErYixDQUFDO0FBRTljLFNBQVMsZ0JBQWdCO0lBQ3ZCLElBQUk7UUFDRCxLQUFhLENBQUMsSUFBSSxFQUFFLENBQUM7S0FDdkI7SUFBQyxPQUFPLENBQUMsRUFBRTtRQUNWLE9BQU8sQ0FBQyxDQUFDLEtBQUssQ0FBQztLQUNoQjtBQUNILENBQUM7QUFHQyw0Q0FBZ0IifQ==
+//# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJmaWxlIjoic2ltcGxlLWVycm9yLXN0YWNrLmpzIiwic291cmNlUm9vdCI6IiIsInNvdXJjZXMiOlsic2ltcGxlLWVycm9yLXN0YWNrLnRzIl0sIm5hbWVzIjpbXSwibWFwcGluZ3MiOiJBQUFBLFlBQVksQ0FBQzs7QUFpQlgsNENBQWdCO0FBZmxCLGlGQUFpRjtBQUVqRixJQUFNLEtBQUssR0FBRywrYkFBK2IsQ0FBQztBQUU5YyxTQUFTLGdCQUFnQjtJQUN2QixDQUFDLENBQUMsQ0FBQyxDQUFDLEdBQUcsQ0FBQztRQUNOLElBQUksQ0FBQztZQUNGLEtBQWEsQ0FBQyxJQUFJLEVBQUUsQ0FBQztRQUN4QixDQUFDO1FBQUMsT0FBTyxDQUFDLEVBQUUsQ0FBQztZQUNYLE9BQU8sQ0FBQyxDQUFDLEtBQUssQ0FBQztRQUNqQixDQUFDO0lBQ0gsQ0FBQyxDQUFDLENBQUE7QUFDSixDQUFDIn0=
\ No newline at end of file

filename: benchmark/fixtures/simple-error-stack.ts
patch: @@ -5,11 +5,13 @@
 const lorem = 'Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.';
 
 function simpleErrorStack() {
-  try {
-    (lorem as any).BANG();
-  } catch (e) {
-    return e.stack;
-  }
+  [1].map(() => {
+    try {
+      (lorem as any).BANG();
+    } catch (e) {
+      return e.stack;
+    }
+  })
 }
 
 export {

filename: lib/internal/source_map/prepare_stack_trace.js
patch: @@ -53,9 +53,15 @@ function prepareStackTraceWithSourceMaps(error, trace) {
       const sm = fileName === lastFileName ?
         lastSourceMap :
         findSourceMap(fileName);
-      lastSourceMap = sm;
-      lastFileName = fileName;
+      // Only when a source map is found, cache it for the next iteration.
+      // This is a performance optimization to avoid interleaving with JS builtin function
+      // invalidating the cache.
+      // - at myFunc (file:///path/to/file.js:1:2)
+      // - at Array.map (<anonymous>)
+      // - at myFunc (file:///path/to/file.js:3:4)
       if (sm) {
+        lastSourceMap = sm;
+        lastFileName = fileName;
         return `${kStackLineAt}${serializeJSStackFrame(sm, callSite, trace[i + 1])}`;
       }
     } catch (err) {

filename: lib/internal/source_map/source_map_cache.js
patch: @@ -347,6 +347,11 @@ function findSourceMap(sourceURL) {
     return undefined;
   }
 
+  // No source maps for builtin modules.
+  if (sourceURL.startsWith('node:')) {
+    return undefined;
+  }
+
   SourceMap ??= require('internal/source_map/source_map').SourceMap;
   try {
     if (RegExpPrototypeExec(kLeadingProtocol, sourceURL) === null) {