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

chore: rework component onboarding in launchpad #25713

Merged
merged 40 commits into from
Feb 13, 2023
Merged
Show file tree
Hide file tree
Changes from 29 commits
Commits
Show all changes
40 commits
Select commit Hold shift + click to select a range
b920973
chore: refactoring and types
lmiller1990 Feb 3, 2023
9af7df5
rework source of frameworks
lmiller1990 Feb 3, 2023
b0e6a54
revert rename
lmiller1990 Feb 3, 2023
8685358
fix tests
lmiller1990 Feb 6, 2023
7f46405
Merge remote-tracking branch 'origin/develop' into lmiller/ct-public-…
lmiller1990 Feb 6, 2023
bd446d7
fix more tests
lmiller1990 Feb 6, 2023
169fd2d
types
lmiller1990 Feb 6, 2023
9a58381
update code
lmiller1990 Feb 6, 2023
fe5c399
use same public API internally
lmiller1990 Feb 6, 2023
04eff95
Merge remote-tracking branch 'origin/develop' into lmiller/ct-public-…
lmiller1990 Feb 6, 2023
c9dc13b
rename interfaces
lmiller1990 Feb 6, 2023
57a8c33
rename
lmiller1990 Feb 6, 2023
9582e8d
work on dev server api
lmiller1990 Feb 7, 2023
aa03f22
fix types
lmiller1990 Feb 7, 2023
55eeadf
fix test
lmiller1990 Feb 7, 2023
2c722c3
attempt to support getDevServerConfig
lmiller1990 Feb 7, 2023
6c73ff5
tests
lmiller1990 Feb 7, 2023
7d3535f
add function to define framework [skip ci]
lmiller1990 Feb 7, 2023
2ae85c0
rework a lot of types
lmiller1990 Feb 7, 2023
b8ff1a0
fix test
lmiller1990 Feb 7, 2023
e9257c7
update tests and types
lmiller1990 Feb 7, 2023
681294a
Merge remote-tracking branch 'origin/feature/ct-public-api' into lmil…
lmiller1990 Feb 8, 2023
08dba6b
refactor
lmiller1990 Feb 8, 2023
1d959ae
revert changes
lmiller1990 Feb 8, 2023
3dbd6c1
lint
lmiller1990 Feb 8, 2023
54fee26
fix test
lmiller1990 Feb 8, 2023
b441be4
revert
lmiller1990 Feb 8, 2023
57c2ab9
remove
lmiller1990 Feb 8, 2023
bf884c7
add "community" label [skip ci]
lmiller1990 Feb 8, 2023
33feea4
refactor
lmiller1990 Feb 10, 2023
c8087c1
types
lmiller1990 Feb 10, 2023
270e4e7
lint
lmiller1990 Feb 10, 2023
5060900
fix bug
lmiller1990 Feb 10, 2023
6d6d718
update function name
lmiller1990 Feb 10, 2023
29c8b45
Merge branch 'feature/ct-public-api' into lmiller/ct-public-api-refactor
ZachJW34 Feb 10, 2023
08b705a
address feedback
ZachJW34 Feb 10, 2023
82fe744
improve types with Pick
lmiller1990 Feb 12, 2023
da254fd
refactor using type guard
lmiller1990 Feb 12, 2023
988142c
Merge branch 'feature/ct-public-api' into lmiller/ct-public-api-refactor
lmiller1990 Feb 12, 2023
45bbd45
correct label
lmiller1990 Feb 12, 2023
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
156 changes: 156 additions & 0 deletions cli/types/cypress.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3244,6 +3244,162 @@ declare namespace Cypress {

type PickConfigOpt<T> = T extends keyof DefineDevServerConfig ? DefineDevServerConfig[T] : any

interface DependencyToInstall {
dependency: CypressComponentDependency
satisfied: boolean
loc: string | null
detectedVersion: string | null
}

interface CypressComponentDependency {
/**
* Unique idenitifer.
* @example 'reactscripts'
*/
type: string

/**
* Name to display in the user interface.
* @example "React Scripts"
*/
name: string

/**
* Package name on npm.
* @example react-scripts
*/
package: string

/**
* Code to run when installing. Version is optional.
*
* Should be <package_name>@<version>.
*
* @example `react`
* @example `react@18`
* @example `react-scripts`
*/
installer: string

/**
* Description shown in UI. It is recommended to use the same one the package uses on npm.
* @example 'Create React apps with no build configuration'
*/
description: string

/**
* Minimum version supported. Should conform to Semantic Versioning as used in `package.json`.
* @see https://docs.npmjs.com/cli/v9/configuring-npm/package-json#dependencies
* @example '^=4.0.0 || ^=5.0.0'
* @example '^2.0.0'
*/
minVersion: string
}

interface ResolvedComponentFrameworkDefinition {
/**
* A semantic, unique identifier. Must begin with `cypress-ct-` for third party implementations.
* @example: 'reactscripts', 'nextjs', 'cypress-ct-solid-js'
*/
type: string
Copy link
Contributor

Choose a reason for hiding this comment

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

Here we say the type must start with cypress-ct-, but the configFramework doesn't have this restriction even though inside of webpack-dev-server/src/devServer.ts we expect it to also have this same restriction. Looks like they should be the same or at least both should share the cypress-ct- prefix

Copy link
Contributor Author

Choose a reason for hiding this comment

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

Hm good point, maybe we just expose name in the public API and for third parties, in processFrameworkDefinition, do

configFramework = name

Copy link
Contributor Author

Choose a reason for hiding this comment

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

So configFramework will be @private

Copy link
Contributor Author

Choose a reason for hiding this comment

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

Done


/**
* Used as the flag for `getPreset` for meta framworks, such as finding the webpack config for CRA, Angular, etc.
*
* configFramwork: () => {
* return getSolidJsMetaFrameworkBundlerConfig()
* }
* It is also the name of the string added to `cypress.config`
*
* @example
*
* export default {
* component: {
* devServer: {
* framework: 'create-react-app' // can be 'next', 'create-react-app', etc etc.
* }
* }
* }
*/
configFramework: string

/**
* Library (React, Vue) or template (aka "meta framework") (CRA, Next.js, Angular)
*/
category: 'library' | 'template'

/**
* Name displayed in Launchpad when doing initial setup.
* @example 'Solid.js', 'Create React App'
*/
name: string

/**
* Supported bundlers.
*/
supportedBundlers: Array<'webpack' | 'vite'>

/**
* Used to attempt to automatically select the correct framework/bundler from the dropdown.
* @example
*
* const SOLID_DETECTOR: Dependency = {
* type: 'solid',
* name: 'Solid.js',
* package: 'solid-js',
* installer: 'solid-js',
* description: 'Solid is a declarative JavaScript library for creating user interfaces',
* minVersion: '^1.0.0',
* }
*/
detectors: CypressComponentDependency[]

/**
* Array of required dependencies. This could be the bundler and JavaScript library.
* It's the same type as `detectors`.
*/
dependencies: (bundler: 'webpack' | 'vite', projectPath: string) => Promise<DependencyToInstall[]>

/**
* @internal
* This is used interally by Cypress for the "Create From Component" feature.
*/
codeGenFramework?: 'react' | 'vue' | 'svelte' | 'angular'

/**
* @internal
* This is used interally by Cypress for the "Create From Component" feature.
* @example '*.{js,jsx,tsx}'
*/
glob?: string

/**
* This is the path to get mount, eg `import { mount } from <mount_module>,
* @example: `cypress-ct-solidjs/src/mount`
*/
mountModule: (projectPath: string) => Promise<string>
Copy link
Contributor

Choose a reason for hiding this comment

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

Mentioned this in the tech-brief but I'm curious what you think of making the ThirdPartyComponentFrameworkDefinition have mountModule: string for simplicity?

Copy link
Contributor Author

Choose a reason for hiding this comment

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

Good point, I was trying to make the APIs as similar as possible but it's probably not worth it - better to opt for some internal complexity and expose a nicer public API

Copy link
Contributor Author

Choose a reason for hiding this comment

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

We don't need mountModule at all for third parties now... https://github.com/cypress-io/engineering-documentation/pull/71

Since we assume it's named export from the default entry point, we can assume import { mount } from '<package>' is valid.


/**
* Support status. Internally alpha | beta | full.
* Community integrations are "community".
* @internal
*/
supportStatus: 'alpha' | 'beta' | 'full' | 'community'

/**
* Function returning string for used for the component-index.html file.
* Cypress provides a default if one isn't specified for third party integrations.
*/
componentIndexHtml?: () => string

/**
* Used for the Create From Comopnent feature.
* This is currently not supported for third party frameworks.
* @internal
*/
specPattern?: '**/*.cy.ts'
}

interface AngularDevServerProjectConfig {
root: string
sourceRoot: string
Expand Down
9 changes: 8 additions & 1 deletion npm/webpack-dev-server/src/devServer.ts
Original file line number Diff line number Diff line change
Expand Up @@ -115,6 +115,13 @@ export type PresetHandlerResult = { frameworkConfig: Configuration, sourceWebpac
type Optional<T, K extends keyof T> = Pick<Partial<T>, K> & Omit<T, K>

async function getPreset (devServerConfig: WebpackDevServerConfig): Promise<Optional<PresetHandlerResult, 'frameworkConfig'>> {
const defaultWebpackModules = () => ({ sourceWebpackModulesResult: sourceDefaultWebpackDependencies(devServerConfig) })

// Third party library (eg solid-js, lit, etc)
if (devServerConfig.framework?.startsWith('cypress-ct-')) {
return defaultWebpackModules()
}

switch (devServerConfig.framework) {
case 'create-react-app':
return createReactAppHandler(devServerConfig)
Expand All @@ -134,7 +141,7 @@ async function getPreset (devServerConfig: WebpackDevServerConfig): Promise<Opti
case 'vue':
case 'svelte':
case undefined:
return { sourceWebpackModulesResult: sourceDefaultWebpackDependencies(devServerConfig) }
return defaultWebpackModules()

default:
throw new Error(`Unexpected framework ${(devServerConfig as any).framework}, please visit https://on.cypress.io/component-framework-configuration to see a list of supported frameworks`)
Expand Down
5 changes: 2 additions & 3 deletions packages/data-context/src/actions/CodegenActions.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,6 @@ import type { DataContext } from '..'
import { SpecOptions, codeGenerator } from '../codegen'
import templates from '../codegen/templates'
import type { CodeGenType } from '../gen/graphcache-config.gen'
import { WizardFrontendFramework, WIZARD_FRAMEWORKS } from '@packages/scaffold-config'
import { parse as parseReactComponent, resolver as reactDocgenResolvers } from 'react-docgen'
import { visit } from 'ast-types'

Expand Down Expand Up @@ -152,7 +151,7 @@ export class CodegenActions {
})
}

getWizardFrameworkFromConfig (): WizardFrontendFramework | undefined {
Copy link
Contributor Author

Choose a reason for hiding this comment

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

In general I think we should move away from naming things "Wizard". 🧙 are pretty cool, but it's probably a confusing, considering these are used throughout the entire app, not just in the Launchpad wizard.

We should just call them ComponentFrontendFramework, since that's what they are.

Copy link
Contributor

Choose a reason for hiding this comment

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

I agree Wizards are pretty cool

getWizardFrameworkFromConfig (): Cypress.ResolvedComponentFrameworkDefinition | undefined {
const config = this.ctx.lifecycleManager.loadedConfigFile

// If devServer is a function, they are using a custom dev server.
Expand All @@ -161,7 +160,7 @@ export class CodegenActions {
}

// @ts-ignore - because of the conditional above, we know that devServer isn't a function
return WIZARD_FRAMEWORKS.find((framework) => framework.configFramework === config?.component?.devServer.framework)
return this.ctx.coreData.wizard.frameworks.find((framework) => framework.configFramework === config?.component?.devServer.framework)
}
}

Expand Down
39 changes: 27 additions & 12 deletions packages/data-context/src/actions/WizardActions.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import type { NexusGenObjects } from '@packages/graphql/src/gen/nxs.gen'
import { detectFramework, WIZARD_FRAMEWORKS, commandsFileBody, supportFileComponent, supportFileE2E, WizardBundler, WizardFrontendFramework } from '@packages/scaffold-config'
import { detectFramework, commandsFileBody, supportFileComponent, supportFileE2E, getBundler } from '@packages/scaffold-config'
import assert from 'assert'
import path from 'path'
import Debug from 'debug'
Expand All @@ -9,6 +9,7 @@ const debug = Debug('cypress:data-context:wizard-actions')

import type { DataContext } from '..'
import { addTestingTypeToCypressConfig, AddTestingTypeToCypressConfigOptions } from '@packages/config'
import componentIndexHtmlGenerator from '@packages/scaffold-config/src/component-index-template'

export class WizardActions {
constructor (private ctx: DataContext) {}
Expand All @@ -23,14 +24,14 @@ export class WizardActions {
return this.ctx.wizardData
}

setFramework (framework: WizardFrontendFramework | null): void {
const next = WIZARD_FRAMEWORKS.find((x) => x.type === framework?.type)
setFramework (framework: Cypress.ResolvedComponentFrameworkDefinition | null): void {
const next = this.ctx.coreData.wizard.frameworks.find((x) => x.type === framework?.type)

this.ctx.update((coreData) => {
coreData.wizard.chosenFramework = framework
})

if (next?.supportedBundlers?.length === 1) {
if (next?.supportedBundlers?.[0] && next.supportedBundlers.length === 1) {
this.setBundler(next?.supportedBundlers?.[0])

return
Expand All @@ -41,7 +42,7 @@ export class WizardActions {
// if the previous bundler was incompatible with the
// new framework that was selected, we need to reset it
const doesNotSupportChosenBundler = (chosenBundler && !new Set(
this.ctx.coreData.wizard.chosenFramework?.supportedBundlers.map((x) => x.type) || [],
this.ctx.coreData.wizard.chosenFramework?.supportedBundlers ?? [],
).has(chosenBundler.type)) ?? false

const prevFramework = this.ctx.coreData.wizard.chosenFramework?.type ?? null
Expand All @@ -51,9 +52,21 @@ export class WizardActions {
}
}

setBundler (bundler: WizardBundler | null) {
getNullableBundler (bundler: 'vite' | 'webpack' | null) {
Copy link
Contributor Author

@lmiller1990 lmiller1990 Feb 8, 2023

Choose a reason for hiding this comment

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

So the reason for all the change around bundler is previously we did something like:

export const WIZARD_DEPENDENCY_WEBPACK = {
  type: 'webpack',
  name: 'Webpack',
  package: 'webpack',
  installer: 'webpack',
  description: 'Webpack is a module bundler',
  minVersion: '^=4.0.0 || ^=5.0.0',
} 

supportedBundlers: [WIZARD_DEPENDENCY_WEBPACK]

But for a third party to do this, we'd need to expose the WIZARD_DEPENDENCY_WEBPACK, which is not really ideal or in line with what we currently do and how we define public APIs. In cypress.config, we just do

bundler: 'webpack'

I reworked the internal API (which is also now the public API) to use a string, webpack | vite, instead of the complex WIZARD_DEPENDENCY_WEBPACK object.

Now, it's just

supportedBundlers: ['webpack']

It's way more ergonomic, and mirrors how cypress.config looks. I like this parallel. If we do need the full object, we just use getNullableBundler to grab it.

if (!bundler) {
return null
}

try {
return getBundler(bundler)
} catch (e) {
return null
}
}

setBundler (bundler: 'vite' | 'webpack' | null) {
this.ctx.update((coreData) => {
coreData.wizard.chosenBundler = bundler
coreData.wizard.chosenBundler = this.getNullableBundler(bundler)
})

return this.ctx.coreData.wizard
Expand Down Expand Up @@ -87,7 +100,7 @@ export class WizardActions {

this.resetWizard()

const detected = await detectFramework(this.ctx.currentProject)
const detected = await detectFramework(this.ctx.currentProject, this.ctx.coreData.wizard.frameworks)

debug('detected %o', detected)

Expand All @@ -100,8 +113,8 @@ export class WizardActions {
return
}

coreData.wizard.detectedBundler = detected.bundler || detected.framework.supportedBundlers[0]
coreData.wizard.chosenBundler = detected.bundler || detected.framework.supportedBundlers[0]
coreData.wizard.detectedBundler = this.getNullableBundler(detected.bundler || detected.framework.supportedBundlers[0])
coreData.wizard.chosenBundler = this.getNullableBundler(detected.bundler || detected.framework.supportedBundlers[0])
})
}
}
Expand Down Expand Up @@ -295,14 +308,16 @@ export class WizardActions {
}
}

private async scaffoldComponentIndexHtml (chosenFramework: WizardFrontendFramework): Promise<NexusGenObjects['ScaffoldedFile']> {
private async scaffoldComponentIndexHtml (chosenFramework: Cypress.ResolvedComponentFrameworkDefinition): Promise<NexusGenObjects['ScaffoldedFile']> {
const componentIndexHtmlPath = path.join(this.projectRoot, 'cypress', 'support', 'component-index.html')

await this.ensureDir('support')

const defaultComponentIndex = componentIndexHtmlGenerator('')
mike-plummer marked this conversation as resolved.
Show resolved Hide resolved

return this.scaffoldFile(
componentIndexHtmlPath,
chosenFramework.componentIndexHtml(),
chosenFramework.componentIndexHtml?.() ?? defaultComponentIndex(),
Copy link
Contributor Author

Choose a reason for hiding this comment

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

The reason this is now nullable is since third parties CAN provide a custom component-index.html, but don't need to. If they don't, they get our default one.

'The HTML wrapper that each component is served with. Used for global fonts, CSS, JS, HTML, etc.',
)
}
Expand Down
3 changes: 1 addition & 2 deletions packages/data-context/src/codegen/spec-options.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,5 @@
import type { ParsedPath } from 'path'
import type { CodeGenType } from '@packages/graphql/src/gen/nxs.gen'
import type { WizardFrontendFramework } from '@packages/scaffold-config'
import fs from 'fs-extra'
import { uniq, upperFirst } from 'lodash'
import path from 'path'
Expand All @@ -14,7 +13,7 @@ interface CodeGenOptions {
isDefaultSpecPattern: boolean
specPattern: string[]
currentProject: string | null
framework?: WizardFrontendFramework
framework?: Cypress.ResolvedComponentFrameworkDefinition
specs?: FoundSpec[]
componentName?: string
isDefault?: boolean
Expand Down
17 changes: 11 additions & 6 deletions packages/data-context/src/data/ProjectConfigManager.ts
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@ import { CypressEnv } from './CypressEnv'
import { autoBindDebug } from '../util/autoBindDebug'
import type { EventRegistrar } from './EventRegistrar'
import type { DataContext } from '../DataContext'
import { DependencyToInstall, isDependencyInstalled, WIZARD_BUNDLERS, WIZARD_DEPENDENCIES, WIZARD_FRAMEWORKS } from '@packages/scaffold-config'
import { isDependencyInstalled, WIZARD_BUNDLERS } from '@packages/scaffold-config'

const debug = debugLib(`cypress:lifecycle:ProjectConfigManager`)

Expand Down Expand Up @@ -191,14 +191,19 @@ export class ProjectConfigManager {

// Use a map since sometimes the same dependency can appear in `bundler` and `framework`,
// for example webpack appears in both `bundler: 'webpack', framework: 'react-scripts'`
const unsupportedDeps = new Map<DependencyToInstall['dependency']['type'], DependencyToInstall>()
const unsupportedDeps = new Map<Cypress.DependencyToInstall['dependency']['type'], Cypress.DependencyToInstall>()

if (!bundler) {
return
}

const isFrameworkSatisfied = async (bundler: typeof WIZARD_BUNDLERS[number], framework: typeof WIZARD_FRAMEWORKS[number]) => {
for (const dep of await (framework.dependencies(bundler.type, this.options.projectRoot))) {
const isFrameworkSatisfied = async (bundler: typeof WIZARD_BUNDLERS[number], framework: Cypress.ResolvedComponentFrameworkDefinition) => {
const deps = await (framework.dependencies(bundler.type, this.options.projectRoot))
mike-plummer marked this conversation as resolved.
Show resolved Hide resolved

debug('deps are %o', deps)

for (const dep of deps) {
Copy link
Contributor

Choose a reason for hiding this comment

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

Could do this in a bit more compact fashion with every:

return deps.every((dep) => {
  debug('detecting %s in %s', dep.dependency.name, this.options.projectRoot)
  const res = await isDependencyInstalled(dep.dependency, this.options.projectRoot)
  return res.satisfied
})

Automatically takes care of ejecting from the loop once when it hits the first false

Copy link
Contributor

Choose a reason for hiding this comment

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

Unless I'm doing something weird I don't think .every/.some supports async callbacks. The callback needs to return a boolean, not a Promise<boolean>.

Copy link
Contributor

Choose a reason for hiding this comment

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

Ugh, totally glossed over the async nature here. Oops.

Copy link
Contributor Author

Choose a reason for hiding this comment

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

Still likely possible if we really do not like for loops:

const installed = await Promise.all(deps.map(async (dep) => {
  debug('detecting %s in %s', dep.dependency.name, this.options.projectRoot)
  const res = await isDependencyInstalled(dep.dependency, this.options.projectRoot)
  return res.satisfied
}))

const result = installed.every(Boolean)

for loop seems more sane at this point.

debug('detecting %s in %s', dep.dependency.name, this.options.projectRoot)
const res = await isDependencyInstalled(dep.dependency, this.options.projectRoot)

if (!res.satisfied) {
Expand All @@ -209,9 +214,9 @@ export class ProjectConfigManager {
return true
}

const frameworks = WIZARD_FRAMEWORKS.filter((x) => x.configFramework === devServerOptions.framework)
const frameworks = this.options.ctx.coreData.wizard.frameworks.filter((x) => x.configFramework === devServerOptions.framework)
Copy link
Contributor

Choose a reason for hiding this comment

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

There are a couple places we're filtering through this coreData.wizard.frameworks array - worth extracting these into some findBy... utils under WizardDataSource?


const mismatchedFrameworkDeps = new Map<typeof WIZARD_DEPENDENCIES[number]['type'], DependencyToInstall>()
const mismatchedFrameworkDeps = new Map<string, Cypress.DependencyToInstall>()

let isSatisfied = false

Expand Down
Loading