@babel/test262-stream 0.0.0-stage → 2.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,27 @@
1
+ Copyright (c) 2017, Bocoup LLC
2
+ All rights reserved.
3
+
4
+ Redistribution and use in source and binary forms, with or without
5
+ modification, are permitted provided that the following conditions are met:
6
+
7
+ * Redistributions of source code must retain the above copyright notice, this
8
+ list of conditions and the following disclaimer.
9
+
10
+ * Redistributions in binary form must reproduce the above copyright notice,
11
+ this list of conditions and the following disclaimer in the documentation
12
+ and/or other materials provided with the distribution.
13
+
14
+ * Neither the name of [project] nor the names of its
15
+ contributors may be used to endorse or promote products derived from
16
+ this software without specific prior written permission.
17
+
18
+ THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
19
+ AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
20
+ IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
21
+ DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
22
+ FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
23
+ DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
24
+ SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
25
+ CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
26
+ OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
27
+ OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
@@ -0,0 +1,27 @@
1
+ Copyright (c) 2014, Microsoft Corporation
2
+ All rights reserved.
3
+
4
+ Redistribution and use in source and binary forms, with or without
5
+ modification, are permitted provided that the following conditions are met:
6
+
7
+ * Redistributions of source code must retain the above copyright notice, this
8
+ list of conditions and the following disclaimer.
9
+
10
+ * Redistributions in binary form must reproduce the above copyright notice,
11
+ this list of conditions and the following disclaimer in the documentation
12
+ and/or other materials provided with the distribution.
13
+
14
+ * Neither the name of test262-parser nor the names of its
15
+ contributors may be used to endorse or promote products derived from
16
+ this software without specific prior written permission.
17
+
18
+ THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
19
+ AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
20
+ IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
21
+ DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
22
+ FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
23
+ DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
24
+ SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
25
+ CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
26
+ OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
27
+ OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
package/LICENSE.txt ADDED
@@ -0,0 +1,27 @@
1
+ Copyright (c) 2026, Babel contributors
2
+ All rights reserved.
3
+
4
+ Redistribution and use in source and binary forms, with or without
5
+ modification, are permitted provided that the following conditions are met:
6
+
7
+ * Redistributions of source code must retain the above copyright notice, this
8
+ list of conditions and the following disclaimer.
9
+
10
+ * Redistributions in binary form must reproduce the above copyright notice,
11
+ this list of conditions and the following disclaimer in the documentation
12
+ and/or other materials provided with the distribution.
13
+
14
+ * Neither the name of [project] nor the names of its
15
+ contributors may be used to endorse or promote products derived from
16
+ this software without specific prior written permission.
17
+
18
+ THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
19
+ AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
20
+ IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
21
+ DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
22
+ FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
23
+ DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
24
+ SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
25
+ CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
26
+ OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
27
+ OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
package/README.md CHANGED
@@ -1,3 +1,81 @@
1
- # Temporary Holding Version
1
+ # Test262-Stream
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ A [Node.js](https://nodejs.org) API for traversing [the Test262 test
4
+ suite](https://github.com/tc39/test262).
5
+
6
+ ## Usage
7
+
8
+ ```js
9
+ var TestStream = require('@babel/test262-stream');
10
+ var stream = new TestStream('/path/to/test262', {
11
+ // Directory from which to load "includes" files (defaults to the
12
+ // appropriate subdirectory of the provided `test262Dir`
13
+ // Optional. Defaults to './harness'
14
+ includesDir: '/path/to/includes/dir',
15
+
16
+ // File system paths refining the set of tests that should be produced;
17
+ // only tests whose source file matches one of these values (in the case of
18
+ // file paths) or is contained by one of these paths (in the case of
19
+ // directory paths) will be created; all paths are interpreted relative to
20
+ // the root of the provided `test262Dir`
21
+ // Optional. Defaults to ['test']
22
+ paths: ['test/built-ins/eval', 'test/language/statements/empty/S12.3_A1.js'],
23
+
24
+ // Flag to disable the insertion of code necessary to execute the test
25
+ // (e.g. assertion functions and "include" files); defaults to `false`
26
+ omitRuntime: true,
27
+
28
+ // By default, this stream will emit an error if the provided version of
29
+ // Test262 is not supported; this behavior may be disabled by providing a
30
+ // value of the expected version. Use of this option may cause the stream
31
+ // to emit invalid tests; consider updating the library instead.
32
+ acceptVersion: '2.0.0'
33
+ });
34
+
35
+ stream.on('data', function(test) {
36
+ // the path to the file from which the test was derived, relative to the
37
+ // provided Test262 directory
38
+ console.log(test.file);
39
+
40
+ // the complete source text for the test; this contains any "includes"
41
+ // files specified in the frontmatter, "prelude" content if specified (see
42
+ // below), and any "scenario" transformations
43
+ console.log(test.contents);
44
+
45
+ // an object representation of the metadata declared in the test's
46
+ // "frontmatter" section
47
+ console.log(test.attrs);
48
+
49
+ // the licensing information included within the test (if any)
50
+ console.log(test.copyright);
51
+
52
+ // name describing how the source file was interpreted to create the test
53
+ console.log(test.scenario);
54
+
55
+ // numeric offset within the `contents` string at which one or more
56
+ // statements may be inserted without necessarily invalidating the test
57
+ console.log(test.insertionIndex);
58
+ });
59
+
60
+ stream.on('end', function() {
61
+ console.log('No further tests.');
62
+ });
63
+
64
+ stream.on('error', function(err) {
65
+ console.error('Something went wrong:', err);
66
+ });
67
+ ```
68
+
69
+ The package includes TypeScript typings, in which the stream's tests are of
70
+ type `TestStream.Test`.
71
+
72
+ Tests are emitted in no specified order: files are read concurrently, so the
73
+ tests of different files, and of different `paths`, may be interleaved.
74
+
75
+ An error, such as a file that cannot be read or invalid frontmatter, ends the
76
+ stream: it emits an `error` event, and no further tests or `end` event.
77
+
78
+ ## License
79
+
80
+ Copyright 2026, Babel contributors, and 2017, Bocoup LLC, under the 3-Clause BSD
81
+ License (see `LICENSE.txt` and `LICENSE-BOCOUP.txt`)
package/lib/builder.js ADDED
@@ -0,0 +1,81 @@
1
+ 'use strict';
2
+ const fs = require('fs');
3
+ const path = require('path');
4
+ const TestFile = require('./test-file');
5
+
6
+ // Harness files are the same for every test, so a stream reads each of them
7
+ // once rather than once per test.
8
+ function readInclude(options, name) {
9
+ const cache = options.includesCache;
10
+ let contents = cache && cache.get(name);
11
+
12
+ if (contents === undefined) {
13
+ contents = fs.readFileSync(path.join(options.includesDir, name), 'utf-8');
14
+ if (cache) {
15
+ cache.set(name, contents);
16
+ }
17
+ }
18
+
19
+ return contents;
20
+ }
21
+
22
+ function concatIncludes(options, includes) {
23
+ let includeContents = '';
24
+ for (let i = 0; i < includes.length; i++) {
25
+ includeContents += readInclude(options, includes[i]) + '\n';
26
+ }
27
+ return includeContents;
28
+ }
29
+
30
+ module.exports = function builder(file, contents, options) {
31
+ options = options || {};
32
+ if (!options.test262Dir && !options.includesDir) {
33
+ throw new Error('Need one of test262Dir or includesDir options');
34
+ }
35
+
36
+ if (options.test262Dir && !options.includesDir) {
37
+ options.includesDir = path.join(options.test262Dir, 'harness');
38
+ }
39
+
40
+ const test = new TestFile(file, contents);
41
+
42
+ if (test.attrs.flags.raw || options.omitRuntime) {
43
+ test.insertionIndex = test.attrs.flags.raw ? -1 : 0;
44
+ return test;
45
+ }
46
+
47
+ // Prepend assert.js, sta.js, and (if needed) doneprintHandle.js,
48
+ // preserving their relative order. Building a new list is faster than
49
+ // prepending to the test's.
50
+ // https://github.com/tc39/test262/blob/main/INTERPRETING.md#includes
51
+ const includes = test.attrs.flags.async ?
52
+ ['assert.js', 'sta.js', 'doneprintHandle.js'] :
53
+ ['assert.js', 'sta.js'];
54
+ const testIncludes = test.attrs.includes;
55
+ for (let i = 0; i < testIncludes.length; i++) {
56
+ includes.push(testIncludes[i]);
57
+ }
58
+ test.attrs.includes = includes;
59
+
60
+ // Most tests only include the harness files that every test, or every
61
+ // async test, includes, so a stream concatenates these once. File names
62
+ // cannot contain "\0", so the keys do not clash with theirs.
63
+ const cache = options.includesCache;
64
+ let includeContents;
65
+
66
+ if (cache && testIncludes.length === 0) {
67
+ const key = test.attrs.flags.async ? '\0async' : '\0default';
68
+ includeContents = cache.get(key);
69
+ if (includeContents === undefined) {
70
+ includeContents = concatIncludes(options, includes);
71
+ cache.set(key, includeContents);
72
+ }
73
+ } else {
74
+ includeContents = concatIncludes(options, includes);
75
+ }
76
+
77
+ test.contents = includeContents + test.contents;
78
+ test.insertionIndex = includeContents.length;
79
+
80
+ return test;
81
+ };
package/lib/compile.js ADDED
@@ -0,0 +1,27 @@
1
+ 'use strict';
2
+ const fs = require('fs');
3
+ const builder = require('./builder');
4
+ const createScenarios = require('./create-scenarios');
5
+
6
+ // `file` is the path of the file relative to `options.test262Dir`.
7
+ module.exports = function(filePath, file, options, done) {
8
+ fs.readFile(filePath, 'utf-8', (error, contents) => {
9
+ if (error) {
10
+ done(error);
11
+ return;
12
+ }
13
+
14
+ let tests;
15
+
16
+ try {
17
+ tests = createScenarios(
18
+ builder(file, contents, options)
19
+ );
20
+ } catch (error) {
21
+ done(error);
22
+ return;
23
+ }
24
+
25
+ done(null, tests);
26
+ });
27
+ };
@@ -0,0 +1,55 @@
1
+ 'use strict';
2
+ const usd = '"use strict";\n';
3
+ const usdLength = usd.length;
4
+
5
+ // Copies attributes, and their lists and mappings, such as `includes`,
6
+ // `features` and `negative`, so that changing those of one scenario does not
7
+ // change the other's.
8
+ function copyAttrs(attrs) {
9
+ const copy = Object.assign({}, attrs);
10
+ const keys = Object.keys(copy);
11
+
12
+ for (let i = 0; i < keys.length; i++) {
13
+ const value = copy[keys[i]];
14
+
15
+ if (Array.isArray(value)) {
16
+ copy[keys[i]] = value.slice();
17
+ } else if (typeof value === 'object' && value !== null) {
18
+ copy[keys[i]] = Object.assign({}, value);
19
+ }
20
+ }
21
+
22
+ return copy;
23
+ }
24
+
25
+ module.exports = function scenariosForTest(test) {
26
+ const scenarios = [];
27
+
28
+ if (test.attrs.flags.module) {
29
+ test.scenario = 'default';
30
+ scenarios.push(test);
31
+ } else {
32
+ if (!test.attrs.flags.onlyStrict) {
33
+ test.scenario = 'default';
34
+ scenarios.push(test);
35
+ }
36
+
37
+ if (!test.attrs.flags.noStrict && !test.attrs.flags.raw) {
38
+ const attrs = copyAttrs(test.attrs);
39
+ attrs.description += ' (Strict Mode)';
40
+
41
+ // The properties of a Test262File, in order. A literal is faster to
42
+ // create than a copy with Object.assign.
43
+ scenarios.push({
44
+ file: test.file,
45
+ contents: usd + test.contents,
46
+ attrs,
47
+ copyright: test.copyright,
48
+ scenario: 'strict mode',
49
+ insertionIndex: test.insertionIndex + usdLength
50
+ });
51
+ }
52
+ }
53
+
54
+ return scenarios;
55
+ };
package/lib/index.d.ts ADDED
@@ -0,0 +1,137 @@
1
+ import { Readable, ReadableOptions } from 'stream';
2
+
3
+ /**
4
+ * A Node.js readable stream that emits an object for every test in a Test262
5
+ * directory.
6
+ *
7
+ * Tests are emitted in no specified order: files are read concurrently, so
8
+ * the tests of different files, and of different `paths`, may be interleaved.
9
+ *
10
+ * An error, such as a file that cannot be read or invalid frontmatter, ends
11
+ * the stream: it emits an `error` event, and no further tests or `end` event.
12
+ */
13
+ declare class TestStream extends Readable {
14
+ /**
15
+ * @param test262Dir - path to a directory containing Test262
16
+ */
17
+ constructor(test262Dir: string, options?: TestStream.Options);
18
+
19
+ read(size?: number): TestStream.Test | null;
20
+
21
+ [Symbol.asyncIterator](): TestStream.TestIterator;
22
+
23
+ addListener(event: 'data', listener: (test: TestStream.Test) => void): this;
24
+ addListener(event: string | symbol, listener: (...args: any[]) => void): this;
25
+ on(event: 'data', listener: (test: TestStream.Test) => void): this;
26
+ on(event: string | symbol, listener: (...args: any[]) => void): this;
27
+ once(event: 'data', listener: (test: TestStream.Test) => void): this;
28
+ once(event: string | symbol, listener: (...args: any[]) => void): this;
29
+ prependListener(event: 'data', listener: (test: TestStream.Test) => void): this;
30
+ prependListener(event: string | symbol, listener: (...args: any[]) => void): this;
31
+ prependOnceListener(event: 'data', listener: (test: TestStream.Test) => void): this;
32
+ prependOnceListener(event: string | symbol, listener: (...args: any[]) => void): this;
33
+ }
34
+
35
+ declare namespace TestStream {
36
+ interface Options extends Omit<ReadableOptions, 'objectMode' | 'read'> {
37
+ /**
38
+ * Directory from which to load "includes" files; defaults to the
39
+ * `harness` directory of `test262Dir`.
40
+ */
41
+ includesDir?: string;
42
+ /**
43
+ * Files and directories, relative to `test262Dir`, to read tests from;
44
+ * defaults to `['test']`.
45
+ */
46
+ paths?: string[];
47
+ /**
48
+ * Whether to leave out the code that tests need to run, such as
49
+ * assert.js and the "includes" files; defaults to `false`.
50
+ */
51
+ omitRuntime?: boolean;
52
+ /**
53
+ * Version of Test262 to accept although this library does not support
54
+ * it. Use of this option may cause the stream to emit invalid tests.
55
+ */
56
+ acceptVersion?: string;
57
+ }
58
+
59
+ /**
60
+ * The iterator of the tests of a stream, which `for await` uses: the
61
+ * iterator of Readable streams, whose type depends on the version of
62
+ * @types/node, with its values typed as tests.
63
+ */
64
+ interface TestIterator extends Omit<
65
+ ReturnType<Readable[typeof Symbol.asyncIterator]>,
66
+ 'next' | 'return' | 'throw' | typeof Symbol.asyncIterator
67
+ > {
68
+ next(...args: [] | [unknown]): Promise<IteratorResult<Test, any>>;
69
+ return?(value?: any): Promise<IteratorResult<Test, any>>;
70
+ throw?(error?: any): Promise<IteratorResult<Test, any>>;
71
+ [Symbol.asyncIterator](): TestIterator;
72
+ }
73
+
74
+ interface Test {
75
+ /** Path of the test's file, relative to `test262Dir`. */
76
+ file: string;
77
+ /**
78
+ * Source text of the test, including the "includes" files and any
79
+ * scenario transformation, such as a "use strict" directive.
80
+ */
81
+ contents: string;
82
+ /** Metadata from the test's YAML frontmatter. */
83
+ attrs: Attrs;
84
+ /** Copyright line of the test, or `''` if it has none. */
85
+ copyright: string;
86
+ /** How the test's file was interpreted to create the test. */
87
+ scenario: 'default' | 'strict mode';
88
+ /**
89
+ * Offset in `contents` at which statements may be inserted without
90
+ * necessarily invalidating the test, or -1 for `raw` tests.
91
+ */
92
+ insertionIndex: number;
93
+ }
94
+
95
+ /**
96
+ * Metadata from a test's YAML frontmatter.
97
+ * https://github.com/tc39/test262/blob/main/INTERPRETING.md#metadata
98
+ */
99
+ interface Attrs {
100
+ description: string;
101
+ /** Harness files to include, including the default ones. */
102
+ includes: string[];
103
+ flags: Flags;
104
+ negative?: Negative;
105
+ features?: string[];
106
+ locale?: string | string[];
107
+ esid?: string;
108
+ es5id?: string | number;
109
+ es6id?: string | number;
110
+ info?: string;
111
+ author?: string;
112
+ [key: string]: unknown;
113
+ }
114
+
115
+ /**
116
+ * Flags of a test, each `true` if the test has it.
117
+ */
118
+ interface Flags {
119
+ onlyStrict?: true;
120
+ noStrict?: true;
121
+ module?: true;
122
+ raw?: true;
123
+ async?: true;
124
+ generated?: true;
125
+ CanBlockIsFalse?: true;
126
+ CanBlockIsTrue?: true;
127
+ [flag: string]: true | undefined;
128
+ }
129
+
130
+ interface Negative {
131
+ phase: 'parse' | 'resolution' | 'runtime';
132
+ /** Name of the error constructor, such as `SyntaxError`. */
133
+ type: string;
134
+ }
135
+ }
136
+
137
+ export = TestStream;
package/lib/index.js ADDED
@@ -0,0 +1,331 @@
1
+ 'use strict';
2
+
3
+ const fs = require('fs');
4
+ const path = require('path');
5
+ const Readable = require('stream').Readable;
6
+
7
+ const compile = require('./compile');
8
+
9
+ const compileOpts = Symbol('compileOpts');
10
+ const acceptVersion = Symbol('acceptVersion');
11
+ const started = Symbol('started');
12
+ const pending = Symbol('pending');
13
+ const active = Symbol('active');
14
+ const ended = Symbol('ended');
15
+ const failed = Symbol('failed');
16
+ const wanted = Symbol('wanted');
17
+ const next = Symbol('next');
18
+ const visit = Symbol('visit');
19
+ const enqueue = Symbol('enqueue');
20
+ const done = Symbol('done');
21
+ const fail = Symbol('fail');
22
+
23
+ const supportedVersion = /^[12345]\./;
24
+ const fixturePattern = /_FIXTURE/;
25
+
26
+ // Returns `path.relative(test262Dir, filePath)`, where `filePath` is
27
+ // `path.join(test262Dir, relativePath)`, without resolving both paths against
28
+ // the working directory when `relativePath` is within `test262Dir`.
29
+ function relativeFile(test262Dir, relativePath, filePath) {
30
+ let file = path.normalize(relativePath);
31
+
32
+ // `path.normalize` keeps a trailing separator, as in `./` or `test/`.
33
+ if (file.length > 1 && file[file.length - 1] === path.sep) {
34
+ file = file.slice(0, -1);
35
+ }
36
+
37
+ if (
38
+ path.isAbsolute(relativePath) ||
39
+ file === '.' ||
40
+ file === '..' ||
41
+ file.slice(0, 3) === '..' + path.sep
42
+ ) {
43
+ return path.relative(test262Dir, filePath);
44
+ }
45
+
46
+ return file;
47
+ }
48
+
49
+ // Maximum number of file system operations in flight. Reading files one at a
50
+ // time leaves the main thread idle while it waits for each of them.
51
+ const concurrency = 64;
52
+
53
+ /**
54
+ * A Node.js readable stream that emits an object value for every test in a
55
+ * given filesystem directory. This object has the following properties:
56
+ *
57
+ * - file {string} - the path to the file from which the test was derived,
58
+ * relative to the provided Test262 directory
59
+ * - contents {string} - the complete source text for the test; this contains
60
+ * any "includes" files specified in the frontmatter,
61
+ * "prelude" content if specified (see below), and any
62
+ * "scenario" transformations
63
+ * - attrs {object} - an object representation of the metadata declared in the
64
+ * test's YAML-formatted "frontmatter" section
65
+ * - copyright {string} - the licensing information included within the test
66
+ * (if any)
67
+ * - scenario {string} - name describing how the source file was interpreted to
68
+ * create the test
69
+ * - insertionIndex {number} - numeric offset within the `contents` string at
70
+ * which one or more statements may be inserted
71
+ * without necessarily invalidating the test
72
+ *
73
+ * Tests are emitted in no specified order: files are read concurrently, so
74
+ * the tests of different files, and of different `paths`, may be interleaved.
75
+ *
76
+ * An error, such as a file that cannot be read or invalid frontmatter, ends
77
+ * the stream: it emits an `error` event, and no further tests or `end` event.
78
+ *
79
+ * @param {string} test262Dir - filesystem path to a directory containing
80
+ * Test262
81
+ * @param {object} [options]
82
+ * @param {string} [options.includesDir] - directory from which to load
83
+ * "includes" files (defaults to the
84
+ * appropriate subdirectory of the
85
+ * provided `test262Dir`
86
+ * @param {Array<string>} [options.paths] - file system paths refining the set
87
+ * of tests that should be produced;
88
+ * only tests whose source file
89
+ * matches one of these values (in the
90
+ * case of file paths) or is contained
91
+ * by one of these paths (in the case
92
+ * of directory paths) will be
93
+ * created; all paths are interpreted
94
+ * relative to the root of the
95
+ * provided `test262Dir`
96
+ * @param {string} [options.prelude] - string contents to inject into each
97
+ * test that does not carry the `raw`
98
+ * metadata flag; defaults to the empty
99
+ * string (e.g. no injection)
100
+ * @param {boolean} [options.omitRuntime] - flag to disable the insertion of
101
+ * code necessary to execute the test
102
+ * (e.g. assertion functions and
103
+ * "include" files); defaults to
104
+ * `false`
105
+ * @param {string} [options.acceptVersion] - by default, this stream will emit
106
+ * an error if the provided version
107
+ * of Test262 is not supported; this
108
+ * behavior may be disabled by
109
+ * providing a value of the expected
110
+ * version. Use of this option may
111
+ * cause the stream to emit invalid
112
+ * tests; consider updating the
113
+ * library instead.
114
+ *
115
+ * @returns {object} readable stream
116
+ */
117
+ module.exports = class TestStream extends Readable {
118
+ constructor(test262Dir, options) {
119
+ options = Object.assign({}, options);
120
+ options.objectMode = true;
121
+ super(options);
122
+ this[compileOpts] = {
123
+ test262Dir,
124
+ includesDir: options.includesDir,
125
+ omitRuntime: !!options.omitRuntime,
126
+ includesCache: new Map()
127
+ };
128
+ this[acceptVersion] = options.acceptVersion;
129
+ this[started] = false;
130
+ // Stack of paths to visit, the next one last, with their `file` relative
131
+ // to `test262Dir`. `isDirectory` is undefined for the paths given in
132
+ // `options.paths`, which are not known to be files or directories until
133
+ // they are read.
134
+ this[pending] = (options.paths || ['test'])
135
+ .map(relativePath => {
136
+ const filePath = path.join(test262Dir, relativePath);
137
+ return {
138
+ path: filePath,
139
+ file: relativeFile(test262Dir, relativePath, filePath),
140
+ isDirectory: undefined
141
+ };
142
+ })
143
+ .reverse();
144
+ this[active] = 0;
145
+ this[ended] = false;
146
+ this[failed] = false;
147
+ // Whether the stream's buffer has room for more tests, as signaled by
148
+ // `_read` and `push`.
149
+ this[wanted] = false;
150
+ }
151
+
152
+ _read() {
153
+ this[wanted] = true;
154
+
155
+ if (this[started]) {
156
+ this[next]();
157
+ return;
158
+ }
159
+ this[started] = true;
160
+
161
+ const packagePath = path.join(this[compileOpts].test262Dir, 'package.json');
162
+
163
+ fs.readFile(packagePath, 'utf-8', (error, contents) => {
164
+ if (error) {
165
+ if (error.code === 'ENOENT') {
166
+ this[next]();
167
+ return;
168
+ }
169
+
170
+ this[fail](error);
171
+ return;
172
+ }
173
+
174
+ let packageData;
175
+
176
+ try {
177
+ packageData = JSON.parse(contents);
178
+ } catch (error) {
179
+ this[fail](error);
180
+ return;
181
+ }
182
+
183
+ const version = packageData.version;
184
+
185
+ if (!supportedVersion.test(version) && this[acceptVersion] !== version) {
186
+ this[fail](
187
+ new Error(`Unsupported version of Test262: '${version}'`)
188
+ );
189
+ return;
190
+ }
191
+
192
+ this[next]();
193
+ });
194
+ }
195
+
196
+ // Starts visiting paths until reaching the concurrency limit or filling the
197
+ // stream's buffer, and ends the stream once every path has been visited.
198
+ [next]() {
199
+ if (this[failed] || this.destroyed) {
200
+ return;
201
+ }
202
+
203
+ while (
204
+ this[wanted] &&
205
+ this[active] < concurrency &&
206
+ this[pending].length > 0
207
+ ) {
208
+ this[active] += 1;
209
+ this[visit](this[pending].pop());
210
+ }
211
+
212
+ if (this[active] === 0 && this[pending].length === 0 && !this[ended]) {
213
+ this[ended] = true;
214
+ this.push(null);
215
+ }
216
+ }
217
+
218
+ [done]() {
219
+ this[active] -= 1;
220
+ this[next]();
221
+ }
222
+
223
+ // Node.js 8's default implementation ends the stream, which then emits an
224
+ // `end` event after the `error` one.
225
+ _destroy(error, callback) {
226
+ callback(error);
227
+ }
228
+
229
+ // Stops reading, and does not end the stream.
230
+ [fail](error) {
231
+ // Until Node.js 14, destroying a destroyed stream emits the error again,
232
+ // after the consumer that destroyed it might have stopped listening.
233
+ if (this[failed] || this.destroyed) {
234
+ return;
235
+ }
236
+ this[failed] = true;
237
+
238
+ // `destroy` is only available from Node.js 8.
239
+ if (typeof this.destroy === 'function') {
240
+ this.destroy(error);
241
+ } else {
242
+ this.emit('error', error);
243
+ }
244
+ }
245
+
246
+ // Skips fixtures and hidden files. Like a directory listing, symbolic
247
+ // links are not followed.
248
+ [enqueue](filePath, file, name, isDirectory, isFile) {
249
+ if (isDirectory) {
250
+ this[pending].push({ path: filePath, file, isDirectory: true });
251
+ } else if (isFile && name[0] !== '.' && !fixturePattern.test(filePath)) {
252
+ this[pending].push({ path: filePath, file, isDirectory: false });
253
+ }
254
+ }
255
+
256
+ [visit](item) {
257
+ if (item.isDirectory === undefined) {
258
+ fs.lstat(item.path, (error, stats) => {
259
+ if (error) {
260
+ this[fail](error);
261
+ } else {
262
+ this[enqueue](
263
+ item.path,
264
+ item.file,
265
+ path.basename(item.path),
266
+ stats.isDirectory(),
267
+ stats.isFile()
268
+ );
269
+ }
270
+ this[done]();
271
+ });
272
+ } else if (item.isDirectory) {
273
+ fs.readdir(item.path, { withFileTypes: true }, (error, entries) => {
274
+ if (error) {
275
+ this[fail](error);
276
+ } else {
277
+ // `path.join` would normalize the paths of every entry, which are
278
+ // already normalized.
279
+ const pathPrefix = item.path[item.path.length - 1] === path.sep ?
280
+ item.path : item.path + path.sep;
281
+ const filePrefix = item.file === '' ? '' : item.file + path.sep;
282
+
283
+ // Push in reverse so that reading the entries starts in order. The
284
+ // reads finish in any order, and so are the tests emitted.
285
+ for (let i = entries.length - 1; i >= 0; i--) {
286
+ const entry = entries[i];
287
+
288
+ // Before Node.js 10.10, `readdir` ignores `withFileTypes` and
289
+ // only returns names, so the entries are lstat'ed when visited.
290
+ if (typeof entry === 'string') {
291
+ this[pending].push({
292
+ path: pathPrefix + entry,
293
+ file: filePrefix + entry,
294
+ isDirectory: undefined
295
+ });
296
+ } else {
297
+ this[enqueue](
298
+ pathPrefix + entry.name,
299
+ filePrefix + entry.name,
300
+ entry.name,
301
+ entry.isDirectory(),
302
+ entry.isFile()
303
+ );
304
+ }
305
+ }
306
+ }
307
+ this[done]();
308
+ });
309
+ } else {
310
+ compile(item.path, item.file, this[compileOpts], (error, tests) => {
311
+ if (this[failed] || this.destroyed) {
312
+ return;
313
+ } else if (error) {
314
+ this[fail](error);
315
+ } else {
316
+ for (let i = 0; i < tests.length; i++) {
317
+ // The consumer may destroy the stream when it receives a test,
318
+ // and pushing to a destroyed stream still emits until Node.js 14.
319
+ if (this.destroyed) {
320
+ break;
321
+ }
322
+ if (!this.push(tests[i])) {
323
+ this[wanted] = false;
324
+ }
325
+ }
326
+ }
327
+ this[done]();
328
+ });
329
+ }
330
+ }
331
+ };
@@ -0,0 +1,173 @@
1
+ // Based on
2
+ // https://github.com/smikes/test262-parser/blob/04902c58d2e2d1b452b34754924b8e75f2e5f3ac/lib/parser.js
3
+ // Copyright (C) 2014, Microsoft Corporation. All rights reserved.
4
+ // This code is governed by the BSD License found in the LICENSE-MICROSOFT.txt
5
+ 'use strict';
6
+
7
+ const yaml = require('js-yaml');
8
+ const yamlStart = '/*---';
9
+ const yamlEnd = '---*/';
10
+
11
+ // The copyright line. With the `m` flag, `^` matches at the start of every
12
+ // line, and `.` does not match line terminators, so this matches line by line
13
+ // without splitting the contents into lines.
14
+ // `(?:\/\/.*)*` backtracks exponentially on lines made of many slashes,
15
+ // and `.*` already matches any further `//`, so one optional group
16
+ // matches the same lines.
17
+ const copyrightPattern = /^(?:\/\/.*)? Copyright.*/mg;
18
+
19
+ // Line terminators: \n, \r, U+2028 and U+2029.
20
+ function isLineTerminator(code) {
21
+ return code === 10 || code === 13 || code === 0x2028 || code === 0x2029;
22
+ }
23
+
24
+ /**
25
+ * Extract copyright message
26
+ *
27
+ * @method extractCopyright
28
+ * @param {Test262File} file - file object
29
+ * @return {string} the copyright string extracted from contents
30
+ * @private
31
+ */
32
+ function extractCopyright(test262File) {
33
+ // The very first line may be a hashbang, so look at
34
+ // all lines until reaching a line that looks close
35
+ // enough to copyright
36
+ const contents = test262File.contents;
37
+
38
+ // Only a line containing " Copyright" can match, so start matching at the
39
+ // first one, rather than trying every position of the contents before it,
40
+ // or of all of them when there is no copyright.
41
+ const index = contents.indexOf(' Copyright');
42
+
43
+ if (index === -1) {
44
+ return '';
45
+ }
46
+
47
+ let lineStart = index;
48
+ while (lineStart > 0 && !isLineTerminator(contents.charCodeAt(lineStart - 1))) {
49
+ lineStart -= 1;
50
+ }
51
+
52
+ copyrightPattern.lastIndex = lineStart;
53
+ const result = copyrightPattern.exec(contents);
54
+
55
+ return result ? result[0] : '';
56
+ }
57
+
58
+ /**
59
+ * Extract YAML frontmatter from a test262 test
60
+ * @method extractYAML
61
+ * @param {Test262File} file - file object
62
+ * @return {string} the YAML frontmatter or empty string if none
63
+ */
64
+ function extractYAML(test262File) {
65
+ let start = test262File.contents.indexOf(yamlStart);
66
+
67
+ if (start > -1) {
68
+ return test262File.contents.substring(start + 5, test262File.contents.indexOf(yamlEnd));
69
+ }
70
+
71
+ return '';
72
+ }
73
+
74
+ /**
75
+ * Extract and parse frontmatter from a test
76
+ * @method loadAttrs
77
+ * @param {Test262File} file - file object
78
+ * @return {Object} - raw, unnormalized attributes
79
+ * @private
80
+ */
81
+ function loadAttrs(test262File) {
82
+ let extracted = extractYAML(test262File);
83
+
84
+ if (extracted) {
85
+ try {
86
+ return yaml.load(extracted);
87
+ } catch (e) {
88
+ throw new Error(`Error loading frontmatter from file ${test262File.file}\n${e.message}`);
89
+ }
90
+ }
91
+
92
+ return {};
93
+ }
94
+
95
+ /**
96
+ * Normalize attributes; ensure that flags, includes exist
97
+ *
98
+ * @method extractAttrs
99
+ * @param {Test262File} file - file object
100
+ * @return {Test262FileAttrs} normalized attributes
101
+ * @private
102
+ */
103
+ function extractAttrs(test262File) {
104
+ const attrs = loadAttrs(test262File);
105
+ attrs.flags = attrs.flags || [];
106
+ attrs.flags = attrs.flags.reduce((acc, v) => {
107
+ acc[v] = true;
108
+ return acc;
109
+ }, {});
110
+
111
+ attrs.includes = attrs.includes || [];
112
+
113
+ return attrs;
114
+ }
115
+
116
+ /**
117
+ * filename
118
+ * @property {string} file
119
+ */
120
+ /**
121
+ * test code
122
+ * @property {string} contents
123
+ */
124
+ /**
125
+ * parsed, normalized attributes
126
+ * @property {Object} attrs
127
+ */
128
+ /**
129
+ * copyright message
130
+ * @property {string} copyright
131
+ */
132
+
133
+ /**
134
+ * list of harness files to include
135
+ * @attribute {Array} includes
136
+ */
137
+ /**
138
+ * test flags;
139
+ * https://github.com/tc39/test262/blob/master/INTERPRETING.md#flags
140
+ * valid values include:
141
+ * - async
142
+ * - module
143
+ * - noStrict
144
+ * - onlyStrict
145
+ * - raw
146
+ * @attribute {Object} flags
147
+ */
148
+ /**
149
+ * author name
150
+ * @attribute {String} author
151
+ * @optional
152
+ */
153
+
154
+ class Test262File {
155
+ constructor(file, contents) {
156
+ if (!file) {
157
+ throw new Error('Test262File: missing "file"');
158
+ }
159
+
160
+ if (!contents) {
161
+ throw new Error('Test262File: missing "contents"');
162
+ }
163
+
164
+ this.file = file;
165
+ this.contents = contents;
166
+ this.attrs = extractAttrs(this);
167
+ this.copyright = extractCopyright(this);
168
+ this.scenario = null;
169
+ this.insertionIndex = null;
170
+ }
171
+ }
172
+
173
+ module.exports = Test262File;
package/package.json CHANGED
@@ -1,6 +1,42 @@
1
1
  {
2
2
  "name": "@babel/test262-stream",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "2.0.0",
4
+ "description": "A Node.js API for traversing the Test262 test suite",
5
+ "main": "lib/index.js",
6
+ "directories": {
7
+ "test": "test"
8
+ },
9
+ "scripts": {
10
+ "lint": "jshint lib test benchmark",
11
+ "test": "npm run lint && npm run test-unit",
12
+ "test-unit": "node test/test.js",
13
+ "bench": "node --experimental-bench benchmark/index.js",
14
+ "test-coverage": "node --test --experimental-test-coverage --test-coverage-include='lib/**' --test-coverage-exclude='test/**' --test-coverage-lines=100 --test-coverage-branches=100 --test-coverage-functions=100 test/test.js",
15
+ "test-types": "tsc -p test/types"
16
+ },
17
+ "author": "",
18
+ "license": "BSD-3-Clause",
19
+ "repository": {
20
+ "type": "git",
21
+ "url": "git+https://github.com/babel/test262-stream.git"
22
+ },
23
+ "publishConfig": {
24
+ "access": "public"
25
+ },
26
+ "devDependencies": {
27
+ "@types/node": "^26.6.6",
28
+ "jshint": "^2.10.2",
29
+ "tape": "^5.11.0",
30
+ "typescript": "^7.0.2"
31
+ },
32
+ "dependencies": {
33
+ "js-yaml": "^3.2.1"
34
+ },
35
+ "files": [
36
+ "lib",
37
+ "LICENSE-MICROSOFT.txt",
38
+ "LICENSE-BOCOUP.txt",
39
+ "LICENSE.txt"
40
+ ],
41
+ "types": "lib/index.d.ts"
42
+ }