Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

vendor node_preamble so the test binary can be used by the Dart SDK #2423

Closed
wants to merge 1 commit into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 4 additions & 0 deletions pkgs/test/CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -1,3 +1,7 @@
## 1.25.13-wip

* Vendor node_preamble since it can't be pulled into the Dart SDK.

## 1.25.12

* Fix hang when running multiple precompiled browser tests.
Expand Down
4 changes: 2 additions & 2 deletions pkgs/test/lib/src/runner/node/platform.dart
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,6 @@ import 'dart:convert';
import 'dart:io';

import 'package:async/async.dart';
import 'package:node_preamble/preamble.dart' as preamble;
import 'package:package_config/package_config.dart';
import 'package:path/path.dart' as p;
import 'package:stream_channel/stream_channel.dart';
Expand All @@ -33,6 +32,7 @@ import 'package:yaml/yaml.dart';

import '../../util/package_map.dart';
import '../executable_settings.dart';
import 'preamble.dart';

/// A platform that loads tests in Node.js processes.
class NodePlatform extends PlatformPlugin
Expand Down Expand Up @@ -193,7 +193,7 @@ class NodePlatform extends PlatformPlugin
// compatible. Use the minified version so the source map remains valid.
var jsFile = File(jsPath);
await jsFile.writeAsString(
preamble.getPreamble(minified: true) + await jsFile.readAsString());
getPreamble(minified: true) + await jsFile.readAsString());

