Skip to content

Commit

Permalink
Merge pull request #291 from dart-lang/merge-source_map_stack_trace-p…
Browse files Browse the repository at this point in the history
…ackage

Merge `source_map_stack_trace` package
  • Loading branch information
mosuem authored Aug 21, 2024
2 parents 5b15f8b + 5b2a616 commit d32231a
Show file tree
Hide file tree
Showing 12 changed files with 641 additions and 0 deletions.
76 changes: 76 additions & 0 deletions .github/workflows/source_map_stack_trace.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,76 @@
name: Dart CI

on:
# Run on PRs and pushes to the default branch.
push:
branches: [ main ]
paths:
- '.github/workflows/source_map_stack_trace.yml'
- 'pkgs/source_map_stack_trace/**'
pull_request:
branches: [ main ]
paths:
- '.github/workflows/source_map_stack_trace.yml'
- 'pkgs/source_map_stack_trace/**'
schedule:
- cron: "0 0 * * 0"

env:
PUB_ENVIRONMENT: bot.github

jobs:
# Check code formatting and static analysis on a single OS (linux)
# against Dart dev.
analyze:
runs-on: ubuntu-latest
defaults:
run:
working-directory: pkgs/source_map_stack_trace/
strategy:
fail-fast: false
matrix:
sdk: [dev]
steps:
- uses: actions/checkout@692973e3d937129bcbf40652eb9f2f61becf3332
- uses: dart-lang/setup-dart@0a8a0fc875eb934c15d08629302413c671d3f672
with:
sdk: ${{ matrix.sdk }}
- id: install
name: Install dependencies
run: dart pub get
- name: Check formatting
run: dart format --output=none --set-exit-if-changed .
if: always() && steps.install.outcome == 'success'
- name: Analyze code
run: dart analyze --fatal-infos
if: always() && steps.install.outcome == 'success'

