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

add ESM support (take 2) #1649

Merged
merged 33 commits into from
Sep 18, 2021
Merged
Show file tree
Hide file tree
Changes from 24 commits
Commits
Show all changes
33 commits
Select commit Hold shift + click to select a range
d268a8d
Revert "temporarily revert ESM change (#1647)"
davidjgoss Apr 21, 2021
e6ae1e7
add failing scenario for deep imports
davidjgoss Apr 22, 2021
836b968
merge main
davidjgoss Jun 20, 2021
0f46a86
merge main
davidjgoss Jul 1, 2021
ec04d2f
define entry point with dot
davidjgoss Jul 1, 2021
16e4f2f
make deep imports work via export patterns
davidjgoss Jul 1, 2021
a3a0414
move doc to own file
davidjgoss Jul 1, 2021
ce73823
link to doc from readme
davidjgoss Jul 1, 2021
3bc91ad
add changelog entry
davidjgoss Jul 1, 2021
47a2c68
add example to doc
davidjgoss Jul 2, 2021
6b8ffd9
remove confusing comment
davidjgoss Jul 2, 2021
947b39f
remove cli option, use import by default
davidjgoss Jul 3, 2021
5fa807c
update documentation
davidjgoss Jul 8, 2021
2b59f6e
remove redundant describe
davidjgoss Jul 8, 2021
5465783
fix ordering
davidjgoss Jul 8, 2021
7dec8dc
Merge remote-tracking branch 'origin/main' into esm-take-2
davidjgoss Jul 8, 2021
6d782de
Merge branch 'main' into esm-take-2
davidjgoss Jul 10, 2021
7cfdd73
Update features/esm.feature
davidjgoss Jul 12, 2021
0244b61
Update features/esm.feature
davidjgoss Jul 12, 2021
148f4c4
Merge branch 'main' into esm-take-2
davidjgoss Jul 28, 2021
c71d5b9
simplify tagging
davidjgoss Jul 28, 2021
809f5af
use import only if a javascript file
davidjgoss Jul 28, 2021
a870138
add note about no transpilers
davidjgoss Jul 28, 2021
46125e2
inline to avoid confusing reassignment
davidjgoss Jul 28, 2021
ebbf550
whoops, re-add try/catch
davidjgoss Jul 28, 2021
9fefa63
merge main
davidjgoss Sep 5, 2021
8ece5f8
use require with transpilers; import otherwise
davidjgoss Sep 5, 2021
b3e81cc
remove pointless return
davidjgoss Sep 5, 2021
1bf48db
Merge branch 'main' into esm-take-2
aurelien-reeves Sep 7, 2021
c457355
support .cjs config file
davidjgoss Sep 5, 2021
6714025
Merge branch 'main' into esm-take-2
davidjgoss Sep 16, 2021
8037766
type and import the importer
davidjgoss Sep 16, 2021
83e513b
actually dont import - causes issues
davidjgoss Sep 18, 2021
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
2 changes: 2 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,8 @@ See the [migration guide](./docs/migration.md) for details of how to migrate fro

### Added

* Add support for user code as native ES modules

### Changed

### Deprecated
Expand Down
1 change: 1 addition & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -67,6 +67,7 @@ The following documentation is for master. See below for documentation for older
* [Attachments](/docs/support_files/attachments.md)
* [API Reference](/docs/support_files/api_reference.md)
* Guides
* [ES Modules](./docs/esm.md)
* [Running in parallel](./docs/parallel.md)
* [Retrying failing scenarios](./docs/retry.md)
* [Profiles](./docs/profiles.md)
Expand Down
1 change: 1 addition & 0 deletions dependency-lint.yml
Original file line number Diff line number Diff line change
Expand Up @@ -44,6 +44,7 @@ requiredModules:
- 'dist/**/*'
- 'lib/**/*'
- 'node_modules/**/*'
- 'src/importer.js'
- 'tmp/**/*'
root: '**/*.{js,ts}'
stripLoaders: false
Expand Down
32 changes: 32 additions & 0 deletions docs/esm.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
# ES Modules (experimental)

You can optionally write your support code (steps, hooks, etc) with native ES modules syntax - i.e. using `import` and `export` statements without transpiling. This is enabled without any additional configuration, and you can use either of the `.js` or `.mjs` file extensions.

Example (adapted from [our original example](./nodejs_example.md)):

```javascript
// features/support/steps.mjs
import { Given, When, Then } from '@cucumber/cucumber'
import { strict as assert } from 'assert'

Given('a variable set to {int}', function (number) {
this.setTo(number)
})

When('I increment the variable by {int}', function (number) {
this.incrementBy(number)
})

Then('the variable should contain {int}', function (number) {
assert.equal(this.variable, number)
})
```