StackTraceMapper? mapper;
if (!suiteConfig.jsTrace) {
Expand Down
133 changes: 133 additions & 0 deletions pkgs/test/lib/src/runner/node/preamble.dart
Original file line number Diff line number Diff line change
@@ -0,0 +1,133 @@
// Copyright (c) 2024, 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.
//
// Vendored version of node_preamble.

final _minified =
r'''var dartNodeIsActuallyNode="undefined"!=typeof process&&(process.versions||{}).hasOwnProperty("node"),self=dartNodeIsActuallyNode?Object.create(globalThis):globalThis;if(self.scheduleImmediate="undefined"!=typeof setImmediate?function(e){setImmediate(e)}:function(e){setTimeout(e,0)},"undefined"!=typeof require)self.require=require;if("undefined"!=typeof exports)self.exports=exports;if("undefined"!=typeof process)self.process=process;if("undefined"!=typeof __dirname)self.__dirname=__dirname;if("undefined"!=typeof __filename)self.__filename=__filename;if("undefined"!=typeof Buffer)self.Buffer=Buffer;if(dartNodeIsActuallyNode){var url=("undefined"!=typeof __webpack_require__?__non_webpack_require__:require)("url");Object.defineProperty(self,"location",{value:{get href(){if(url.pathToFileURL)return url.pathToFileURL(process.cwd()).href+"/";else return"file://"+function(){var e=process.cwd();if("win32"!=process.platform)return e;else return"/"+e.replace(/\\/g,"/")}()+"/"}}}),function(){function e(){try{throw new Error}catch(n){var e=n.stack,r=new RegExp("^ *at [^(]*\\((.*):[0-9]*:[0-9]*\\)$","mg"),f=null;do{var t=r.exec(e);if(null!=t)f=t}while(null!=t);return f[1]}}var r=null;Object.defineProperty(self,"document",{value:{get currentScript(){if(null==r)r={src:e()};return r}}})}(),self.dartDeferredLibraryLoader=function(e,r,f){try{load(e),r()}catch(e){f(e)}}}''';

final _normal = r'''
var dartNodeIsActuallyNode = typeof process !== "undefined" && (process.versions || {}).hasOwnProperty('node');

// make sure to keep this as 'var'
// we don't want block scoping
var self = dartNodeIsActuallyNode ? Object.create(globalThis) : globalThis;

self.scheduleImmediate = typeof setImmediate !== "undefined"
? function (cb) {
setImmediate(cb);
}
: function(cb) {
setTimeout(cb, 0);
};

// CommonJS globals.
if (typeof require !== "undefined") {
self.require = require;
}
if (typeof exports !== "undefined") {
self.exports = exports;
}

// Node.js specific exports, check to see if they exist & or polyfilled

if (typeof process !== "undefined") {
self.process = process;
}

if (typeof __dirname !== "undefined") {
self.__dirname = __dirname;
}

if (typeof __filename !== "undefined") {
self.__filename = __filename;
}

if (typeof Buffer !== "undefined") {
self.Buffer = Buffer;
}

// if we're running in a browser, Dart supports most of this out of box
// make sure we only run these in Node.js environment

if (dartNodeIsActuallyNode) {
// This line is to:
// 1) Prevent Webpack from bundling.
// 2) In Webpack on Node.js, make sure we're using the native Node.js require, which is available via __non_webpack_require__
// https://github.com/mbullington/node_preamble.dart/issues/18#issuecomment-527305561
var url = ("undefined" !== typeof __webpack_require__ ? __non_webpack_require__ : require)("url");

// Setting `self.location=` in Electron throws a `TypeError`, so we define it
// as a property instead to be safe.
Object.defineProperty(self, "location", {
value: {
get href() {
if (url.pathToFileURL) {
return url.pathToFileURL(process.cwd()).href + "/";
} else {
// This isn't really a correct transformation, but it's the best we have
// for versions of Node <10.12.0 which introduced `url.pathToFileURL()`.
// For example, it will fail for paths that contain characters that need
// to be escaped in URLs.
return "file://" + (function() {
var cwd = process.cwd();
if (process.platform != "win32") return cwd;
return "/" + cwd.replace(/\\/g, "/");
})() + "/"
}
}
}
});

(function() {
function computeCurrentScript() {
try {
throw new Error();
} catch(e) {
var stack = e.stack;
var re = new RegExp("^ *at [^(]*\\((.*):[0-9]*:[0-9]*\\)$", "mg");
var lastMatch = null;
do {
var match = re.exec(stack);
if (match != null) lastMatch = match;
} while (match != null);
return lastMatch[1];
}
}

// Setting `self.document=` isn't known to throw an error anywhere like
// `self.location=` does on Electron, but it's better to be future-proof
// just in case..
var cachedCurrentScript = null;
Object.defineProperty(self, "document", {
value: {
get currentScript() {
if (cachedCurrentScript == null) {
cachedCurrentScript = {src: computeCurrentScript()};
}
return cachedCurrentScript;
}
}
});
})();

self.dartDeferredLibraryLoader = function(uri, successCallback, errorCallback) {
try {
load(uri);
successCallback();
} catch (error) {
errorCallback(error);
}
};
}
''';

/// Returns the text of the preamble.
///
/// If [minified] is true, returns the minified version rather than the
/// human-readable version.
String getPreamble(
Copy link
Member

Choose a reason for hiding this comment

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

As a drive by comment, if we want to keep the package content as close to the upstream package as possible, this looks good. If however we're forking and want to have less to maintain, you can remove the _minified content above, and the minified and additionalGlobals args here.

Copy link
Contributor Author

@jakemac53 jakemac53 Dec 5, 2024

Choose a reason for hiding this comment

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

Yeah I considered that... but I came to the conclusion it would be easiest to just keep it identical. I don't feel strongly either way.

{bool minified = false, List<String> additionalGlobals = const []}) =>
(minified ? _minified : _normal) +
(additionalGlobals.map((global) => 'self.$global=$global;').join());
3 changes: 1 addition & 2 deletions pkgs/test/pubspec.yaml
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
name: test
version: 1.25.12
version: 1.25.13-wip
description: >-
A full featured library for writing and running Dart tests across platforms.
repository: https://github.com/dart-lang/test/tree/master/pkgs/test
Expand All @@ -22,7 +22,6 @@ dependencies:
# properly constrains all features it provides.
matcher: '>=0.12.16 <0.12.17'

node_preamble: ^2.0.0
package_config: ^2.0.0
path: ^1.8.0
pool: ^1.5.0
Expand Down
4 changes: 2 additions & 2 deletions pkgs/test/test/runner/precompiled_test.dart
Original file line number Diff line number Diff line change
Expand Up @@ -10,9 +10,9 @@ import 'dart:async';
import 'dart:io';
import 'dart:isolate';

import 'package:node_preamble/preamble.dart' as preamble;
import 'package:package_config/package_config.dart';
import 'package:path/path.dart' as p;
import 'package:test/src/runner/node/preamble.dart';
import 'package:test/test.dart';
import 'package:test_descriptor/test_descriptor.dart' as d;
import 'package:test_process/test_process.dart';
Expand Down Expand Up @@ -102,7 +102,7 @@ void main() {

var jsFile = File(jsPath);
await jsFile.writeAsString(
preamble.getPreamble(minified: true) + await jsFile.readAsString());
getPreamble(minified: true) + await jsFile.readAsString());

await d.dir('test', [d.file('test.dart', 'invalid dart}')]).create();
});
Expand Down
Loading