# Run tests on a matrix consisting of two dimensions:
# 1. OS: ubuntu-latest, (macos-latest, windows-latest)
# 2. release channel: dev
test:
needs: analyze
runs-on: ${{ matrix.os }}
defaults:
run:
working-directory: pkgs/source_map_stack_trace/
strategy:
fail-fast: false
matrix:
# Add macos-latest and/or windows-latest if relevant for this package.
os: [ubuntu-latest]
sdk: [3.3, dev]
steps:
- uses: actions/checkout@692973e3d937129bcbf40652eb9f2f61becf3332
- uses: dart-lang/setup-dart@0a8a0fc875eb934c15d08629302413c671d3f672
with:
sdk: ${{ matrix.sdk }}
- id: install
name: Install dependencies
run: dart pub get
- name: Run VM tests
run: dart test --platform vm
if: always() && steps.install.outcome == 'success'
- name: Run Chrome tests
run: dart test --platform chrome
if: always() && steps.install.outcome == 'success'
1 change: 1 addition & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@ don't naturally belong to other topic monorepos (like
| [extension_discovery](pkgs/extension_discovery/) | A convention and utilities for package extension discovery. | [![pub package](https://img.shields.io/pub/v/extension_discovery.svg)](https://pub.dev/packages/extension_discovery) |
| [graphs](pkgs/graphs/) | Graph algorithms that operate on graphs in any representation | [![pub package](https://img.shields.io/pub/v/graphs.svg)](https://pub.dev/packages/graphs) |
| [unified_analytics](pkgs/unified_analytics/) | A package for logging analytics for all Dart and Flutter related tooling to Google Analytics. | [![pub package](https://img.shields.io/pub/v/unified_analytics.svg)](https://pub.dev/packages/unified_analytics) |
| [source_map_stack_trace](pkgs/source_map_stack_trace/) | A package for applying source maps to stack traces. | [![pub package](https://img.shields.io/pub/v/source_map_stack_trace.svg)](https://pub.dev/packages/source_map_stack_trace) |

## Publishing automation

Expand Down
4 changes: 4 additions & 0 deletions pkgs/source_map_stack_trace/.gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
.dart_tool/
.packages
.pub/
pubspec.lock
5 changes: 5 additions & 0 deletions pkgs/source_map_stack_trace/.test_config
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
{
"test_package": {
"platforms": ["vm"]
}
}
6 changes: 6 additions & 0 deletions pkgs/source_map_stack_trace/AUTHORS
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
# Below is a list of people and organizations that have contributed
# to the project. Names should be added to the list like so:
#
# Name/Organization <email address>

Google Inc.
80 changes: 80 additions & 0 deletions pkgs/source_map_stack_trace/CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,80 @@
## 2.1.2-wip

* Require Dart 3.3.0
* Move to `dart-lang/tools` monorepo.

## 2.1.1

* Populate the pubspec `repository` field.

## 2.1.0

* Stable release for null safety.
* Require Dart 2.12

## 2.0.0

### Breaking Changes

* Removed dependency on `package_resolver` and changed the apis to accept a
`Map<String, Uri>` which maps package names to the base uri to resolve the
`package:` uris for those packages.
* The `sdkRoot` argument must be an `Uri`. Use `Uri.parse` for use
cases previously passing a `String`.
* The deprecated `packageRoot` argument has been removed.

## 1.1.5

* Set max SDK version to `<3.0.0`.

## 1.1.4

* Support source maps that depend on the uri of the location to resolve spans
correctly.

## 1.1.3

* Add a missing dependency on `path`.

## 1.1.2

* Fix a typo in the previous fix.

## 1.1.1

* Don't crash if the `SyncPackageResolver` has no package information at all.

## 1.1.0

* `mapStackTrace()` now uses a `SyncPackageResolver` object from the
[`package_resolver` package][package_resolver] to recreate `package:` URIs.

* **Deprecation**: the `packageRoot` parameter to `mapStackTrace` is deprecated
in favor of the `packageInfo` parameter described above. It will be removed in
a future release.

[package_resolver]: https://pub.dartlang.org/packages/package_resolver

## 1.0.5

* Add compatibility for member names that include named arguments.

## 1.0.4

* Add compatibility for Dart 1.10-style name munging.

## 1.0.3

* Prefer "dart:" URLs to "package:" URLs.

## 1.0.2

* Fix an off-by-one bug that was causing line numbers to be slightly off.

## 1.0.1

* Don't crash when mapping stack chains.

## 1.0.0

* Initial release.
27 changes: 27 additions & 0 deletions pkgs/source_map_stack_trace/LICENSE
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
Copyright 2015, the Dart project authors.

Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are
met:

* Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above
copyright notice, this list of conditions and the following
disclaimer in the documentation and/or other materials provided
with the distribution.
* Neither the name of Google LLC nor the names of its
contributors may be used to endorse or promote products derived
from this software without specific prior written permission.

THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
50 changes: 50 additions & 0 deletions pkgs/source_map_stack_trace/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,50 @@
[![Dart CI](https://github.com/dart-lang/source_map_stack_trace/actions/workflows/test-package.yml/badge.svg)](https://github.com/dart-lang/source_map_stack_trace/actions/workflows/test-package.yml)
[![pub package](https://img.shields.io/pub/v/source_map_stack_trace.svg)](https://pub.dev/packages/source_map_stack_trace)
[![package publisher](https://img.shields.io/pub/publisher/source_map_stack_trace.svg)](https://pub.dev/packages/source_map_stack_trace/publisher)

`source_map_stack_trace` is a package for converting stack traces generated by
dart2js-compiled JavaScript code into readable native Dart stack traces using
source maps. For example:

```dart
import 'package:source_map_stack_trace/source_map_stack_trace.dart';
void main() {
var jsTrace = // Get a StackTrace generated by dart2js.
var mapping = // Get a source map mapping the JS to the Dart source.
// Convert jsTrace to refer to the Dart source instead.
var dartTrace = mapStackTrace(jsTrace, sourceMap);
print(dartTrace);
}
```

This can convert the following JavaScript trace:

```
expect_async_test.dart.browser_test.dart.js 2636:15 dart.wrapException
expect_async_test.dart.browser_test.dart.js 14661:15 main__closure16.call$0
expect_async_test.dart.browser_test.dart.js 18237:26 Declarer_test__closure.call$1
expect_async_test.dart.browser_test.dart.js 17905:23 StackZoneSpecification_registerUnaryCallback__closure.call$0
expect_async_test.dart.browser_test.dart.js 17876:16 StackZoneSpecification._stack_zone_specification$_run$2
expect_async_test.dart.browser_test.dart.js 17899:26 StackZoneSpecification_registerUnaryCallback_closure.call$1
expect_async_test.dart.browser_test.dart.js 6115:16 _rootRunUnary
expect_async_test.dart.browser_test.dart.js 8576:39 _CustomZone.runUnary$2
expect_async_test.dart.browser_test.dart.js 7135:57 _Future__propagateToListeners_handleValueCallback.call$0
expect_async_test.dart.browser_test.dart.js 7031:147 dart._Future.static._Future__propagateToListeners
```

to:

```
dart:_internal/compiler/js_lib/js_helper.dart 1210:1 wrapException
test/frontend/expect_async_test.dart 24:5 main.<fn>.<fn>
package:test/src/backend/declarer.dart 45:48 Declarer.test.<fn>.<fn>
package:stack_trace/src/stack_zone_specification.dart 134:30 StackZoneSpecification.registerUnaryCallback.<fn>.<fn>
package:stack_trace/src/stack_zone_specification.dart 210:7 StackZoneSpecification._run
package:stack_trace/src/stack_zone_specification.dart 135:5 StackZoneSpecification.registerUnaryCallback.<fn>
dart:async/zone.dart 904:14 _rootRunUnary
dart:async/zone.dart 806:3 _CustomZone.runUnary
dart:async/future_impl.dart 486:13 _Future._propagateToListeners.handleValueCallback
dart:async/future_impl.dart 567:32 _Future._propagateToListeners
```
7 changes: 7 additions & 0 deletions pkgs/source_map_stack_trace/analysis_options.yaml
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
# https://dart.dev/tools/analysis#the-analysis-options-file
include: package:dart_flutter_team_lints/analysis_options.yaml

analyzer:
language:
strict-casts: true
strict-raw-types: true
104 changes: 104 additions & 0 deletions pkgs/source_map_stack_trace/lib/source_map_stack_trace.dart
Original file line number Diff line number Diff line change
@@ -0,0 +1,104 @@
// Copyright (c) 2015, the Dart project authors. Please see the AUTHORS file
// for details. All rights reserved. Use of this source code is governed by a
// BSD-style license that can be found in the LICENSE file.

import 'package:path/path.dart' as p;
import 'package:source_maps/source_maps.dart';
import 'package:stack_trace/stack_trace.dart';

/// Convert [stackTrace], a stack trace generated by dart2js-compiled
/// JavaScript, to a native-looking stack trace using [sourceMap].
///
/// [minified] indicates whether or not the dart2js code was minified. If it
/// hasn't, this tries to clean up the stack frame member names.
///
/// The [packageMap] maps package names to the base uri used to resolve the
/// `package:` uris for those packages. It is used to it's used to reconstruct
/// `package:` URIs for stack frames that come from packages.
///
/// [sdkRoot] is the URI surfaced in the stack traces for SDK libraries.
/// If it's passed, stack frames from the SDK will have `dart:` URLs.
StackTrace mapStackTrace(Mapping sourceMap, StackTrace stackTrace,
{bool minified = false, Map<String, Uri>? packageMap, Uri? sdkRoot}) {
if (stackTrace is Chain) {
return Chain(stackTrace.traces.map((trace) {
return Trace.from(mapStackTrace(sourceMap, trace,
minified: minified, packageMap: packageMap, sdkRoot: sdkRoot));
}));
}

var sdkLib = sdkRoot == null ? null : '$sdkRoot/lib';

var trace = Trace.from(stackTrace);
return Trace(trace.frames.map((frame) {
var line = frame.line;
// If there's no line information, there's no way to translate this frame.
// We could return it as-is, but these lines are usually not useful anyways.
if (line == null) return null;

// If there's no column, try using the first column of the line.
var column = frame.column ?? 0;

// Subtract 1 because stack traces use 1-indexed lines and columns and
// source maps uses 0-indexed.
var span =
sourceMap.spanFor(line - 1, column - 1, uri: frame.uri.toString());

// If we can't find a source span, ignore the frame. It's probably something
// internal that the user doesn't care about.
if (span == null) return null;

var sourceUrl = span.sourceUrl.toString();
if (sdkLib != null && p.url.isWithin(sdkLib, sourceUrl)) {
sourceUrl = 'dart:${p.url.relative(sourceUrl, from: sdkLib)}';
} else if (packageMap != null) {
for (var package in packageMap.keys) {
var packageUrl = packageMap[package].toString();
if (!p.url.isWithin(packageUrl, sourceUrl)) continue;

sourceUrl =
'package:$package/${p.url.relative(sourceUrl, from: packageUrl)}';
break;
}
}

return Frame(
Uri.parse(sourceUrl),
span.start.line + 1,
span.start.column + 1,
// If the dart2js output is minified, there's no use trying to prettify
// its member names. Use the span's identifier if available, otherwise
// use the minified member name.
minified
? (span.isIdentifier ? span.text : frame.member)
: _prettifyMember(frame.member!));
}).whereType<Frame>());
}

/// Reformats a JS member name to make it look more Dart-like.
String _prettifyMember(String member) {
return member
// Get rid of the noise that Firefox sometimes adds.
.replaceAll(RegExp(r'/?<$'), '')
// Get rid of arity indicators and named arguments.
.replaceAll(RegExp(r'\$\d+(\$[a-zA-Z_0-9]+)*$'), '')
// Convert closures to <fn>.
.replaceAllMapped(
RegExp(r'(_+)closure\d*\.call$'),
// The number of underscores before "closure" indicates how nested it
// is.
(match) => '.<fn>' * match[1]!.length)
// Get rid of explicitly-generated calls.
.replaceAll(RegExp(r'\.call$'), '')
// Get rid of the top-level method prefix.
.replaceAll(RegExp(r'^dart\.'), '')
// Get rid of library namespaces.
.replaceAll(RegExp(r'[a-zA-Z_0-9]+\$'), '')
// Get rid of the static method prefix. The class name also exists in the
// invocation, so we're not getting rid of any information.
.replaceAll(RegExp(r'^[a-zA-Z_0-9]+.(static|dart).'), '')
// Convert underscores after identifiers to dots. This runs the risk of
// incorrectly converting members that contain underscores, but those are
// contrary to the style guide anyway.
.replaceAllMapped(RegExp(r'([a-zA-Z0-9]+)_'), (match) => '${match[1]!}.');
}
17 changes: 17 additions & 0 deletions pkgs/source_map_stack_trace/pubspec.yaml
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
name: source_map_stack_trace
version: 2.1.2-wip
description: A package for applying source maps to stack traces.
repository: https://github.com/dart-lang/tools/tree/main/pkgs/source_map_stack_trace

environment:
sdk: ^3.3.0

dependencies:
path: ^1.8.0
source_maps: ^0.10.10
stack_trace: ^1.10.0

dev_dependencies:
dart_flutter_team_lints: ^2.0.0
source_span: ^1.8.0
test: ^1.16.0
Loading

0 comments on commit d32231a

Please sign in to comment.