As well as support code, these things can also be in ES modules syntax:

- Custom formatters
- Custom snippets

You can use ES modules selectively/incrementally - so you can have a mixture of CommonJS and ESM in the same project.
davidjgoss marked this conversation as resolved.
Show resolved Hide resolved

When using a transpiler for e.g. TypeScript, ESM isn't supported - you'll need to configure your transpiler to output modules in CommonJS syntax (for now).
17 changes: 17 additions & 0 deletions features/direct_imports.feature
Original file line number Diff line number Diff line change
Expand Up @@ -44,3 +44,20 @@ Feature: Core feature elements execution using direct imports
"""
features/step_definitions/cucumber_steps.js:3
"""

Scenario: deep imports don't break everything
Given a file named "features/a.feature" with:
"""
Feature: some feature
Scenario: some scenario
Given a step passes
"""
And a file named "features/step_definitions/cucumber_steps.js" with:
"""
const {Given} = require('@cucumber/cucumber')
const TestCaseHookDefinition = require('@cucumber/cucumber/lib/models/test_case_hook_definition')

Given(/^a step passes$/, function() {});
"""
When I run cucumber-js
Then it passes
57 changes: 57 additions & 0 deletions features/esm.feature
Original file line number Diff line number Diff line change
@@ -0,0 +1,57 @@
@esm
Feature: ES modules support

cucumber-js works with native ES modules

Scenario Outline: native module syntax works in support code, formatters and snippets
Given a file named "features/a.feature" with:
"""
Feature:
Scenario: one
Given a step passes

Scenario: two
Given a step passes
"""
And a file named "features/step_definitions/cucumber_steps.js" with:
"""
import {Given} from '@cucumber/cucumber'

Given(/^a step passes$/, function() {});
"""
And a file named "custom-formatter.js" with:
"""
import {SummaryFormatter} from '@cucumber/cucumber'

export default class CustomFormatter extends SummaryFormatter {}
"""
And a file named "custom-snippet-syntax.js" with:
"""
export default class CustomSnippetSyntax {
build(opts) {
return 'hello world'
}
}
"""
When I run cucumber-js with `<options> --format ./custom-formatter.js --format-options '{"snippetSyntax": "./custom-snippet-syntax.js"}' <args>`
Then it passes
Examples:
| args |
| |
| --parallel 2 |

Scenario: .mjs support code files are matched by default
Given a file named "features/a.feature" with:
"""
Feature:
Scenario:
Given a step passes
"""
And a file named "features/step_definitions/cucumber_steps.mjs" with:
"""
import {Given} from '@cucumber/cucumber'

Given(/^a step passes$/, function() {});
"""
When I run cucumber-js
Then it passes
10 changes: 9 additions & 1 deletion features/support/hooks.ts
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@ Before('@debug', function (this: World) {
this.debug = true
})

Before('@spawn', function (this: World) {
Before('@spawn or @esm', function (this: World) {
this.spawn = true
})

Expand Down Expand Up @@ -43,6 +43,14 @@ Before(function (
this.localExecutablePath = path.join(projectPath, 'bin', 'cucumber-js')
})

Before('@esm', function (this: World) {
fsExtra.writeJSONSync(path.join(this.tmpDir, 'package.json'), {
name: 'feature-test-pickle',
type: 'module',
})
return undefined
davidjgoss marked this conversation as resolved.
Show resolved Hide resolved
})

Before('@global-install', function (this: World) {
const tmpObject = tmp.dirSync({ unsafeCleanup: true })

Expand Down
12 changes: 10 additions & 2 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -163,6 +163,15 @@
"lib": "./lib"
},
"main": "./lib/index.js",
"exports": {
".": {
"import": "./lib/wrapper.mjs",
"require": "./lib/index.js"
},
"./lib/*": {
"require": "./lib/*.js"
}
},
"types": "./lib/index.d.ts",
"engines": {
"node": ">=12"
Expand All @@ -180,7 +189,6 @@
"cli-table3": "^0.6.0",
"colors": "^1.4.0",
"commander": "^8.0.0",
"create-require": "^1.1.1",
"duration": "^0.2.2",
"durations": "^3.4.2",
"figures": "^3.2.0",
Expand Down Expand Up @@ -252,7 +260,7 @@
"typescript": "4.3.5"
},
"scripts": {
"build-local": "tsc -p tsconfig.node.json",
"build-local": "tsc -p tsconfig.node.json && cp src/importer.js lib/ && cp src/wrapper.mjs lib/",
"cck-test": "mocha 'compatibility/**/*_spec.ts'",
"feature-test": "node ./bin/cucumber-js",
"html-formatter": "node ./bin/cucumber-js --profile htmlFormatter",
Expand Down
2 changes: 1 addition & 1 deletion src/cli/configuration_builder.ts
Original file line number Diff line number Diff line change
Expand Up @@ -76,7 +76,7 @@ export default class ConfigurationBuilder {
}
supportCodePaths = await this.expandPaths(
unexpandedSupportCodePaths,
'.js'
'.@(js|mjs)'
)
}
return {
Expand Down
8 changes: 5 additions & 3 deletions src/cli/configuration_builder_spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -71,8 +71,10 @@ describe('Configuration', () => {
const relativeFeaturePath = path.join('features', 'a.feature')
const featurePath = path.join(cwd, relativeFeaturePath)
await fsExtra.outputFile(featurePath, '')
const supportCodePath = path.join(cwd, 'features', 'a.js')
await fsExtra.outputFile(supportCodePath, '')
const jsSupportCodePath = path.join(cwd, 'features', 'a.js')
await fsExtra.outputFile(jsSupportCodePath, '')
const esmSupportCodePath = path.join(cwd, 'features', 'a.mjs')
await fsExtra.outputFile(esmSupportCodePath, '')
const argv = baseArgv.concat([relativeFeaturePath])

// Act
Expand All @@ -82,7 +84,7 @@ describe('Configuration', () => {
// Assert
expect(featurePaths).to.eql([featurePath])
expect(pickleFilterOptions.featurePaths).to.eql([relativeFeaturePath])
expect(supportCodePaths).to.eql([supportCodePath])
expect(supportCodePaths).to.eql([jsSupportCodePath, esmSupportCodePath])
})

it('deduplicates the .feature files before returning', async function () {
Expand Down
26 changes: 16 additions & 10 deletions src/cli/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -29,7 +29,10 @@ import { IParsedArgvFormatOptions } from './argv_parser'
import HttpStream from '../formatter/http_stream'
import { promisify } from 'util'
import { Writable } from 'stream'
import { pathToFileURL } from 'url'

// eslint-disable-next-line @typescript-eslint/no-var-requires
const { importer } = require('../importer')
const { incrementing, uuid } = IdGenerator

export interface ICliRunResult {
Expand Down Expand Up @@ -143,29 +146,32 @@ export default class Cli {
)
type = 'progress'
}
return FormatterBuilder.build(type, typeOptions)
return await FormatterBuilder.build(type, typeOptions)
})
)
return async function () {
await Promise.all(formatters.map(async (f) => await f.finished()))
}
}

getSupportCodeLibrary({
async getSupportCodeLibrary({
newId,
supportCodeRequiredModules,
supportCodePaths,
}: IGetSupportCodeLibraryRequest): ISupportCodeLibrary {
}: IGetSupportCodeLibraryRequest): Promise<ISupportCodeLibrary> {
supportCodeRequiredModules.map((module) => require(module))
supportCodeLibraryBuilder.reset(this.cwd, newId)
supportCodePaths.forEach((codePath) => {
try {
for (const codePath of supportCodePaths) {
if (
codePath.endsWith('.js') ||
codePath.endsWith('.mjs') ||
codePath.endsWith('.cjs')
) {
await importer(pathToFileURL(codePath))
} else {
require(codePath)
aurelien-reeves marked this conversation as resolved.
Show resolved Hide resolved
} catch (e) {
console.error(e.stack)
console.error('codepath: ' + codePath)
}
})
}
return supportCodeLibraryBuilder.finalize()
}

Expand All @@ -184,7 +190,7 @@ export default class Cli {
configuration.predictableIds && configuration.parallel <= 1
? incrementing()
: uuid()
const supportCodeLibrary = this.getSupportCodeLibrary({
const supportCodeLibrary = await this.getSupportCodeLibrary({
newId,
supportCodePaths: configuration.supportCodePaths,
supportCodeRequiredModules: configuration.supportCodeRequiredModules,
Expand Down
9 changes: 3 additions & 6 deletions src/cli/profile_loader.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,19 +4,16 @@ import stringArgv from 'string-argv'
import { doesHaveValue, doesNotHaveValue } from '../value_checker'

export default class ProfileLoader {
private readonly directory: string

constructor(directory: string) {
this.directory = directory
}
constructor(private readonly directory: string) {}

async getDefinitions(): Promise<Record<string, string>> {
const definitionsFilePath = path.join(this.directory, 'cucumber.js')
const exists = await fs.exists(definitionsFilePath)
if (!exists) {
return {}
}
const definitions = require(definitionsFilePath) // eslint-disable-line @typescript-eslint/no-var-requires
// eslint-disable-next-line @typescript-eslint/no-var-requires
const definitions = require(definitionsFilePath)
if (typeof definitions !== 'object') {
throw new Error(`${definitionsFilePath} does not export an object`)
}
Expand Down
Loading