diff --git a/packages/babel-preset-sui/src/index.js b/packages/babel-preset-sui/src/index.js index 9b8c84530..f37794122 100644 --- a/packages/babel-preset-sui/src/index.js +++ b/packages/babel-preset-sui/src/index.js @@ -1,17 +1,10 @@ -const { - DEFAULT_LEGACY_BROWSER_TARGETS, - DEFAULT_BROWSER_TARGETS, - DEFAULT_SERVER_TARGETS -} = require('./defaults.js') +const {DEFAULT_LEGACY_BROWSER_TARGETS, DEFAULT_BROWSER_TARGETS, DEFAULT_SERVER_TARGETS} = require('./defaults.js') const getTargets = ({targets = {}, isModern, isServer}) => { const {server, browser} = targets if (isModern && isServer) return server ?? DEFAULT_SERVER_TARGETS - return ( - browser ?? - (isModern ? DEFAULT_BROWSER_TARGETS : DEFAULT_LEGACY_BROWSER_TARGETS) - ) + return browser ?? (isModern ? DEFAULT_BROWSER_TARGETS : DEFAULT_LEGACY_BROWSER_TARGETS) } const plugins = (api, {useESModules = true} = {}) => [ @@ -47,10 +40,7 @@ const presets = (api, opts = {}) => { useBuiltIns: false } ], - [ - require('@babel/preset-react').default, - {runtime: 'automatic', useBuiltIns: true} - ] + [require('@babel/preset-react').default, {runtime: 'automatic', useBuiltIns: true}] ] } diff --git a/packages/sui-bundler/bin/sui-bundler-build.js b/packages/sui-bundler/bin/sui-bundler-build.js index da08cd73d..017743973 100755 --- a/packages/sui-bundler/bin/sui-bundler-build.js +++ b/packages/sui-bundler/bin/sui-bundler-build.js @@ -41,12 +41,7 @@ program }) .parse(process.argv) -const { - clean = false, - context, - saveStats, - linkPackage: packagesToLink = [] -} = program.opts() +const {clean = false, context, saveStats, linkPackage: packagesToLink = []} = program.opts() config.context = context || config.context @@ -106,10 +101,7 @@ compiler.run(async (error, stats) => { const resolvePublicFile = file => path.resolve(process.cwd(), 'public', file) if (offlinePageExists) { - fs.copyFileSync( - path.resolve(offlinePath), - resolvePublicFile('offline.html') - ) + fs.copyFileSync(path.resolve(offlinePath), resolvePublicFile('offline.html')) } if (offlinePageExists || staticsCacheOnly) { @@ -126,31 +118,19 @@ compiler.run(async (error, stats) => { const importScripts = offlineConfig.importScripts || [] - const stringImportScripts = importScripts - .map(url => `importScripts("${url}")`) - .join('\n') + const stringImportScripts = importScripts.map(url => `importScripts("${url}")`).join('\n') - Boolean(importScripts.length) && - console.log('\nExternal Scripts Added to the SW:\n', stringImportScripts) + Boolean(importScripts.length) && console.log('\nExternal Scripts Added to the SW:\n', stringImportScripts) // read the service worker template - const swTemplate = fs.readFileSync( - path.resolve(__dirname, '..', 'service-worker.js'), - 'utf-8' - ) + const swTemplate = fs.readFileSync(path.resolve(__dirname, '..', 'service-worker.js'), 'utf-8') // replace all the variables from the template with the actual values const swCode = swTemplate .replace('// IMPORT_SCRIPTS_HERE', stringImportScripts) .replace("require('static-manifest')", JSON.stringify(manifestStatics)) - .replace( - "require('static-cache-name')", - JSON.stringify(Date.now().toString()) - ) - .replace( - "require('static-statics-cache-only')", - JSON.stringify(staticsCacheOnly) - ) + .replace("require('static-cache-name')", JSON.stringify(Date.now().toString())) + .replace("require('static-statics-cache-only')", JSON.stringify(staticsCacheOnly)) const swFilePath = resolvePublicFile('service-worker.js') @@ -158,9 +138,7 @@ compiler.run(async (error, stats) => { console.log('\nService worker generated succesfully!\n') } - log.success( - `Your app is compiled in ${process.env.NODE_ENV} mode in /public. It's ready to roll!` - ) + log.success(`Your app is compiled in ${process.env.NODE_ENV} mode in /public. It's ready to roll!`) compiler.close(closeErr => { const exitCode = closeErr ? 1 : 0 diff --git a/packages/sui-bundler/bin/sui-bundler-dev.js b/packages/sui-bundler/bin/sui-bundler-dev.js index b2d29cb45..fbdbe985b 100755 --- a/packages/sui-bundler/bin/sui-bundler-dev.js +++ b/packages/sui-bundler/bin/sui-bundler-dev.js @@ -28,10 +28,7 @@ const DEFAULT_WATCH = !CI if (!module.parent) { program .option('-c, --context [folder]', 'Context folder (cwd by default)') - .option( - '-L, --link-all [monorepo]', - 'Link all packages inside of monorepo multipackage' - ) + .option('-L, --link-all [monorepo]', 'Link all packages inside of monorepo multipackage') .option( '-l, --link-package [package]', 'Replace each occurrence of this package with an absolute path to this folder', @@ -41,11 +38,7 @@ if (!module.parent) { }, [] ) - .option( - '-w, --watch', - 'Watch files and restart the server on change', - DEFAULT_WATCH - ) + .option('-w, --watch', 'Watch files and restart the server on change', DEFAULT_WATCH) .on('--help', () => { console.log(' Examples:') console.log('') @@ -61,21 +54,11 @@ if (!module.parent) { webpackConfig.context = context || webpackConfig.context } -const start = async ({ - config = webpackConfig, - packagesToLink = program.opts().linkPackage || [] -} = {}) => { +const start = async ({config = webpackConfig, packagesToLink = program.opts().linkPackage || []} = {}) => { clearConsole() // Warn and crash if required files are missing - if ( - !checkRequiredFiles([ - path.join(config.context, 'index.html'), - path.join(config.context, 'app.js') - ]) - ) { - log.error( - `✖ Required files are missing, create and index.html and app.js inside your src folder.` - ) + if (!checkRequiredFiles([path.join(config.context, 'index.html'), path.join(config.context, 'app.js')])) { + log.error(`✖ Required files are missing, create and index.html and app.js inside your src folder.`) process.exit(1) } diff --git a/packages/sui-bundler/bin/sui-bundler-lib.js b/packages/sui-bundler/bin/sui-bundler-lib.js index a89b5ecf0..a0a9f8ae9 100755 --- a/packages/sui-bundler/bin/sui-bundler-lib.js +++ b/packages/sui-bundler/bin/sui-bundler-lib.js @@ -16,10 +16,7 @@ program .option('-o, --output [output]', 'Bundle folder path') .option('-u, --umd [libraryName]', 'Whether to output library as umb') .option('-r, --root', 'Create build in root dir instead of version subdir') - .option( - '-p, --path [path]', - 'Absolute public path where files will be located.' - ) + .option('-p, --path [path]', 'Absolute public path where files will be located.') .on('--help', () => console.log(`Examples: $ sui-bundler lib src/index.js -o umd/my-lib -p http://my-cdn.com/my-lib -C' @@ -48,12 +45,7 @@ if (!publicPath) { process.env.NODE_ENV = process.env.NODE_ENV || 'production' const version = getPackageJson(process.cwd()).version -const outputFolder = path.join( - process.cwd(), - output, - path.sep, - root ? '' : version -) +const outputFolder = path.join(process.cwd(), output, path.sep, root ? '' : version) const webpackConfig = {...config, entry: path.resolve(process.cwd(), entry)} webpackConfig.output.publicPath = publicPath + (root ? '' : version + '/') webpackConfig.output.path = outputFolder @@ -94,7 +86,5 @@ webpack(webpackConfig).run((error, stats) => { } console.log(`Webpack stats: ${stats}`) - log.success( - `Your library is compiled in production mode in: \n${outputFolder}` - ) + log.success(`Your library is compiled in production mode in: \n${outputFolder}`) }) diff --git a/packages/sui-bundler/bin/sui-bundler.js b/packages/sui-bundler/bin/sui-bundler.js index eb2bcf735..ae17c403d 100755 --- a/packages/sui-bundler/bin/sui-bundler.js +++ b/packages/sui-bundler/bin/sui-bundler.js @@ -9,9 +9,6 @@ program .command('dev', 'open a server dev to start the development') .command('build', 'Compile all assets and create a public folder') .command('lib', 'Compile a library to a bundle with chunks.') - .command( - 'analyzer', - 'Compile all assets and create a HTML inspector for your bundle' - ) + .command('analyzer', 'Compile all assets and create a HTML inspector for your bundle') program.parse(process.argv) diff --git a/packages/sui-bundler/example/src/app.js b/packages/sui-bundler/example/src/app.js index d8d81e960..3a8c6037e 100644 --- a/packages/sui-bundler/example/src/app.js +++ b/packages/sui-bundler/example/src/app.js @@ -4,11 +4,9 @@ import {render} from 'react-dom' import Hello from './hello.js' // eslint-next-disable-line -import(/* webpackChunkName: "my-chunk-name" */ './foo.js').then( - ({default: foo}) => { - console.log('loaded async chunk') - foo() - } -) +import(/* webpackChunkName: "my-chunk-name" */ './foo.js').then(({default: foo}) => { + console.log('loaded async chunk') + foo() +}) render(, document.getElementById('root')) diff --git a/packages/sui-bundler/factories/createCompiler.js b/packages/sui-bundler/factories/createCompiler.js index 47ee2e562..aad69e529 100644 --- a/packages/sui-bundler/factories/createCompiler.js +++ b/packages/sui-bundler/factories/createCompiler.js @@ -32,9 +32,7 @@ module.exports = (config, urls) => { // Log the correct message of compilation depending if we have warnings if (isSuccessful) { - stats.hasWarnings() - ? log.warn('⚠ Compiled with warnings') - : log.success('✔ Compiled successfully') + stats.hasWarnings() ? log.warn('⚠ Compiled with warnings') : log.success('✔ Compiled successfully') } // Even with warnings, we show instructions to access localhost if we have a compilation @@ -52,9 +50,7 @@ module.exports = (config, urls) => { // With warnings, even after showing the instructions we must list the warnings we have if (stats.hasWarnings()) { - const messages = formatWebpackMessages( - stats.toJson('errors-warnings', true) - ) + const messages = formatWebpackMessages(stats.toJson('errors-warnings', true)) log.warn(messages.warnings.join('\n\n')) } }) diff --git a/packages/sui-bundler/loaders/ExternalsManifestLoader.js b/packages/sui-bundler/loaders/ExternalsManifestLoader.js index 33b78d9b8..a52104c20 100644 --- a/packages/sui-bundler/loaders/ExternalsManifestLoader.js +++ b/packages/sui-bundler/loaders/ExternalsManifestLoader.js @@ -46,9 +46,7 @@ async function externalsManifestLoader(source) { try { const manifest = await getRemoteManifest( - typeof manifestURL === 'string' - ? manifestURL - : manifestURL[process.env.NODE_ENV] + typeof manifestURL === 'string' ? manifestURL : manifestURL[process.env.NODE_ENV] ) const entries = Object.entries(manifest) const nextSource = entries.reduce((acc, entry) => { diff --git a/packages/sui-bundler/loaders/linkLoaderConfigBuilder.js b/packages/sui-bundler/loaders/linkLoaderConfigBuilder.js index 166e4681e..b127e282c 100644 --- a/packages/sui-bundler/loaders/linkLoaderConfigBuilder.js +++ b/packages/sui-bundler/loaders/linkLoaderConfigBuilder.js @@ -14,9 +14,7 @@ const diccFromAbsolutePaths = (paths, init = {}) => log.success(`✔ ${pkg.name} from path "${packagePath}"`) return acc } catch (e) { - log.warn( - `⚠ Package from path "${packagePath}" can't be linked.\n Path is wrong or package.json is missing.` - ) + log.warn(`⚠ Package from path "${packagePath}" can't be linked.\n Path is wrong or package.json is missing.`) return acc } }, init) @@ -24,11 +22,7 @@ const diccFromAbsolutePaths = (paths, init = {}) => const absolutePathForMonoRepo = base => { if (!base) return [] return fg - .sync([ - `${path.resolve(base)}/**/package.json`, - '!**/node_modules/**', - '!**/lib/**' - ]) + .sync([`${path.resolve(base)}/**/package.json`, '!**/node_modules/**', '!**/lib/**']) .map(p => path.dirname(p)) } diff --git a/packages/sui-bundler/loaders/sassLinkImporter.js b/packages/sui-bundler/loaders/sassLinkImporter.js index 75d62934d..c46d753ba 100644 --- a/packages/sui-bundler/loaders/sassLinkImporter.js +++ b/packages/sui-bundler/loaders/sassLinkImporter.js @@ -8,10 +8,7 @@ const createSassLinkImporter = entryPoints => url => { const [org, name] = url.split(/\//) const pkg = [org.replace('~', ''), name].join('/') - const absoluteUrl = url.replace( - new RegExp(`~?${pkg}(\\/lib)?`, 'g'), - entryPoints[pkg] - ) + const absoluteUrl = url.replace(new RegExp(`~?${pkg}(\\/lib)?`, 'g'), entryPoints[pkg]) return {file: absoluteUrl} } return null diff --git a/packages/sui-bundler/service-worker.js b/packages/sui-bundler/service-worker.js index a17e93da4..500b83b49 100644 --- a/packages/sui-bundler/service-worker.js +++ b/packages/sui-bundler/service-worker.js @@ -50,9 +50,7 @@ const copyResponse = async function (response) { statusText: clonedResponse.statusText } - const body = canConstructResponseFromBodyStream() - ? clonedResponse.body - : await clonedResponse.blob() + const body = canConstructResponseFromBodyStream() ? clonedResponse.body : await clonedResponse.blob() return new Response(body, responseInit) } diff --git a/packages/sui-bundler/shared/config.js b/packages/sui-bundler/shared/config.js index 4a7d8bb46..807567c5e 100644 --- a/packages/sui-bundler/shared/config.js +++ b/packages/sui-bundler/shared/config.js @@ -1,14 +1,8 @@ /* Extract sui-bundler from package.json -> "config": {"sui-bundler": { ... }} */ -const { - config: packageJsonConfig = {} -} = require(`${process.cwd()}/package.json`) +const {config: packageJsonConfig = {}} = require(`${process.cwd()}/package.json`) const {'sui-bundler': config = {}} = packageJsonConfig -const { - extractComments = false, - sourcemaps, - supportLegacyBrowsers = true -} = config +const {extractComments = false, sourcemaps, supportLegacyBrowsers = true} = config exports.config = config exports.supportLegacyBrowsers = supportLegacyBrowsers diff --git a/packages/sui-bundler/shared/inline-chunk-html-plugin.js b/packages/sui-bundler/shared/inline-chunk-html-plugin.js index e0a5237ed..bd0f73fa7 100644 --- a/packages/sui-bundler/shared/inline-chunk-html-plugin.js +++ b/packages/sui-bundler/shared/inline-chunk-html-plugin.js @@ -19,9 +19,7 @@ class InlineChunkHtmlPlugin { if (tag.tagName !== 'script' || !(tag.attributes && tag.attributes.src)) { return tag } - const scriptName = publicPath - ? tag.attributes.src.replace(publicPath, '') - : tag.attributes.src + const scriptName = publicPath ? tag.attributes.src.replace(publicPath, '') : tag.attributes.src if (!this.tests.some(test => scriptName.match(test))) { return tag } @@ -39,8 +37,7 @@ class InlineChunkHtmlPlugin { } compiler.hooks.compilation.tap('InlineChunkHtmlPlugin', compilation => { - const tagFunction = tag => - this.getInlinedTag(publicPath, compilation.assets, tag) + const tagFunction = tag => this.getInlinedTag(publicPath, compilation.assets, tag) const hooks = this.htmlWebpackPlugin.getHooks(compilation) hooks.alterAssetTagGroups.tap('InlineChunkHtmlPlugin', assets => { diff --git a/packages/sui-bundler/shared/minify-js.js b/packages/sui-bundler/shared/minify-js.js index 266a49348..1c62031a7 100644 --- a/packages/sui-bundler/shared/minify-js.js +++ b/packages/sui-bundler/shared/minify-js.js @@ -22,6 +22,4 @@ const terserMinifier = ({extractComments, sourceMap}) => }) module.exports = ({extractComments, sourceMap}) => - supportLegacyBrowsers - ? terserMinifier({extractComments, sourceMap}) - : esbuildMinifier({sourceMap}) + supportLegacyBrowsers ? terserMinifier({extractComments, sourceMap}) : esbuildMinifier({sourceMap}) diff --git a/packages/sui-bundler/shared/module-rules-babel.js b/packages/sui-bundler/shared/module-rules-babel.js index 1e22fea26..52126e5fa 100644 --- a/packages/sui-bundler/shared/module-rules-babel.js +++ b/packages/sui-bundler/shared/module-rules-babel.js @@ -5,11 +5,7 @@ const EXCLUDED_FOLDERS_REGEXP = new RegExp( `node_modules(?!${path.sep}@s-ui(${path.sep}studio)(${path.sep}workbench)?${path.sep}src)` ) -module.exports = ({ - isServer = false, - isDevelopment = false, - supportLegacyBrowsers = true -} = {}) => ({ +module.exports = ({isServer = false, isDevelopment = false, supportLegacyBrowsers = true} = {}) => ({ test: /\.jsx?$/, exclude: EXCLUDED_FOLDERS_REGEXP, use: [ @@ -20,9 +16,7 @@ module.exports = ({ cacheCompression: false, babelrc: false, compact: true, - plugins: [ - isDevelopment && require.resolve('react-refresh/babel') - ].filter(Boolean), + plugins: [isDevelopment && require.resolve('react-refresh/babel')].filter(Boolean), presets: [ [ require.resolve('babel-preset-sui'), diff --git a/packages/sui-bundler/shared/resolve-alias.js b/packages/sui-bundler/shared/resolve-alias.js index ddd15521a..de6e0dcf7 100644 --- a/packages/sui-bundler/shared/resolve-alias.js +++ b/packages/sui-bundler/shared/resolve-alias.js @@ -9,33 +9,22 @@ const {PWD} = process.env * So you should use the exact same imported file from node_modules, and the linked package * would try to use another different from its own node_modules. This will prevent that. */ -const defaultPackagesToAlias = [ - 'react', - 'react-router-dom', - '@s-ui/pde', - '@s-ui/react-context', - '@s-ui/react-router' -] +const defaultPackagesToAlias = ['react', 'react-router-dom', '@s-ui/pde', '@s-ui/react-context', '@s-ui/react-router'] -const createAliasPath = pkgName => - path.resolve(path.join(PWD, `./node_modules/${pkgName}`)) +const createAliasPath = pkgName => path.resolve(path.join(PWD, `./node_modules/${pkgName}`)) const mustPackagesToAlias = { 'react/jsx-dev-runtime': 'react/jsx-dev-runtime.js', 'react/jsx-runtime': 'react/jsx-runtime.js' } -exports.defaultAlias = Object.fromEntries( - defaultPackagesToAlias.map(pkgName => [pkgName, createAliasPath(pkgName)]) -) +exports.defaultAlias = Object.fromEntries(defaultPackagesToAlias.map(pkgName => [pkgName, createAliasPath(pkgName)])) const aliasFromConfig = config.alias ? Object.entries(config.alias).reduce( (obj, [aliasName, aliasPath]) => ({ ...obj, - [aliasName]: aliasPath.startsWith('./') - ? path.join(PWD, aliasPath) - : aliasPath + [aliasName]: aliasPath.startsWith('./') ? path.join(PWD, aliasPath) : aliasPath }), {} ) diff --git a/packages/sui-bundler/shared/resolve-loader.js b/packages/sui-bundler/shared/resolve-loader.js index 162de9e5f..2e13d809a 100644 --- a/packages/sui-bundler/shared/resolve-loader.js +++ b/packages/sui-bundler/shared/resolve-loader.js @@ -1,7 +1,5 @@ exports.resolveLoader = { alias: { - 'externals-manifest-loader': require.resolve( - '../loaders/ExternalsManifestLoader' - ) + 'externals-manifest-loader': require.resolve('../loaders/ExternalsManifestLoader') } } diff --git a/packages/sui-bundler/test/server/integration/static-server.js b/packages/sui-bundler/test/server/integration/static-server.js index dc5a9bba0..67ca80d1a 100644 --- a/packages/sui-bundler/test/server/integration/static-server.js +++ b/packages/sui-bundler/test/server/integration/static-server.js @@ -15,7 +15,5 @@ const server = http.createServer((req, res) => { }) server.listen(port, hostname, () => { - console.log( - `Static manifest serve from http://${hostname}:${port}/manifest.json` - ) + console.log(`Static manifest serve from http://${hostname}:${port}/manifest.json`) }) diff --git a/packages/sui-bundler/test/server/integrationSpec.js b/packages/sui-bundler/test/server/integrationSpec.js index 34cc6211f..3267481ed 100755 --- a/packages/sui-bundler/test/server/integrationSpec.js +++ b/packages/sui-bundler/test/server/integrationSpec.js @@ -10,16 +10,13 @@ const SUI_BUNDLER_BINARY_DIR = path.join(__dirname, '..', '..', 'bin') const getCWD = app => path.join(__dirname, 'integration', app) const executeBundler = async ({cwd, env = {}}) => { - const {stdout} = await exec( - `node "${SUI_BUNDLER_BINARY_DIR}/sui-bundler-build" -C`, - { - cwd, - env: { - ...process.env, - ...env - } + const {stdout} = await exec(`node "${SUI_BUNDLER_BINARY_DIR}/sui-bundler-build" -C`, { + cwd, + env: { + ...process.env, + ...env } - ) + }) if (stdout.includes('Error')) { console.error(stdout) @@ -46,22 +43,17 @@ describe('[Integration] sui-bundler', () => { expect(stdout.includes('Error')).to.be.false - const {stdout: lsStdout} = await exec( - `ls "${cwd}/public" | grep -E ".js$" || true`, - { - cwd - } - ) + const {stdout: lsStdout} = await exec(`ls "${cwd}/public" | grep -E ".js$" || true`, { + cwd + }) const mainJSContent = getMainFileContent({cwd, CDN}) expect(lsStdout).to.be.not.eql('') - expect(fs.existsSync(path.join(`${cwd}/public/asset-manifest.json`))).to.be - .true + expect(fs.existsSync(path.join(`${cwd}/public/asset-manifest.json`))).to.be.true - expect(fs.readFileSync(path.join(`${cwd}/public/index.html`)).includes(CDN)) - .to.be.true + expect(fs.readFileSync(path.join(`${cwd}/public/index.html`)).includes(CDN)).to.be.true expect(mainJSContent.includes('test_app')).to.be.true }) @@ -85,20 +77,13 @@ describe('[Integration] sui-bundler', () => { // tofix const OFFLINE_APP_PATH = '' - const {stdout} = await exec( - `node "${SUI_BUNDLER_BINARY_DIR}/sui-bundler-build" -C`, - { - cwd: OFFLINE_APP_PATH - } - ) + const {stdout} = await exec(`node "${SUI_BUNDLER_BINARY_DIR}/sui-bundler-build" -C`, { + cwd: OFFLINE_APP_PATH + }) - const manifest = require(path.join( - `${OFFLINE_APP_PATH}/public/asset-manifest.json` - )) + const manifest = require(path.join(`${OFFLINE_APP_PATH}/public/asset-manifest.json`)) - const sw = fs.readFileSync( - path.join(`${OFFLINE_APP_PATH}/public/service-worker.js`) - ) + const sw = fs.readFileSync(path.join(`${OFFLINE_APP_PATH}/public/service-worker.js`)) Object.entries(manifest).forEach(([original, hashed]) => { const isRuntime = original.match('runtime') @@ -107,12 +92,9 @@ describe('[Integration] sui-bundler', () => { expect(stdout.includes('Error')).to.be.false - expect(fs.existsSync(path.join(`${OFFLINE_APP_PATH}/public/offline.html`))) - .to.be.true + expect(fs.existsSync(path.join(`${OFFLINE_APP_PATH}/public/offline.html`))).to.be.true - expect( - fs.existsSync(path.join(`${OFFLINE_APP_PATH}/public/service-worker.js`)) - ).to.be.true + expect(fs.existsSync(path.join(`${OFFLINE_APP_PATH}/public/service-worker.js`))).to.be.true expect( fs @@ -127,13 +109,9 @@ describe('[Integration] sui-bundler', () => { const EXTERNAL_MANIFEST_APP_PATH = 'tofix' let server try { - server = childProcess.spawn( - 'node', - [path.join(__dirname, 'integration', 'static-server.js')], - { - detached: false - } - ) + server = childProcess.spawn('node', [path.join(__dirname, 'integration', 'static-server.js')], { + detached: false + }) // server.stdout.pipe(process.stdout) // server.stderr.pipe(process.stdout) @@ -141,26 +119,20 @@ describe('[Integration] sui-bundler', () => { cwd: EXTERNAL_MANIFEST_APP_PATH }) - const manifest = require(path.join( - `${EXTERNAL_MANIFEST_APP_PATH}/public/asset-manifest.json` - )) + const manifest = require(path.join(`${EXTERNAL_MANIFEST_APP_PATH}/public/asset-manifest.json`)) const mainJS = manifest['main.js'].replace('/', '') const mainCSS = manifest['main.css'].replace('/', '') expect( fs - .readFileSync( - path.join(`${EXTERNAL_MANIFEST_APP_PATH}/public/${mainJS}`) - ) + .readFileSync(path.join(`${EXTERNAL_MANIFEST_APP_PATH}/public/${mainJS}`)) .includes('http://localhost:1234/image.123abc.jpeg') ).to.be.true expect( fs - .readFileSync( - path.join(`${EXTERNAL_MANIFEST_APP_PATH}/public/${mainCSS}`) - ) + .readFileSync(path.join(`${EXTERNAL_MANIFEST_APP_PATH}/public/${mainCSS}`)) .includes('http://localhost:1234/css-image.456def.jpeg') ).to.be.true } finally { diff --git a/packages/sui-bundler/test/server/linkLoaderSpec.js b/packages/sui-bundler/test/server/linkLoaderSpec.js index c48e899fd..b854066a4 100644 --- a/packages/sui-bundler/test/server/linkLoaderSpec.js +++ b/packages/sui-bundler/test/server/linkLoaderSpec.js @@ -48,9 +48,7 @@ describe('LinkLoader', () => { "require('@s-ui/module/lib/level/mod.js')" ) - expect(nextSource).to.be.eql( - "require('/User/Developer/sui/module/src/level/mod.js')" - ) + expect(nextSource).to.be.eql("require('/User/Developer/sui/module/src/level/mod.js')") }) it('Double quotes: Should rewrite the source code for JS files for a deeper route', async () => { @@ -66,9 +64,7 @@ describe('LinkLoader', () => { 'require("@s-ui/module/lib/level/mod.js")' ) - expect(nextSource).to.be.eql( - 'require("/User/Developer/sui/module/src/level/mod.js")' - ) + expect(nextSource).to.be.eql('require("/User/Developer/sui/module/src/level/mod.js")') }) it('Single quotes: Should rewrite the source code for SASS files in the root', async () => { @@ -84,9 +80,7 @@ describe('LinkLoader', () => { '@import "~@s-ui/module/lib/index";' ) - expect(nextSource).to.be.eql( - '@import "/User/Developer/sui/module/src/index";' - ) + expect(nextSource).to.be.eql('@import "/User/Developer/sui/module/src/index";') }) it('Double quotes: Should rewrite the source code for SASS files in the root', async () => { @@ -102,8 +96,6 @@ describe('LinkLoader', () => { "@import '~@s-ui/module/lib/index';" ) - expect(nextSource).to.be.eql( - "@import '/User/Developer/sui/module/src/index';" - ) + expect(nextSource).to.be.eql("@import '/User/Developer/sui/module/src/index';") }) }) diff --git a/packages/sui-bundler/utils/WebpackDevServerUtils.js b/packages/sui-bundler/utils/WebpackDevServerUtils.js index 388486b80..0202892c8 100644 --- a/packages/sui-bundler/utils/WebpackDevServerUtils.js +++ b/packages/sui-bundler/utils/WebpackDevServerUtils.js @@ -51,11 +51,7 @@ function prepareUrls(protocol, host, port, pathname = '/') { if (lanUrlForConfig) { // Check if the address is a private ip // https://en.wikipedia.org/wiki/Private_network#Private_IPv4_address_spaces - if ( - /^10[.]|^172[.](1[6-9]|2[0-9]|3[0-1])[.]|^192[.]168[.]/.test( - lanUrlForConfig - ) - ) { + if (/^10[.]|^172[.](1[6-9]|2[0-9]|3[0-1])[.]|^192[.]168[.]/.test(lanUrlForConfig)) { // Address is private, format it for later use lanUrlForTerminal = prettyPrintUrl(lanUrlForConfig) } else { @@ -94,21 +90,11 @@ function printInstructions(appName, urls, useYarn) { console.log() console.log('Note that the development build is not optimized.') - console.log( - `To create a production build, use ` + - `${cyan(`${useYarn ? 'yarn' : 'npm run'} build`)}.` - ) + console.log(`To create a production build, use ` + `${cyan(`${useYarn ? 'yarn' : 'npm run'} build`)}.`) console.log() } -function createCompiler({ - appName, - config, - urls, - useYarn, - useTypeScript, - webpack -}) { +function createCompiler({appName, config, urls, useYarn, useTypeScript, webpack}) { // "Compiler" is a low-level interface to webpack. // It lets us listen to some events and provide our own custom messages. let compiler @@ -181,11 +167,7 @@ function createCompiler({ console.log(messages.warnings.join('\n\n')) // Teach some ESLint tricks. - console.log( - `\nSearch for the ${yellow( - 'keywords' - )} to learn more about each warning.` - ) + console.log(`\nSearch for the ${yellow('keywords')} to learn more about each warning.`) } }) @@ -221,13 +203,9 @@ function prepareProxy(proxy, appPublicFolder, servedPathname) { if (!proxy) return undefined if (typeof proxy !== 'string') { - console.log( - red('When specified, "proxy" in package.json must be a string.') - ) + console.log(red('When specified, "proxy" in package.json must be a string.')) console.log(red('Instead, the type of "proxy" was "' + typeof proxy + '".')) - console.log( - red('Either remove "proxy" from package.json, or make it a string.') - ) + console.log(red('Either remove "proxy" from package.json, or make it a string.')) process.exit(1) } @@ -237,23 +215,15 @@ function prepareProxy(proxy, appPublicFolder, servedPathname) { const sockPath = process.env.WDS_SOCKET_PATH || '/ws' const isDefaultSockHost = !process.env.WDS_SOCKET_HOST function mayProxy(pathname) { - const maybePublicPath = path.resolve( - appPublicFolder, - pathname.replace(new RegExp('^' + servedPathname), '') - ) + const maybePublicPath = path.resolve(appPublicFolder, pathname.replace(new RegExp('^' + servedPathname), '')) const isPublicFileRequest = fs.existsSync(maybePublicPath) // used by webpackHotDevClient - const isWdsEndpointRequest = - isDefaultSockHost && pathname.startsWith(sockPath) + const isWdsEndpointRequest = isDefaultSockHost && pathname.startsWith(sockPath) return !(isPublicFileRequest || isWdsEndpointRequest) } if (!/^http(s)?:\/\//.test(proxy)) { - console.log( - red( - 'When "proxy" is specified in package.json it must start with either http:// or https://' - ) - ) + console.log(red('When "proxy" is specified in package.json it must start with either http:// or https://')) process.exit(1) } @@ -276,9 +246,7 @@ function prepareProxy(proxy, appPublicFolder, servedPathname) { context: function (pathname, req) { return ( req.method !== 'GET' || - (mayProxy(pathname) && - req.headers.accept && - req.headers.accept.indexOf('text/html') === -1) + (mayProxy(pathname) && req.headers.accept && req.headers.accept.indexOf('text/html') === -1) ) }, onProxyReq: proxyReq => { diff --git a/packages/sui-bundler/utils/clearConsole.js b/packages/sui-bundler/utils/clearConsole.js index 8e2c624a3..8d3a79e6b 100644 --- a/packages/sui-bundler/utils/clearConsole.js +++ b/packages/sui-bundler/utils/clearConsole.js @@ -6,9 +6,7 @@ */ function clearConsole() { - process.stdout.write( - process.platform === 'win32' ? '\x1B[2J\x1B[0f' : '\x1B[2J\x1B[3J\x1B[H' - ) + process.stdout.write(process.platform === 'win32' ? '\x1B[2J\x1B[0f' : '\x1B[2J\x1B[3J\x1B[H') } module.exports = clearConsole diff --git a/packages/sui-bundler/utils/formatWebpackMessages.js b/packages/sui-bundler/utils/formatWebpackMessages.js index 1a8978f9c..6fa271b4c 100644 --- a/packages/sui-bundler/utils/formatWebpackMessages.js +++ b/packages/sui-bundler/utils/formatWebpackMessages.js @@ -34,9 +34,7 @@ function formatMessage(message) { // Transform parsing error into syntax error // TODO: move this to our ESLint formatter? lines = lines.map(line => { - const parsingError = /Line (\d+):(?:(\d+):)?\s*Parsing error: (.+)$/.exec( - line - ) + const parsingError = /Line (\d+):(?:(\d+):)?\s*Parsing error: (.+)$/.exec(line) if (!parsingError) { return line } @@ -46,10 +44,7 @@ function formatMessage(message) { message = lines.join('\n') // Smoosh syntax errors (commonly found in CSS) - message = message.replace( - /SyntaxError\s+\((\d+):(\d+)\)\s*(.+?)\n/g, - `${friendlySyntaxErrorLabel} $3 ($1:$2)\n` - ) + message = message.replace(/SyntaxError\s+\((\d+):(\d+)\)\s*(.+?)\n/g, `${friendlySyntaxErrorLabel} $3 ($1:$2)\n`) // Clean up export errors message = message.replace( /^.*export '(.+?)' was not found in '(.+?)'.*$/gm, @@ -76,17 +71,14 @@ function formatMessage(message) { if (lines[1] && lines[1].indexOf('Module not found: ') === 0) { lines = [ lines[0], - lines[1] - .replace('Error: ', '') - .replace('Module not found: Cannot find file:', 'Cannot find file:') + lines[1].replace('Error: ', '').replace('Module not found: Cannot find file:', 'Cannot find file:') ] } // Add helpful message for users trying to use Sass for the first time if (lines[1] && lines[1].match(/Cannot find module.+sass/)) { lines[1] = 'To import Sass files, you first need to install sass.\n' - lines[1] += - 'Run `npm install sass` or `yarn add sass` inside your workspace.' + lines[1] += 'Run `npm install sass` or `yarn add sass` inside your workspace.' } message = lines.join('\n') @@ -94,18 +86,12 @@ function formatMessage(message) { // exception of stacks containing `webpack:` because they're normally // from user code generated by webpack. For more information see // https://github.com/facebook/create-react-app/pull/1050 - message = message.replace( - /^\s*at\s((?!webpack:).)*:\d+:\d+[\s)]*(\n|$)/gm, - '' - ) // at ... ...:x:y + message = message.replace(/^\s*at\s((?!webpack:).)*:\d+:\d+[\s)]*(\n|$)/gm, '') // at ... ...:x:y message = message.replace(/^\s*at\s(\n|$)/gm, '') // at lines = message.split('\n') // Remove duplicated newlines - lines = lines.filter( - (line, index, arr) => - index === 0 || line.trim() !== '' || line.trim() !== arr[index - 1].trim() - ) + lines = lines.filter((line, index, arr) => index === 0 || line.trim() !== '' || line.trim() !== arr[index - 1].trim()) // Reassemble the message message = lines.join('\n') diff --git a/packages/sui-bundler/utils/getProcessForPort.js b/packages/sui-bundler/utils/getProcessForPort.js index 328e20139..b096a63c4 100644 --- a/packages/sui-bundler/utils/getProcessForPort.js +++ b/packages/sui-bundler/utils/getProcessForPort.js @@ -21,11 +21,7 @@ const execOptions = { * @returns {string} The process id */ function getProcessIdOnPort(port) { - return execFileSync( - 'lsof', - [`-i:${port}`, '-P', '-t', '-sTCP:LISTEN'], - execOptions - ) + return execFileSync('lsof', [`-i:${port}`, '-P', '-t', '-sTCP:LISTEN'], execOptions) .split('\n')[0] .trim() } @@ -36,10 +32,7 @@ function getProcessIdOnPort(port) { * @returns {string} - The process name */ function getProcessCommand(processId) { - const command = execSync( - 'ps -o command -p ' + processId + ' | sed -n 2p', - execOptions - ) + const command = execSync('ps -o command -p ' + processId + ' | sed -n 2p', execOptions) return command.replace(/\n$/, '') } @@ -50,10 +43,7 @@ function getProcessCommand(processId) { * @returns {string} - The process directory */ function getDirectoryOfProcessById(processId) { - return execSync( - `lsof -p ${processId} | awk '$4=="cwd" {for (i=9; i<=NF; i++) printf "%s ", $i}'`, - execOptions - ).trim() + return execSync(`lsof -p ${processId} | awk '$4=="cwd" {for (i=9; i<=NF; i++) printf "%s ", $i}'`, execOptions).trim() } /** @@ -67,12 +57,7 @@ function getProcessForPort(port) { const directory = getDirectoryOfProcessById(processId) const command = getProcessCommand(processId) - return ( - bold(command) + - gray(' (pid ' + processId + ')\n') + - gray(' in ') + - cyan(directory) - ) + return bold(command) + gray(' (pid ' + processId + ')\n') + gray(' in ') + cyan(directory) } catch (e) { return null } diff --git a/packages/sui-bundler/utils/ignoredFiles.js b/packages/sui-bundler/utils/ignoredFiles.js index d18debcf1..b28f63552 100644 --- a/packages/sui-bundler/utils/ignoredFiles.js +++ b/packages/sui-bundler/utils/ignoredFiles.js @@ -13,10 +13,5 @@ const path = require('path') const escape = require('escape-string-regexp') module.exports = function ignoredFiles(appSrc) { - return new RegExp( - `^(?!${escape( - path.normalize(appSrc + '/').replace(/[\\]+/g, '/') - )}).+/node_modules/`, - 'g' - ) + return new RegExp(`^(?!${escape(path.normalize(appSrc + '/').replace(/[\\]+/g, '/'))}).+/node_modules/`, 'g') } diff --git a/packages/sui-bundler/webpack.config.dev.js b/packages/sui-bundler/webpack.config.dev.js index 93b959799..e207479c9 100644 --- a/packages/sui-bundler/webpack.config.dev.js +++ b/packages/sui-bundler/webpack.config.dev.js @@ -5,13 +5,7 @@ const webpack = require('webpack') const HtmlWebpackPlugin = require('html-webpack-plugin') const ReactRefreshWebpackPlugin = require('@pmmmwh/react-refresh-webpack-plugin') -const { - envVars, - MAIN_ENTRY_POINT, - config, - cleanList, - when -} = require('./shared/index.js') +const {envVars, MAIN_ENTRY_POINT, config, cleanList, when} = require('./shared/index.js') const definePlugin = require('./shared/define.js') const manifestLoaderRules = require('./shared/module-rules-manifest-loader.js') const {aliasFromConfig, defaultAlias} = require('./shared/resolve-alias.js') @@ -114,14 +108,11 @@ const webpackConfig = { require.resolve('@s-ui/sass-loader') ]) }, - when(config['externals-manifest'], () => - manifestLoaderRules(config['externals-manifest']) - ) + when(config['externals-manifest'], () => manifestLoaderRules(config['externals-manifest'])) ]) }, watch: !CI, - devtool: - config.sourcemaps && config.sourcemaps.dev ? config.sourcemaps.dev : false + devtool: config.sourcemaps && config.sourcemaps.dev ? config.sourcemaps.dev : false } module.exports = webpackConfig diff --git a/packages/sui-bundler/webpack.config.lib.js b/packages/sui-bundler/webpack.config.lib.js index 188ba9256..e8d8d846c 100644 --- a/packages/sui-bundler/webpack.config.lib.js +++ b/packages/sui-bundler/webpack.config.lib.js @@ -1,21 +1,12 @@ const webpack = require('webpack') const MiniCssExtractPlugin = require('mini-css-extract-plugin') -const { - cleanList, - envVars, - MAIN_ENTRY_POINT, - config -} = require('./shared/index.js') +const {cleanList, envVars, MAIN_ENTRY_POINT, config} = require('./shared/index.js') const path = require('path') const minifyJs = require('./shared/minify-js.js') const definePlugin = require('./shared/define.js') const createBabelRules = require('./shared/module-rules-babel.js') const sassRules = require('./shared/module-rules-sass.js') -const { - extractComments, - sourceMap, - supportLegacyBrowsers -} = require('./shared/config.js') +const {extractComments, sourceMap, supportLegacyBrowsers} = require('./shared/config.js') const {aliasFromConfig} = require('./shared/resolve-alias.js') const cssFileName = 'styles.css' diff --git a/packages/sui-bundler/webpack.config.prod.js b/packages/sui-bundler/webpack.config.prod.js index 3c933dab1..1f22b70df 100644 --- a/packages/sui-bundler/webpack.config.prod.js +++ b/packages/sui-bundler/webpack.config.prod.js @@ -9,19 +9,9 @@ const {WebpackManifestPlugin} = require('webpack-manifest-plugin') const MiniCssExtractPlugin = require('mini-css-extract-plugin') const InlineChunkHtmlPlugin = require('./shared/inline-chunk-html-plugin.js') -const { - when, - cleanList, - envVars, - MAIN_ENTRY_POINT, - config -} = require('./shared/index.js') +const {when, cleanList, envVars, MAIN_ENTRY_POINT, config} = require('./shared/index.js') const {aliasFromConfig} = require('./shared/resolve-alias.js') -const { - extractComments, - sourceMap, - supportLegacyBrowsers -} = require('./shared/config.js') +const {extractComments, sourceMap, supportLegacyBrowsers} = require('./shared/config.js') const {resolveLoader} = require('./shared/resolve-loader.js') const createBabelRules = require('./shared/module-rules-babel.js') const sassRules = require('./shared/module-rules-sass.js') @@ -34,13 +24,9 @@ const CWD = process.cwd() const PUBLIC_PATH = process.env.CDN || config.cdn || '/' const PWD = process.env.PWD ?? '' -const filename = config.onlyHash - ? '[contenthash:8].js' - : '[name].[contenthash:8].js' +const filename = config.onlyHash ? '[contenthash:8].js' : '[name].[contenthash:8].js' -const cssFileName = config.onlyHash - ? '[contenthash:8].css' - : '[name].[contenthash:8].css' +const cssFileName = config.onlyHash ? '[contenthash:8].css' : '[name].[contenthash:8].css' const target = supportLegacyBrowsers ? ['web', 'es5'] : 'web' @@ -77,9 +63,7 @@ const webpackConfig = { optimization: { checkWasmTypes: false, minimize: true, - minimizer: [minifyJs({extractComments, sourceMap}), minifyCss()].filter( - Boolean - ), + minimizer: [minifyJs({extractComments, sourceMap}), minifyCss()].filter(Boolean), runtimeChunk: true }, plugins: cleanList([ @@ -116,9 +100,7 @@ const webpackConfig = { rules: cleanList([ createBabelRules({supportLegacyBrowsers}), sassRules, - when(config['externals-manifest'], () => - manifestLoaderRules(config['externals-manifest']) - ) + when(config['externals-manifest'], () => manifestLoaderRules(config['externals-manifest'])) ]) }, resolveLoader diff --git a/packages/sui-bundler/webpack.config.server.js b/packages/sui-bundler/webpack.config.server.js index 9d4407749..b4b02df35 100644 --- a/packages/sui-bundler/webpack.config.server.js +++ b/packages/sui-bundler/webpack.config.server.js @@ -48,9 +48,7 @@ const webpackConfig = { dataUrl: () => '' } }, - when(config['externals-manifest'], () => - manifestLoaderRules(config['externals-manifest']) - ) + when(config['externals-manifest'], () => manifestLoaderRules(config['externals-manifest'])) ]) } } diff --git a/packages/sui-ci/bin/sui-ci-update-commit-status.js b/packages/sui-ci/bin/sui-ci-update-commit-status.js index b3fb982d0..af4ccb346 100644 --- a/packages/sui-ci/bin/sui-ci-update-commit-status.js +++ b/packages/sui-ci/bin/sui-ci-update-commit-status.js @@ -15,9 +15,7 @@ const { TRAVIS_REPO_SLUG } = process.env -const buildUrl = - TRAVIS_BUILD_WEB_URL || - `${GITHUB_SERVER_URL}/${GITHUB_REPOSITORY}/actions/runs/${GITHUB_RUN_ID}` +const buildUrl = TRAVIS_BUILD_WEB_URL || `${GITHUB_SERVER_URL}/${GITHUB_REPOSITORY}/actions/runs/${GITHUB_RUN_ID}` // GH_TOKEN is deprecated but yet used as a fallback for compatibility const gitHubToken = GITHUB_TOKEN || GH_TOKEN @@ -25,21 +23,9 @@ const gitHubToken = GITHUB_TOKEN || GH_TOKEN const repoSlug = GITHUB_REPOSITORY || TRAVIS_REPO_SLUG program - .option( - '-s, --state ', - 'State of the commit. Accepted values:"OK", "KO", "RUN"', - 'KO' - ) - .option( - '-u, --url ', - 'Url where the details link navigates to', - buildUrl - ) - .option( - '-t, --topic ', - 'Topic telling what is the commit about', - topicFromEnv - ) + .option('-s, --state ', 'State of the commit. Accepted values:"OK", "KO", "RUN"', 'KO') + .option('-u, --url ', 'Url where the details link navigates to', buildUrl) + .option('-t, --topic ', 'Topic telling what is the commit about', topicFromEnv) .parse(process.argv) const {state: stateKey, topic, url: targetUrl} = program.opts() diff --git a/packages/sui-ci/src/updateCommitStatus.js b/packages/sui-ci/src/updateCommitStatus.js index 84cbb5d89..68e32c9f8 100644 --- a/packages/sui-ci/src/updateCommitStatus.js +++ b/packages/sui-ci/src/updateCommitStatus.js @@ -25,15 +25,13 @@ const getDomain = (url = '') => { * @return {Promise} API base url */ async function getApiBaseUrl() { - const {stdout: gitRemoteOriginUrl} = await exec( - `git config --get remote.origin.url` - ).catch(() => 'git@github.com:sui/remote-url.git') + const {stdout: gitRemoteOriginUrl} = await exec(`git config --get remote.origin.url`).catch( + () => 'git@github.com:sui/remote-url.git' + ) const domain = getDomain(gitRemoteOriginUrl) - return domain === 'github.com' - ? 'https://api.github.com' - : `https://${domain}/api/v3` + return domain === 'github.com' ? 'https://api.github.com' : `https://${domain}/api/v3` } /** @@ -60,21 +58,13 @@ function createDefaultDescriptionDictionary(topic) { * @param {string} params.repoSlug Slug with the format ${owner}/${repositoryName} * @returns {Promise} */ -export default async function updateCommitStatus({ - commit, - gitHubToken, - repoSlug, - stateKey, - targetUrl, - topic -}) { +export default async function updateCommitStatus({commit, gitHubToken, repoSlug, stateKey, targetUrl, topic}) { const [owner, repo] = repoSlug.split('/') const state = STATUS_STATES[stateKey] const baseUrl = await getApiBaseUrl() - const descriptionDictionaryForTopic = - STATUS_DESCRIPTION[topic] || createDefaultDescriptionDictionary(topic) + const descriptionDictionaryForTopic = STATUS_DESCRIPTION[topic] || createDefaultDescriptionDictionary(topic) const body = JSON.stringify({ context: `${STATUS_CONTEXT} (${topic})`, diff --git a/packages/sui-ci/test/server/updateCommitStatusSpec.js b/packages/sui-ci/test/server/updateCommitStatusSpec.js index 7dbd703bc..70c29bb09 100644 --- a/packages/sui-ci/test/server/updateCommitStatusSpec.js +++ b/packages/sui-ci/test/server/updateCommitStatusSpec.js @@ -19,9 +19,7 @@ describe('sui-ci', () => { it('calls GitHub Api to update status of a commit with the correct message for install topic', done => { mockGitHubRequest(({method, href, body}) => { expect(method).to.equal('POST') - expect(href).to.equal( - 'https://api.github.com/repos/SUI-Components/sui-components/statuses/commit-sha' - ) + expect(href).to.equal('https://api.github.com/repos/SUI-Components/sui-components/statuses/commit-sha') expect(body).to.eql({ context: '@s-ui/ci (install)', @@ -39,9 +37,7 @@ describe('sui-ci', () => { it('calls GitHub Api to update status of a commit with a default message for unknown topic', done => { mockGitHubRequest(({method, href, body}) => { expect(method).to.equal('POST') - expect(href).to.equal( - 'https://api.github.com/repos/SUI-Components/sui-components/statuses/commit-sha' - ) + expect(href).to.equal('https://api.github.com/repos/SUI-Components/sui-components/statuses/commit-sha') expect(body).to.eql({ context: '@s-ui/ci (whatever)', diff --git a/packages/sui-consents/test/common/hookSpec.js b/packages/sui-consents/test/common/hookSpec.js index d732eeb2a..0d147ad63 100644 --- a/packages/sui-consents/test/common/hookSpec.js +++ b/packages/sui-consents/test/common/hookSpec.js @@ -25,10 +25,7 @@ const triggerTcfEventFromConsents = consents => triggerTcfEvent({ eventStatus: 'useractioncomplete', purpose: { - consents: consents.reduce( - (acc, consentId) => ({...acc, [consentId]: true}), - {} - ) + consents: consents.reduce((acc, consentId) => ({...acc, [consentId]: true}), {}) } }) diff --git a/packages/sui-critical-css-middleware/src/index.js b/packages/sui-critical-css-middleware/src/index.js index 9c578e86f..5a4aee7b3 100644 --- a/packages/sui-critical-css-middleware/src/index.js +++ b/packages/sui-critical-css-middleware/src/index.js @@ -6,8 +6,7 @@ const pathToRegexp = require('path-to-regexp') const CRITICAL_CSS_DIR = 'critical-css' const CACHE_CRITICAL_CSS = {} -const getFilePath = ({file, criticalDir}) => - path.join(process.cwd(), criticalDir, file) +const getFilePath = ({file, criticalDir}) => path.join(process.cwd(), criticalDir, file) const getDisplayNameFrom = (matchResult = {}) => { const {renderProps = {}} = matchResult @@ -30,9 +29,7 @@ module.exports = const {matchResult, path: pathFromRequest} = req const displayName = getDisplayNameFrom(matchResult) - const criticalKey = - (manifest[displayName] && displayName) || - findCriticalKeyFrom({manifest, pathFromRequest}) + const criticalKey = (manifest[displayName] && displayName) || findCriticalKeyFrom({manifest, pathFromRequest}) if (!criticalKey) return next() diff --git a/packages/sui-critical-css/src/config.js b/packages/sui-critical-css/src/config.js index 8972430dd..59196aed2 100644 --- a/packages/sui-critical-css/src/config.js +++ b/packages/sui-critical-css/src/config.js @@ -9,8 +9,7 @@ export const blockedResourceTypes = [ 'texttrack' ] -const GOOGLE_BOT_UA = - '(compatible; Googlebot/2.1; +http://www.google.com/bot.html)' +const GOOGLE_BOT_UA = '(compatible; Googlebot/2.1; +http://www.google.com/bot.html)' const CRITICAL_UA = `CriticalCSS` export const devices = { diff --git a/packages/sui-critical-css/src/extract-from-app.js b/packages/sui-critical-css/src/extract-from-app.js index 47d0d0c45..49bf12739 100644 --- a/packages/sui-critical-css/src/extract-from-app.js +++ b/packages/sui-critical-css/src/extract-from-app.js @@ -14,17 +14,13 @@ const configForMobileDevice = devices.m export const createUrlFrom = ({hostname, pathOptions}) => { const path = typeof pathOptions === 'string' ? pathOptions : pathOptions.url - return Array.isArray(path) - ? path.map(current => `${hostname}${current}`) - : `${hostname}${path}` + return Array.isArray(path) ? path.map(current => `${hostname}${current}`) : `${hostname}${path}` } const waitForHealthCheck = ({healthCheckUrl}) => { return new Promise(resolve => { async function retry(retries) { - console.log( - `Waiting for health check. Checking ${healthCheckUrl}, remaining ${retries} retries...` - ) + console.log(`Waiting for health check. Checking ${healthCheckUrl}, remaining ${retries} retries...`) if (retries === 0) return resolve(false) let isResponseOK = false @@ -33,25 +29,16 @@ const waitForHealthCheck = ({healthCheckUrl}) => { isResponseOK = response.ok } catch (e) {} - return isResponseOK - ? resolve(true) - : globalThis.setTimeout(() => retry(--retries), TIME_BETWEEN_RETRIES) + return isResponseOK ? resolve(true) : globalThis.setTimeout(() => retry(--retries), TIME_BETWEEN_RETRIES) } retry(TIMES_TO_RETRY) }) } -const extractCriticalCSS = async ({ - requiredClassNames, - retries = 3, - url, - configForMobileDevice -} = {}) => { +const extractCriticalCSS = async ({requiredClassNames, retries = 3, url, configForMobileDevice} = {}) => { if (retries === 0) { - console.log( - `Attempt limit reached. requiredClassNames has not been found in ${url}` - ) + console.log(`Attempt limit reached. requiredClassNames has not been found in ${url}`) return '' } @@ -65,16 +52,12 @@ const extractCriticalCSS = async ({ if (!requiredClassNames) return css - const hasRequiredClasses = requiredClassNames.every(className => - css?.includes(className) - ) + const hasRequiredClasses = requiredClassNames.every(className => css?.includes(className)) if (!hasRequiredClasses) { const nextTryNumber = retries - 1 - console.log( - `requiredClassNames has not been found. Retries remaining: ${nextTryNumber}` - ) + console.log(`requiredClassNames has not been found. Retries remaining: ${nextTryNumber}`) return extractCriticalCSS({ requiredClassNames, diff --git a/packages/sui-critical-css/src/extract-from-url.js b/packages/sui-critical-css/src/extract-from-url.js index c2869adf0..c24df4711 100644 --- a/packages/sui-critical-css/src/extract-from-url.js +++ b/packages/sui-critical-css/src/extract-from-url.js @@ -27,13 +27,7 @@ const getBrowser = async () => { return browser } -export async function extractCSSFromUrl({ - customHeaders, - height, - url, - userAgent, - width -}) { +export async function extractCSSFromUrl({customHeaders, height, url, userAgent, width}) { let page try { // Get a browser instance @@ -45,14 +39,12 @@ export async function extractCSSFromUrl({ await page.setViewportSize({width, height}) page.setDefaultNavigationTimeout(15000) - const hasCustomHeaders = - typeof customHeaders === 'object' && Object.keys(customHeaders).length + const hasCustomHeaders = typeof customHeaders === 'object' && Object.keys(customHeaders).length hasCustomHeaders && (await page.setExtraHTTPHeaders(customHeaders)) await page.route('**/*', route => { const request = route.request() - return blockedResourceTypes.includes(request.resourceType()) || - skippedResources.includes(request.url()) + return blockedResourceTypes.includes(request.resourceType()) || skippedResources.includes(request.url()) ? route.abort().catch(() => {}) : route.continue().catch(() => {}) }) @@ -63,9 +55,7 @@ export async function extractCSSFromUrl({ const responses = [] for (url of urls) { - const response = await page - .goto(url, {waitUntil: 'networkidle'}) - .catch(error => ({error})) + const response = await page.goto(url, {waitUntil: 'networkidle'}).catch(error => ({error})) responses.push(response) } @@ -83,14 +73,9 @@ export async function extractCSSFromUrl({ if (error) await closeAll(error) - const current = responses.find( - response => !response.ok() && response.status() !== 304 - ) + const current = responses.find(response => !response.ok() && response.status() !== 304) - if (current) - await closeAll( - `Response status code ${current.status()} for url ${current.url()}` - ) + if (current) await closeAll(`Response status code ${current.status()} for url ${current.url()}`) console.log('[ok] Got response') @@ -109,9 +94,7 @@ export async function extractCSSFromUrl({ // return minified css const {styles, stats} = css.minify(coveredCSS) - console.log( - `[css] Minified from ${stats.originalSize} to ${stats.minifiedSize} bytes` - ) + console.log(`[css] Minified from ${stats.originalSize} to ${stats.minifiedSize} bytes`) return styles } catch (e) { console.log(e) diff --git a/packages/sui-dashboard/bin/sui-dashboard-components.js b/packages/sui-dashboard/bin/sui-dashboard-components.js index 61671b12f..7fb5ef294 100755 --- a/packages/sui-dashboard/bin/sui-dashboard-components.js +++ b/packages/sui-dashboard/bin/sui-dashboard-components.js @@ -73,23 +73,12 @@ const repositories = [ ] const cloneSUIComponentsCommand = [ - [ - 'git', - [ - 'clone', - 'https://github.com/SUI-Components/sui-components', - join(WORK_DIRECTORY, 'sui-components') - ] - ] + ['git', ['clone', 'https://github.com/SUI-Components/sui-components', join(WORK_DIRECTORY, 'sui-components')]] ] const cloneCommands = repositories.map(repo => [ 'git', - [ - 'clone', - `git@github.mpi-internal.com:scmspain/${repo}.git`, - join(WORK_DIRECTORY, repo) - ] + ['clone', `git@github.mpi-internal.com:scmspain/${repo}.git`, join(WORK_DIRECTORY, repo)] ]) const installCommands = repositories.map(repo => [ diff --git a/packages/sui-dashboard/src/index.js b/packages/sui-dashboard/src/index.js index 3beee6269..a6b29f59e 100644 --- a/packages/sui-dashboard/src/index.js +++ b/packages/sui-dashboard/src/index.js @@ -8,38 +8,26 @@ const getPackageContent = filepath => JSON.parse(readFileSync(filepath)) export async function stats({repositories, root, getVersions = false}) { const suiComponents = fg - .sync([ - `${root}/sui-components/components/**/package.json`, - '!**/node_modules/**' - ]) + .sync([`${root}/sui-components/components/**/package.json`, '!**/node_modules/**']) .map(path => require(path).name) const componentsInstalled = flat( - repositories.map(repo => [ - `${root}/${repo}/node_modules/@s-ui/*`, - `${root}/${repo}/node_modules/@schibstedspain/*` - ]) + repositories.map(repo => [`${root}/${repo}/node_modules/@s-ui/*`, `${root}/${repo}/node_modules/@schibstedspain/*`]) ) const dirs = fg.sync(componentsInstalled, {onlyDirectories: true}) - const statsSUIComponentUsedInProjects = suiComponents.reduce( - (acc, component) => { - acc[component] = dirs - .filter(dir => dir.includes(component)) - .map(dir => { - const pkg = getVersions && getPackageContent(`${dir}/package.json`) - return dir - .replace(root, '') - .replace( - /(?[a-z|-]+)\/.*/, - '$' + (getVersions ? ` – v${pkg.version}` : '') - ) - }) - return acc - }, - {} - ) + const statsSUIComponentUsedInProjects = suiComponents.reduce((acc, component) => { + acc[component] = dirs + .filter(dir => dir.includes(component)) + .map(dir => { + const pkg = getVersions && getPackageContent(`${dir}/package.json`) + return dir + .replace(root, '') + .replace(/(?[a-z|-]+)\/.*/, '$' + (getVersions ? ` – v${pkg.version}` : '')) + }) + return acc + }, {}) const statsSUIComponentUsedByProjects = repositories.reduce((acc, repo) => { acc[repo] = dirs @@ -47,26 +35,23 @@ export async function stats({repositories, root, getVersions = false}) { .filter(dir => suiComponents.some(sui => dir.includes(sui))) .map(dir => { const pkg = getVersions && getPackageContent(`${dir}/package.json`) - return dir.replace( - /^.+(?@[a-z|-]+\/[a-z|-]+$)/, - '$' + (getVersions ? `@${pkg.version}` : '') - ) + return dir.replace(/^.+(?@[a-z|-]+\/[a-z|-]+$)/, '$' + (getVersions ? `@${pkg.version}` : '')) }) return acc }, {}) const totalSUIComponents = Object.keys(statsSUIComponentUsedInProjects).length - const totalReusedSUIComponents = Object.values( - statsSUIComponentUsedInProjects - ).reduce((acc, list) => (acc += list.length), 0) + const totalReusedSUIComponents = Object.values(statsSUIComponentUsedInProjects).reduce( + (acc, list) => (acc += list.length), + 0 + ) const maxPossible = totalSUIComponents * repositories.length return { statsSUIComponentUsedByProjects, statsSUIComponentUsedInProjects, suiStats: { - percentage: - Math.ceil((totalReusedSUIComponents * 100) / maxPossible) + '%', + percentage: Math.ceil((totalReusedSUIComponents * 100) / maxPossible) + '%', totalSUIComponents, totalReusedSUIComponents, maxPossible diff --git a/packages/sui-decorators/src/decorators/cache/algorithms/Redis.js b/packages/sui-decorators/src/decorators/cache/algorithms/Redis.js index bead28a98..27d66ef9c 100644 --- a/packages/sui-decorators/src/decorators/cache/algorithms/Redis.js +++ b/packages/sui-decorators/src/decorators/cache/algorithms/Redis.js @@ -4,12 +4,7 @@ import Cache from './Cache.js' import RedisClient from './RedisClient.js' export default class Redis extends Cache { - constructor({ - redisConnection = {host: '127.0.0.1', port: 6379}, - size = 100, - namespace, - ttl = 500 - } = {}) { + constructor({redisConnection = {host: '127.0.0.1', port: 6379}, size = 100, namespace, ttl = 500} = {}) { super() this._ttl = ttl this._redisClient = RedisClient.getInstance({redisConnection}).client @@ -27,16 +22,10 @@ export default class Redis extends Cache { async get(key) { try { - const resp = await Promise.race([ - this._lruRedis.get(key), - this._delay(100) - ]) + const resp = await Promise.race([this._lruRedis.get(key), this._delay(100)]) return resp } catch (err) { - console.error( - `[sui-decorators/cache]:Redis Error Getting cache item for key: ${key}.`, - err.message - ) + console.error(`[sui-decorators/cache]:Redis Error Getting cache item for key: ${key}.`, err.message) return null } } @@ -50,10 +39,7 @@ export default class Redis extends Cache { set(key, value, maxAge = this._ttl) { const ret = this._lruRedis.set(key, value, maxAge) Promise.race([ret, this._delay(100)]).catch(err => { - console.error( - `[sui-decorators/cache]:Redis Error Setting cache item for key: ${key}.`, - err.message - ) + console.error(`[sui-decorators/cache]:Redis Error Setting cache item for key: ${key}.`, err.message) }) } @@ -61,10 +47,7 @@ export default class Redis extends Cache { try { this._lruRedis.del(key) } catch (err) { - console.error( - `[sui-decorators/cache]:Redis Error deleting cache item for key: ${key}.`, - err.message - ) + console.error(`[sui-decorators/cache]:Redis Error deleting cache item for key: ${key}.`, err.message) } } diff --git a/packages/sui-decorators/src/decorators/cache/algorithms/RedisClient.js b/packages/sui-decorators/src/decorators/cache/algorithms/RedisClient.js index 9a0ef092d..81fd4eb44 100644 --- a/packages/sui-decorators/src/decorators/cache/algorithms/RedisClient.js +++ b/packages/sui-decorators/src/decorators/cache/algorithms/RedisClient.js @@ -17,9 +17,7 @@ export default class RedisClient { : redisMock.createClient() this._redisClient.on('error', function () { - console.error( - `[sui-decorators/cache]:RedisClient Error creating Redis client` - ) + console.error(`[sui-decorators/cache]:RedisClient Error creating Redis client`) }) } diff --git a/packages/sui-decorators/src/decorators/cache/handlers/inMemory.js b/packages/sui-decorators/src/decorators/cache/handlers/inMemory.js index 61f234af5..54e5b8c4c 100644 --- a/packages/sui-decorators/src/decorators/cache/handlers/inMemory.js +++ b/packages/sui-decorators/src/decorators/cache/handlers/inMemory.js @@ -27,7 +27,5 @@ export const inMemory = cache.del(key) } - return cache.get(key) !== undefined - ? cache.get(key).returns - : original.apply(instance, args) + return cache.get(key) !== undefined ? cache.get(key).returns : original.apply(instance, args) } diff --git a/packages/sui-decorators/src/decorators/cache/handlers/inRedis.js b/packages/sui-decorators/src/decorators/cache/handlers/inRedis.js index 7e609fdfb..503b32915 100644 --- a/packages/sui-decorators/src/decorators/cache/handlers/inRedis.js +++ b/packages/sui-decorators/src/decorators/cache/handlers/inRedis.js @@ -1,9 +1,8 @@ import {createHash} from '@s-ui/js/lib/hash' -const VERSION_NAMESPACE_TAG = - global.USE_VERSION_NAMESPACE_FOR_REDIS_SUI_DECORATORS_CACHE - ? `${global.USE_VERSION_NAMESPACE_FOR_REDIS_SUI_DECORATORS_CACHE}::` - : '' +const VERSION_NAMESPACE_TAG = global.USE_VERSION_NAMESPACE_FOR_REDIS_SUI_DECORATORS_CACHE + ? `${global.USE_VERSION_NAMESPACE_FOR_REDIS_SUI_DECORATORS_CACHE}::` + : '' export const inRedis = (target, cache, original, fnName, instance, ttl, cacheKey) => @@ -24,12 +23,8 @@ export const inRedis = } const isInlineErrorResponseWithoutError = - Array.isArray(response) && - response.__INLINE_ERROR__ && - response[0] === null && - response[1] - const isNormalResponseWithoutError = - response && !response.__INLINE_ERROR__ + Array.isArray(response) && response.__INLINE_ERROR__ && response[0] === null && response[1] + const isNormalResponseWithoutError = response && !response.__INLINE_ERROR__ if (isInlineErrorResponseWithoutError || isNormalResponseWithoutError) { cache.set(key, response, ttl) diff --git a/packages/sui-decorators/src/decorators/cache/index.js b/packages/sui-decorators/src/decorators/cache/index.js index ef8a1df97..0aa8f17e9 100644 --- a/packages/sui-decorators/src/decorators/cache/index.js +++ b/packages/sui-decorators/src/decorators/cache/index.js @@ -10,17 +10,7 @@ const DEFAULT_TTL = 500 const caches = {} -const _cache = ({ - algorithm, - fnName, - instance, - original, - size, - target, - ttl, - redis, - cacheKeyString -} = {}) => { +const _cache = ({algorithm, fnName, instance, original, size, target, ttl, redis, cacheKeyString} = {}) => { const shouldUseRedisCache = redis && isNode const shouldUseMemoryCache = !isNode || !redis const cacheKey = cacheKeyString || `${target.constructor.name}::${fnName}` diff --git a/packages/sui-decorators/src/decorators/error.js b/packages/sui-decorators/src/decorators/error.js index c192c5f93..01e99a702 100644 --- a/packages/sui-decorators/src/decorators/error.js +++ b/packages/sui-decorators/src/decorators/error.js @@ -9,10 +9,7 @@ const _runner = ({instance, original} = {}) => { value: true }) try { - const returns = original.apply( - instance.__STREAMIFY__ ? this : instance, - args - ) + const returns = original.apply(instance.__STREAMIFY__ ? this : instance, args) if (isPromise(returns)) { return returns .then(r => { diff --git a/packages/sui-decorators/src/decorators/streamify.js b/packages/sui-decorators/src/decorators/streamify.js index 3a0a47e1d..863ac0fb5 100644 --- a/packages/sui-decorators/src/decorators/streamify.js +++ b/packages/sui-decorators/src/decorators/streamify.js @@ -10,9 +10,7 @@ const dispatchToListeners = ({onError, onNext, params, result}) => { .then(value => { if (value.__INLINE_ERROR__) { const [error, val] = value - return !error - ? onNext({params, result: val}) - : onError({params, error}) + return !error ? onNext({params, result: val}) : onError({params, error}) } onNext({params, result: value}) }) @@ -77,9 +75,7 @@ export default (...methods) => { Target.prototype.__STREAMIFY__ = true Object.assign( Target.prototype, - methods - .filter(method => !!Target.prototype[method]) - .reduce(reducer.bind(null, Target), {}) + methods.filter(method => !!Target.prototype[method]).reduce(reducer.bind(null, Target), {}) ) return Target } diff --git a/packages/sui-decorators/src/decorators/tracer/index.js b/packages/sui-decorators/src/decorators/tracer/index.js index 9c88bcaba..b8fc7df41 100644 --- a/packages/sui-decorators/src/decorators/tracer/index.js +++ b/packages/sui-decorators/src/decorators/tracer/index.js @@ -9,9 +9,7 @@ export {DataDogReporter} from './reporters/DataDogReporter.js' const getPerformanceMeter = () => (isNode ? performance : window.performance) const getReporter = () => { - const customReporter = isNode - ? global.__SUI_DECORATOR_TRACER_REPORTER__ - : window.__SUI_DECORATOR_TRACER_REPORTER__ + const customReporter = isNode ? global.__SUI_DECORATOR_TRACER_REPORTER__ : window.__SUI_DECORATOR_TRACER_REPORTER__ return customReporter || new ConsoleReporter() } diff --git a/packages/sui-decorators/src/decorators/tracer/reporters/DataDogReporter.js b/packages/sui-decorators/src/decorators/tracer/reporters/DataDogReporter.js index c414c6299..abc765679 100644 --- a/packages/sui-decorators/src/decorators/tracer/reporters/DataDogReporter.js +++ b/packages/sui-decorators/src/decorators/tracer/reporters/DataDogReporter.js @@ -15,10 +15,6 @@ export class DataDogReporter extends ReporterInterface { const siteNameSubString = `${this._siteName ? `${this._siteName}.` : ''}` - this._client.timing( - `frontend.${siteNameSubString}tracer.datadog.reporter`, - value, - globalTags - ) + this._client.timing(`frontend.${siteNameSubString}tracer.datadog.reporter`, value, globalTags) } } diff --git a/packages/sui-decorators/src/helpers/isNode.js b/packages/sui-decorators/src/helpers/isNode.js index 9398d0c5a..549ded085 100644 --- a/packages/sui-decorators/src/helpers/isNode.js +++ b/packages/sui-decorators/src/helpers/isNode.js @@ -3,6 +3,5 @@ module.exports = false // Only Node.JS has a process variable that is of [[Class]] process try { - module.exports = - Object.prototype.toString.call(global.process) === '[object process]' + module.exports = Object.prototype.toString.call(global.process) === '[object process]' } catch (e) {} diff --git a/packages/sui-decorators/src/helpers/isPromise.js b/packages/sui-decorators/src/helpers/isPromise.js index 836cda71c..a73816e02 100644 --- a/packages/sui-decorators/src/helpers/isPromise.js +++ b/packages/sui-decorators/src/helpers/isPromise.js @@ -1,2 +1 @@ -export default obj => - typeof obj !== 'undefined' && typeof obj.then === 'function' +export default obj => typeof obj !== 'undefined' && typeof obj.then === 'function' diff --git a/packages/sui-decorators/test/browser/cacheSpec.js b/packages/sui-decorators/test/browser/cacheSpec.js index 95931c5ff..9a3bf314f 100644 --- a/packages/sui-decorators/test/browser/cacheSpec.js +++ b/packages/sui-decorators/test/browser/cacheSpec.js @@ -72,12 +72,10 @@ describe('Cache in browser', () => { } } const dummy = new Dummy() - Promise.all([dummy.asyncRndNumber(), dummy.asyncRndNumber()]).then( - ([firstCall, secondCall]) => { - expect(firstCall).to.be.eql(secondCall) - done() - } - ) + Promise.all([dummy.asyncRndNumber(), dummy.asyncRndNumber()]).then(([firstCall, secondCall]) => { + expect(firstCall).to.be.eql(secondCall) + done() + }) }) it('with cacheKeyString param defined should return twice the same random number without params', done => { @@ -89,12 +87,10 @@ describe('Cache in browser', () => { } } const dummy = new Dummy2() - Promise.all([dummy.asyncRndNumber(), dummy.asyncRndNumber()]).then( - ([firstCall, secondCall]) => { - expect(firstCall).to.be.eql(secondCall) - done() - } - ) + Promise.all([dummy.asyncRndNumber(), dummy.asyncRndNumber()]).then(([firstCall, secondCall]) => { + expect(firstCall).to.be.eql(secondCall) + done() + }) }) it('return different numbers if the promise fails', done => { @@ -104,12 +100,8 @@ describe('Cache in browser', () => { @inlineError asyncRndNumber(num) { const prms = !fail - ? new Promise((resolve, reject) => - setTimeout(resolve, 100, Math.random()) - ) - : new Promise((resolve, reject) => - setTimeout(reject, 100, Math.random()) - ) + ? new Promise((resolve, reject) => setTimeout(resolve, 100, Math.random())) + : new Promise((resolve, reject) => setTimeout(reject, 100, Math.random())) fail = !fail return prms } @@ -156,9 +148,7 @@ describe('Cache in browser', () => { } const dummy = new Dummy() expect(dummy.syncRndNumber(1, 2)).to.be.eql(dummy.syncRndNumber(1, 2)) - expect(dummy.syncRndNumber({a: 'b'})).to.be.eql( - dummy.syncRndNumber({a: 'b'}) - ) + expect(dummy.syncRndNumber({a: 'b'})).to.be.eql(dummy.syncRndNumber({a: 'b'})) }) describe('have a TTL for each key', () => { diff --git a/packages/sui-decorators/test/browser/streamifySpec.js b/packages/sui-decorators/test/browser/streamifySpec.js index 6c527329c..b5251190b 100644 --- a/packages/sui-decorators/test/browser/streamifySpec.js +++ b/packages/sui-decorators/test/browser/streamifySpec.js @@ -49,12 +49,7 @@ describe('Streamify', () => { let subscription beforeEach(() => { - const DummyDecorate = streamify( - 'dummyMethod', - 'dummyMethodPromise', - 'throwError', - 'asyncThrowError' - )(Dummy) + const DummyDecorate = streamify('dummyMethod', 'dummyMethodPromise', 'throwError', 'asyncThrowError')(Dummy) dummyDecorate = new DummyDecorate('Carlos') }) @@ -88,11 +83,7 @@ describe('Streamify', () => { done() } - subscription = dummyDecorate.$.throwError.subscribe( - console.log.bind(console), - onError, - console.log.bind(console) - ) + subscription = dummyDecorate.$.throwError.subscribe(console.log.bind(console), onError, console.log.bind(console)) try { dummyDecorate.throwError() @@ -177,8 +168,7 @@ describe('Streamify', () => { describe('dispose', () => { it('unsubscribe to calls and results for Async method', done => { const onNext = sinon.spy() - const subscription = - dummyDecorate.$.dummyMethodPromise.subscribe(onNext) + const subscription = dummyDecorate.$.dummyMethodPromise.subscribe(onNext) // unsubscribe immediately to check onNext is not called subscription.dispose() diff --git a/packages/sui-decorators/test/server/cacheSpec.js b/packages/sui-decorators/test/server/cacheSpec.js index f3fe978aa..6fe533a9b 100644 --- a/packages/sui-decorators/test/server/cacheSpec.js +++ b/packages/sui-decorators/test/server/cacheSpec.js @@ -93,12 +93,10 @@ describe('Cache in the server', () => { } } const dummy = new Dummy() - Promise.all([dummy.asyncRndNumber(), dummy.asyncRndNumber()]).then( - ([firstCall, secondCall]) => { - expect(firstCall).to.be.eql(secondCall) - done() - } - ) + Promise.all([dummy.asyncRndNumber(), dummy.asyncRndNumber()]).then(([firstCall, secondCall]) => { + expect(firstCall).to.be.eql(secondCall) + done() + }) }) it('should not apply cache for inlineError decorated error response and cache ok response', async () => { @@ -146,12 +144,10 @@ describe('Cache in the server', () => { } } const dummy = new Dummy2() - Promise.all([dummy.asyncRndNumber(), dummy.asyncRndNumber()]).then( - ([firstCall, secondCall]) => { - expect(firstCall).to.be.eql(secondCall) - done() - } - ) + Promise.all([dummy.asyncRndNumber(), dummy.asyncRndNumber()]).then(([firstCall, secondCall]) => { + expect(firstCall).to.be.eql(secondCall) + done() + }) }) }) diff --git a/packages/sui-decorators/test/server/streamifySpec.js b/packages/sui-decorators/test/server/streamifySpec.js index c04bc7bdb..12f241e2b 100644 --- a/packages/sui-decorators/test/server/streamifySpec.js +++ b/packages/sui-decorators/test/server/streamifySpec.js @@ -49,12 +49,7 @@ describe('Streamify', () => { let subscription beforeEach(() => { - const DummyDecorate = streamify( - 'dummyMethod', - 'dummyMethodPromise', - 'throwError', - 'asyncThrowError' - )(Dummy) + const DummyDecorate = streamify('dummyMethod', 'dummyMethodPromise', 'throwError', 'asyncThrowError')(Dummy) dummyDecorate = new DummyDecorate('Carlos') }) @@ -88,11 +83,7 @@ describe('Streamify', () => { done() } - subscription = dummyDecorate.$.throwError.subscribe( - console.log.bind(console), - onError, - console.log.bind(console) - ) + subscription = dummyDecorate.$.throwError.subscribe(console.log.bind(console), onError, console.log.bind(console)) try { dummyDecorate.throwError() @@ -178,8 +169,7 @@ describe('Streamify', () => { describe('dispose', () => { it('unsubscribe to calls and results for Async method', done => { const onNext = sinon.spy() - const subscription = - dummyDecorate.$.dummyMethodPromise.subscribe(onNext) + const subscription = dummyDecorate.$.dummyMethodPromise.subscribe(onNext) // unsubscribe immediately to check onNext is not called subscription.dispose() diff --git a/packages/sui-domain/src/EntryPointFactory.js b/packages/sui-domain/src/EntryPointFactory.js index 5ff482058..f283bdf90 100644 --- a/packages/sui-domain/src/EntryPointFactory.js +++ b/packages/sui-domain/src/EntryPointFactory.js @@ -30,8 +30,7 @@ export default ({useCases, config, logger, pde}) => // get the useCase using the key passed by the user const useCase = this._useCases[key] // if the useCase doesn't exist, then let developer know that the useCase is not implemented - if (typeof useCase === 'undefined') - return createNotImplementedUseCase(key) + if (typeof useCase === 'undefined') return createNotImplementedUseCase(key) const isDynamicImportWholeFactory = useCase instanceof Array @@ -39,9 +38,7 @@ export default ({useCases, config, logger, pde}) => ? useCase // for the whole factory we extract the single method from the array : [useCase] // for the single factory, the method is undefined as is default - const getMethod = isDynamicImportWholeFactory - ? factory => factory.default[method] - : factory => factory.default + const getMethod = isDynamicImportWholeFactory ? factory => factory.default[method] : factory => factory.default // if loader is undefined then is not implemented, otherwhise load async the useCase return loader === undefined @@ -59,15 +56,11 @@ export default ({useCases, config, logger, pde}) => }).execute(params) ) .then(result => { - subscriptionsForUseCase.forEach(fn => - fn({error: null, params, result}) - ) + subscriptionsForUseCase.forEach(fn => fn({error: null, params, result})) return result }) .catch(e => { - subscriptionsForUseCase.forEach(fn => - fn({error: e, params, result: null}) - ) + subscriptionsForUseCase.forEach(fn => fn({error: e, params, result: null})) return Promise.reject(e) }) }, @@ -78,9 +71,7 @@ export default ({useCases, config, logger, pde}) => // return a way to remove the listener return { unsubscribe: () => { - this.subscribers[key] = this.subscribers[key].filter( - l => l !== callback - ) + this.subscribers[key] = this.subscribers[key].filter(l => l !== callback) } } }, diff --git a/packages/sui-domain/src/createNotImplementedUseCase.js b/packages/sui-domain/src/createNotImplementedUseCase.js index 15afc5ae9..33a1bcba9 100644 --- a/packages/sui-domain/src/createNotImplementedUseCase.js +++ b/packages/sui-domain/src/createNotImplementedUseCase.js @@ -8,10 +8,5 @@ * * */ export default key => ({ - execute: () => - Promise.resolve( - console.warn( - `Service ${key} is not implemented in the current version of the domain` - ) - ) + execute: () => Promise.resolve(console.warn(`Service ${key} is not implemented in the current version of the domain`)) }) diff --git a/packages/sui-domain/src/fetcher/FetcherInterceptor.js b/packages/sui-domain/src/fetcher/FetcherInterceptor.js index bc1c731fc..6d64d320a 100644 --- a/packages/sui-domain/src/fetcher/FetcherInterceptor.js +++ b/packages/sui-domain/src/fetcher/FetcherInterceptor.js @@ -31,9 +31,7 @@ export default class FetcherInterceptor { let result = originalResult if (this._isPromiseType(result)) { - result = new Promise((resolve, reject) => - this._catchExceptions({resolve, reject, originalResult}) - ) + result = new Promise((resolve, reject) => this._catchExceptions({resolve, reject, originalResult})) } return result @@ -51,10 +49,7 @@ export default class FetcherInterceptor { const response = await originalResult resolve(response) } catch (error) { - if ( - FetcherInterceptor.errorInterceptor !== null && - typeof FetcherInterceptor.errorInterceptor === 'function' - ) { + if (FetcherInterceptor.errorInterceptor !== null && typeof FetcherInterceptor.errorInterceptor === 'function') { FetcherInterceptor.errorInterceptor(error) } diff --git a/packages/sui-domain/test/common/EntryPointSpec.js b/packages/sui-domain/test/common/EntryPointSpec.js index f8a58d3ff..5fb2c5417 100644 --- a/packages/sui-domain/test/common/EntryPointSpec.js +++ b/packages/sui-domain/test/common/EntryPointSpec.js @@ -23,9 +23,7 @@ describe('EntryPointFactory', () => { const EntryPoint = EntryPointFactory({config, useCases}) const domain = new EntryPoint() - const useCase = domain.get( - 'use_case_from_factory_with_multiple_use_cases' - ) + const useCase = domain.get('use_case_from_factory_with_multiple_use_cases') const response = await useCase.execute() expect(useCase.execute).to.be.a('function') @@ -35,8 +33,7 @@ describe('EntryPointFactory', () => { it('should be able to import a single UseCase factory', async () => { const useCases = { - use_case_from_single_factory_use_case: () => - import('./fixtures/factoryWithSingleUseCase.js') + use_case_from_single_factory_use_case: () => import('./fixtures/factoryWithSingleUseCase.js') } const EntryPoint = EntryPointFactory({config, useCases}) const domain = new EntryPoint() @@ -51,20 +48,17 @@ describe('EntryPointFactory', () => { it('should be able to subscribe to useCase execution', done => { const useCases = { - use_case_from_single_factory_use_case: () => - import('./fixtures/factoryWithSingleUseCase.js') + use_case_from_single_factory_use_case: () => import('./fixtures/factoryWithSingleUseCase.js') } const EntryPoint = EntryPointFactory({config, useCases}) const domain = new EntryPoint() - domain - .get('use_case_from_single_factory_use_case') - .subscribe(({error, result, params}) => { - expect(error).to.be.null - expect(params).to.deep.equal({foo: 'bar'}) - expect(result).to.be.true - done() - }) + domain.get('use_case_from_single_factory_use_case').subscribe(({error, result, params}) => { + expect(error).to.be.null + expect(params).to.deep.equal({foo: 'bar'}) + expect(result).to.be.true + done() + }) domain.get('use_case_from_single_factory_use_case').execute({foo: 'bar'}) }) @@ -72,20 +66,17 @@ describe('EntryPointFactory', () => { it('should be able to unsubscribe to useCase subscription', done => { let callCount = 0 const useCases = { - use_case_from_single_factory_use_case: () => - import('./fixtures/factoryWithSingleUseCase.js') + use_case_from_single_factory_use_case: () => import('./fixtures/factoryWithSingleUseCase.js') } const EntryPoint = EntryPointFactory({config, useCases}) const domain = new EntryPoint() - const {unsubscribe} = domain - .get('use_case_from_single_factory_use_case') - .subscribe(({error, result, params}) => { - expect(error).to.be.null - expect(params).to.deep.equal({foo: 'bar'}) - expect(result).to.be.true - callCount++ - }) + const {unsubscribe} = domain.get('use_case_from_single_factory_use_case').subscribe(({error, result, params}) => { + expect(error).to.be.null + expect(params).to.deep.equal({foo: 'bar'}) + expect(result).to.be.true + callCount++ + }) domain .get('use_case_from_single_factory_use_case') @@ -116,9 +107,7 @@ describe('EntryPointFactory', () => { const EntryPoint = EntryPointFactory({config, useCases, logger}) const domain = new EntryPoint() - const useCase = domain.get( - 'use_case_from_factory_with_multiple_use_cases_and_logger' - ) + const useCase = domain.get('use_case_from_factory_with_multiple_use_cases_and_logger') const response = await useCase.execute() expect(useCase.execute).to.be.a('function') @@ -137,9 +126,7 @@ describe('EntryPointFactory', () => { const EntryPoint = EntryPointFactory({config, useCases, logger}) const domain = new EntryPoint() - const useCase = domain.get( - 'use_case_from_single_factory_use_case_and_logger' - ) + const useCase = domain.get('use_case_from_single_factory_use_case_and_logger') const response = await useCase.execute() expect(useCase.execute).to.be.a('function') @@ -158,21 +145,17 @@ describe('EntryPointFactory', () => { const EntryPoint = EntryPointFactory({config, useCases, logger}) const domain = new EntryPoint() - domain - .get('use_case_from_single_factory_use_case_and_logger') - .subscribe(({error, result, params}) => { - expect(error).to.be.null - expect(params).to.deep.equal({foo: 'bar'}) - expect(result).to.be.true - expect(logger.log.called).to.eql(true) - expect(logger.error.called).to.eql(true) - expect(logger.metric.called).to.eql(true) - done() - }) - - domain - .get('use_case_from_single_factory_use_case_and_logger') - .execute({foo: 'bar'}) + domain.get('use_case_from_single_factory_use_case_and_logger').subscribe(({error, result, params}) => { + expect(error).to.be.null + expect(params).to.deep.equal({foo: 'bar'}) + expect(result).to.be.true + expect(logger.log.called).to.eql(true) + expect(logger.error.called).to.eql(true) + expect(logger.metric.called).to.eql(true) + done() + }) + + domain.get('use_case_from_single_factory_use_case_and_logger').execute({foo: 'bar'}) }) it('should be able to unsubscribe to useCase subscription', done => { diff --git a/packages/sui-domain/test/common/FetcherInterceptorSpec.js b/packages/sui-domain/test/common/FetcherInterceptorSpec.js index 62f205455..ebc257120 100644 --- a/packages/sui-domain/test/common/FetcherInterceptorSpec.js +++ b/packages/sui-domain/test/common/FetcherInterceptorSpec.js @@ -7,8 +7,7 @@ describe('FetcherInterceptor', () => { const interceptableMockedFetcher = statusCode => { return { get: async () => { - if (statusCode !== 200) - throw new Error(`HTTP simulated error: ${statusCode}`) + if (statusCode !== 200) throw new Error(`HTTP simulated error: ${statusCode}`) return 'It works!' } diff --git a/packages/sui-domain/test/common/fixtures/factoryWithSingleUseCaseAndLogger.js b/packages/sui-domain/test/common/fixtures/factoryWithSingleUseCaseAndLogger.js index 8ef1742eb..07b2c2676 100644 --- a/packages/sui-domain/test/common/fixtures/factoryWithSingleUseCaseAndLogger.js +++ b/packages/sui-domain/test/common/fixtures/factoryWithSingleUseCaseAndLogger.js @@ -1,4 +1,3 @@ import EmptyUseCaseWithLogger from './EmptyUseCaseWithLogger.js' -export default ({config, logger}) => - new EmptyUseCaseWithLogger({config, logger}) +export default ({config, logger}) => new EmptyUseCaseWithLogger({config, logger}) diff --git a/packages/sui-helpers/cli.js b/packages/sui-helpers/cli.js index 6ed7f3613..1f87f89ae 100644 --- a/packages/sui-helpers/cli.js +++ b/packages/sui-helpers/cli.js @@ -15,10 +15,7 @@ const CODE_OK = 0 * @return {Promise} Resolved with exit code, when all commands where executed on one failed. */ function serialSpawn(commands, options = {}) { - return commands.reduce( - (promise, args) => promise.then(() => getSpawnPromise(...args, options)), - Promise.resolve() - ) + return commands.reduce((promise, args) => promise.then(() => getSpawnPromise(...args, options)), Promise.resolve()) } /** @@ -30,23 +27,15 @@ function serialSpawn(commands, options = {}) { function parallelSpawn(commands, options = {}) { const {chunks = 15, title} = options - commands = commands.map(([bin, args, opts]) => [ - bin, - args, - {...opts, ...options} - ]) + commands = commands.map(([bin, args, opts]) => [bin, args, {...opts, ...options}]) const commandsTitle = title || 'commands' - console.log( - colors.cyan(`›› Running ${commands.length} ${commandsTitle} in parallel.`) - ) + console.log(colors.cyan(`›› Running ${commands.length} ${commandsTitle} in parallel.`)) return spawnList(commands, {chunks, title}) .then(() => { - logUpdate.done( - colors.green(`✔ ${commands.length} ${commandsTitle} run successfully.`) - ) + logUpdate.done(colors.green(`✔ ${commands.length} ${commandsTitle} run successfully.`)) return CODE_OK }) .catch(showError) @@ -63,9 +52,7 @@ function spawnList(commands, {chunks = 15, title = ''} = {}) { const concurrency = Number(chunks) const queue = new Queue({concurrency}) const logUpdateProgress = (title, pending) => { - const pendingMessage = colors.cyan( - `${pending} of ${commands.length} pending` - ) + const pendingMessage = colors.cyan(`${pending} of ${commands.length} pending`) logUpdate(`› ${title} ─ ${pendingMessage}`) } @@ -80,8 +67,7 @@ function spawnList(commands, {chunks = 15, title = ''} = {}) { }) ) .then(() => { - const titleToUse = - title || titleFromCommand || getCommandCallMessage(bin, args, opts) + const titleToUse = title || titleFromCommand || getCommandCallMessage(bin, args, opts) const {size, pending} = queue const totalPending = size + pending logUpdateProgress(titleToUse, totalPending) @@ -122,9 +108,7 @@ function getSpawnPromise(bin, args, options = {}) { * @return {String} */ function getCommandCallMessage(bin, args, options = {}) { - const folder = options.cwd - ? options.cwd.split(path.sep).slice(-2).join(path.sep) - : '' + const folder = options.cwd ? options.cwd.split(path.sep).slice(-2).join(path.sep) : '' const command = bin.split(path.sep).pop() + ' ' + args.join(' ') return `${colors.bold(command)} ${colors.cyan(folder)}` diff --git a/packages/sui-helpers/colors.js b/packages/sui-helpers/colors.js index 87fd690e8..1bfcd3662 100644 --- a/packages/sui-helpers/colors.js +++ b/packages/sui-helpers/colors.js @@ -15,8 +15,7 @@ const DEFINED_COLORS = { const colors = {} Object.entries(DEFINED_COLORS).forEach(([colorKey, colorPrefix]) => { - colors[colorKey] = msg => - `${colorify(colorPrefix)}${msg}${colorify(RESET_COLOR)}` + colors[colorKey] = msg => `${colorify(colorPrefix)}${msg}${colorify(RESET_COLOR)}` }) module.exports = colors diff --git a/packages/sui-helpers/packages.js b/packages/sui-helpers/packages.js index 7a2f3cd3f..ad8c8d1df 100644 --- a/packages/sui-helpers/packages.js +++ b/packages/sui-helpers/packages.js @@ -53,16 +53,10 @@ const resolveLazyNPMBin = async (binPath, pkg, cwd = process.cwd()) => { try { return resolvePkgBin() } catch (e) { - console.info( - `It looks like the lazy installed dep '${pkg}' is missing. It will be installed now.` - ) - return getSpawnPromise( - 'npm', - ['install', `${pkg}`, '--no-save', '--no-fund', '--no-audit'], - { - cwd - } - ).then(resolvePkgBin) + console.info(`It looks like the lazy installed dep '${pkg}' is missing. It will be installed now.`) + return getSpawnPromise('npm', ['install', `${pkg}`, '--no-save', '--no-fund', '--no-audit'], { + cwd + }).then(resolvePkgBin) } } diff --git a/packages/sui-helpers/test/server/cliSpec.js b/packages/sui-helpers/test/server/cliSpec.js index e96ce27f3..d44feb71e 100644 --- a/packages/sui-helpers/test/server/cliSpec.js +++ b/packages/sui-helpers/test/server/cliSpec.js @@ -1,13 +1,7 @@ import {expect} from 'chai' import sinon from 'sinon' -import { - getSpawnPromise, - parallelSpawn, - serialSpawn, - showError, - showWarning -} from '../../cli.js' +import {getSpawnPromise, parallelSpawn, serialSpawn, showError, showWarning} from '../../cli.js' describe('[sui-helpers] cli.js utils', () => { describe('getSpawnPromise', () => { @@ -49,12 +43,8 @@ describe('[sui-helpers] cli.js utils', () => { ['echo', ['secondCall']] ]).then(() => { const calls = console.log.getCalls() - const firstEcho = calls.findIndex(call => - call.firstArg.includes('firstCall') - ) - const secondEcho = calls.findIndex(call => - call.firstArg.includes('secondCall') - ) + const firstEcho = calls.findIndex(call => call.firstArg.includes('firstCall')) + const secondEcho = calls.findIndex(call => call.firstArg.includes('secondCall')) expect(firstEcho < secondEcho).to.be.true done() }) diff --git a/packages/sui-helpers/test/server/packagesSpec.js b/packages/sui-helpers/test/server/packagesSpec.js index 0d54f442a..742bc145c 100644 --- a/packages/sui-helpers/test/server/packagesSpec.js +++ b/packages/sui-helpers/test/server/packagesSpec.js @@ -3,11 +3,7 @@ import path from 'path' import {expect} from 'chai' -import { - getPackageJson, - getPackagesPaths, - resolveLazyNPMBin -} from '../../packages.js' +import {getPackageJson, getPackagesPaths, resolveLazyNPMBin} from '../../packages.js' const PACKAGE_JSON_CONTENT = { name: 'package-name', @@ -53,11 +49,7 @@ describe('[sui-helpers] packages.js utils', () => { describe.skip('resolveLazyNPMBin', () => { it('install a lazy dependency for the binary and return', async function () { this.timeout(30000) // allow npm install to have plenty of time - const bin = await resolveLazyNPMBin( - '.bin/premove', - 'premove@3.0.1', - __dirname - ) + const bin = await resolveLazyNPMBin('.bin/premove', 'premove@3.0.1', __dirname) expect(bin).to.include('premove/bin.js') }) }) diff --git a/packages/sui-hoc/src/withIntersectionObserver.js b/packages/sui-hoc/src/withIntersectionObserver.js index 6092f5ddb..bed7b47e2 100644 --- a/packages/sui-hoc/src/withIntersectionObserver.js +++ b/packages/sui-hoc/src/withIntersectionObserver.js @@ -32,9 +32,7 @@ export const hocIntersectionObserverWithOptions = async componentDidMount() { const target = this.refTarget if (shouldLoadIntersectionObserver()) { - await import( - /* webpackChunkName: "intersection-observer" */ 'intersection-observer' - ) + await import(/* webpackChunkName: "intersection-observer" */ 'intersection-observer') } this.setState( { @@ -52,13 +50,7 @@ export const hocIntersectionObserverWithOptions = render() { const {isIntersecting: isVisible} = this.state - return ( - - ) + return } } } diff --git a/packages/sui-hoc/src/withOpenToggle.js b/packages/sui-hoc/src/withOpenToggle.js index 1d111cc6e..c60afbe6f 100644 --- a/packages/sui-hoc/src/withOpenToggle.js +++ b/packages/sui-hoc/src/withOpenToggle.js @@ -26,9 +26,7 @@ export default BaseComponent => { render() { const {handleToggle, props} = this const {isOpen} = this.state - return ( - - ) + return } } } diff --git a/packages/sui-hoc/src/withStateValueTags.js b/packages/sui-hoc/src/withStateValueTags.js index af7958080..3152111c1 100644 --- a/packages/sui-hoc/src/withStateValueTags.js +++ b/packages/sui-hoc/src/withStateValueTags.js @@ -53,15 +53,7 @@ const withStateValueTags = BaseComponent => { const {value} = this.props const {onChangeTags, onChange, props} = this - return ( - - ) + return } } diff --git a/packages/sui-hoc/src/withSwitchValue.js b/packages/sui-hoc/src/withSwitchValue.js index dade1d7a2..400ec2a82 100644 --- a/packages/sui-hoc/src/withSwitchValue.js +++ b/packages/sui-hoc/src/withSwitchValue.js @@ -5,11 +5,7 @@ import PropTypes from 'prop-types' const withSwitchValue = BaseComponent => { const displayName = BaseComponent.displayName - const BaseComponentWithState = ({ - value: valueFromProps = false, - onChange: onChangeFromProps, - ...props - }) => { + const BaseComponentWithState = ({value: valueFromProps = false, onChange: onChangeFromProps, ...props}) => { const [value, setValue] = useState(Boolean(valueFromProps)) const onChange = ev => { diff --git a/packages/sui-html-tagger/src/index.js b/packages/sui-html-tagger/src/index.js index 300fa1525..922ca20bc 100644 --- a/packages/sui-html-tagger/src/index.js +++ b/packages/sui-html-tagger/src/index.js @@ -19,9 +19,7 @@ function onIdle(cb) { timerId = window.requestIdleCallback(function (idleDeadline) { // reschedule if there's less than 1ms remaining on the tick // and a timer did not expire - return idleDeadline.timeRemaining() <= 1 && !idleDeadline.didTimeout - ? onIdle(cb) - : cb(idleDeadline) + return idleDeadline.timeRemaining() <= 1 && !idleDeadline.didTimeout ? onIdle(cb) : cb(idleDeadline) }) return window.cancelIdleCallback.bind(window, timerId) } else if (hasRAF) { @@ -33,11 +31,7 @@ function onIdle(cb) { } export function tagHTML({tags}) { - const fireTagging = debounce( - () => onIdle(searchTagsToTrackOnDocument), - 500, - true - ) + const fireTagging = debounce(() => onIdle(searchTagsToTrackOnDocument), 500, true) // check if the DOMContentLoaded has been already fired if (/comp|inter|loaded/.test(document.readyState)) { @@ -102,9 +96,7 @@ export function tagHTML({tags}) { function searchTagsToTrackOnDocument() { for (const key in tags) { - const arrayDOMElements = Array.prototype.slice.call( - document.querySelectorAll(key) - ) + const arrayDOMElements = Array.prototype.slice.call(document.querySelectorAll(key)) for (let i = 0; i < arrayDOMElements.length; i++) { addTrackingTagsToElement(arrayDOMElements[i], tags[key]) } diff --git a/packages/sui-html-tagger/test/indexSpec.js b/packages/sui-html-tagger/test/indexSpec.js index a44a02555..77de437de 100644 --- a/packages/sui-html-tagger/test/indexSpec.js +++ b/packages/sui-html-tagger/test/indexSpec.js @@ -39,18 +39,14 @@ describe('Tagger', () => { it('should tag correctly a div specified in the tags list', done => { setTimeout(() => { - expect( - document.querySelector('.simple-div').getAttribute('data-tracking-tag') - ).to.equal('c_tracking_tag') + expect(document.querySelector('.simple-div').getAttribute('data-tracking-tag')).to.equal('c_tracking_tag') done() }, 200) }) it('should tag correctly elements specified in the tags list', done => { setTimeout(() => { - expect( - document.querySelector('.button').getAttribute('data-tracking-tag') - ).to.equal('c_tracking_button') + expect(document.querySelector('.button').getAttribute('data-tracking-tag')).to.equal('c_tracking_button') done() }, 200) }) @@ -58,14 +54,10 @@ describe('Tagger', () => { it('should tag correctly elements added later in the dom', done => { const dynamicHTML = `
Dynamic content FTW!
` - document - .getElementById('fixture') - .insertAdjacentHTML('afterbegin', dynamicHTML) + document.getElementById('fixture').insertAdjacentHTML('afterbegin', dynamicHTML) setTimeout(() => { - expect( - document.querySelector('.added-later').getAttribute('data-tracking-tag') - ).to.equal('c_tracking_dynamic') + expect(document.querySelector('.added-later').getAttribute('data-tracking-tag')).to.equal('c_tracking_dynamic') done() }, 1000) }) diff --git a/packages/sui-i18n/src/adapters/polyglot.js b/packages/sui-i18n/src/adapters/polyglot.js index bed2ee50f..151e97a10 100644 --- a/packages/sui-i18n/src/adapters/polyglot.js +++ b/packages/sui-i18n/src/adapters/polyglot.js @@ -61,21 +61,7 @@ const pluralTypes = { // Mapping from pluralization group to individual locales. const pluralTypeToLanguages = { chinese: ['fa', 'id', 'ja', 'ko', 'lo', 'ms', 'th', 'tr', 'zh'], - german: [ - 'da', - 'de', - 'en', - 'es', - 'fi', - 'el', - 'he', - 'hu', - 'it', - 'nl', - 'no', - 'pt', - 'sv' - ], + german: ['da', 'de', 'en', 'es', 'fi', 'el', 'he', 'hu', 'it', 'nl', 'no', 'pt', 'sv'], french: ['fr', 'tl', 'pt-br'], russian: ['hr', 'ru'], czech: ['cs'], @@ -153,11 +139,7 @@ class Polyglot { } if (typeof phrase === 'string') { options = clone(options) - result = this.choosePluralForm( - phrase, - this.currentLocale, - options.smart_count - ) + result = this.choosePluralForm(phrase, this.currentLocale, options.smart_count) result = this.interpolate(result, options) } return result @@ -207,10 +189,7 @@ class Polyglot { interpolate(phrase, options) { for (const arg in options) { if (arg !== '_' && options.hasOwnProperty(arg)) { - phrase = phrase.replace( - new RegExp('%\\{' + arg + '\\}', 'g'), - options[arg] - ) + phrase = phrase.replace(new RegExp('%\\{' + arg + '\\}', 'g'), options[arg]) } } return phrase diff --git a/packages/sui-i18n/src/console.js b/packages/sui-i18n/src/console.js index 4f65d3b63..d2ba19dbf 100644 --- a/packages/sui-i18n/src/console.js +++ b/packages/sui-i18n/src/console.js @@ -1,8 +1,4 @@ /* eslint no-console:0 */ export function warn(msg, ...args) { - return ( - console && - console.warn && - console.warn.apply(console, ['WARN LOG:', msg].concat(args)) - ) + return console && console.warn && console.warn.apply(console, ['WARN LOG:', msg].concat(args)) } diff --git a/packages/sui-i18n/src/i18n.js b/packages/sui-i18n/src/i18n.js index a81657c25..75ef9f641 100644 --- a/packages/sui-i18n/src/i18n.js +++ b/packages/sui-i18n/src/i18n.js @@ -108,9 +108,7 @@ export default class Rosetta { return Object.fromEntries( Object.keys(this._languages).map(language => [ language, - key - .split('.') - .reduce((level, newKey) => level[newKey], this._languages[language]) + key.split('.').reduce((level, newKey) => level[newKey], this._languages[language]) ]) ) } @@ -156,10 +154,8 @@ export default class Rosetta { * @param {Object} options Specific options for the specified type */ f(type, value, options = {}) { - if (typeof type !== 'string') - throw new Error('i18n.f should receive a string as a first argument') - if (typeof value === 'undefined') - throw new Error('i18n.f should receive any value as a second argument') + if (typeof type !== 'string') throw new Error('i18n.f should receive a string as a first argument') + if (typeof value === 'undefined') throw new Error('i18n.f should receive any value as a second argument') switch (type) { case 'percentage': { @@ -200,8 +196,7 @@ export default class Rosetta { // Interpolate each text chunk, returning an array of all the transformed chunks. interpolate(key, values = {}) { // Redeclare the RegExp on each call to make it stateless - const interpolateRegExp = - /%\[(?[\S\s]*?)\b\](?[\S\s]*?)\[\1\]%/gi + const interpolateRegExp = /%\[(?[\S\s]*?)\b\](?[\S\s]*?)\[\1\]%/gi // Perform basic replace for static values const str = this.t(key, values) @@ -223,8 +218,7 @@ export default class Rosetta { const option = values[key] // Check if there is an available replacement for each match - const replacement = - typeof option === 'function' ? option({children}) : option + const replacement = typeof option === 'function' ? option({children}) : option // Split the remaining string piece by the first occurence and keep the edges const [beforeMatch, ...afterMatch] = remaining.split(occurrence) diff --git a/packages/sui-i18n/test/i18nSpec.js b/packages/sui-i18n/test/i18nSpec.js index cab34e50c..8c96bce99 100644 --- a/packages/sui-i18n/test/i18nSpec.js +++ b/packages/sui-i18n/test/i18nSpec.js @@ -80,9 +80,7 @@ describe('I18N', () => { }) it('generate url properly', () => { - expect(i18n.url('/profilePathSegment/privacyPathSegment')).to.eql( - '/my-profile/privacy' - ) + expect(i18n.url('/profilePathSegment/privacyPathSegment')).to.eql('/my-profile/privacy') }) describe('with pound sterling (GBP) as currency type', () => { @@ -224,9 +222,7 @@ describe('I18N', () => { }) it('with custom separator', () => { - expect(i18n.f('phone', '123123123', {separator: '-'})).to.eql( - '123-123-123' - ) + expect(i18n.f('phone', '123123123', {separator: '-'})).to.eql('123-123-123') }) it('from agglomerated digits, using the formatPhone method', () => { @@ -238,9 +234,7 @@ describe('I18N', () => { }) it('with custom separator, using the formatPhone method', () => { - expect(i18n.formatPhone('123123123', {separator: '-'})).to.eql( - '123-123-123' - ) + expect(i18n.formatPhone('123123123', {separator: '-'})).to.eql('123-123-123') }) }) }) @@ -259,9 +253,7 @@ describe('I18N', () => { }) it('returns object with translations of "literalOne" properly', () => { - expect(i18n.getAllTranslations('SCOPE.LITERAL_ONE')).to.eql( - ALL_TRANSLATIONS - ) + expect(i18n.getAllTranslations('SCOPE.LITERAL_ONE')).to.eql(ALL_TRANSLATIONS) }) }) }) diff --git a/packages/sui-i18n/test/polyglotSpec.js b/packages/sui-i18n/test/polyglotSpec.js index b7d671a06..289249b6a 100644 --- a/packages/sui-i18n/test/polyglotSpec.js +++ b/packages/sui-i18n/test/polyglotSpec.js @@ -13,12 +13,9 @@ const phrases = { hello: 'Hello', hi_name_welcome_to_place: 'Hi, %{name}, welcome to %{place}!', name_your_name_is_name: '%{name}, your name is %{name}!', - name_your_name_is_bold_name_bold: - '%{name}, your name is %[bold]%{name}[bold]%!', - multiple_name_your_name_is_bold_name_bold: - '%[bold]%{name}[bold]%, your name is %[bold]%{name}[bold]%!', - nested_placeholders: - 'Hello, this is an %[bold]important %[link]resource[link]%[bold]% for this page!', + name_your_name_is_bold_name_bold: '%{name}, your name is %[bold]%{name}[bold]%!', + multiple_name_your_name_is_bold_name_bold: '%[bold]%{name}[bold]%, your name is %[bold]%{name}[bold]%!', + nested_placeholders: 'Hello, this is an %[bold]important %[link]resource[link]%[bold]% for this page!', empty_string: '' } } @@ -65,22 +62,18 @@ describe('I18N with polyglot adapter', () => { i18n.culture = 'en-GB' }) - it('should translate a simple string', () => - expect(i18n.t('hello')).to.eql('Hello')) + it('should translate a simple string', () => expect(i18n.t('hello')).to.eql('Hello')) - it('should return the key if translation not found', () => - expect(i18n.t('bogus_key')).to.eql('bogus_key')) + it('should return the key if translation not found', () => expect(i18n.t('bogus_key')).to.eql('bogus_key')) it('should interpolate', () => { - expect( - i18n.t('hi_name_welcome_to_place', {name: 'Spike', place: 'the webz'}) - ).to.eql('Hi, Spike, welcome to the webz!') + expect(i18n.t('hi_name_welcome_to_place', {name: 'Spike', place: 'the webz'})).to.eql( + 'Hi, Spike, welcome to the webz!' + ) }) it('should interpolate the same placeholder multiple times', () => { - expect(i18n.t('name_your_name_is_name', {name: 'Spike'})).to.eql( - 'Spike, your name is Spike!' - ) + expect(i18n.t('name_your_name_is_name', {name: 'Spike'})).to.eql('Spike, your name is Spike!') }) it('should allow you to supply default values', () => { @@ -93,9 +86,7 @@ describe('I18N with polyglot adapter', () => { }) it('should return the non-interpolated key if not initialized with allowMissing and translation not found', () => { - expect(i18n.t('Welcome %{name}', {name: 'Robert'})).to.eql( - 'Welcome %{name}' - ) + expect(i18n.t('Welcome %{name}', {name: 'Robert'})).to.eql('Welcome %{name}') }) describe('setting allowMissing', () => { @@ -106,9 +97,7 @@ describe('I18N with polyglot adapter', () => { i18n.adapter.instance.allowMissing = false }) it('should return an interpolated key if initialized with allowMissing and translation not found', () => { - expect(i18n.t('Welcome %{name}', {name: 'Robert'})).to.eql( - 'Welcome Robert' - ) + expect(i18n.t('Welcome %{name}', {name: 'Robert'})).to.eql('Welcome Robert') }) }) @@ -195,8 +184,7 @@ describe('I18N with polyglot adapter', () => { i18n.culture = 'en-GB' }) - it('should translate a simple string into an array', () => - expect(i18n.interpolate('hello')).to.eql(['Hello'])) + it('should translate a simple string into an array', () => expect(i18n.interpolate('hello')).to.eql(['Hello'])) it('should return the key into an array if translation not found', () => expect(i18n.interpolate('bogus_key')).to.eql(['bogus_key'])) @@ -220,9 +208,7 @@ describe('I18N with polyglot adapter', () => { }) it('should interpolate the same placeholder multiple times', () => { - expect( - i18n.interpolate('name_your_name_is_name', {name: 'Spike'}) - ).to.eql(['Spike, your name is Spike!']) + expect(i18n.interpolate('name_your_name_is_name', {name: 'Spike'})).to.eql(['Spike, your name is Spike!']) expect( i18n.interpolate('multiple_name_your_name_is_bold_name_bold', { name: 'Spike', @@ -237,11 +223,7 @@ describe('I18N with polyglot adapter', () => { bold: ({children}) => ({content: children}), link: ({children}) => ({content: children}) }) - ).to.eql([ - 'Hello, this is an ', - {content: ['important ', {content: 'resource'}]}, - ' for this page!' - ]) + ).to.eql(['Hello, this is an ', {content: ['important ', {content: 'resource'}]}, ' for this page!']) }) it('should allow you to supply default values', () => { @@ -254,9 +236,7 @@ describe('I18N with polyglot adapter', () => { }) it('should return the non-interpolated key into an array if not initialized with allowMissing and translation not found', () => { - expect(i18n.interpolate('Welcome %{name}', {name: 'Robert'})).to.eql([ - 'Welcome %{name}' - ]) + expect(i18n.interpolate('Welcome %{name}', {name: 'Robert'})).to.eql(['Welcome %{name}']) }) }) }) diff --git a/packages/sui-jest/bin/sui-jest.js b/packages/sui-jest/bin/sui-jest.js index b5a45fd54..4351eda2e 100755 --- a/packages/sui-jest/bin/sui-jest.js +++ b/packages/sui-jest/bin/sui-jest.js @@ -7,8 +7,6 @@ process.env.NODE_ENV = 'test' const args = process.argv.slice(2) const config = - !args.includes('--config') && !hasFile('jest.config.js') - ? ['--config', JSON.stringify(require('./config.js'))] - : [] + !args.includes('--config') && !hasFile('jest.config.js') ? ['--config', JSON.stringify(require('./config.js'))] : [] require('jest').run([...config, ...args]) diff --git a/packages/sui-js-compiler/index.js b/packages/sui-js-compiler/index.js index d81b6f13d..c28fc438b 100755 --- a/packages/sui-js-compiler/index.js +++ b/packages/sui-js-compiler/index.js @@ -66,9 +66,7 @@ const getTsConfig = () => { const compileFile = async (file, options) => { const {code} = await transformFile(file, getSWCConfig(options)) - const outputPath = file - .replace(SOURCE_DIR, OUTPUT_DIR) - .replace(TS_EXTENSION_REGEX, COMPILED_EXTENSION) + const outputPath = file.replace(SOURCE_DIR, OUTPUT_DIR).replace(TS_EXTENSION_REGEX, COMPILED_EXTENSION) await fs.outputFile(outputPath, code) } @@ -93,11 +91,7 @@ const compileTypes = async (files, options) => { const commaSeparatedList = value => value.split(',') program - .option( - '--ignore [glob]', - 'List of patterns to ignore during the compilation', - commaSeparatedList - ) + .option('--ignore [glob]', 'List of patterns to ignore during the compilation', commaSeparatedList) .option('--modern', 'Transpile using modern browser targets') .on('--help', () => { console.log(' Examples:') diff --git a/packages/sui-js-compiler/swc-config.js b/packages/sui-js-compiler/swc-config.js index 4bd20e808..ff493c407 100644 --- a/packages/sui-js-compiler/swc-config.js +++ b/packages/sui-js-compiler/swc-config.js @@ -11,12 +11,8 @@ const DEFAULT_BROWSER_TARGETS = { } export const getSWCConfig = ({isModern, isTypeScript}) => { - const targets = isModern - ? DEFAULT_BROWSER_TARGETS - : DEFAULT_LEGACY_BROWSER_TARGETS - const syntaxOptions = isTypeScript - ? {syntax: 'typescript', tsx: true} - : {syntax: 'ecmascript', jsx: true} + const targets = isModern ? DEFAULT_BROWSER_TARGETS : DEFAULT_LEGACY_BROWSER_TARGETS + const syntaxOptions = isTypeScript ? {syntax: 'typescript', tsx: true} : {syntax: 'ecmascript', jsx: true} return { minify: true, diff --git a/packages/sui-js-compiler/test/server/jsCompilerSpec.js b/packages/sui-js-compiler/test/server/jsCompilerSpec.js index bca71bfae..1e5eac42a 100644 --- a/packages/sui-js-compiler/test/server/jsCompilerSpec.js +++ b/packages/sui-js-compiler/test/server/jsCompilerSpec.js @@ -48,12 +48,9 @@ describe('@s-ui/js-compiler', () => { }).timeout(DEFAULT_TIMEOUT) it('should exclude all the files matching the passed patterns when the "ignore" option exists', async () => { - const {stdout} = await exec( - 'node ../../index.js --ignore="./src/**.test.js"', - { - cwd - } - ) + const {stdout} = await exec('node ../../index.js --ignore="./src/**.test.js"', { + cwd + }) const compiledFilenames = await fs.readdir(libPath) @@ -92,10 +89,6 @@ describe('@s-ui/js-compiler', () => { // THEN package files and types are properly compiled expect(stdout).to.contain('[sui-js-compiler]') - expect(compiledFilenames).to.eql([ - 'example.d.ts', - 'example.js', - 'example.test.js' - ]) + expect(compiledFilenames).to.eql(['example.d.ts', 'example.js', 'example.test.js']) }).timeout(DEFAULT_TIMEOUT) }) diff --git a/packages/sui-js/src/dom/index.js b/packages/sui-js/src/dom/index.js index f66fcfd07..315fbb051 100644 --- a/packages/sui-js/src/dom/index.js +++ b/packages/sui-js/src/dom/index.js @@ -2,8 +2,6 @@ export const getCurrentElementFocused = () => document.activeElement export const getFocusedItemIndex = items => { const currentElementFocused = getCurrentElementFocused() - const index = Array.from(items).findIndex( - item => item === currentElementFocused - ) + const index = Array.from(items).findIndex(item => item === currentElementFocused) return index === -1 ? null : index } diff --git a/packages/sui-js/src/react/index.js b/packages/sui-js/src/react/index.js index e363b028a..50a89b1f8 100644 --- a/packages/sui-js/src/react/index.js +++ b/packages/sui-js/src/react/index.js @@ -13,9 +13,7 @@ const findDOMElements = target => { let selection = document.querySelectorAll(target) if (!selection.length) selection = document.querySelectorAll(`#${target}`) if (!selection.length) { - throw new Error( - `The target '${target}' could not be identified in the dom, tip: check spelling` - ) + throw new Error(`The target '${target}' could not be identified in the dom, tip: check spelling`) } return selection } diff --git a/packages/sui-js/src/string/highlighter.js b/packages/sui-js/src/string/highlighter.js index 951818fb6..0fc02cd35 100644 --- a/packages/sui-js/src/string/highlighter.js +++ b/packages/sui-js/src/string/highlighter.js @@ -12,10 +12,7 @@ export const highlightText = ({value, query, startTag, endTag}) => { const highlighterReducer = (valueHighlightedAccumulator, match, i) => { const start = match.start + i * tagsLength const end = match.end + i * tagsLength - return `${valueHighlightedAccumulator.slice( - 0, - start - )}${startTag}${valueHighlightedAccumulator.slice( + return `${valueHighlightedAccumulator.slice(0, start)}${startTag}${valueHighlightedAccumulator.slice( start, end )}${endTag}${value.slice(match.end)}` diff --git a/packages/sui-js/src/string/index.js b/packages/sui-js/src/string/index.js index a5e2374c3..106f50d92 100644 --- a/packages/sui-js/src/string/index.js +++ b/packages/sui-js/src/string/index.js @@ -10,8 +10,7 @@ export {default as toQueryString} from './to-query-string.js' * use toQueryString(queryParams, {arrayFormat: 'comma'}) instead * it may not be very convenient to decode with decodeURIComponent knowing that it will be used in the url */ -export const fromArrayToCommaQueryString = query => - decodeURIComponent(toQueryString(query, {arrayFormat: 'comma'})) +export const fromArrayToCommaQueryString = query => decodeURIComponent(toQueryString(query, {arrayFormat: 'comma'})) export {fromSnakeToCamelCase, fromCamelToSnakeCase} from './snake-case.js' export {has as hasAccents, remove as removeAccents} from 'remove-accents' diff --git a/packages/sui-js/src/string/snake-case.js b/packages/sui-js/src/string/snake-case.js index 20ecd8dc2..12e47c11f 100644 --- a/packages/sui-js/src/string/snake-case.js +++ b/packages/sui-js/src/string/snake-case.js @@ -1,4 +1,2 @@ -export const fromSnakeToCamelCase = string => - string.replace(/(_\w)/g, m => m[1].toUpperCase()) -export const fromCamelToSnakeCase = string => - string.replace(/([A-Z])/g, s => '_' + s.toLowerCase()) +export const fromSnakeToCamelCase = string => string.replace(/(_\w)/g, m => m[1].toUpperCase()) +export const fromCamelToSnakeCase = string => string.replace(/([A-Z])/g, s => '_' + s.toLowerCase()) diff --git a/packages/sui-js/test/classesSpec.js b/packages/sui-js/test/classesSpec.js index f7097480d..66b070bef 100644 --- a/packages/sui-js/test/classesSpec.js +++ b/packages/sui-js/test/classesSpec.js @@ -8,16 +8,14 @@ describe('@s-ui/js', () => { it('should create a valid class name with children following convention', () => { const baseComponent = suitClass('baseComponent') const childrenComponent = baseComponent({children: 'childrenComponent'}) - expect( - childrenComponent({element: 'element', modifier: 'modifier'}) - ).to.be.equal('baseComponent-childrenComponent-element--modifier') + expect(childrenComponent({element: 'element', modifier: 'modifier'})).to.be.equal( + 'baseComponent-childrenComponent-element--modifier' + ) }) it('should create a valid class name without children following convention', () => { const baseComponent = suitClass('baseComponent')() - expect( - baseComponent({element: 'element', modifier: 'modifier'}) - ).to.be.equal('baseComponent-element--modifier') + expect(baseComponent({element: 'element', modifier: 'modifier'})).to.be.equal('baseComponent-element--modifier') }) it('should create a valid class name without children nor element following convention', () => { @@ -27,9 +25,7 @@ describe('@s-ui/js', () => { it('should create a valid class name with element', () => { const baseComponent = suitClass('baseComponent')() - expect(baseComponent({element: 'element'})).to.be.equal( - 'baseComponent-element' - ) + expect(baseComponent({element: 'element'})).to.be.equal('baseComponent-element') }) }) }) diff --git a/packages/sui-js/test/domSpec.js b/packages/sui-js/test/domSpec.js index 9ef79dbdc..a4d5a168d 100644 --- a/packages/sui-js/test/domSpec.js +++ b/packages/sui-js/test/domSpec.js @@ -1,10 +1,7 @@ /* eslint-env mocha */ import {expect} from 'chai' -import { - getCurrentElementFocused, - getFocusedItemIndex -} from '../src/dom/index.js' +import {getCurrentElementFocused, getFocusedItemIndex} from '../src/dom/index.js' const ID_FIXTURE_ELEMENT = 'fixture-getCurrentElementFocused' const ID_FIXTURE_LIST = 'fixture-getFocusedItemIndex' diff --git a/packages/sui-js/test/pipeSpec.js b/packages/sui-js/test/pipeSpec.js index f376e766a..3d988c65f 100644 --- a/packages/sui-js/test/pipeSpec.js +++ b/packages/sui-js/test/pipeSpec.js @@ -20,22 +20,10 @@ describe('@s-ui/js', () => { expect(pipe(textToUpperCase, textToArray)(title)).to.be.an('array') }) xit('should be the same length as the title ', () => { - expect(pipe(textToUpperCase, textToArray)(title)).to.have.lengthOf( - title.length - ) + expect(pipe(textToUpperCase, textToArray)(title)).to.have.lengthOf(title.length) }) xit('should return the title in camelcase and array form ', () => { - expect(pipe(textToUpperCase, textToArray)(title)).to.deep.equal([ - 'S', - 'C', - 'H', - 'I', - 'B', - 'S', - 'T', - 'E', - 'D' - ]) + expect(pipe(textToUpperCase, textToArray)(title)).to.deep.equal(['S', 'C', 'H', 'I', 'B', 'S', 'T', 'E', 'D']) }) }) }) diff --git a/packages/sui-js/test/stringSpec.js b/packages/sui-js/test/stringSpec.js index 98c39173f..4210ff5f3 100644 --- a/packages/sui-js/test/stringSpec.js +++ b/packages/sui-js/test/stringSpec.js @@ -92,9 +92,7 @@ describe('@s-ui/js', () => { endTag: '' }) expect(highlightedText).to.be.an('string') - expect(highlightedText).to.be.equal( - `laca` - ) + expect(highlightedText).to.be.equal(`laca`) }) }) }) diff --git a/packages/sui-lint/bin/sui-lint-js.js b/packages/sui-lint/bin/sui-lint-js.js index d6f657d09..a42604e76 100755 --- a/packages/sui-lint/bin/sui-lint-js.js +++ b/packages/sui-lint/bin/sui-lint-js.js @@ -3,12 +3,7 @@ // @ts-check const program = require('commander') -const { - checkFilesToLint, - getFilesToLint, - getGitIgnoredFiles, - stageFilesIfRequired -} = require('../src/helpers.js') +const {checkFilesToLint, getFilesToLint, getGitIgnoredFiles, stageFilesIfRequired} = require('../src/helpers.js') const {ESLint} = require('eslint') const config = require('../eslintrc.js') diff --git a/packages/sui-lint/bin/sui-lint-sass.js b/packages/sui-lint/bin/sui-lint-sass.js index 4b169a663..6a9a5125f 100755 --- a/packages/sui-lint/bin/sui-lint-sass.js +++ b/packages/sui-lint/bin/sui-lint-sass.js @@ -5,12 +5,7 @@ const program = require('commander') const stylelint = require('stylelint') const config = require('../stylelint.config.js') -const { - checkFilesToLint, - getGitIgnoredFiles, - getFilesToLint, - stageFilesIfRequired -} = require('../src/helpers.js') +const {checkFilesToLint, getGitIgnoredFiles, getFilesToLint, stageFilesIfRequired} = require('../src/helpers.js') const EXTENSIONS = ['scss'] const IGNORE_PATTERNS = ['**/node_modules/**', '**/lib/**', '**/dist/**'] @@ -20,50 +15,44 @@ program .option('--add-fixes') .option('--staged') .option('--fix', 'fix automatically problems with sass files') - .option( - '--pattern ', - 'root path to locate the sass files', - DEFAULT_PATTERN - ) + .option('--pattern ', 'root path to locate the sass files', DEFAULT_PATTERN) .parse(process.argv) const {addFixes, fix, pattern, staged} = program.opts() -getFilesToLint({extensions: EXTENSIONS, defaultPattern: pattern, staged}).then( - files => { - if ( - !checkFilesToLint({ - files, - language: 'SCSS', - defaultPattern: DEFAULT_PATTERN - }) - ) - return - - return stylelint - .lint({ - files, - formatter: 'string', - config: { - ...config, - ignoreFiles: IGNORE_PATTERNS.concat(getGitIgnoredFiles()) - }, - fix - }) - .then(({output, errored}) => { - console.log(output) - - if (fix) { - stageFilesIfRequired({extensions: EXTENSIONS, staged, addFixes}) - } - - if (errored) { - throw new Error('You must fix linting errors before continuing...') - } - }) - .catch(error => { - process.exitCode = 1 - console.error('[sui-lint]', error) - }) - } -) +getFilesToLint({extensions: EXTENSIONS, defaultPattern: pattern, staged}).then(files => { + if ( + !checkFilesToLint({ + files, + language: 'SCSS', + defaultPattern: DEFAULT_PATTERN + }) + ) + return + + return stylelint + .lint({ + files, + formatter: 'string', + config: { + ...config, + ignoreFiles: IGNORE_PATTERNS.concat(getGitIgnoredFiles()) + }, + fix + }) + .then(({output, errored}) => { + console.log(output) + + if (fix) { + stageFilesIfRequired({extensions: EXTENSIONS, staged, addFixes}) + } + + if (errored) { + throw new Error('You must fix linting errors before continuing...') + } + }) + .catch(error => { + process.exitCode = 1 + console.error('[sui-lint]', error) + }) +}) diff --git a/packages/sui-lint/bin/sui-lint.js b/packages/sui-lint/bin/sui-lint.js index 8b89307ae..78c90c0aa 100755 --- a/packages/sui-lint/bin/sui-lint.js +++ b/packages/sui-lint/bin/sui-lint.js @@ -4,8 +4,6 @@ const {version} = require('../package.json') program.version(version, ' --version') -program - .command('js', 'lint javascript files') - .command('sass', 'lint sass files') +program.command('js', 'lint javascript files').command('sass', 'lint sass files') program.parse(process.argv) diff --git a/packages/sui-lint/eslintrc.js b/packages/sui-lint/eslintrc.js index bf62bca3b..c247117c7 100644 --- a/packages/sui-lint/eslintrc.js +++ b/packages/sui-lint/eslintrc.js @@ -37,10 +37,7 @@ const REACT_RULES = { } const TESTING_RULES = { - 'chai-friendly/no-unused-expressions': [ - RULES.ERROR, - {allowShortCircuit: true, allowTernary: true} - ], + 'chai-friendly/no-unused-expressions': [RULES.ERROR, {allowShortCircuit: true, allowTernary: true}], 'no-only-tests/no-only-tests': RULES.ERROR } @@ -125,13 +122,7 @@ const IMPORT_SORT_GROUPS = [ // S-UI & ADV-UI organization packages. ['^@s-ui', '^@adv-ui'], // Relative imports. Put `./` last. - [ - '^\\.\\.(?!/?$)', - '^\\.\\./?$', - '^\\./(?=.*/)(?!/?$)', - '^\\.(?!/?$)', - '^\\./?$' - ], + ['^\\.\\.(?!/?$)', '^\\.\\./?$', '^\\./(?=.*/)(?!/?$)', '^\\.(?!/?$)', '^\\./?$'], // Style imports. ['^.+\\.s?css$'] ] @@ -201,10 +192,7 @@ module.exports = { 'no-prototype-builtins': RULES.OFF, 'no-return-await': RULES.WARNING, 'no-unused-expressions': RULES.OFF, - 'no-unused-vars': [ - RULES.ERROR, - {args: 'none', ignoreRestSiblings: true, varsIgnorePattern: 'React'} - ], + 'no-unused-vars': [RULES.ERROR, {args: 'none', ignoreRestSiblings: true, varsIgnorePattern: 'React'}], 'no-var': RULES.WARNING, strict: RULES.OFF, 'prefer-regex-literals': RULES.WARNING, diff --git a/packages/sui-lint/scripts/add-package-json-fields.js b/packages/sui-lint/scripts/add-package-json-fields.js index 4ed0d732c..0c3463e42 100644 --- a/packages/sui-lint/scripts/add-package-json-fields.js +++ b/packages/sui-lint/scripts/add-package-json-fields.js @@ -34,9 +34,7 @@ try { } // check if actual package has different lint config - const areDifferentLintConfig = - JSON.stringify({eslintConfig, prettier, stylelint}) !== - JSON.stringify(LINT_CONFIGS) + const areDifferentLintConfig = JSON.stringify({eslintConfig, prettier, stylelint}) !== JSON.stringify(LINT_CONFIGS) // if they're different, we're going to rewrite the package.json if (areDifferentLintConfig) { @@ -49,10 +47,9 @@ try { ...LINT_CONFIGS } // write the new package.json with the linter conifg - writeFile( - ACTUAL_PACKAGE_PATH, - JSON.stringify(newPackageJSON, null, 2) - ).then(() => console.log('Added @s-ui/lint config successfully')) + writeFile(ACTUAL_PACKAGE_PATH, JSON.stringify(newPackageJSON, null, 2)).then(() => + console.log('Added @s-ui/lint config successfully') + ) } else { console.log('@s-ui/lint config already in your package.json. Great!') } diff --git a/packages/sui-lint/src/helpers.js b/packages/sui-lint/src/helpers.js index 3d4ccc6ca..ff45460db 100644 --- a/packages/sui-lint/src/helpers.js +++ b/packages/sui-lint/src/helpers.js @@ -13,15 +13,13 @@ const GIT_IGNORE_PATH = `${process.cwd()}/.gitignore` * @param {String} path * @returns {Array} */ -const getFileLinesAsArray = path => - existsSync(path) ? readFileSync(path, 'utf8').split('\n').filter(Boolean) : [] +const getFileLinesAsArray = path => (existsSync(path) ? readFileSync(path, 'utf8').split('\n').filter(Boolean) : []) /** * Get as array .gitignore files and filter lines that are comments * @returns {Array} */ -const getGitIgnoredFiles = () => - getFileLinesAsArray(GIT_IGNORE_PATH).filter(line => !line.startsWith('#')) +const getGitIgnoredFiles = () => getFileLinesAsArray(GIT_IGNORE_PATH).filter(line => !line.startsWith('#')) /** * Get from git status name of staged files @@ -32,17 +30,11 @@ const getGitIgnoredFiles = () => * @returns {Promise} Array of file paths */ const getGitDiffFiles = async ({extensions, range = null, staged = true}) => { - const command = [ - 'git diff --name-only --diff-filter=d', - range && `${range}`, - staged && '--cached' - ] + const command = ['git diff --name-only --diff-filter=d', range && `${range}`, staged && '--cached'] .filter(Boolean) .join(' ') - return exec(command).then(({stdout: summary = ''}) => - getFilesFromDiff({summary, extensions}) - ) + return exec(command).then(({stdout: summary = ''}) => getFilesFromDiff({summary, extensions})) } /** @@ -53,9 +45,7 @@ const getGitDiffFiles = async ({extensions, range = null, staged = true}) => { * @returns {string[]} Array of file paths */ const getFilesFromDiff = ({extensions, summary}) => - summary - .split('\n') - .filter(file => extensions.includes(extname(file).substring(1))) + summary.split('\n').filter(file => extensions.includes(extname(file).substring(1))) /** * Get the commit range depending on the CI used (Travis or GitHub Actions) @@ -84,9 +74,7 @@ const getCommitRange = () => { return commitRange } - console.log( - '[sui-lint] No commit range found using GitHub Event from Actions' - ) + console.log('[sui-lint] No commit range found using GitHub Event from Actions') } return null @@ -104,9 +92,7 @@ const getFilesToLint = async ({extensions, defaultPattern, staged = false}) => { const range = getCommitRange() const getFromDiff = range || staged - return getFromDiff - ? getGitDiffFiles({extensions, range, staged}) - : [defaultPattern] + return getFromDiff ? getGitDiffFiles({extensions, range, staged}) : [defaultPattern] } /** diff --git a/packages/sui-mock/src/index.js b/packages/sui-mock/src/index.js index 8e9483b38..71d386519 100644 --- a/packages/sui-mock/src/index.js +++ b/packages/sui-mock/src/index.js @@ -3,10 +3,7 @@ import {rest} from 'msw' import {getBrowserMocker} from './browser.js' import {getServerMocker} from './server.js' -const isNode = - Object.prototype.toString.call( - typeof process !== 'undefined' ? process : 0 - ) === '[object process]' +const isNode = Object.prototype.toString.call(typeof process !== 'undefined' ? process : 0) === '[object process]' const setupMocker = isNode ? getServerMocker : getBrowserMocker diff --git a/packages/sui-mockmock/src/http/clientMocker.js b/packages/sui-mockmock/src/http/clientMocker.js index 80d18527d..bfd64c691 100644 --- a/packages/sui-mockmock/src/http/clientMocker.js +++ b/packages/sui-mockmock/src/http/clientMocker.js @@ -28,11 +28,11 @@ class ClientMocker extends Mocker { } class ClientMock extends Mock { - _responseResolver = ( - response, + _responseResolver = (response, statusCode, headers = {'Content-Type': 'application/json'}) => [ statusCode, - headers = {'Content-Type': 'application/json'} - ) => [statusCode, headers, JSON.stringify(response)] + headers, + JSON.stringify(response) + ] constructor(server, baseUrl) { super() diff --git a/packages/sui-mockmock/src/http/index.js b/packages/sui-mockmock/src/http/index.js index 0c6a0ebf5..536161390 100644 --- a/packages/sui-mockmock/src/http/index.js +++ b/packages/sui-mockmock/src/http/index.js @@ -1,9 +1,6 @@ import ClientMocker from './clientMocker' import ServerMocker from './serverMocker' -const isNode = - Object.prototype.toString.call( - typeof process !== 'undefined' ? process : 0 - ) === '[object process]' +const isNode = Object.prototype.toString.call(typeof process !== 'undefined' ? process : 0) === '[object process]' export default isNode ? ServerMocker : ClientMocker diff --git a/packages/sui-mono/README.md b/packages/sui-mono/README.md index 18de6b785..6473afa81 100644 --- a/packages/sui-mono/README.md +++ b/packages/sui-mono/README.md @@ -35,8 +35,8 @@ We use: - [`workspaces`](#workspaces) - [`overrides`](#overrides) - [Examples](#examples) - - [Project Example](#project-example) - - [Case `sui-studio`](#case-sui-studio) + - [Project Example](#project-example) + - [Case `sui-studio`](#case-sui-studio) - [Manual scopes](#manual-scopes) - [Migration from v1](#migration-from-v1) - [`packagesFolder` and `deepLevel` are not longer used](#packagesfolder-and-deeplevel-are-not-longer-used) diff --git a/packages/sui-mono/bin/sui-mono-changelog.js b/packages/sui-mono/bin/sui-mono-changelog.js index fd41e3365..c4677e3c7 100644 --- a/packages/sui-mono/bin/sui-mono-changelog.js +++ b/packages/sui-mono/bin/sui-mono-changelog.js @@ -3,11 +3,7 @@ const program = require('commander') const fs = require('fs') const path = require('path') const conventionalChangelog = require('conventional-changelog') -const { - checkIsMonoPackage, - getWorkspaces, - getChangelogFilename -} = require('../src/config.js') +const {checkIsMonoPackage, getWorkspaces, getChangelogFilename} = require('../src/config.js') program .usage(' ') @@ -15,9 +11,7 @@ program console.log(' Description:') console.log('') console.log(' Generates a CHANGELOG.md of the given folders.') - console.log( - ' If no folder is specified, CHANGELOG.md will be generated for all packages.' - ) + console.log(' If no folder is specified, CHANGELOG.md will be generated for all packages.') console.log('') console.log(' Examples:') console.log('') diff --git a/packages/sui-mono/bin/sui-mono-check.js b/packages/sui-mono/bin/sui-mono-check.js index d06b7e760..106d09a29 100644 --- a/packages/sui-mono/bin/sui-mono-check.js +++ b/packages/sui-mono/bin/sui-mono-check.js @@ -9,9 +9,7 @@ program console.log('') console.log(' Reports if any package should be released based on ComVer') console.log('') - console.log( - ' It will create a MAJOR only if there are BREAKING CHANGES in the commit description' - ) + console.log(' It will create a MAJOR only if there are BREAKING CHANGES in the commit description') console.log(' The types fix, perf and feat will generate a MINOR') console.log(' All other commit types will not generate a version change') console.log('') @@ -36,9 +34,7 @@ const showReportHeaderPositive = () => { } const showReportHeaderNegative = () => { - console.log( - colors.yellow('Nothing to release according to your recent commits.') - ) + console.log(colors.yellow('Nothing to release according to your recent commits.')) } const showReport = status => { @@ -55,9 +51,7 @@ const showReport = status => { console.log(` ${pkgName} ─ new ${versionString} version: `) status[pkg].commits.forEach(commit => { - const messagePrefix = checker.isCommitBreakingChange(commit) - ? `› ${colors.red('BREAKING CHANGE')} -` - : '›' + const messagePrefix = checker.isCommitBreakingChange(commit) ? `› ${colors.red('BREAKING CHANGE')} -` : '›' console.log(` ${messagePrefix} ${commit.header}`) }) console.log('') diff --git a/packages/sui-mono/bin/sui-mono-commit-all.js b/packages/sui-mono/bin/sui-mono-commit-all.js index 84961c290..8dbd118fc 100644 --- a/packages/sui-mono/bin/sui-mono-commit-all.js +++ b/packages/sui-mono/bin/sui-mono-commit-all.js @@ -19,9 +19,7 @@ program console.log('') console.log(' Examples:') console.log('') - console.log( - ' $ sui-mono commit-all --type=fix -m "bump dependency to major version"' - ) + console.log(' $ sui-mono commit-all --type=fix -m "bump dependency to major version"') console.log(' $ sui-mono --help') console.log(' $ sui-mono -h') console.log('') @@ -76,10 +74,5 @@ const checkStageFuncs = getWorkspaces().map(pkg => { }) getSpawnPromise('git', ['reset']) // Unstage all prossible staged files - .then(() => - checkStageFuncs.reduce( - (promise, func) => promise.then(func), - Promise.resolve() - ) - ) + .then(() => checkStageFuncs.reduce((promise, func) => promise.then(func), Promise.resolve())) .catch(showError) diff --git a/packages/sui-mono/bin/sui-mono-phoenix.js b/packages/sui-mono/bin/sui-mono-phoenix.js index bed5ccd52..14f56ccaf 100644 --- a/packages/sui-mono/bin/sui-mono-phoenix.js +++ b/packages/sui-mono/bin/sui-mono-phoenix.js @@ -22,19 +22,10 @@ program '--ci', 'Optimized mode for CI. Avoid removing folders, showing progress, auditing, write package-lock files and more' ) - .option( - '--strict-peer-deps', - 'Install peer dependencies using the modern strict peer dependency install' - ) + .option('--strict-peer-deps', 'Install peer dependencies using the modern strict peer dependency install') .option('--no-audit', 'Avoid auditing packages for better performance') - .option( - '--no-root', - 'Avoid executing the script on root folder in case you already did it' - ) - .option( - '--no-progress', - 'Force to not show progress of tasks (perfect for CI environments)' - ) + .option('--no-root', 'Avoid executing the script on root folder in case you already did it') + .option('--no-progress', 'Force to not show progress of tasks (perfect for CI environments)') .option('--production', 'Install only production packages') .on('--help', () => { console.log(` @@ -89,11 +80,7 @@ const removeDependencies = cmd => { const createInstallPackagesCommand = (cwd = process.cwd()) => { const executionParams = {cwd} if (ci) { - const commandArgs = [ - 'install', - ...CI_FLAGS, - production ? '--production' : '' - ] + const commandArgs = ['install', ...CI_FLAGS, production ? '--production' : ''] return [NPM_BIN, commandArgs, executionParams] } @@ -108,8 +95,7 @@ const installPackages = async () => { if (!root) return Promise.resolve() console.log(`[sui-mono] Installing packages...`) - const [installBin, installArgs, installExecutionParams] = - createInstallPackagesCommand() + const [installBin, installArgs, installExecutionParams] = createInstallPackagesCommand() await getSpawnPromise(installBin, installArgs, installExecutionParams) console.log('[sui-mono] Installed packages') @@ -125,9 +111,7 @@ const removeDependenciesForPackages = () => { console.log(`[sui-mono] Removing previous packages...`) // if we're on CI, we don't need to remove folders - const removeFoldersPromise = ci - ? Promise.resolve() - : Promise.all(getWorkspaces().map(removeDependencies)) + const removeFoldersPromise = ci ? Promise.resolve() : Promise.all(getWorkspaces().map(removeDependencies)) return removeFoldersPromise } diff --git a/packages/sui-mono/bin/sui-mono-release.js b/packages/sui-mono/bin/sui-mono-release.js index a499574c6..05011b657 100644 --- a/packages/sui-mono/bin/sui-mono-release.js +++ b/packages/sui-mono/bin/sui-mono-release.js @@ -7,11 +7,7 @@ const {showError} = require('@s-ui/helpers/cli') const {getPackageJson} = require('@s-ui/helpers/packages') const exec = promisify(require('child_process').exec) const gitUrlParse = require('git-url-parse') -const { - checkIsMonoPackage, - getChangelogFilename, - getPublishAccess -} = require('../src/config.js') +const {checkIsMonoPackage, getChangelogFilename, getPublishAccess} = require('../src/config.js') const checker = require('../src/check.js') program @@ -26,9 +22,7 @@ program console.log('') console.log(' Release your packages based on the version check output') console.log('') - console.log( - " It's adviced that you inspect the output on sui-mono check before releasing" - ) + console.log(" It's adviced that you inspect the output on sui-mono check before releasing") console.log(' Release is the process of:') console.log(' - Build your project (executing prepare npm script)') console.log(' - Updating package.json version') @@ -45,14 +39,7 @@ program }) .parse(process.argv) -const { - scope: packageScope, - githubEmail, - githubToken, - githubUser, - lock, - skipCi -} = program.opts() +const {scope: packageScope, githubEmail, githubToken, githubUser, lock, skipCi} = program.opts() const BASE_DIR = process.cwd() @@ -83,8 +70,7 @@ const releasePackage = async ({pkg, code, skipCi} = {}) => { const packageScope = isMonoPackage ? 'Root' : pkg.replace(path.sep, '/') const cwd = isMonoPackage ? BASE_DIR : path.join(process.cwd(), pkg) - const {private: isPrivatePackage, config: localPackageConfig} = - getPackageJson(cwd, true) + const {private: isPrivatePackage, config: localPackageConfig} = getPackageJson(cwd, true) await exec(`npm --no-git-tag-version version ${RELEASE_CODES[code]}`, {cwd}) await exec(`git add ${path.join(cwd, 'package.json')}`, {cwd}) @@ -114,20 +100,14 @@ const checkIsMasterBranchActive = async () => { return stdout.trim() === 'master' } -const prepareAutomaticRelease = async ({ - githubToken, - githubUser, - githubEmail -}) => { +const prepareAutomaticRelease = async ({githubToken, githubUser, githubEmail}) => { const {stdout} = await exec('git config --get remote.origin.url') const repoURL = stdout.trim() const gitURL = gitUrlParse(repoURL).toString('https') const authURL = new URL(gitURL) authURL.username = githubToken - const {stdout: rawIsShallowRepository} = await exec( - 'git rev-parse --is-shallow-repository' - ) + const {stdout: rawIsShallowRepository} = await exec('git rev-parse --is-shallow-repository') const isShallowRepository = rawIsShallowRepository === 'true' if (isShallowRepository) await exec(`git pull --unshallow --quiet`) @@ -140,8 +120,7 @@ const prepareAutomaticRelease = async ({ await exec(`git pull origin master`) } -const checkIsAutomaticRelease = ({githubToken, githubUser, githubEmail}) => - githubToken && githubUser && githubEmail +const checkIsAutomaticRelease = ({githubToken, githubUser, githubEmail}) => githubToken && githubUser && githubEmail const checkShouldRelease = async () => { await exec('git pull origin master') @@ -172,9 +151,7 @@ checkShouldRelease() }) } - const packagesToRelease = releasesByPackages({status}).filter( - ({code}) => code !== 0 - ) + const packagesToRelease = releasesByPackages({status}).filter(({code}) => code !== 0) for (const pkg of packagesToRelease) { await releasePackage({...pkg, skipCi}) @@ -186,17 +163,13 @@ checkShouldRelease() 'npm install --package-lock-only --legacy-peer-deps --no-audit --no-fund --ignore-scripts --production=false' ) await exec('git add package-lock.json') - await exec( - 'git commit -m "chore(Root): update package-lock.json [skip ci]" --no-verify' - ) + await exec('git commit -m "chore(Root): update package-lock.json [skip ci]" --no-verify') } await exec('git push -f --tags origin HEAD') } - console.log( - `[sui-mono release] ${packagesToRelease.length} packages released` - ) + console.log(`[sui-mono release] ${packagesToRelease.length} packages released`) }) }) .catch(err => { diff --git a/packages/sui-mono/bin/sui-mono.js b/packages/sui-mono/bin/sui-mono.js index 562b4d3e2..1f86fb1a7 100755 --- a/packages/sui-mono/bin/sui-mono.js +++ b/packages/sui-mono/bin/sui-mono.js @@ -14,10 +14,7 @@ program.command('check', 'Gives information if something should be updated') program.command('changelog', 'Generate CHANGELOG.md files') -program.command( - 'phoenix', - 'Reset project and packages reinstalling all dependencies' -) +program.command('phoenix', 'Reset project and packages reinstalling all dependencies') program.command('release', 'Release whatever need to be release') diff --git a/packages/sui-mono/src/check.js b/packages/sui-mono/src/check.js index cb1715e27..a11e3291e 100644 --- a/packages/sui-mono/src/check.js +++ b/packages/sui-mono/src/check.js @@ -3,12 +3,7 @@ const conventionalChangelog = require('conventional-changelog') const {readJsonSync} = require('fs-extra') -const { - checkIsMonoPackage, - getProjectName, - getWorkspaces, - getOverrides -} = require('./config.js') +const {checkIsMonoPackage, getProjectName, getWorkspaces, getOverrides} = require('./config.js') const gitRawCommitsOpts = {reverse: true, topoOrder: true} @@ -22,9 +17,7 @@ const PACKAGE_VERSION_INCREMENT = { const isCommitBreakingChange = commit => { const {body, footer} = commit - return [body, footer].some( - msg => typeof msg === 'string' && msg.includes('BREAKING CHANGE') - ) + return [body, footer].some(msg => typeof msg === 'string' && msg.includes('BREAKING CHANGE')) } const isCommitReleaseTrigger = commit => { @@ -32,8 +25,7 @@ const isCommitReleaseTrigger = commit => { return COMMIT_TYPES_WITH_RELEASE.includes(commit.type) } -const flattenForMonopackage = status => - checkIsMonoPackage() ? {[getProjectName()]: flatten(status)} : status +const flattenForMonopackage = status => (checkIsMonoPackage() ? {[getProjectName()]: flatten(status)} : status) const flatten = status => Object.keys(status).reduce( @@ -67,26 +59,17 @@ const getTransform = if (!packages.includes(pkg)) return cb() if (pkgToOverride) { - status[pkgToOverride].increment = Math.max( - status[pkgToOverride].increment, - PACKAGE_VERSION_INCREMENT.MINOR - ) + status[pkgToOverride].increment = Math.max(status[pkgToOverride].increment, PACKAGE_VERSION_INCREMENT.MINOR) toPush = commit } if (isCommitReleaseTrigger(commit)) { - status[pkg].increment = Math.max( - status[pkg].increment, - PACKAGE_VERSION_INCREMENT.MINOR - ) + status[pkg].increment = Math.max(status[pkg].increment, PACKAGE_VERSION_INCREMENT.MINOR) toPush = commit } if (isCommitBreakingChange(commit)) { - status[pkg].increment = Math.max( - status[pkg].increment, - PACKAGE_VERSION_INCREMENT.MAJOR - ) + status[pkg].increment = Math.max(status[pkg].increment, PACKAGE_VERSION_INCREMENT.MAJOR) toPush = commit } diff --git a/packages/sui-mono/src/config.js b/packages/sui-mono/src/config.js index 924e608d2..fffe00234 100644 --- a/packages/sui-mono/src/config.js +++ b/packages/sui-mono/src/config.js @@ -10,10 +10,7 @@ const getWorkspaces = workspaces => { if (workspaces.length === 0) return ['.'] // If we have more than one workspace, we join // folders with the pattern {components/**,demo/**,tests/**}/package.json - const pattern = - workspaces.length > 1 - ? `{${workspaces.join()}}/package.json` - : `${workspaces[0]}/package.json` + const pattern = workspaces.length > 1 ? `{${workspaces.join()}}/package.json` : `${workspaces[0]}/package.json` const paths = glob.sync(pattern, { ignore: ['**/node_modules/**', './node_modules/**'] @@ -32,11 +29,7 @@ const getPublishAccess = ({localPackageConfig = {}, packageConfig = {}}) => { } function factoryConfigMethods(packageFile) { - const { - config: packageConfig = {}, - name: packageName, - workspaces = [] - } = packageFile + const {config: packageConfig = {}, name: packageName, workspaces = []} = packageFile return { checkIsMonoPackage: () => workspaces.length === 0, diff --git a/packages/sui-mono/src/prompter-manager.js b/packages/sui-mono/src/prompter-manager.js index cfd596133..4c382dd9c 100644 --- a/packages/sui-mono/src/prompter-manager.js +++ b/packages/sui-mono/src/prompter-manager.js @@ -31,9 +31,7 @@ const getCommitSteps = ({scopesWithChanges}) => [ type: 'select', name: 'scope', message: '\nDenote the SCOPE of this change:', - choices: scopesWithChanges - .concat(defaultScopes) - .filter(scopes => scopes.name !== '.') + choices: scopesWithChanges.concat(defaultScopes).filter(scopes => scopes.name !== '.') }, { type: 'input', @@ -45,8 +43,7 @@ const getCommitSteps = ({scopesWithChanges}) => [ { type: 'input', name: 'body', - message: - 'Provide a LONGER description of the change (optional). Use "|" to break new line:\n' + message: 'Provide a LONGER description of the change (optional). Use "|" to break new line:\n' }, { type: 'input', @@ -60,8 +57,7 @@ const getCommitSteps = ({scopesWithChanges}) => [ { type: 'input', name: 'footer', - message: - 'List any ISSUES CLOSED by this change (optional). E.g.: #31, #34:\n' + message: 'List any ISSUES CLOSED by this change (optional). E.g.: #31, #34:\n' }, { type: 'confirm', @@ -89,16 +85,12 @@ const checkIfHasChangedFiles = async path => { module.exports = async function startMainCommitFlow() { const scopesWithChanges = await Promise.all( - scopes.map(pkg => - checkIfHasChangedFiles(pkg.name).then(hasFiles => hasFiles && pkg) - ) + scopes.map(pkg => checkIfHasChangedFiles(pkg.name).then(hasFiles => hasFiles && pkg)) ).then(result => result.filter(Boolean)) - const answers = await prompt(getCommitSteps({scopesWithChanges})).catch( - err => { - console.error(err) - } - ) + const answers = await prompt(getCommitSteps({scopesWithChanges})).catch(err => { + console.error(err) + }) if (answers && answers.confirmCommit === true) { const commitMsg = buildCommit(answers) diff --git a/packages/sui-mono/test/server/checkSpec.js b/packages/sui-mono/test/server/checkSpec.js index 555dee45b..f47e26346 100644 --- a/packages/sui-mono/test/server/checkSpec.js +++ b/packages/sui-mono/test/server/checkSpec.js @@ -1,10 +1,6 @@ import {expect} from 'chai' -import { - getTransform, - isCommitBreakingChange, - isCommitReleaseTrigger -} from '../../src/check.js' +import {getTransform, isCommitBreakingChange, isCommitReleaseTrigger} from '../../src/check.js' describe('check', () => { describe('isCommitBreakingChange', () => { diff --git a/packages/sui-pde/src/adapters/optimizely/index.js b/packages/sui-pde/src/adapters/optimizely/index.js index 12b5e422b..1f784d3d5 100644 --- a/packages/sui-pde/src/adapters/optimizely/index.js +++ b/packages/sui-pde/src/adapters/optimizely/index.js @@ -16,8 +16,7 @@ const DEFAULT_TIMEOUT = 500 const {enums: LOG_LEVEL} = optimizelySDK -const LOGGER_LEVEL = - process.env.NODE_ENV === 'production' ? LOG_LEVEL.error : LOG_LEVEL.info +const LOGGER_LEVEL = process.env.NODE_ENV === 'production' ? LOG_LEVEL.error : LOG_LEVEL.info export default class OptimizelyAdapter { /** @@ -28,17 +27,9 @@ export default class OptimizelyAdapter { * @param {object} param.activeIntegrations segment activated by default * @param {boolean} param.hasUserConsents */ - constructor({ - optimizely, - userId, - activeIntegrations = {segment: true}, - hasUserConsents, - applicationAttributes = {} - }) { + constructor({optimizely, userId, activeIntegrations = {segment: true}, hasUserConsents, applicationAttributes = {}}) { if (!optimizely) { - throw new Error( - 'optimizely instance is mandatory to use OptimizelyAdapter' - ) + throw new Error('optimizely instance is mandatory to use OptimizelyAdapter') } this._optimizely = optimizely @@ -66,11 +57,7 @@ export default class OptimizelyAdapter { const options = {...DEFAULT_DATAFILE_OPTIONS, ...optionParameter} optimizely.setLogLevel(LOGGER_LEVEL) optimizely.setLogger(optimizely.logging.createLogger()) - if ( - !datafile && - typeof window !== 'undefined' && - window.__INITIAL_CONTEXT_VALUE__?.pde - ) { + if (!datafile && typeof window !== 'undefined' && window.__INITIAL_CONTEXT_VALUE__?.pde) { datafile = window.__INITIAL_CONTEXT_VALUE__.pde sdkKey = undefined } @@ -146,9 +133,7 @@ export default class OptimizelyAdapter { } onReady() { - return this._optimizely - .onReady({timeout: DEFAULT_TIMEOUT}) - .then(() => this._optimizely) + return this._optimizely.onReady({timeout: DEFAULT_TIMEOUT}).then(() => this._optimizely) } /** @@ -159,15 +144,11 @@ export default class OptimizelyAdapter { * @returns {isActive: boolean, linkedExperiments: number[]} */ isFeatureEnabled({featureKey, attributes}) { - const experimentsMap = - this.getOptimizelyConfig()?.featuresMap[featureKey]?.experimentsMap || {} + const experimentsMap = this.getOptimizelyConfig()?.featuresMap[featureKey]?.experimentsMap || {} const linkedExperimentNames = Object.keys(experimentsMap) // check for user consents only if featureKey is a feature that belongs to a feature test or if a userId is available - if ( - (linkedExperimentNames.length > 0 && !this._hasUserConsents) || - !this._userId - ) { + if ((linkedExperimentNames.length > 0 && !this._hasUserConsents) || !this._userId) { return {isActive: false, linkedExperiments: []} } @@ -188,11 +169,7 @@ export default class OptimizelyAdapter { * @returns {object} */ getAllFeatureVariables({featureKey, attributes}) { - return this._optimizely.getAllFeatureVariables( - featureKey, - this._userId, - attributes - ) + return this._optimizely.getAllFeatureVariables(featureKey, this._userId, attributes) } updateConsents({hasUserConsents}) { diff --git a/packages/sui-pde/src/adapters/optimizely/integrations/handler.js b/packages/sui-pde/src/adapters/optimizely/integrations/handler.js index 0caf94e58..950e923e2 100644 --- a/packages/sui-pde/src/adapters/optimizely/integrations/handler.js +++ b/packages/sui-pde/src/adapters/optimizely/integrations/handler.js @@ -12,11 +12,7 @@ const integrations = [segmentIntegration] * @param {object} param.activeIntegrations * @param {object} param.optimizelyInstance */ -export const updateIntegrations = ({ - hasUserConsents, - activeIntegrations, - optimizelyInstance -}) => { +export const updateIntegrations = ({hasUserConsents, activeIntegrations, optimizelyInstance}) => { integrations.forEach(integration => integration({ activeIntegrations, diff --git a/packages/sui-pde/src/adapters/optimizely/integrations/segment.js b/packages/sui-pde/src/adapters/optimizely/integrations/segment.js index bb2a252aa..96dea52bf 100644 --- a/packages/sui-pde/src/adapters/optimizely/integrations/segment.js +++ b/packages/sui-pde/src/adapters/optimizely/integrations/segment.js @@ -8,11 +8,7 @@ * Example {segment: true, braze: true} * @param {object} param.optimizelyInstance */ -export const segment = ({ - activeIntegrations, - optimizelyInstance, - hasUserConsents -}) => { +export const segment = ({activeIntegrations, optimizelyInstance, hasUserConsents}) => { if (!activeIntegrations.segment || typeof window === 'undefined') return if (!hasUserConsents) { delete window.optimizelyClientInstance diff --git a/packages/sui-pde/src/adapters/optimizely/multiple.js b/packages/sui-pde/src/adapters/optimizely/multiple.js index e5af6596d..a259a7a00 100644 --- a/packages/sui-pde/src/adapters/optimizely/multiple.js +++ b/packages/sui-pde/src/adapters/optimizely/multiple.js @@ -7,11 +7,7 @@ class MultipleOptimizelyAdapter { return Object.keys(optionsByInstance).reduce((acc, adapterId) => { let {datafile, sdkKey, ...restOptions} = optionsByInstance[adapterId] - if ( - !datafile && - typeof window !== 'undefined' && - window.__INITIAL_CONTEXT_VALUE__?.pde[adapterId] - ) { + if (!datafile && typeof window !== 'undefined' && window.__INITIAL_CONTEXT_VALUE__?.pde[adapterId]) { datafile = window.__INITIAL_CONTEXT_VALUE__.pde[adapterId] sdkKey = undefined } @@ -31,13 +27,10 @@ class MultipleOptimizelyAdapter { constructor(optimizelyAdapters) { defaultAdapterId = Object.keys(optimizelyAdapters)[0] // first adapter will be the defaultAdapter - this.#adapters = Object.keys(optimizelyAdapters).reduce( - (acc, adapterId) => { - acc[adapterId] = new OptimizelyAdapter(optimizelyAdapters[adapterId]) - return acc - }, - {} - ) + this.#adapters = Object.keys(optimizelyAdapters).reduce((acc, adapterId) => { + acc[adapterId] = new OptimizelyAdapter(optimizelyAdapters[adapterId]) + return acc + }, {}) } getInitialData() { @@ -52,9 +45,7 @@ class MultipleOptimizelyAdapter { } onReady() { - return Promise.all( - Object.values(this.#adapters).map(adapter => adapter.onReady()) - ) + return Promise.all(Object.values(this.#adapters).map(adapter => adapter.onReady())) } getEnabledFeatures({adapterId = defaultAdapterId, ...props}) { diff --git a/packages/sui-pde/src/components/experiment.js b/packages/sui-pde/src/components/experiment.js index c4e557ded..8b5871aa5 100644 --- a/packages/sui-pde/src/components/experiment.js +++ b/packages/sui-pde/src/components/experiment.js @@ -2,13 +2,7 @@ import PropTypes from 'prop-types' import useExperiment from '../hooks/useExperiment.js' -export default function Experiment({ - experimentName, - attributes, - trackExperimentViewed, - queryString, - children -}) { +export default function Experiment({experimentName, attributes, trackExperimentViewed, queryString, children}) { const {variation} = useExperiment({ experimentName, attributes, diff --git a/packages/sui-pde/src/components/feature.js b/packages/sui-pde/src/components/feature.js index 3239df1e7..f66d678c6 100644 --- a/packages/sui-pde/src/components/feature.js +++ b/packages/sui-pde/src/components/feature.js @@ -2,12 +2,7 @@ import PropTypes from 'prop-types' import useFeature from '../hooks/useFeature.js' -export default function Feature({ - children, - featureKey, - attributes, - queryString -}) { +export default function Feature({children, featureKey, attributes, queryString}) { const {isActive, variables} = useFeature(featureKey, attributes, queryString) return children({isActive, variables}) } diff --git a/packages/sui-pde/src/hooks/common/platformStrategies.js b/packages/sui-pde/src/hooks/common/platformStrategies.js index 24cd1e5cd..f56b4a540 100644 --- a/packages/sui-pde/src/hooks/common/platformStrategies.js +++ b/packages/sui-pde/src/hooks/common/platformStrategies.js @@ -40,9 +40,7 @@ const getBrowserStrategy = ({customTrackExperimentViewed, cache}) => ({ if (!window.analytics?.track) { // eslint-disable-next-line no-console - console.error( - "[sui-pde: useExperiment] window.analytics.track expected to exists but doesn't" - ) + console.error("[sui-pde: useExperiment] window.analytics.track expected to exists but doesn't") return } diff --git a/packages/sui-pde/src/hooks/useExperiment.js b/packages/sui-pde/src/hooks/useExperiment.js index d1c3c421c..c9e2020a2 100644 --- a/packages/sui-pde/src/hooks/useExperiment.js +++ b/packages/sui-pde/src/hooks/useExperiment.js @@ -21,10 +21,7 @@ export default function useExperiment({ adapterId } = {}) { const {pde} = useContext(PdeContext) - if (pde === null) - throw new Error( - '[sui-pde: useExperiment] sui-pde provider is required to work' - ) + if (pde === null) throw new Error('[sui-pde: useExperiment] sui-pde provider is required to work') const variation = useMemo(() => { let variationName @@ -55,14 +52,7 @@ export default function useExperiment({ } return variationName - }, [ - trackExperimentViewed, - experimentName, - queryString, - pde, - attributes, - adapterId - ]) + }, [trackExperimentViewed, experimentName, queryString, pde, attributes, adapterId]) return {variation} } diff --git a/packages/sui-pde/src/hooks/useFeature.js b/packages/sui-pde/src/hooks/useFeature.js index 635c8bc3d..710e79503 100644 --- a/packages/sui-pde/src/hooks/useFeature.js +++ b/packages/sui-pde/src/hooks/useFeature.js @@ -13,11 +13,7 @@ const VARIATION_NAME_OFF = 'Off State' * @param {function} param.trackExperimentViewed * @param {string} param.featureKey */ -const trackFeatureFlagViewed = ({ - isActive, - trackExperimentViewed, - featureKey -}) => { +const trackFeatureFlagViewed = ({isActive, trackExperimentViewed, featureKey}) => { const variationName = isActive ? VARIATION_NAME_ON : VARIATION_NAME_OFF trackExperimentViewed({experimentName: featureKey, variationName}) } @@ -31,13 +27,7 @@ const trackFeatureFlagViewed = ({ * @param {object} pde * @param {string} adapterId */ -const trackLinkedExperimentsViewed = ({ - linkedExperiments, - trackExperimentViewed, - attributes, - pde, - adapterId -}) => { +const trackLinkedExperimentsViewed = ({linkedExperiments, trackExperimentViewed, attributes, pde, adapterId}) => { if (!linkedExperiments) return linkedExperiments.forEach(experimentName => { const variationName = pde.getVariation({ @@ -57,16 +47,9 @@ const trackLinkedExperimentsViewed = ({ * @param {string} adapterId * @return {{isActive: boolean}} */ -export default function useFeature( - featureKey, - attributes, - queryString, - adapterId, - shouldTrackExperimentViewed -) { +export default function useFeature(featureKey, attributes, queryString, adapterId, shouldTrackExperimentViewed) { const {pde} = useContext(PdeContext) - if (pde === null) - throw new Error('[useFeature] sui-pde provider is required to work') + if (pde === null) throw new Error('[useFeature] sui-pde provider is required to work') const strategy = getPlatformStrategy() diff --git a/packages/sui-pde/test/common/pdeSpec.js b/packages/sui-pde/test/common/pdeSpec.js index f4a2d7c07..ccf9e3f2b 100644 --- a/packages/sui-pde/test/common/pdeSpec.js +++ b/packages/sui-pde/test/common/pdeSpec.js @@ -115,9 +115,7 @@ describe('@s-ui pde', () => { expect(isActive).to.equal(true) expect(linkedExperiments).to.deep.equal(['1234']) expect(optimizelyInstanceStub.isFeatureEnabled.called).to.equal(true) - expect(optimizelyInstanceStub.isFeatureEnabled.args[0][0]).to.equal( - 'featureUsedInTest' - ) + expect(optimizelyInstanceStub.isFeatureEnabled.args[0][0]).to.equal('featureUsedInTest') }) it('should call optimizelys sdk activate fn', () => { @@ -163,9 +161,7 @@ describe('@s-ui pde', () => { optimizely: optimizelyInstanceStub }) - expect(optimizelyAdapter.activateExperiment({name: 'fakeTest'})).to.equal( - null - ) + expect(optimizelyAdapter.activateExperiment({name: 'fakeTest'})).to.equal(null) expect(optimizelyInstanceStub.activate.notCalled).to.equal(true) }) @@ -223,28 +219,24 @@ describe('@s-ui pde', () => { }) }) - it.client( - 'uses the optimizely adapter by default as global object to integrate with segment', - () => { - delete window.optimizelyClientInstance - // own copy to ensure to be able to test if it's the same object as added to the window - const optimizelyInstanceStub = { - activate: sinon.stub().returns('variationA'), - onReady: async () => true, - getEnabledFeatures: () => ['a', 'b'] - } - // only executed to create window.optimizelyClientInstance - // eslint-disable-next-line no-new - new OptimizelyAdapter({ - optimizely: optimizelyInstanceStub, - userId: '123', - hasUserConsents: true - }) - // eslint-disable-next-line eqeqeq - expect(window.optimizelyClientInstance == optimizelyInstanceStub).to.be - .true + it.client('uses the optimizely adapter by default as global object to integrate with segment', () => { + delete window.optimizelyClientInstance + // own copy to ensure to be able to test if it's the same object as added to the window + const optimizelyInstanceStub = { + activate: sinon.stub().returns('variationA'), + onReady: async () => true, + getEnabledFeatures: () => ['a', 'b'] } - ) + // only executed to create window.optimizelyClientInstance + // eslint-disable-next-line no-new + new OptimizelyAdapter({ + optimizely: optimizelyInstanceStub, + userId: '123', + hasUserConsents: true + }) + // eslint-disable-next-line eqeqeq + expect(window.optimizelyClientInstance == optimizelyInstanceStub).to.be.true + }) it.client('does not create segment integration if passed by as off', () => { delete window.optimizelyClientInstance @@ -333,11 +325,10 @@ describe('@s-ui pde', () => { alternateInstance = createOptimizelyInstanceStub({ activate: alternateInstanceActiveVariation }) - multipleAdapterInstances = - MultipleOptimizelyAdapter.createMultipleOptimizelyInstances({ - [defaultAdapterId]: {optimizely: defaultInstance}, - [alternateAdapterId]: {optimizely: alternateInstance} - }) + multipleAdapterInstances = MultipleOptimizelyAdapter.createMultipleOptimizelyInstances({ + [defaultAdapterId]: {optimizely: defaultInstance}, + [alternateAdapterId]: {optimizely: alternateInstance} + }) multipleAdapter = new MultipleOptimizelyAdapter({ [defaultAdapterId]: { optimizely: multipleAdapterInstances[defaultAdapterId] @@ -357,12 +348,8 @@ describe('@s-ui pde', () => { name: 'default-test', adapterId: defaultAdapterId }) - expect(variationOnDefaultWithAdapterId).to.equal( - variationOnDefaultWithoutAdapterId - ) - expect(variationOnDefaultWithAdapterId).to.equal( - defaultInstanceActiveVariation - ) + expect(variationOnDefaultWithAdapterId).to.equal(variationOnDefaultWithoutAdapterId) + expect(variationOnDefaultWithAdapterId).to.equal(defaultInstanceActiveVariation) }) it('should use alternate adapter id', () => { @@ -370,9 +357,7 @@ describe('@s-ui pde', () => { name: 'default-test', adapterId: alternateAdapterId }) - expect(variationOnAlternateWithAdapterId).to.equal( - alternateInstanceActiveVariation - ) + expect(variationOnAlternateWithAdapterId).to.equal(alternateInstanceActiveVariation) }) it('should be ready on multiple instances', async () => { @@ -406,12 +391,12 @@ describe('@s-ui pde', () => { [alternateAdapterId]: {optimizely: optimizelySDK2} }) - expect( - optimizelySDK1.createInstance.firstCall.args[0].datafile - ).to.deep.equal({initialDatafile: defaultAdapterId}) - expect( - optimizelySDK2.createInstance.firstCall.args[0].datafile - ).to.deep.equal({initialDatafile: alternateAdapterId}) + expect(optimizelySDK1.createInstance.firstCall.args[0].datafile).to.deep.equal({ + initialDatafile: defaultAdapterId + }) + expect(optimizelySDK2.createInstance.firstCall.args[0].datafile).to.deep.equal({ + initialDatafile: alternateAdapterId + }) }) it('should accept a single adapter', () => { diff --git a/packages/sui-pde/test/common/useExperimentSpec.js b/packages/sui-pde/test/common/useExperimentSpec.js index 9aab041c6..efda4f103 100644 --- a/packages/sui-pde/test/common/useExperimentSpec.js +++ b/packages/sui-pde/test/common/useExperimentSpec.js @@ -32,9 +32,7 @@ describe('useExperiment hook', () => { getVariation = sinon.stub().returns('getVariationA') // eslint-disable-next-line react/prop-types wrapper = ({children}) => ( - + {children} ) @@ -56,18 +54,13 @@ describe('useExperiment hook', () => { }) it('should return the right variationName and launch the Experiment Viewed event', () => { - const {result} = renderHook( - () => useExperiment({experimentName: 'test_experiment_id_1'}), - { - wrapper - } - ) + const {result} = renderHook(() => useExperiment({experimentName: 'test_experiment_id_1'}), { + wrapper + }) expect(result.current.variation).to.equal('activateExperimentA') sinon.assert.callCount(console.error, 0) sinon.assert.callCount(window.analytics.track, 1) - expect(window.analytics.track.args[0][0]).to.equal( - 'Experiment Viewed' - ) + expect(window.analytics.track.args[0][0]).to.equal('Experiment Viewed') expect(window.analytics.track.args[0][1]).to.deep.equal({ variationName: 'activateExperimentA', experimentName: 'test_experiment_id_1' @@ -90,18 +83,12 @@ describe('useExperiment hook', () => { describe('when the same experiment is loaded more than once', () => { it('should only track once', () => { - renderHook( - () => useExperiment({experimentName: 'test_experiment_id'}), - { - wrapper - } - ) - renderHook( - () => useExperiment({experimentName: 'test_experiment_id'}), - { - wrapper - } - ) + renderHook(() => useExperiment({experimentName: 'test_experiment_id'}), { + wrapper + }) + renderHook(() => useExperiment({experimentName: 'test_experiment_id'}), { + wrapper + }) expect(window.analytics.track.args.length).to.equal(1) }) }) @@ -118,17 +105,12 @@ describe('useExperiment hook', () => { it('should return the right variationName and log an error', () => { delete window.analytics - const {result} = renderHook( - () => useExperiment({experimentName: 'test_experiment_id_2'}), - { - wrapper - } - ) + const {result} = renderHook(() => useExperiment({experimentName: 'test_experiment_id_2'}), { + wrapper + }) expect(result.current.variation).to.equal('activateExperimentA') sinon.assert.callCount(console.error, 1) - expect(console.error.args[0][0]).to.include( - 'window.analytics.track expected' - ) + expect(console.error.args[0][0]).to.include('window.analytics.track expected') }) }) @@ -173,12 +155,9 @@ describe('useExperiment hook', () => { }) it('should return the right variationName and launch the Experiment Viewed event', () => { - const {result} = renderHook( - () => useExperiment({experimentName: 'test_experiment_id'}), - { - wrapper - } - ) + const {result} = renderHook(() => useExperiment({experimentName: 'test_experiment_id'}), { + wrapper + }) expect(result.current.variation).to.equal('getVariationA') sinon.assert.callCount(console.error, 0) }) @@ -189,14 +168,10 @@ describe('useExperiment hook', () => { let activateExperiment let wrapper beforeEach(() => { - activateExperiment = sinon - .stub() - .throws(new Error('fake activation error')) + activateExperiment = sinon.stub().throws(new Error('fake activation error')) // eslint-disable-next-line react/prop-types wrapper = ({children}) => ( - - {children} - + {children} ) }) @@ -206,85 +181,68 @@ describe('useExperiment hook', () => { }) }) - describe.client( - 'when calling twice the useExperiment hook with the same feature key', - () => { - let wrapper - let getVariation - let stubFactory - - beforeEach(() => { - window.analytics = { - ready: cb => cb(), - track: sinon.spy() - } + describe.client('when calling twice the useExperiment hook with the same feature key', () => { + let wrapper + let getVariation + let stubFactory - stubFactory = activateExperiment => { - getVariation = sinon.stub().returns('getVariationA') - // eslint-disable-next-line react/prop-types - wrapper = ({children}) => ( - - {children} - - ) - } - }) + beforeEach(() => { + window.analytics = { + ready: cb => cb(), + track: sinon.spy() + } + + stubFactory = activateExperiment => { + getVariation = sinon.stub().returns('getVariationA') + // eslint-disable-next-line react/prop-types + wrapper = ({children}) => ( + + {children} + + ) + } + }) - afterEach(() => { - delete window.analytics - }) + afterEach(() => { + delete window.analytics + }) - describe('when the second time returns the same value as the first time', () => { - beforeEach(() => { - const activateExperiment = sinon.stub() - activateExperiment.onCall(0).returns('A') - activateExperiment.onCall(1).returns('A') + describe('when the second time returns the same value as the first time', () => { + beforeEach(() => { + const activateExperiment = sinon.stub() + activateExperiment.onCall(0).returns('A') + activateExperiment.onCall(1).returns('A') - stubFactory(activateExperiment) + stubFactory(activateExperiment) + }) + it('should send only one experiment viewed event', () => { + renderHook(() => useExperiment({experimentName: 'repeatedFeatureFlagKey'}), { + wrapper }) - it('should send only one experiment viewed event', () => { - renderHook( - () => useExperiment({experimentName: 'repeatedFeatureFlagKey'}), - { - wrapper - } - ) - renderHook( - () => useExperiment({experimentName: 'repeatedFeatureFlagKey'}), - { - wrapper - } - ) - expect(window.analytics.track.args.length).to.equal(1) + renderHook(() => useExperiment({experimentName: 'repeatedFeatureFlagKey'}), { + wrapper }) + expect(window.analytics.track.args.length).to.equal(1) }) + }) - describe('when the second time returns a different value as the first time', () => { - beforeEach(() => { - const activateExperiment = sinon.stub() - activateExperiment.onCall(0).returns('A') - activateExperiment.onCall(1).returns('B') + describe('when the second time returns a different value as the first time', () => { + beforeEach(() => { + const activateExperiment = sinon.stub() + activateExperiment.onCall(0).returns('A') + activateExperiment.onCall(1).returns('B') - stubFactory(activateExperiment) + stubFactory(activateExperiment) + }) + it('should send two experiment viewed events', () => { + renderHook(() => useExperiment({experimentName: 'repeatedFeatureFlagKey'}), { + wrapper }) - it('should send two experiment viewed events', () => { - renderHook( - () => useExperiment({experimentName: 'repeatedFeatureFlagKey'}), - { - wrapper - } - ) - renderHook( - () => useExperiment({experimentName: 'repeatedFeatureFlagKey'}), - { - wrapper - } - ) - expect(window.analytics.track.args.length).to.equal(2) + renderHook(() => useExperiment({experimentName: 'repeatedFeatureFlagKey'}), { + wrapper }) + expect(window.analytics.track.args.length).to.equal(2) }) - } - ) + }) + }) }) diff --git a/packages/sui-pde/test/common/useFeatureSpec.js b/packages/sui-pde/test/common/useFeatureSpec.js index 6e607350e..74b5fcedd 100644 --- a/packages/sui-pde/test/common/useFeatureSpec.js +++ b/packages/sui-pde/test/common/useFeatureSpec.js @@ -22,26 +22,17 @@ describe('when pde context is set', () => { let isFeatureEnabled let getAllFeatureVariables beforeEach(() => { - isFeatureEnabled = sinon - .stub() - .returns({isActive: true, linkedExperiments: []}) + isFeatureEnabled = sinon.stub().returns({isActive: true, linkedExperiments: []}) getAllFeatureVariables = sinon.stub().returns(variables) // eslint-disable-next-line react/prop-types wrapper = ({children}) => ( - - {children} - + {children} ) }) it('should check if a feature is enabled', () => { - const {result} = renderHook( - () => useFeature('featureKey1', {attribute1: 'value'}), - {wrapper} - ) + const {result} = renderHook(() => useFeature('featureKey1', {attribute1: 'value'}), {wrapper}) expect(result.current.isActive).to.equal(true) expect(isFeatureEnabled.called).to.equal(true) expect(isFeatureEnabled.args[0][0]).to.deep.equal({ @@ -52,10 +43,7 @@ describe('when pde context is set', () => { }) it('should return feature variables', () => { - const {result} = renderHook( - () => useFeature('featureKey2', {attribute1: 'value'}), - {wrapper} - ) + const {result} = renderHook(() => useFeature('featureKey2', {attribute1: 'value'}), {wrapper}) expect(result.current.variables).to.be.deep.equal(variables) expect(isFeatureEnabled.called).to.equal(true) @@ -68,176 +56,120 @@ describe('when pde context is set', () => { describe.client('and the hook is executed by the browser', () => { it('should check that a feature has been forced to be active', () => { - const {result} = renderHook( - () => useFeature('featureKey3', {}, '?suipde_feature1=on'), - {wrapper} - ) + const {result} = renderHook(() => useFeature('featureKey3', {}, '?suipde_feature1=on'), {wrapper}) expect(result.current.isActive).to.equal(true) }) it('should check that a feature has been forced to be not active', () => { - const {result} = renderHook( - () => - useFeature( - 'featureKey3', - {}, - '?suipde_featureKey3=off&suipde_feature1=on' - ), - {wrapper} - ) + const {result} = renderHook(() => useFeature('featureKey3', {}, '?suipde_featureKey3=off&suipde_feature1=on'), { + wrapper + }) expect(result.current.isActive).to.equal(false) }) }) }) - describe.client( - 'when checking if a feature flag is active or not in browser', - () => { - let isFeatureEnabled - let getAllFeatureVariables - let getVariation - - describe.client('when a feature flag is active', () => { - beforeEach(() => { - isFeatureEnabled = sinon.stub().returns({ - isActive: true, - linkedExperiments: [] - }) - getAllFeatureVariables = sinon.stub().returns(variables) - getVariation = sinon.stub().returns('variation1') - - window.analytics = { - ready: cb => cb(), - track: sinon.spy() - } - - // eslint-disable-next-line react/prop-types - wrapper = ({children}) => ( - - {children} - - ) - }) + describe.client('when checking if a feature flag is active or not in browser', () => { + let isFeatureEnabled + let getAllFeatureVariables + let getVariation - afterEach(() => { - delete window.analytics + describe.client('when a feature flag is active', () => { + beforeEach(() => { + isFeatureEnabled = sinon.stub().returns({ + isActive: true, + linkedExperiments: [] }) + getAllFeatureVariables = sinon.stub().returns(variables) + getVariation = sinon.stub().returns('variation1') - it('should send the on state experiment viewed', () => { - renderHook( - () => - useFeature( - 'activeFeatureFlagKey', - undefined, - undefined, - undefined, - true - ), - { - wrapper - } - ) - expect(window.analytics.track.args[0][0]).to.equal( - 'Experiment Viewed' - ) - expect(window.analytics.track.args[0][1]).to.deep.equal({ - experimentName: 'activeFeatureFlagKey', - variationName: 'On State' - }) - }) + window.analytics = { + ready: cb => cb(), + track: sinon.spy() + } - describe.client('when a feature is seen twice', () => { - it('should only track one experiment viewed event', () => { - renderHook( - () => - useFeature( - 'repeatedFeatureFlagKey', - undefined, - undefined, - undefined, - true - ), - { - wrapper - } - ) - renderHook( - () => - useFeature( - 'repeatedFeatureFlagKey', - undefined, - undefined, - undefined, - true - ), - { - wrapper - } - ) - expect(window.analytics.track.args.length).to.equal(1) - }) + // eslint-disable-next-line react/prop-types + wrapper = ({children}) => ( + + {children} + + ) + }) + + afterEach(() => { + delete window.analytics + }) + + it('should send the on state experiment viewed', () => { + renderHook(() => useFeature('activeFeatureFlagKey', undefined, undefined, undefined, true), { + wrapper + }) + expect(window.analytics.track.args[0][0]).to.equal('Experiment Viewed') + expect(window.analytics.track.args[0][1]).to.deep.equal({ + experimentName: 'activeFeatureFlagKey', + variationName: 'On State' }) }) - describe.client('when a feature flag is deactivated', () => { - beforeEach(() => { - isFeatureEnabled = sinon.stub().returns({ - isActive: false, - linkedExperiments: [] + describe.client('when a feature is seen twice', () => { + it('should only track one experiment viewed event', () => { + renderHook(() => useFeature('repeatedFeatureFlagKey', undefined, undefined, undefined, true), { + wrapper }) - getAllFeatureVariables = sinon.stub().returns(variables) - getVariation = sinon.stub().returns('variation1') - - window.analytics = { - ready: cb => cb(), - track: sinon.spy() - } - - // eslint-disable-next-line react/prop-types - wrapper = ({children}) => ( - - {children} - - ) + renderHook(() => useFeature('repeatedFeatureFlagKey', undefined, undefined, undefined, true), { + wrapper + }) + expect(window.analytics.track.args.length).to.equal(1) }) + }) + }) - afterEach(() => { - delete window.analytics + describe.client('when a feature flag is deactivated', () => { + beforeEach(() => { + isFeatureEnabled = sinon.stub().returns({ + isActive: false, + linkedExperiments: [] }) + getAllFeatureVariables = sinon.stub().returns(variables) + getVariation = sinon.stub().returns('variation1') - it('should send the off state experiment viewed', () => { - renderHook( - () => - useFeature( - 'notActiveFeatureFlagKey', - undefined, - undefined, - undefined, - true - ), - { - wrapper - } - ) - expect(window.analytics.track.args[0][0]).to.equal( - 'Experiment Viewed' - ) - expect(window.analytics.track.args[0][1]).to.deep.equal({ - experimentName: 'notActiveFeatureFlagKey', - variationName: 'Off State' - }) + window.analytics = { + ready: cb => cb(), + track: sinon.spy() + } + + // eslint-disable-next-line react/prop-types + wrapper = ({children}) => ( + + {children} + + ) + }) + + afterEach(() => { + delete window.analytics + }) + + it('should send the off state experiment viewed', () => { + renderHook(() => useFeature('notActiveFeatureFlagKey', undefined, undefined, undefined, true), { + wrapper + }) + expect(window.analytics.track.args[0][0]).to.equal('Experiment Viewed') + expect(window.analytics.track.args[0][1]).to.deep.equal({ + experimentName: 'notActiveFeatureFlagKey', + variationName: 'Off State' }) }) - } - ) + }) + }) describe.client('when its a feature test, so an experiment is linked', () => { let isFeatureEnabled @@ -278,19 +210,9 @@ describe('when pde context is set', () => { }) it('should send experiment viewed event for every test asociated and the experiment viewed associated to the feature flag itself', () => { - renderHook( - () => - useFeature( - 'featureKey4', - {attribute1: 'value'}, - undefined, - undefined, - true - ), - { - wrapper - } - ) + renderHook(() => useFeature('featureKey4', {attribute1: 'value'}, undefined, undefined, true), { + wrapper + }) // feature being called expect(window.analytics.track.args[0][0]).to.equal('Experiment Viewed') @@ -315,128 +237,85 @@ describe('when pde context is set', () => { }) }) - describe.client( - 'when calling twice the useFeature hook with the same feature key', - () => { - let getAllFeatureVariables - let getVariation - let stubFactory + describe.client('when calling twice the useFeature hook with the same feature key', () => { + let getAllFeatureVariables + let getVariation + let stubFactory - beforeEach(() => { - window.analytics = { - ready: cb => cb(), - track: sinon.spy() - } + beforeEach(() => { + window.analytics = { + ready: cb => cb(), + track: sinon.spy() + } - stubFactory = isFeatureEnabled => { - getAllFeatureVariables = sinon.stub().returns(variables) - - // eslint-disable-next-line react/prop-types - wrapper = ({children}) => ( - - {children} - - ) - } - }) + stubFactory = isFeatureEnabled => { + getAllFeatureVariables = sinon.stub().returns(variables) + + // eslint-disable-next-line react/prop-types + wrapper = ({children}) => ( + + {children} + + ) + } + }) - afterEach(() => { - delete window.analytics - }) + afterEach(() => { + delete window.analytics + }) - describe('when the second time returns the same value as the first time', () => { - beforeEach(() => { - const isFeatureEnabled = sinon.stub() - isFeatureEnabled.onCall(0).returns({ - isActive: true - }) - isFeatureEnabled.onCall(1).returns({ - isActive: true - }) + describe('when the second time returns the same value as the first time', () => { + beforeEach(() => { + const isFeatureEnabled = sinon.stub() + isFeatureEnabled.onCall(0).returns({ + isActive: true + }) + isFeatureEnabled.onCall(1).returns({ + isActive: true + }) - stubFactory(isFeatureEnabled) + stubFactory(isFeatureEnabled) + }) + it('should send only one experiment viewed event', () => { + renderHook(() => useFeature('repeatedFeatureFlagKey', undefined, undefined, undefined, true), { + wrapper }) - it('should send only one experiment viewed event', () => { - renderHook( - () => - useFeature( - 'repeatedFeatureFlagKey', - undefined, - undefined, - undefined, - true - ), - { - wrapper - } - ) - renderHook( - () => - useFeature( - 'repeatedFeatureFlagKey', - undefined, - undefined, - undefined, - true - ), - { - wrapper - } - ) - expect(window.analytics.track.args.length).to.equal(1) + renderHook(() => useFeature('repeatedFeatureFlagKey', undefined, undefined, undefined, true), { + wrapper }) + expect(window.analytics.track.args.length).to.equal(1) }) + }) - describe('when the second time returns a different value as the first time', () => { - beforeEach(() => { - const isFeatureEnabled = sinon.stub() - isFeatureEnabled.onCall(0).returns({ - isActive: true - }) - isFeatureEnabled.onCall(1).returns({ - isActive: false - }) + describe('when the second time returns a different value as the first time', () => { + beforeEach(() => { + const isFeatureEnabled = sinon.stub() + isFeatureEnabled.onCall(0).returns({ + isActive: true + }) + isFeatureEnabled.onCall(1).returns({ + isActive: false + }) - stubFactory(isFeatureEnabled) + stubFactory(isFeatureEnabled) + }) + it('should send two experiment viewed events', () => { + renderHook(() => useFeature('repeatedFeatureFlagKey', undefined, undefined, undefined, true), { + wrapper }) - it('should send two experiment viewed events', () => { - renderHook( - () => - useFeature( - 'repeatedFeatureFlagKey', - undefined, - undefined, - undefined, - true - ), - { - wrapper - } - ) - renderHook( - () => - useFeature( - 'repeatedFeatureFlagKey', - undefined, - undefined, - undefined, - true - ), - { - wrapper - } - ) - expect(window.analytics.track.args.length).to.equal(2) + renderHook(() => useFeature('repeatedFeatureFlagKey', undefined, undefined, undefined, true), { + wrapper }) + expect(window.analytics.track.args.length).to.equal(2) }) - } - ) + }) + }) }) diff --git a/packages/sui-polyfills/src/element-closest.js b/packages/sui-polyfills/src/element-closest.js index 1838a7a10..3ba8158a4 100644 --- a/packages/sui-polyfills/src/element-closest.js +++ b/packages/sui-polyfills/src/element-closest.js @@ -5,9 +5,7 @@ if (typeof window !== 'undefined') { // Polyfill for Element.closest() // from https://developer.mozilla.org/en-US/docs/Web/API/Element/closest#Polyfill if (!Element.prototype.matches) { - Element.prototype.matches = - Element.prototype.msMatchesSelector || - Element.prototype.webkitMatchesSelector + Element.prototype.matches = Element.prototype.msMatchesSelector || Element.prototype.webkitMatchesSelector } if (!Element.prototype.closest) { diff --git a/packages/sui-precommit/bin/sui-precommit.js b/packages/sui-precommit/bin/sui-precommit.js index 545c62e38..1d08d2aee 100755 --- a/packages/sui-precommit/bin/sui-precommit.js +++ b/packages/sui-precommit/bin/sui-precommit.js @@ -45,25 +45,11 @@ if (CI === false && name !== '@s-ui/precommit') { writeFile(commitMsgPath, '#!/bin/sh\nnpm run commit-msg --if-present'), writeFile(preCommitPath, '#!/bin/sh\nnpm run pre-commit --if-present'), writeFile(prePushPath, '#!/bin/sh\nnpm run pre-push --if-present') - ]).then(() => - Promise.all([ - chmod(commitMsgPath, '755'), - chmod(preCommitPath, '755'), - chmod(prePushPath, '755') - ]) - ) + ]).then(() => Promise.all([chmod(commitMsgPath, '755'), chmod(preCommitPath, '755'), chmod(prePushPath, '755')])) try { - addToPackageJson( - 'sui-lint js --staged && sui-lint sass --staged', - 'scripts.lint', - false - ) - addToPackageJson( - 'echo "Skipping tests as they are not present"', - 'scripts.test', - false - ) + addToPackageJson('sui-lint js --staged && sui-lint sass --staged', 'scripts.lint', false) + addToPackageJson('echo "Skipping tests as they are not present"', 'scripts.test', false) addToPackageJson('npm run lint', 'scripts.pre-commit', false) addToPackageJson('npm run test', 'scripts.pre-push', false) removeFromPackageJson('husky') diff --git a/packages/sui-react-head/test/browser/browserSpec.js b/packages/sui-react-head/test/browser/browserSpec.js index b752f6008..eb00129d1 100644 --- a/packages/sui-react-head/test/browser/browserSpec.js +++ b/packages/sui-react-head/test/browser/browserSpec.js @@ -1,17 +1,13 @@ import {expect} from 'chai' -import { - render as testingLibraryRender, - waitForDomChange -} from '@testing-library/react' +import {render as testingLibraryRender, waitForDomChange} from '@testing-library/react' import {descriptorsByEnvironmentPatcher} from '@s-ui/test/lib/descriptor-environment-patcher' import Head, {HeadProvider} from '../../lib/index' descriptorsByEnvironmentPatcher() -const getMetaByName = name => - document.head.querySelector(`meta[name="${name}"]`) +const getMetaByName = name => document.head.querySelector(`meta[name="${name}"]`) const getLinkByRel = rel => document.head.querySelector(`link[rel="${rel}"]`) @@ -90,12 +86,8 @@ describe.client('react-head on client', () => { ) - expect(getMetaByName('meta-1').getAttribute('content')).to.equal( - 'Awesome description' - ) - expect(getMetaByName('meta-2').getAttribute('content')).to.equal( - 'viewport value' - ) + expect(getMetaByName('meta-1').getAttribute('content')).to.equal('Awesome description') + expect(getMetaByName('meta-2').getAttribute('content')).to.equal('viewport value') }) }) @@ -108,12 +100,8 @@ describe.client('react-head on client', () => { ) - expect(getLinkByRel('link-1').getAttribute('href')).to.equal( - 'awesome-link' - ) - expect(getLinkByRel('link-2').getAttribute('href')).to.equal( - 'awesome-value' - ) + expect(getLinkByRel('link-1').getAttribute('href')).to.equal('awesome-link') + expect(getLinkByRel('link-2').getAttribute('href')).to.equal('awesome-value') }) }) @@ -144,19 +132,11 @@ describe.client('react-head on client', () => { /> ) - expect(getMetaByName('meta-1').getAttribute('content')).to.equal( - 'Awesome description' - ) - expect(getMetaByName('meta-2').getAttribute('content')).to.equal( - 'viewport value' - ) + expect(getMetaByName('meta-1').getAttribute('content')).to.equal('Awesome description') + expect(getMetaByName('meta-2').getAttribute('content')).to.equal('viewport value') - expect(getLinkByRel('link-1').getAttribute('href')).to.equal( - 'awesome-link' - ) - expect(getLinkByRel('link-2').getAttribute('href')).to.equal( - 'awesome-value' - ) + expect(getLinkByRel('link-1').getAttribute('href')).to.equal('awesome-link') + expect(getLinkByRel('link-2').getAttribute('href')).to.equal('awesome-value') }) }) }) diff --git a/packages/sui-react-head/test/server/serverSpec.js b/packages/sui-react-head/test/server/serverSpec.js index 1b4e75b7e..86f2acd6c 100644 --- a/packages/sui-react-head/test/server/serverSpec.js +++ b/packages/sui-react-head/test/server/serverSpec.js @@ -45,18 +45,14 @@ describe.server('react-head on server', () => { const headTags = render( My awesome title - + ) - const {headString, bodyAttributes, htmlAttributes} = - renderHeadTagsToString(headTags) + const {headString, bodyAttributes, htmlAttributes} = renderHeadTagsToString(headTags) expect(headString).to.equal( 'My awesome title' @@ -82,8 +78,7 @@ describe.server('react-head on server', () => { /> ) - const {headString, bodyAttributes, htmlAttributes} = - renderHeadTagsToString(headTags) + const {headString, bodyAttributes, htmlAttributes} = renderHeadTagsToString(headTags) expect(headString).to.equal( 'My awesome title' @@ -108,17 +103,13 @@ describe.server('react-head on server', () => { title="Dont use this one" > My awesome title - + ) - const {headString, bodyAttributes, htmlAttributes} = - renderHeadTagsToString(headTags) + const {headString, bodyAttributes, htmlAttributes} = renderHeadTagsToString(headTags) expect(headString).to.equal( 'My awesome title' diff --git a/packages/sui-react-router/src/IndexRoute.js b/packages/sui-react-router/src/IndexRoute.js index 692366e29..97ca87221 100644 --- a/packages/sui-react-router/src/IndexRoute.js +++ b/packages/sui-react-router/src/IndexRoute.js @@ -11,10 +11,7 @@ import {falsy} from './internal/PropTypes.js' * a JSX route config. */ const IndexRoute = () => - invariant( - false, - ' elements are for router configuration only and should not be rendered' - ) + invariant(false, ' elements are for router configuration only and should not be rendered') IndexRoute.displayName = 'IndexRoute' IndexRoute.propTypes = { diff --git a/packages/sui-react-router/src/Link.js b/packages/sui-react-router/src/Link.js index b9338314a..926f2103b 100644 --- a/packages/sui-react-router/src/Link.js +++ b/packages/sui-react-router/src/Link.js @@ -14,8 +14,7 @@ import {useRouter} from './hooks.js' * @param {MouseEvent} event Event fired by a mouse on clicking * @returns {Boolean} Returns if the event has been modified */ -const isModifiedEvent = event => - Boolean(event.metaKey || event.altKey || event.ctrlKey || event.shiftKey) +const isModifiedEvent = event => Boolean(event.metaKey || event.altKey || event.ctrlKey || event.shiftKey) /** * Check if the click is the main one, to avoid the contextual ones @@ -37,8 +36,7 @@ const isManageableTarget = target => !target || target === '_self' * @param {import('./types').Router} router * @returns {String} Location */ -const resolveToLocation = (to, router) => - typeof to === 'function' ? to(router.location) : to +const resolveToLocation = (to, router) => (typeof to === 'function' ? to(router.location) : to) const Link = ({ activeClassName, @@ -74,10 +72,7 @@ const Link = ({ // Ignore if rendered outside the context of router if (!router) { - return invariant( - router, - 's rendered outside of a router context cannot navigate.' - ) + return invariant(router, 's rendered outside of a router context cannot navigate.') } // If user does not specify a `to` prop, return an empty anchor tag @@ -91,8 +86,7 @@ const Link = ({ const isActiveRoute = router.isActive(toLocation, onlyActiveOnIndex) // create className and inline styles depending if the route is active // if empty string, we default to `undefined` to avoid empty class attribute - const className = - cx(restOfProps.className, isActiveRoute && activeClassName) || undefined + const className = cx(restOfProps.className, isActiveRoute && activeClassName) || undefined const style = {...restOfProps.style, ...(isActiveRoute && activeStyle)} const anchorProps = { @@ -122,9 +116,7 @@ Link.propTypes = { /** * Get the underlying ref of the component using React.createRef. */ - innerRef: PropTypes.oneOfType([ - PropTypes.shape({current: PropTypes.elementType}) - ]), + innerRef: PropTypes.oneOfType([PropTypes.shape({current: PropTypes.elementType})]), /** * Function to execute when the element is clicked */ diff --git a/packages/sui-react-router/src/PatternUtils.js b/packages/sui-react-router/src/PatternUtils.js index 5e7a65820..8f4cc9b70 100644 --- a/packages/sui-react-router/src/PatternUtils.js +++ b/packages/sui-react-router/src/PatternUtils.js @@ -70,8 +70,7 @@ function _compilePattern(pattern) { const CompiledPatternsCache = Object.create(null) export function compilePattern(pattern) { - if (!CompiledPatternsCache[pattern]) - CompiledPatternsCache[pattern] = _compilePattern(pattern) + if (!CompiledPatternsCache[pattern]) CompiledPatternsCache[pattern] = _compilePattern(pattern) return CompiledPatternsCache[pattern] } @@ -175,14 +174,9 @@ export function formatPattern(pattern, params = {}) { token = tokens[i] if (token === '*' || token === '**') { - paramValue = Array.isArray(params.splat) - ? params.splat[splatIndex++] - : params.splat + paramValue = Array.isArray(params.splat) ? params.splat[splatIndex++] : params.splat - invariant( - paramValue != null || parenCount > 0, - `Missing splat #${splatIndex} for path "${pattern}"` - ) + invariant(paramValue != null || parenCount > 0, `Missing splat #${splatIndex} for path "${pattern}"`) if (paramValue != null) pathname += encodeURI(paramValue) } else if (token === '(') { @@ -202,10 +196,7 @@ export function formatPattern(pattern, params = {}) { paramName = token.substring(1) paramValue = params[paramName] - invariant( - paramValue != null || parenCount > 0, - `Missing "${paramName}" parameter for path "${pattern}"` - ) + invariant(paramValue != null || parenCount > 0, `Missing "${paramName}" parameter for path "${pattern}"`) if (paramValue == null) { if (parenCount) { @@ -222,18 +213,12 @@ export function formatPattern(pattern, params = {}) { } } - invariant( - nextParenIdx > 0, - `Path "${pattern}" is missing end paren at segment "${tokensSubset.join( - '' - )}"` - ) + invariant(nextParenIdx > 0, `Path "${pattern}" is missing end paren at segment "${tokensSubset.join('')}"`) // jump to ending paren i = curTokenIdx + nextParenIdx - 1 } - } else if (parenCount) - parenHistory[parenCount - 1] += encodeURIComponent(paramValue) + } else if (parenCount) parenHistory[parenCount - 1] += encodeURIComponent(paramValue) else pathname += encodeURIComponent(paramValue) } else { if (parenCount) parenHistory[parenCount - 1] += token diff --git a/packages/sui-react-router/src/Redirect.js b/packages/sui-react-router/src/Redirect.js index 9a46dbe74..77912149a 100644 --- a/packages/sui-react-router/src/Redirect.js +++ b/packages/sui-react-router/src/Redirect.js @@ -4,10 +4,7 @@ import invariant from './internal/invariant.js' import {falsy} from './internal/PropTypes.js' const Redirect = () => - invariant( - false, - ' elements are for router configuration only and should not be rendered' - ) + invariant(false, ' elements are for router configuration only and should not be rendered') Redirect.displayName = 'Redirect' Redirect.propTypes = { diff --git a/packages/sui-react-router/src/Route.js b/packages/sui-react-router/src/Route.js index a300edb37..8c1d97c5b 100644 --- a/packages/sui-react-router/src/Route.js +++ b/packages/sui-react-router/src/Route.js @@ -2,11 +2,7 @@ import PropTypes from 'prop-types' import invariant from './internal/invariant.js' -const Route = () => - invariant( - false, - ' elements are for router configuration only and should not be rendered' - ) +const Route = () => invariant(false, ' elements are for router configuration only and should not be rendered') Route.displayName = 'Route' Route.propTypes = { diff --git a/packages/sui-react-router/src/Router.js b/packages/sui-react-router/src/Router.js index 671b1451e..c3521749d 100644 --- a/packages/sui-react-router/src/Router.js +++ b/packages/sui-react-router/src/Router.js @@ -8,10 +8,7 @@ import RouterContext from './internal/Context.js' import {createTransitionManager} from './internal/createTransitionManager.js' import {components, routes} from './internal/PropTypes.js' import {fromReactTreeToJSON} from './internal/ReactUtils.js' -import { - createRouterHistory, - createRouterObject -} from './internal/RouterUtils.js' +import {createRouterHistory, createRouterObject} from './internal/RouterUtils.js' import Route from './Route.js' const renderRouterContent = ({components, params, router}) => { @@ -28,10 +25,7 @@ const renderRouterContent = ({components, params, router}) => { routes } - return components.reduceRight( - (children, component) => h(component, routerInfo, children), - null - ) + return components.reduceRight((children, component) => h(component, routerInfo, children), null) } const createRoutes = ({children, routes}) => { @@ -59,8 +53,7 @@ const Router = ({ jsonRoutes: createRoutes({children, routes}) }) - const router = - routerFromProps ?? createRouterObject(history, transitionManager.isActive) + const router = routerFromProps ?? createRouterObject(history, transitionManager.isActive) const [state, setState] = useState({router, params, components}) @@ -98,11 +91,7 @@ const Router = ({ return () => unlisten() }, []) // eslint-disable-line - return ( - - {renderRouterContent(state)} - - ) + return {renderRouterContent(state)} } Router.displayName = 'Router' diff --git a/packages/sui-react-router/src/browserHistory.js b/packages/sui-react-router/src/browserHistory.js index f4c2d396b..ca04fcd80 100644 --- a/packages/sui-react-router/src/browserHistory.js +++ b/packages/sui-react-router/src/browserHistory.js @@ -10,8 +10,6 @@ import canUseDOM from './internal/canUseDOM.js' import createMemoryHistory from './createMemoryHistory.js' /** If we're on the server, we must be sure importing this file doesn't break anything */ -const browserHistory = canUseDOM - ? useQueries(useBasename(createBrowserHistory))() - : createMemoryHistory() +const browserHistory = canUseDOM ? useQueries(useBasename(createBrowserHistory))() : createMemoryHistory() export default browserHistory diff --git a/packages/sui-react-router/src/internal/PropTypes.js b/packages/sui-react-router/src/internal/PropTypes.js index fa009b838..6db830f9f 100644 --- a/packages/sui-react-router/src/internal/PropTypes.js +++ b/packages/sui-react-router/src/internal/PropTypes.js @@ -8,8 +8,7 @@ import {arrayOf, element, elementType, object, oneOfType} from 'prop-types' * @return {Error | undefined} Return an Error if the prop value is not falsy */ export function falsy(props, propName, componentName) { - if (props[propName]) - return new Error(`<${componentName}> should not have a "${propName}" prop`) + if (props[propName]) return new Error(`<${componentName}> should not have a "${propName}" prop`) } const route = oneOfType([object, element]) diff --git a/packages/sui-react-router/src/internal/ReactUtils.js b/packages/sui-react-router/src/internal/ReactUtils.js index a6bd10aab..19c3c4c57 100644 --- a/packages/sui-react-router/src/internal/ReactUtils.js +++ b/packages/sui-react-router/src/internal/ReactUtils.js @@ -44,9 +44,7 @@ export const fromReactTreeToJSON = (root, parent = {}, level = 1) => { if (getComponent) node.getComponent = getComponent if (path) node.path = path if (children) - node.children = ReactChildren.toArray(children).map(child => - fromReactTreeToJSON(child, node, level + 1) - ) + node.children = ReactChildren.toArray(children).map(child => fromReactTreeToJSON(child, node, level + 1)) return node } diff --git a/packages/sui-react-router/src/internal/RouterUtils.js b/packages/sui-react-router/src/internal/RouterUtils.js index f7a9662b7..72d171000 100644 --- a/packages/sui-react-router/src/internal/RouterUtils.js +++ b/packages/sui-react-router/src/internal/RouterUtils.js @@ -7,8 +7,7 @@ import canUseDOM from './canUseDOM.js' /** * Create the history that the router will use depending on the environment */ -export const createRouterHistory = options => - canUseDOM ? browserHistory : createMemoryHistory(options) +export const createRouterHistory = options => (canUseDOM ? browserHistory : createMemoryHistory(options)) /** * Create the router object that will be availble in the context with all the needed info @@ -17,11 +16,7 @@ export const createRouterHistory = options => * @param {{ location: string, params: object, routes: array }=} state * @returns { import('../types').Router } */ -export const createRouterObject = ( - history, - isActive, - state = {location: null, params: null, routes: null} -) => { +export const createRouterObject = (history, isActive, state = {location: null, params: null, routes: null}) => { const {location, params, routes} = state return { diff --git a/packages/sui-react-router/src/internal/Tree.js b/packages/sui-react-router/src/internal/Tree.js index 69547498c..e314abc6e 100644 --- a/packages/sui-react-router/src/internal/Tree.js +++ b/packages/sui-react-router/src/internal/Tree.js @@ -6,11 +6,7 @@ * @returns {Boolean} */ function hasChildren(node) { - return ( - typeof node === 'object' && - typeof node.children !== 'undefined' && - node.children.length > 0 - ) + return typeof node === 'object' && typeof node.children !== 'undefined' && node.children.length > 0 } export const Tree = { @@ -20,9 +16,6 @@ export const Tree = { // Stop processing tree structure if no further children if (!hasChildren(node)) return acc // Recursive transverse tree structure - return node.children.reduce( - (acc, currentValue) => Tree.reduce(reducerFn, acc, currentValue), - acc - ) + return node.children.reduce((acc, currentValue) => Tree.reduce(reducerFn, acc, currentValue), acc) } } diff --git a/packages/sui-react-router/src/internal/canUseDOM.js b/packages/sui-react-router/src/internal/canUseDOM.js index 11149f268..a195835fe 100644 --- a/packages/sui-react-router/src/internal/canUseDOM.js +++ b/packages/sui-react-router/src/internal/canUseDOM.js @@ -1,6 +1,2 @@ /** Just export a true or false depending on the environment */ -export default Boolean( - typeof window !== 'undefined' && - window.document && - window.document.createElement -) +export default Boolean(typeof window !== 'undefined' && window.document && window.document.createElement) diff --git a/packages/sui-react-router/src/internal/createTransitionManager.js b/packages/sui-react-router/src/internal/createTransitionManager.js index 5b085b1ac..b99cf7e74 100644 --- a/packages/sui-react-router/src/internal/createTransitionManager.js +++ b/packages/sui-react-router/src/internal/createTransitionManager.js @@ -10,8 +10,7 @@ const INITIAL_MATCH_OBJECT = { paramValues: [] } -const checkIntegrity = nodes => - !nodes.some((node, index) => node.level !== index + 1) +const checkIntegrity = nodes => !nodes.some((node, index) => node.level !== index + 1) const createParams = ({paramValues, paramNames}) => paramNames.reduce((acc, name, index) => { @@ -37,9 +36,7 @@ const findRedirect = nodes => { */ const makePromise = (getComponent, routeInfo) => new Promise((resolve, reject) => { - getComponent(routeInfo, (err, component) => - err ? reject(err) : resolve(component) - ) + getComponent(routeInfo, (err, component) => (err ? reject(err) : resolve(component))) }) const createComponents = ({nodes, routeInfo}) => { @@ -52,9 +49,7 @@ const createComponents = ({nodes, routeInfo}) => { const componentsPromises = nodes .filter(node => node.component || node.getComponent) .map(({component, getComponent}) => { - return component - ? Promise.resolve(component) - : makePromise(getComponent, routeInfo) + return component ? Promise.resolve(component) : makePromise(getComponent, routeInfo) }) // return a promise that will resolve when all components are available return Promise.all(componentsPromises) @@ -156,11 +151,7 @@ const matchRoutes = async (tree, location, remainingPathname) => { remainingPathname } - const match = Tree.reduce( - createReducerRoutesTree(location), - initialObject, - tree - ) + const match = Tree.reduce(createReducerRoutesTree(location), initialObject, tree) const {nodes: nodesFromMatch, paramValues, paramNames} = match const params = createParams({paramNames, paramValues}) @@ -172,9 +163,7 @@ const matchRoutes = async (tree, location, remainingPathname) => { } // if it's not a redirect and still there's remainingPathname then is not a match - const nodes = match.remainingPathname - ? INITIAL_MATCH_OBJECT.nodes - : nodesFromMatch + const nodes = match.remainingPathname ? INITIAL_MATCH_OBJECT.nodes : nodesFromMatch const routeInfo = {location, params, routes: nodes} const components = await createComponents({nodes, routeInfo}) @@ -187,10 +176,7 @@ export const createTransitionManager = ({history, jsonRoutes}) => { let state = {} const matchRouteAndUpdateState = async ({location, jsonRoutes}) => { - const {redirectLocation, routeInfo, components} = await matchRoutes( - jsonRoutes, - location - ) + const {redirectLocation, routeInfo, components} = await matchRoutes(jsonRoutes, location) state = { ...state, @@ -207,9 +193,7 @@ export const createTransitionManager = ({history, jsonRoutes}) => { * @param {import('../types').Location} location Current location object */ const match = location => { - location = location - ? history.createLocation(location) - : history.getCurrentLocation() + location = location ? history.createLocation(location) : history.getCurrentLocation() return matchRouteAndUpdateState({jsonRoutes, location}) } @@ -225,9 +209,7 @@ export const createTransitionManager = ({history, jsonRoutes}) => { listener(null, {params: state.params, components: state.components}) } else { try { - const {redirectLocation, components} = await matchRouteAndUpdateState( - {jsonRoutes, location} - ) + const {redirectLocation, components} = await matchRouteAndUpdateState({jsonRoutes, location}) if (redirectLocation) { return history.replace(redirectLocation) @@ -270,13 +252,7 @@ export const createTransitionManager = ({history, jsonRoutes}) => { const isActive = (location, indexOnly) => { location = history.createLocation(location) - return internalIsActive( - location, - indexOnly, - state.location, - state.routes, - state.params - ) + return internalIsActive(location, indexOnly, state.location, state.routes, state.params) } return { diff --git a/packages/sui-react-router/src/internal/isActive.js b/packages/sui-react-router/src/internal/isActive.js index bcf1e98bd..0e493cb56 100644 --- a/packages/sui-react-router/src/internal/isActive.js +++ b/packages/sui-react-router/src/internal/isActive.js @@ -13,11 +13,7 @@ function deepEqual(a, b) { if (a == null || b == null) return false if (Array.isArray(a)) { - return ( - Array.isArray(b) && - a.length === b.length && - a.every((item, index) => deepEqual(item, b[index])) - ) + return Array.isArray(b) && a.length === b.length && a.every((item, index) => deepEqual(item, b[index])) } if (typeof a === 'object') { @@ -106,10 +102,7 @@ function routeIsActive(pathname, routes, params) { // We have an exact match on the route. Just check that all the params // match. // FIXME: This doesn't work on repeated params. - return paramNames.every( - (paramName, index) => - String(paramValues[index]) === String(params[paramName]) - ) + return paramNames.every((paramName, index) => String(paramValues[index]) === String(params[paramName])) } } } @@ -131,13 +124,7 @@ function queryIsActive(query, activeQuery) { * Check if with a given pathname/query combination is currently active. * @returns {Boolean} Returns true if it matches */ -export default function isActive( - {pathname, query}, - indexOnly, - currentLocation, - routes, - params -) { +export default function isActive({pathname, query}, indexOnly, currentLocation, routes, params) { if (currentLocation == null) return false // TODO: This is a bit ugly. It keeps around support for treating pathnames diff --git a/packages/sui-react-router/src/match.js b/packages/sui-react-router/src/match.js index f26176812..fe4178c50 100644 --- a/packages/sui-react-router/src/match.js +++ b/packages/sui-react-router/src/match.js @@ -5,10 +5,7 @@ import {REPLACE} from 'history/lib/Actions' import {createTransitionManager} from './internal/createTransitionManager.js' import {fromReactTreeToJSON} from './internal/ReactUtils.js' -import { - createRouterHistory, - createRouterObject -} from './internal/RouterUtils.js' +import {createRouterHistory, createRouterObject} from './internal/RouterUtils.js' /** * A high-level API to be used for server-side rendering. @@ -21,16 +18,12 @@ import { * @param {{ history?: object, location, routes: import('react').ComponentType }} options * @param {Function} callback Function to be execute after match */ -export default async ( - {history: externalHistory, location, routes}, - callback -) => { +export default async ({history: externalHistory, location, routes}, callback) => { try { const history = externalHistory || createRouterHistory(location) const jsonRoutes = fromReactTreeToJSON(routes) const transitionManager = createTransitionManager({history, jsonRoutes}) - const {components, redirectLocation, routeInfo} = - await transitionManager.match(location) + const {components, redirectLocation, routeInfo} = await transitionManager.match(location) // if it's not a redirection and we don't have components // then we should response with nothing @@ -45,11 +38,7 @@ export default async ( ...routeInfo } - return callback( - null, - redirectLocation && history.createLocation(redirectLocation, REPLACE), - renderProps - ) + return callback(null, redirectLocation && history.createLocation(redirectLocation, REPLACE), renderProps) } catch (err) { callback(err) } diff --git a/packages/sui-react-router/src/withRouter.js b/packages/sui-react-router/src/withRouter.js index 44813579f..654e82474 100644 --- a/packages/sui-react-router/src/withRouter.js +++ b/packages/sui-react-router/src/withRouter.js @@ -18,7 +18,6 @@ export default (Component, {displayName} = {displayName: ''}) => { return } - WrappedComponent.displayName = - displayName || `withRouter(${Component.displayName || Component.name})` + WrappedComponent.displayName = displayName || `withRouter(${Component.displayName || Component.name})` return hoistNonReactStatics(WrappedComponent, Component) } diff --git a/packages/sui-react-router/test/browser/LinkSpec.js b/packages/sui-react-router/test/browser/LinkSpec.js index 8d19e7bb2..09002ee85 100644 --- a/packages/sui-react-router/test/browser/LinkSpec.js +++ b/packages/sui-react-router/test/browser/LinkSpec.js @@ -139,20 +139,12 @@ describe('', () => { )} /> - Link} - /> + Link} /> ) it('is active when its params match', async () => { - render( - - ) + render() fireEvent.click(await screen.findByText('Link')) const link = await screen.findByText('Link to Michael') expect(link.getAttribute('class')).to.equal('active') @@ -160,12 +152,7 @@ describe('', () => { }) it('is not active when its params dont match', async () => { - render( - - ) + render() fireEvent.click(await screen.findByText('Link')) const link = await screen.findByText('Link to Michael') expect(link.getAttribute('class')).to.equal(null) diff --git a/packages/sui-react-router/test/common/IndexRouteSpec.js b/packages/sui-react-router/test/common/IndexRouteSpec.js index f1fcdd656..7becb66f9 100644 --- a/packages/sui-react-router/test/common/IndexRouteSpec.js +++ b/packages/sui-react-router/test/common/IndexRouteSpec.js @@ -8,9 +8,7 @@ import {IndexRoute, match, Route, Router} from '../../src/index.js' const getRenderedString = ({location = '/', withRoutes}) => { return new Promise(resolve => { - match({routes: withRoutes, location}, (_, __, renderProps) => - resolve(renderToString()) - ) + match({routes: withRoutes, location}, (_, __, renderProps) => resolve(renderToString())) }) } @@ -45,9 +43,7 @@ describe('', () => { location: '/test' }) - expect(renderedString).to.equal( - '
parent:
parent: child
' - ) + expect(renderedString).to.equal('
parent:
parent: child
') }) it('renders when its parents combined pathes match', async () => { @@ -65,9 +61,7 @@ describe('', () => { location: '/path/test' }) - expect(renderedString).to.equal( - '
parent:
parent: child
' - ) + expect(renderedString).to.equal('
parent:
parent: child
') }) it('renders when its parents combined pathes match, and its direct parent is path less', async () => { @@ -87,9 +81,7 @@ describe('', () => { location: '/' }) - expect(renderedString).to.equal( - '
parent:
parent:
parent: child
' - ) + expect(renderedString).to.equal('
parent:
parent:
parent: child
') }) }) }) diff --git a/packages/sui-react-router/test/common/LinkSpec.js b/packages/sui-react-router/test/common/LinkSpec.js index a3c186863..3467b4e2d 100644 --- a/packages/sui-react-router/test/common/LinkSpec.js +++ b/packages/sui-react-router/test/common/LinkSpec.js @@ -6,9 +6,7 @@ import {Link, match, Route, Router} from '../../src/index.js' const getRenderedString = ({location = '/', withRoutes}) => { return new Promise(resolve => { - match({routes: withRoutes, location}, (_, __, renderProps) => - resolve(renderToString()) - ) + match({routes: withRoutes, location}, (_, __, renderProps) => resolve(renderToString())) }) } diff --git a/packages/sui-react-router/test/common/RedirectSpec.js b/packages/sui-react-router/test/common/RedirectSpec.js index 6e9a21dda..4a11d4181 100644 --- a/packages/sui-react-router/test/common/RedirectSpec.js +++ b/packages/sui-react-router/test/common/RedirectSpec.js @@ -4,9 +4,7 @@ import {match, Redirect, Route} from '../../src/index.js' const getRedirectLocationFor = ({path = '/', withRoutes}) => { return new Promise(resolve => { - match({routes: withRoutes, location: path}, (_, redirectLocation) => - resolve(redirectLocation) - ) + match({routes: withRoutes, location: path}, (_, redirectLocation) => resolve(redirectLocation)) }) } diff --git a/packages/sui-react-router/test/common/RouteSpec.js b/packages/sui-react-router/test/common/RouteSpec.js index 0d87e1728..020f7388c 100644 --- a/packages/sui-react-router/test/common/RouteSpec.js +++ b/packages/sui-react-router/test/common/RouteSpec.js @@ -45,9 +45,7 @@ describe('', () => { it('Path over Regexp', async () => { const Component = () =>
Hello word
const regexp = /^\/de$/ - const withRoutes = ( - - ) + const withRoutes = const renderedString = await getRenderedString({ location: '/es', withRoutes @@ -59,10 +57,7 @@ describe('', () => { const Component = () =>
Hello word
const regexp = /^\/deeplevel$/ const withRoutes = ( -

Layout: {children}

} - > +

Layout: {children}

}> ) @@ -81,10 +76,7 @@ describe('', () => { ) const regexp = /^\/user\/(?\d+)/ const withRoutes = ( -

Layout: {children}

} - > +

Layout: {children}

}> ', () => { location: '/es/user/123/comment/456', withRoutes }) - expect(renderedString).to.equal( - '

Layout:
Hello word

123

456

' - ) + expect(renderedString).to.equal('

Layout:
Hello word

123

456

') }) it("doesn't render unmatched regexp", async () => { @@ -214,9 +204,7 @@ describe('', () => { withRoutes }) - expect(renderedString).to.equal( - '
App

The HomePage

' - ) + expect(renderedString).to.equal('
App

The HomePage

') }) it('works with dynamic paths', async () => { @@ -231,9 +219,7 @@ describe('', () => { withRoutes }) - expect(renderedString).to.equal( - '
App

Search Results: money

' - ) + expect(renderedString).to.equal('
App

Search Results: money

') }) it('do not match when only part of the nested route is matched', async () => { @@ -255,10 +241,7 @@ describe('', () => { const withRoutes = ( - new Error('do not match ')} - /> + new Error('do not match ')} /> ) @@ -267,9 +250,7 @@ describe('', () => { withRoutes }) - expect(renderedString).to.equal( - '
App

Search Results:

' - ) + expect(renderedString).to.equal('
App

Search Results:

') }) it('match the last route if previous dont working', async () => { diff --git a/packages/sui-react-router/test/common/getParamsSpec.js b/packages/sui-react-router/test/common/getParamsSpec.js index 40280a098..7df0d3f90 100644 --- a/packages/sui-react-router/test/common/getParamsSpec.js +++ b/packages/sui-react-router/test/common/getParamsSpec.js @@ -147,9 +147,7 @@ describe('getParams', () => { expect(getParams('/files/*.jpg', '/files/my/photo.jpg')).to.deep.equal({ splat: 'my/photo' }) - expect( - getParams('/files/*.jpg', '/files/my/new%0Aline.jpg') - ).to.deep.equal({ + expect(getParams('/files/*.jpg', '/files/my/new%0Aline.jpg')).to.deep.equal({ splat: 'my/new\nline' }) }) diff --git a/packages/sui-react-router/test/common/hooksSpec.js b/packages/sui-react-router/test/common/hooksSpec.js index eb22e5ed1..43a7dde4f 100644 --- a/packages/sui-react-router/test/common/hooksSpec.js +++ b/packages/sui-react-router/test/common/hooksSpec.js @@ -2,20 +2,11 @@ import {renderToString} from 'react-dom/server' import {expect} from 'chai' -import { - match, - Route, - Router, - useLocation, - useParams, - useRouter -} from '../../src/index.js' +import {match, Route, Router, useLocation, useParams, useRouter} from '../../src/index.js' const getRenderedString = ({location = '/', withRoutes}) => { return new Promise(resolve => { - match({routes: withRoutes, location}, (_, __, renderProps) => - resolve(renderToString()) - ) + match({routes: withRoutes, location}, (_, __, renderProps) => resolve(renderToString())) }) } @@ -44,9 +35,7 @@ describe('Hooks', () => { params = useParams() return null } - const withRoutes = ( - - ) + const withRoutes = await getRenderedString({ location: '/post/technology/new-product', withRoutes diff --git a/packages/sui-react-router/test/common/isActiveSpec.js b/packages/sui-react-router/test/common/isActiveSpec.js index b637162e8..6d0720bf0 100644 --- a/packages/sui-react-router/test/common/isActiveSpec.js +++ b/packages/sui-react-router/test/common/isActiveSpec.js @@ -29,33 +29,19 @@ describe('isActive', () => { describe('with a query that also matches', () => { it('is active', () => { - expect( - isActive(LOCATIONS.HOME_WITH_QUERY, false, LOCATIONS.HOME_WITH_QUERY) - ).to.be.true + expect(isActive(LOCATIONS.HOME_WITH_QUERY, false, LOCATIONS.HOME_WITH_QUERY)).to.be.true }) }) describe('with a query that also matches by value, but not by type', () => { it('is active', () => { - expect( - isActive( - LOCATIONS.HOME_WITH_QUERY, - false, - LOCATIONS.HOME_WITH_QUERY_STRING - ) - ).to.be.true + expect(isActive(LOCATIONS.HOME_WITH_QUERY, false, LOCATIONS.HOME_WITH_QUERY_STRING)).to.be.true }) }) describe('with a query that does not match', () => { it('is not active', () => { - expect( - isActive( - LOCATIONS.HOME_WITH_QUERY, - false, - LOCATIONS.HOME_WITH_OTHER_QUERY - ) - ).to.be.false + expect(isActive(LOCATIONS.HOME_WITH_QUERY, false, LOCATIONS.HOME_WITH_OTHER_QUERY)).to.be.false }) }) }) diff --git a/packages/sui-react-router/test/common/matchPatternSpec.js b/packages/sui-react-router/test/common/matchPatternSpec.js index b06f8546c..f5d700e08 100644 --- a/packages/sui-react-router/test/common/matchPatternSpec.js +++ b/packages/sui-react-router/test/common/matchPatternSpec.js @@ -5,13 +5,7 @@ import {expect} from 'chai' import {matchPattern} from '../../src/PatternUtils.js' describe('matchPattern', () => { - function assertMatch( - pattern, - pathname, - remainingPathname, - paramNames, - paramValues - ) { + function assertMatch(pattern, pathname, remainingPathname, paramNames, paramValues) { expect(matchPattern(pattern, pathname)).to.deep.equal({ remainingPathname, paramNames, @@ -34,13 +28,7 @@ describe('matchPattern', () => { }) it('works with splat params', () => { - assertMatch( - '/files/*.*', - '/files/path.jpg', - '', - ['splat', 'splat'], - ['path', 'jpg'] - ) + assertMatch('/files/*.*', '/files/path.jpg', '', ['splat', 'splat'], ['path', 'jpg']) }) it('ignores trailing slashes', () => { @@ -52,13 +40,7 @@ describe('matchPattern', () => { }) it('works with greedy and non-greedy splat', () => { - assertMatch( - '/**/*.jpg', - '/files/path/to/file.jpg', - '', - ['splat', 'splat'], - ['files/path/to', 'file'] - ) + assertMatch('/**/*.jpg', '/files/path/to/file.jpg', '', ['splat', 'splat'], ['files/path/to', 'file']) }) it('works with patterns that match built-in names', () => { diff --git a/packages/sui-react-router/test/common/matchSpec.js b/packages/sui-react-router/test/common/matchSpec.js index fe327e619..3d3514a9e 100644 --- a/packages/sui-react-router/test/common/matchSpec.js +++ b/packages/sui-react-router/test/common/matchSpec.js @@ -4,10 +4,8 @@ import {match, Redirect, Route} from '../../src/index.js' const matchPromise = ({location = '/', withRoutes}) => { return new Promise(resolve => { - match( - {routes: withRoutes, location}, - (err, redirectLocation, renderProps) => - resolve({err, redirectLocation, renderProps}) + match({routes: withRoutes, location}, (err, redirectLocation, renderProps) => + resolve({err, redirectLocation, renderProps}) ) }) } diff --git a/packages/sui-react-router/test/common/withRouterSpec.js b/packages/sui-react-router/test/common/withRouterSpec.js index 1fbaecac7..e74c62bcc 100644 --- a/packages/sui-react-router/test/common/withRouterSpec.js +++ b/packages/sui-react-router/test/common/withRouterSpec.js @@ -6,9 +6,7 @@ import {match, Route, Router, withRouter} from '../../src/index.js' const getRenderedString = ({location = '/', withRoutes}) => { return new Promise(resolve => { - match({routes: withRoutes, location}, (_, __, renderProps) => - resolve(renderToString()) - ) + match({routes: withRoutes, location}, (_, __, renderProps) => resolve(renderToString())) }) } @@ -36,26 +34,17 @@ describe('withRouter', function () { await getRenderedString({withRoutes}) - expect(injectedProps).to.include.keys( - 'location', - 'params', - 'routes', - 'router' - ) + expect(injectedProps).to.include.keys('location', 'params', 'routes', 'router') expect(injectedProps.otherProp).to.equal(true) }) it('should set displayName automatically', async () => { - expect(withRouter(EmptyComponent).displayName).to.equal( - 'withRouter(EmptyComponent)' - ) + expect(withRouter(EmptyComponent).displayName).to.equal('withRouter(EmptyComponent)') }) it('should use displayName if passed as parameter', async () => { const displayName = 'AwesomeComponent' - expect(withRouter(EmptyComponent, {displayName}).displayName).to.equal( - displayName - ) + expect(withRouter(EmptyComponent, {displayName}).displayName).to.equal(displayName) }) }) diff --git a/packages/sui-react-web-vitals/src/index.js b/packages/sui-react-web-vitals/src/index.js index 0fe2d5c93..33c3f4f62 100644 --- a/packages/sui-react-web-vitals/src/index.js +++ b/packages/sui-react-web-vitals/src/index.js @@ -23,12 +23,7 @@ const RATING = { POOR: 'poor' } -const DEFAULT_METRICS_REPORTING_ALL_CHANGES = [ - METRICS.CLS, - METRICS.FID, - METRICS.INP, - METRICS.LCP -] +const DEFAULT_METRICS_REPORTING_ALL_CHANGES = [METRICS.CLS, METRICS.FID, METRICS.INP, METRICS.LCP] const DEFAULT_CWV_THRESHOLDS = { [METRICS.CLS]: 100, @@ -100,8 +95,7 @@ export default function WebVitalsReporter({ const amount = name === METRICS.CLS ? value * 1000 : value const pathname = getPathname(route) const hasPathOnRoute = getHasPathOnRoute(route) - const isExcluded = - !pathname || (Array.isArray(pathnames) && !pathnames.includes(pathname)) + const isExcluded = !pathname || (Array.isArray(pathnames) && !pathnames.includes(pathname)) if (isExcluded || !logger?.cwv || rating === RATING.GOOD) return @@ -124,8 +118,7 @@ export default function WebVitalsReporter({ const hasPathOnRoute = getHasPathOnRoute(route) const routeid = getRouteid() const type = getDeviceType() - const isExcluded = - !pathname || (Array.isArray(pathnames) && !pathnames.includes(pathname)) + const isExcluded = !pathname || (Array.isArray(pathnames) && !pathnames.includes(pathname)) if (isExcluded) return @@ -178,8 +171,7 @@ export default function WebVitalsReporter({ metrics.forEach(metric => { reporter[`on${metric}`](handleChange) - if (metricsAllChanges.includes(metric)) - reporter[`on${metric}`](handleAllChanges, {reportAllChanges: true}) + if (metricsAllChanges.includes(metric)) reporter[`on${metric}`](handleAllChanges, {reportAllChanges: true}) }) }) diff --git a/packages/sui-sass-loader/src/index.js b/packages/sui-sass-loader/src/index.js index e5371b506..9915f10c7 100644 --- a/packages/sui-sass-loader/src/index.js +++ b/packages/sui-sass-loader/src/index.js @@ -14,10 +14,8 @@ const utils = require('./utils.js') const BOM_HEADER = '\uFEFF' const EXT_PRECEDENCE = ['.scss', '.css'] const MATCH_URL_ALL = /url\(\s*(['"]?)([^ '"()]+)(\1)\s*\)/g -const MATCH_IMPORTS = - /@import\s+(['"])([^,;'"]+)(\1)(\s*,\s*(['"])([^,;'"]+)(\1))*\s*;/g -const MATCH_USES = - /@use\s+(['"])([^,;'"]+)(\1)(\s*,\s*(['"])([^,;'"]+)(\1))*\s*;/g +const MATCH_IMPORTS = /@import\s+(['"])([^,;'"]+)(\1)(\s*,\s*(['"])([^,;'"]+)(\1))*\s*;/g +const MATCH_USES = /@use\s+(['"])([^,;'"]+)(\1)(\s*,\s*(['"])([^,;'"]+)(\1))*\s*;/g const MATCH_FILES = /(['"])([^,;'"]+)(\1)/g /** @@ -79,11 +77,7 @@ function getImportsToResolve(original, includePaths, transformers) { }) }) - return [ - ...imports, - path.join(dirname, `${basename}/index.scss`), - path.join(dirname, `${basename}/_index.scss`) - ] + return [...imports, path.join(dirname, `${basename}/index.scss`), path.join(dirname, `${basename}/_index.scss`)] } function createTransformersMap(transformers) { @@ -106,9 +100,7 @@ function createTransformersMap(transformers) { * @return {Array} List of transformed path */ const transformRelativeToAbsolutePaths = ({baseUrl, paths}) => { - return paths.map(currentPath => - path.isAbsolute(currentPath) ? currentPath : path.join(baseUrl, currentPath) - ) + return paths.map(currentPath => (path.isAbsolute(currentPath) ? currentPath : path.join(baseUrl, currentPath))) } /** @@ -133,18 +125,9 @@ function getLoaderConfig(ctx) { } const options = utils.mergeDeep(defaults, ctx.getOptions() || {}) - const { - data, - includePaths, - implementation = require('sass'), - resolveURLs, - root, - sassOptions, - transformers - } = options + const {data, includePaths, implementation = require('sass'), resolveURLs, root, sassOptions, transformers} = options - const basedir = - ctx.rootContext || options.context || ctx.options.context || process.cwd() + const basedir = ctx.rootContext || options.context || ctx.options.context || process.cwd() // get webpack config from context ctx const {alias, modules} = getWebpackConfig(ctx) @@ -167,14 +150,7 @@ function getLoaderConfig(ctx) { } } -function* mergeSources( - opts, - entry, - resolve, - dependencies = [], - level = 0, - uses -) { +function* mergeSources(opts, entry, resolve, dependencies = [], level = 0, uses) { const {alias, includePaths, modules, transformers, sassOptions = {}} = opts const {importer} = sassOptions let content @@ -215,9 +191,7 @@ function* mergeSources( // test again if (loaderUtils.isUrlRequest(file)) { const absoluteFile = path.normalize(path.resolve(entryDir, file)) - let relativeFile = path - .relative(opts.baseEntryDir, absoluteFile) - .replace(/\\/g, '/') // fix for windows path + let relativeFile = path.relative(opts.baseEntryDir, absoluteFile).replace(/\\/g, '/') // fix for windows path if (relativeFile[0] !== '.') { relativeFile = './' + relativeFile @@ -282,20 +256,14 @@ function* mergeSources( // eslint-disable-line const originalImport = matched[2].trim() if (!originalImport) { - const err = new Error( - `import file cannot be empty: "${total}" @${entry}` - ) + const err = new Error(`import file cannot be empty: "${total}" @${entry}`) err.file = entry throw err } - const imports = getImportsToResolve( - originalImport, - includePaths, - transformers - ) + const imports = getImportsToResolve(originalImport, includePaths, transformers) let resolvedImport @@ -356,9 +324,7 @@ function* mergeSources( } if (!resolvedImport) { - const err = new Error( - `import file cannot be resolved: "${total}" @${entry}` - ) + const err = new Error(`import file cannot be resolved: "${total}" @${entry}`) err.file = entry @@ -370,16 +336,7 @@ function* mergeSources( if (!dependencies.includes(resolvedImport)) { dependencies.push(resolvedImport) - contents.push( - yield mergeSources( - opts, - resolvedImport, - resolve, - dependencies, - level + 1, - uses - ) - ) + contents.push(yield mergeSources(opts, resolvedImport, resolve, dependencies, level + 1, uses)) } } diff --git a/packages/sui-sass-loader/src/replace.js b/packages/sui-sass-loader/src/replace.js index 202000807..d39bd8e75 100644 --- a/packages/sui-sass-loader/src/replace.js +++ b/packages/sui-sass-loader/src/replace.js @@ -15,11 +15,7 @@ async function replaceAsync(text, rule, replacer) { rule.lastIndex = 0 while ((matches = rule.exec(text))) { - ranges.push([ - rule.lastIndex - matches[0].length, - rule.lastIndex, - matches.slice() - ]) + ranges.push([rule.lastIndex - matches[0].length, rule.lastIndex, matches.slice()]) } const results = [] diff --git a/packages/sui-sass-loader/src/utils.js b/packages/sui-sass-loader/src/utils.js index 8cde39106..60139b697 100644 --- a/packages/sui-sass-loader/src/utils.js +++ b/packages/sui-sass-loader/src/utils.js @@ -12,8 +12,7 @@ const COMMENTS_RULE_MAPS = { * @param {any} item - The item to check * @returns {boolean} */ -const isObject = item => - item && typeof item === 'object' && !Array.isArray(item) +const isObject = item => item && typeof item === 'object' && !Array.isArray(item) function mergeDeep(target, ...sources) { if (!sources.length) return target diff --git a/packages/sui-ssr/archive/index.js b/packages/sui-ssr/archive/index.js index df293792b..52eff1ac8 100644 --- a/packages/sui-ssr/archive/index.js +++ b/packages/sui-ssr/archive/index.js @@ -8,17 +8,11 @@ const {auth, outputFileName} = program.opts() module.exports = ({outputZipPath, pkg, entryPoint, dockerRegistry}) => new Promise((resolve, reject) => { - const authVariableDefinition = auth - ? authDefinitionBuilder(auth.split(':')) - : '' - const entryPointPreWork = !entryPoint - ? '' - : 'COPY ./entry-point ./entry-point\nRUN chmod +x ./entry-point' + const authVariableDefinition = auth ? authDefinitionBuilder(auth.split(':')) : '' + const entryPointPreWork = !entryPoint ? '' : 'COPY ./entry-point ./entry-point\nRUN chmod +x ./entry-point' const entryPointLine = !entryPoint ? '' : 'ENTRYPOINT ["./entry-point"]' - const output = outputFileName - ? fs.createWriteStream(outputZipPath) - : process.stdout + const output = outputFileName ? fs.createWriteStream(outputZipPath) : process.stdout const archive = archiver('zip', { zlib: {level: 9} }) @@ -29,8 +23,7 @@ module.exports = ({outputZipPath, pkg, entryPoint, dockerRegistry}) => '-> File', outputFileName.magenta.bold + '.zip'.magenta.bold, ' was created - size ', - Math.round(archive.pointer() / 1024).toString().blue.bold + - ' kb'.blue.bold + Math.round(archive.pointer() / 1024).toString().blue.bold + ' kb'.blue.bold ) // eslint-disable-next-line no-console console.log(' -> Success ✅'.green) @@ -39,24 +32,18 @@ module.exports = ({outputZipPath, pkg, entryPoint, dockerRegistry}) => }) archive.on('error', reject) archive.pipe(output) - archive.append( - fs.readFileSync(path.join(process.cwd(), 'package.json'), 'utf8'), - { - name: 'package.json' - } - ) + archive.append(fs.readFileSync(path.join(process.cwd(), 'package.json'), 'utf8'), { + name: 'package.json' + }) entryPoint && archive.append(fs.readFileSync(entryPoint, 'utf8'), { name: 'entry-point' }) - archive.append( - fs - .readFileSync(path.join(__dirname, 'pm2.tpl'), 'utf8') - .replace('{{name}}', pkg.name), - {name: 'pm2.json'} - ) + archive.append(fs.readFileSync(path.join(__dirname, 'pm2.tpl'), 'utf8').replace('{{name}}', pkg.name), { + name: 'pm2.json' + }) archive.append( fs diff --git a/packages/sui-ssr/bin/sui-ssr-archive.js b/packages/sui-ssr/bin/sui-ssr-archive.js index a23401b6d..04001c158 100755 --- a/packages/sui-ssr/bin/sui-ssr-archive.js +++ b/packages/sui-ssr/bin/sui-ssr-archive.js @@ -55,10 +55,7 @@ if (clean) { const archiveEntryPoint = entryPoint && path.resolve(entryPoint) const registry = dockerRegistry && `${dockerRegistry}/` -const OUTPUT_ZIP_PATH = path.join( - process.cwd(), - `${outputFileName}-sui-ssr.zip` -) +const OUTPUT_ZIP_PATH = path.join(process.cwd(), `${outputFileName}-sui-ssr.zip`) ;(async () => { // console.log(' -> Compressing files... 🗄'.yellow) await archive({ diff --git a/packages/sui-ssr/bin/sui-ssr-build.js b/packages/sui-ssr/bin/sui-ssr-build.js index 7057d3359..cba270f18 100755 --- a/packages/sui-ssr/bin/sui-ssr-build.js +++ b/packages/sui-ssr/bin/sui-ssr-build.js @@ -75,22 +75,12 @@ const build = () => const html = readFileSync(path.join(PUBLIC_PATH, 'index.html'), 'utf-8') const htmlWithoutThirdParties = removeMarkedTags(html) - writeFileSync( - path.join(PUBLIC_PATH, 'index_without_third_parties.html'), - htmlWithoutThirdParties, - 'utf-8' - ) + writeFileSync(path.join(PUBLIC_PATH, 'index_without_third_parties.html'), htmlWithoutThirdParties, 'utf-8') // copy 404.html and 500.html from public const [copy404, copy500] = await Promise.allSettled([ - copyFile( - path.join(SRC_PATH, '404.html'), - path.join(PUBLIC_PATH, '404.html') - ), - copyFile( - path.join(SRC_PATH, '500.html'), - path.join(PUBLIC_PATH, '500.html') - ) + copyFile(path.join(SRC_PATH, '404.html'), path.join(PUBLIC_PATH, '404.html')), + copyFile(path.join(SRC_PATH, '500.html'), path.join(PUBLIC_PATH, '500.html')) ]) copy404.status === 'fulfilled' && console.log('404.html copied!') diff --git a/packages/sui-ssr/bin/sui-ssr-release.js b/packages/sui-ssr/bin/sui-ssr-release.js index bca718ee5..b26d233c9 100755 --- a/packages/sui-ssr/bin/sui-ssr-release.js +++ b/packages/sui-ssr/bin/sui-ssr-release.js @@ -15,12 +15,8 @@ program .on('--help', () => { console.log(' Description:') console.log('') - console.log( - ' Release a server version. Create a git tag and update a minor version in the package.json' - ) - console.log( - ' It is mandatory setup a $GITHUB_TOKEN envVar to execute this command' - ) + console.log(' Release a server version. Create a git tag and update a minor version in the package.json') + console.log(' It is mandatory setup a $GITHUB_TOKEN envVar to execute this command') console.log('') console.log(' Examples:') console.log('') @@ -29,14 +25,7 @@ program }) .parse(process.argv) -const { - branch = 'master', - email, - name, - skipCi = false, - commit, - npm7 = false -} = program.opts() +const {branch = 'master', email, name, skipCi = false, commit, npm7 = false} = program.opts() const execute = async (cmd, full) => { try { @@ -57,11 +46,7 @@ const getCommitToTag = async () => { return execute('git rev-parse HEAD') } -const getNpmInstall = ({ - legacyPeerDeps: hasLegacyPeerDeps, - packageLockOnly, - only: onlyScope -} = {}) => { +const getNpmInstall = ({legacyPeerDeps: hasLegacyPeerDeps, packageLockOnly, only: onlyScope} = {}) => { const installCommand = [ 'npm install', hasLegacyPeerDeps && '--legacy-peer-deps', @@ -123,18 +108,11 @@ const getNpmInstall = ({ await execute('npm version minor --no-git-tag-version') const nextVersion = require(path.join(cwd, 'package.json')).version - await execute( - `git add ${path.join(cwd, 'package.json')} ${path.join( - cwd, - 'package-lock.json' - )}` - ) + await execute(`git add ${path.join(cwd, 'package.json')} ${path.join(cwd, 'package-lock.json')}`) const skipCiMessage = skipCi ? '[skip ci]' : '' - await execute( - `git commit -m "release(META): ${nextVersion} ${skipCiMessage}"` - ) + await execute(`git commit -m "release(META): ${nextVersion} ${skipCiMessage}"`) await execute(`git tag -a "v${nextVersion}" -m "v${nextVersion}"`) await execute('git status') await execute(`git push --set-upstream --tags origin ${branch}`) diff --git a/packages/sui-ssr/build-device.js b/packages/sui-ssr/build-device.js index 3c8a13994..c6f2a6b9c 100644 --- a/packages/sui-ssr/build-device.js +++ b/packages/sui-ssr/build-device.js @@ -7,8 +7,6 @@ export var buildDeviceFrom = function (params) { return { // https://tc39.github.io/proposal-optional-chaining/ - userAgent: - (request.headers && request.headers['user-agent']) || - (win.navigator && win.navigator.userAgent) + userAgent: (request.headers && request.headers['user-agent']) || (win.navigator && win.navigator.userAgent) } } diff --git a/packages/sui-ssr/scripts/remove-tags.js b/packages/sui-ssr/scripts/remove-tags.js index c43c4f994..8c84c350f 100644 --- a/packages/sui-ssr/scripts/remove-tags.js +++ b/packages/sui-ssr/scripts/remove-tags.js @@ -2,10 +2,7 @@ const parse5 = require('parse5') function hasChildren(node) { return ( - typeof node === 'object' && - node.childNodes && - typeof node.childNodes !== 'undefined' && - node.childNodes.length > 0 + typeof node === 'object' && node.childNodes && typeof node.childNodes !== 'undefined' && node.childNodes.length > 0 ) } @@ -21,10 +18,7 @@ const _removeMarkedTags = document => { const prevNode = document.childNodes[index - 1] - if ( - prevNode.nodeName === '#comment' && - (prevNode.data || '').indexOf('THIRD_PARTY') > -1 - ) { + if (prevNode.nodeName === '#comment' && (prevNode.data || '').indexOf('THIRD_PARTY') > -1) { return false } diff --git a/packages/sui-ssr/server/config.js b/packages/sui-ssr/server/config.js index b9cc5b50b..d6d2afac7 100644 --- a/packages/sui-ssr/server/config.js +++ b/packages/sui-ssr/server/config.js @@ -5,14 +5,11 @@ const DEFAULT_VALUES = { useLegacyContext: true } -const ASYNC_CSS_ATTRS = - 'rel="stylesheet" media="print" as="style" onload="this.media=\'all\'"' +const ASYNC_CSS_ATTRS = 'rel="stylesheet" media="print" as="style" onload="this.media=\'all\'"' let ssrConfig try { - const spaConfig = JSON.parse( - fs.readFileSync(path.join(process.cwd(), 'package.json'), 'utf8') - ) + const spaConfig = JSON.parse(fs.readFileSync(path.join(process.cwd(), 'package.json'), 'utf8')) const {config = {}} = spaConfig ssrConfig = config['sui-ssr'] || {} } catch (e) { diff --git a/packages/sui-ssr/server/hooksFactory/index.js b/packages/sui-ssr/server/hooksFactory/index.js index a21b170d9..6910b9883 100644 --- a/packages/sui-ssr/server/hooksFactory/index.js +++ b/packages/sui-ssr/server/hooksFactory/index.js @@ -35,10 +35,9 @@ const getStaticErrorPageContent = async (status, req) => { if (__PAGES__[status]) { return __PAGES__[status] } - const html = await promisify(readFile)( - resolve(process.cwd(), publicFolder(req), `${status}.html`), - 'utf8' - ).catch(() => `Generic Error Page: ${status}`) + const html = await promisify(readFile)(resolve(process.cwd(), publicFolder(req), `${status}.html`), 'utf8').catch( + () => `Generic Error Page: ${status}` + ) __PAGES__[status] = html return html } @@ -53,9 +52,7 @@ const builAppConfig = (req, res, next) => { export const hooksFactory = async () => { const _userHooksInterOP = userHooks.default || userHooks - const _userHooks = isFunction(_userHooksInterOP) - ? await _userHooksInterOP() - : _userHooksInterOP + const _userHooks = isFunction(_userHooksInterOP) ? await _userHooksInterOP() : _userHooksInterOP return { [TYPES.PRE_HEALTH]: NULL_MDWL, @@ -114,8 +111,7 @@ export const hooksFactory = async () => { return next() }, [TYPES.LOGGING]: NULL_MDWL, - [TYPES.CSP_REPORT]: (req, res) => - res.status(200).json({message: 'Tracking disabled'}), + [TYPES.CSP_REPORT]: (req, res) => res.status(200).json({message: 'Tracking disabled'}), [TYPES.PRE_STATIC_PUBLIC]: NULL_MDWL, [TYPES.SETUP_CONTEXT]: async (req, res, next) => { const startContextCreationTime = process.hrtime() @@ -135,17 +131,13 @@ export const hooksFactory = async () => { [TYPES.PRE_SSR_HANDLER]: NULL_MDWL, [TYPES.APP_CONFIG_SETUP]: builAppConfig, [TYPES.NOT_FOUND]: async (req, res) => { - res - .status(NOT_FOUND_CODE) - .send(await getStaticErrorPageContent(NOT_FOUND_CODE, req)) + res.status(NOT_FOUND_CODE).send(await getStaticErrorPageContent(NOT_FOUND_CODE, req)) }, [TYPES.INTERNAL_ERROR]: async (err, req, res) => { // getInitialProps could throw a 404 error or any other error req.log && req.log.error && req.log.error((' ' + err.message).slice(1)) const status = - err.message && err.message.includes(NOT_FOUND_CODE) - ? NOT_FOUND_CODE - : err.status || INTERNAL_ERROR_CODE + err.message && err.message.includes(NOT_FOUND_CODE) ? NOT_FOUND_CODE : err.status || INTERNAL_ERROR_CODE // Prevents from trying to send headers twice (fatal error) when earlyFlush is enabled if (!res.headersSent) { diff --git a/packages/sui-ssr/server/index.js b/packages/sui-ssr/server/index.js index 9eed1cae9..f449f7a6b 100644 --- a/packages/sui-ssr/server/index.js +++ b/packages/sui-ssr/server/index.js @@ -9,12 +9,7 @@ import TYPES from '../hooks-types.js' import {hooksFactory} from './hooksFactory/index.js' import staticCriticalCss from './middlewares/criticalCss.js' import ssr from './middlewares/ssr.js' -import { - hostFromReq, - isMultiSite, - readHtmlTemplate, - useStaticsByHost -} from './utils/index.js' +import {hostFromReq, isMultiSite, readHtmlTemplate, useStaticsByHost} from './utils/index.js' import ssrConf from './config.js' noOPConsole(console) @@ -30,10 +25,7 @@ app.set('x-powered-by', false) // true: will flush before getInitialProps() was called favoring TTFB // false: will flush after getInitialProps() was called const EARLY_FLUSH_DEFAULT = true -app.locals.earlyFlush = - typeof ssrConf.earlyFlush !== 'undefined' - ? ssrConf.earlyFlush - : EARLY_FLUSH_DEFAULT +app.locals.earlyFlush = typeof ssrConf.earlyFlush !== 'undefined' ? ssrConf.earlyFlush : EARLY_FLUSH_DEFAULT const {PORT = 3000, AUTH_USERNAME, AUTH_PASSWORD} = process.env const runningUnderAuth = AUTH_USERNAME && AUTH_PASSWORD @@ -49,20 +41,14 @@ const _memoizedHtmlTemplatesMapping = {} app.use(hooks[TYPES.BOOTSTRAP]) app.use(hooks[TYPES.PRE_HEALTH]) - app.get('/_health', (req, res) => - res.status(200).json({uptime: process.uptime()}) - ) + app.get('/_health', (req, res) => res.status(200).json({uptime: process.uptime()})) app.use(compression()) app.use(hooks[TYPES.ROUTE_MATCHING]) app.use(hooks[TYPES.LOGGING]) - app.post( - `/${TYPES.CSP_REPORT}`, - bodyParser.json({type: 'application/csp-report'}), - hooks[TYPES.CSP_REPORT] - ) + app.post(`/${TYPES.CSP_REPORT}`, bodyParser.json({type: 'application/csp-report'}), hooks[TYPES.CSP_REPORT]) runningUnderAuth && app.use(basicAuth(AUTH_DEFINITION)) app.use(express.static('statics')) @@ -76,8 +62,7 @@ const _memoizedHtmlTemplatesMapping = {} app.use((req, res, next) => { const {hostname, subdomains} = req - const isLocalhost = - hostname.includes('localhost') || hostname.includes('.local') + const isLocalhost = hostname.includes('localhost') || hostname.includes('.local') if (isLocalhost || subdomains.length) return next() @@ -89,8 +74,7 @@ const _memoizedHtmlTemplatesMapping = {} // we need to define a key for each multi site and one default // for single sites too. const site = isMultiSite ? hostFromReq(req) : 'default' - const memoizedHtmlTemplate = - _memoizedHtmlTemplatesMapping && _memoizedHtmlTemplatesMapping[site] + const memoizedHtmlTemplate = _memoizedHtmlTemplatesMapping && _memoizedHtmlTemplatesMapping[site] if (memoizedHtmlTemplate) { req.htmlTemplate = memoizedHtmlTemplate @@ -112,7 +96,5 @@ const _memoizedHtmlTemplatesMapping = {} app.use(hooks[TYPES.NOT_FOUND]) app.use(hooks[TYPES.INTERNAL_ERROR]) - app.listen(PORT, () => - console.log(`Server up & running 🌍 http://localhost:${PORT}`) - ) // eslint-disable-line + app.listen(PORT, () => console.log(`Server up & running 🌍 http://localhost:${PORT}`)) // eslint-disable-line })() diff --git a/packages/sui-ssr/server/initialContextValue/index.js b/packages/sui-ssr/server/initialContextValue/index.js index 2604094dc..768933121 100644 --- a/packages/sui-ssr/server/initialContextValue/index.js +++ b/packages/sui-ssr/server/initialContextValue/index.js @@ -14,9 +14,7 @@ export const INITIAL_CONTEXT_VALUE = '__INITIAL_CONTEXT_VALUE__' */ export const getInitialContextValue = context => Object.keys(context) - .filter( - contextKey => typeof context[contextKey]?.getInitialData === 'function' - ) + .filter(contextKey => typeof context[contextKey]?.getInitialData === 'function') .reduce((acc, contextKey) => { acc[contextKey] = context[contextKey].getInitialData() return acc diff --git a/packages/sui-ssr/server/middlewares/ssr.js b/packages/sui-ssr/server/middlewares/ssr.js index 37676ccc1..c97643149 100644 --- a/packages/sui-ssr/server/middlewares/ssr.js +++ b/packages/sui-ssr/server/middlewares/ssr.js @@ -13,10 +13,7 @@ import {ssrComponentWithInitialProps} from '@s-ui/react-initial-props' import {Router} from '@s-ui/react-router' import {buildDeviceFrom} from '../../build-device.js' -import { - DEFAULT_REDIRECT_STATUS_CODE, - redirectStatusCodes -} from '../../status-codes.js' +import {DEFAULT_REDIRECT_STATUS_CODE, redirectStatusCodes} from '../../status-codes.js' import ssrConfig from '../config.js' import {getInitialContextValue} from '../initialContextValue/index.js' import replaceWithLoadCSSPolyfill from '../template/cssrelpreload.js' @@ -53,14 +50,7 @@ const convertToAsyncLinks = (allMatch, startingAttrs, endingAttrs) => { } export default async (req, res, next) => { - const { - context, - criticalCSS, - matchResult = {}, - performance, - query, - skipSSR - } = req + const {context, criticalCSS, matchResult = {}, performance, query, skipSSR} = req const {error, redirectLocation, renderProps} = matchResult let [headTplPart, bodyTplPart] = getTplParts(req) @@ -74,9 +64,7 @@ export default async (req, res, next) => { } if (redirectLocation) { - const queryString = Object.keys(query).length - ? `?${qs.stringify(query)}` - : '' + const queryString = Object.keys(query).length ? `?${qs.stringify(query)}` : '' const destination = `${redirectLocation.pathname}${queryString}` return res.redirect(DEFAULT_REDIRECT_STATUS_CODE, destination) } @@ -89,31 +77,21 @@ export default async (req, res, next) => { const hasCriticalCSS = criticalCSS && criticalCSS !== '' // get the pageComponent and its displayName to retrieve its styles - const pageComponent = - renderProps.components[renderProps.components.length - 1] + const pageComponent = renderProps.components[renderProps.components.length - 1] const pageName = pageComponent.displayName if (ssrConfig.createStylesFor && pageName) { const pageStyles = createStylesFor({pageName, async: hasCriticalCSS, req}) - let nextHeadTplPart = headTplPart.replace( - HEAD_OPENING_TAG, - `${HEAD_OPENING_TAG}${pageStyles}` - ) + let nextHeadTplPart = headTplPart.replace(HEAD_OPENING_TAG, `${HEAD_OPENING_TAG}${pageStyles}`) headTplPart = (' ' + nextHeadTplPart).slice(1) nextHeadTplPart = null } if (hasCriticalCSS) { let nextHeadTplPart = headTplPart - .replace( - HEAD_OPENING_TAG, - `${HEAD_OPENING_TAG}` - ) + .replace(HEAD_OPENING_TAG, `${HEAD_OPENING_TAG}`) .replace(cssLinksRegExp, convertToAsyncLinks) - .replace( - HEAD_CLOSING_TAG, - `${replaceWithLoadCSSPolyfill(HEAD_CLOSING_TAG)}` - ) + .replace(HEAD_CLOSING_TAG, `${replaceWithLoadCSSPolyfill(HEAD_CLOSING_TAG)}`) headTplPart = (' ' + nextHeadTplPart).slice(1) nextHeadTplPart = null } @@ -139,13 +117,8 @@ export default async (req, res, next) => { provider: HeadProvider, props: {headTags} }, - ...(typeof contextProviders === 'function' - ? contextProviders({context}) - : contextProviders) - ].reduce( - (acc, {provider, props}) => createElement(provider, props, acc), - null - ) + ...(typeof contextProviders === 'function' ? contextProviders({context}) : contextProviders) + ].reduce((acc, {provider, props}) => createElement(provider, props, acc), null) try { initialData = await ssrComponentWithInitialProps({ @@ -183,11 +156,8 @@ export default async (req, res, next) => { } if (redirectTo) { - const isValidRedirectStatusCode = - redirectStatusCodes.includes(redirectStatusCode) - const validRedirectStatusCode = isValidRedirectStatusCode - ? redirectStatusCode - : DEFAULT_REDIRECT_STATUS_CODE + const isValidRedirectStatusCode = redirectStatusCodes.includes(redirectStatusCode) + const validRedirectStatusCode = isValidRedirectStatusCode ? redirectStatusCode : DEFAULT_REDIRECT_STATUS_CODE return res.redirect(validRedirectStatusCode, redirectTo) } @@ -201,8 +171,7 @@ export default async (req, res, next) => { // The first html content has the be set after any possible call to next(). // Otherwise some undesired/duplicated html could be attached to the error pages if an error occurs - const {bodyAttributes, headString, htmlAttributes} = - renderHeadTagsToString(headTags) + const {bodyAttributes, headString, htmlAttributes} = renderHeadTagsToString(headTags) res.set({ 'Server-Timing': formatServerTimingHeader({ diff --git a/packages/sui-ssr/server/template/index.js b/packages/sui-ssr/server/template/index.js index 215fa406b..e463cbf68 100644 --- a/packages/sui-ssr/server/template/index.js +++ b/packages/sui-ssr/server/template/index.js @@ -30,10 +30,7 @@ HtmlBuilder.buildHead = ({headTplPart, headString = ''}) => { let headElement = copyHeadTplPart.substr(copyHeadTplPart.indexOf('') + 1) - const nextHead = copyHeadTplPart.replace( - headOpenningTag, - `${headOpenningTag}${copyHeadString}` - ) + const nextHead = copyHeadTplPart.replace(headOpenningTag, `${headOpenningTag}${copyHeadString}`) copyHeadTplPart = null copyHeadString = null headElement = null diff --git a/packages/sui-ssr/server/utils/factory.js b/packages/sui-ssr/server/utils/factory.js index 16d6fdd69..ea2048288 100644 --- a/packages/sui-ssr/server/utils/factory.js +++ b/packages/sui-ssr/server/utils/factory.js @@ -10,31 +10,21 @@ export default ({path, fs, config: ssrConf = {}, assetsManifest}) => { const multiSiteMapping = ssrConf.multiSite const multiSiteKeys = multiSiteMapping && Object.keys(multiSiteMapping) - const isMultiSite = - multiSiteKeys && - multiSiteKeys.length > 0 && - multiSiteKeys.includes(DEFAULT_MULTI_SITE_KEY) + const isMultiSite = multiSiteKeys && multiSiteKeys.length > 0 && multiSiteKeys.includes(DEFAULT_MULTI_SITE_KEY) - const hostFromReq = (req, header = DEFAULT_SITE_HEADER) => - req.get(header) || req.hostname + const hostFromReq = (req, header = DEFAULT_SITE_HEADER) => req.get(header) || req.hostname const hostPattern = req => { const host = hostFromReq(req) - return ( - (multiSiteKeys && - multiSiteKeys.find(hostPattern => host.match(hostPattern))) || - DEFAULT_MULTI_SITE_KEY - ) + return (multiSiteKeys && multiSiteKeys.find(hostPattern => host.match(hostPattern))) || DEFAULT_MULTI_SITE_KEY } const multiSitePublicFolder = site => { const publicFolderPrefix = `${DEFAULT_PUBLIC_FOLDER}-` // Keep compatibility with those multi site configurations // that already define the public folder. - return site.includes(publicFolderPrefix) - ? site - : `${publicFolderPrefix}${site}` + return site.includes(publicFolderPrefix) ? site : `${publicFolderPrefix}${site}` } const publicFolder = req => { @@ -44,8 +34,7 @@ export default ({path, fs, config: ssrConf = {}, assetsManifest}) => { return multiSitePublicFolder(site) } - const siteByHostPattern = hostPattern => - isMultiSite && multiSiteMapping[hostPattern] + const siteByHostPattern = hostPattern => isMultiSite && multiSiteMapping[hostPattern] const siteByHost = req => siteByHostPattern(hostPattern(req)) @@ -58,19 +47,14 @@ export default ({path, fs, config: ssrConf = {}, assetsManifest}) => { return { ...acc, - [site]: expressStatic( - multiSitePublicFolder(site), - EXPRESS_STATIC_CONFIG - ) + [site]: expressStatic(multiSitePublicFolder(site), EXPRESS_STATIC_CONFIG) } }, {}) } return function serveStaticByHost(req, res, next) { const site = siteByHost(req) - const middleware = isMultiSite - ? middlewares[site] - : expressStatic(DEFAULT_PUBLIC_FOLDER, EXPRESS_STATIC_CONFIG) + const middleware = isMultiSite ? middlewares[site] : expressStatic(DEFAULT_PUBLIC_FOLDER, EXPRESS_STATIC_CONFIG) middleware(req, res, next) } @@ -97,10 +81,7 @@ export default ({path, fs, config: ssrConf = {}, assetsManifest}) => { try { assetsManifest = JSON.parse( - fs.readFileSync( - path.join(process.cwd(), publicFolder(req), 'asset-manifest.json'), - 'utf8' - ) + fs.readFileSync(path.join(process.cwd(), publicFolder(req), 'asset-manifest.json'), 'utf8') ) if (site) { cachedAssetsManifest = { @@ -133,9 +114,7 @@ export default ({path, fs, config: ssrConf = {}, assetsManifest}) => { shouldCreatePageStyles && getStyleHrefBy({pageName, req}) ].filter(Boolean) const attributes = async ? ssrConf.ASYNC_CSS_ATTRS : '' - const stylesHTML = stylesheets - .map(style => ``) - .join('') + const stylesHTML = stylesheets.map(style => ``).join('') return stylesHTML } @@ -153,10 +132,7 @@ export default ({path, fs, config: ssrConf = {}, assetsManifest}) => { try { criticalManifest = JSON.parse( - fs.readFileSync( - path.join(process.cwd(), criticalDir({req}), 'critical.json'), - 'utf8' - ) + fs.readFileSync(path.join(process.cwd(), criticalDir({req}), 'critical.json'), 'utf8') ) cachedCriticalManifest = criticalManifest } catch (error) { diff --git a/packages/sui-ssr/status-codes.js b/packages/sui-ssr/status-codes.js index 7f45e1f51..a4ca31e97 100644 --- a/packages/sui-ssr/status-codes.js +++ b/packages/sui-ssr/status-codes.js @@ -5,7 +5,4 @@ export const statusCodes = { export const DEFAULT_REDIRECT_STATUS_CODE = statusCodes.MOVED_PERMANENTLY -export const redirectStatusCodes = [ - statusCodes.MOVED_PERMANENTLY, - statusCodes.FOUND -] +export const redirectStatusCodes = [statusCodes.MOVED_PERMANENTLY, statusCodes.FOUND] diff --git a/packages/sui-ssr/test/server/utilsSpec.js b/packages/sui-ssr/test/server/utilsSpec.js index 5d7d8f16a..11572cec9 100644 --- a/packages/sui-ssr/test/server/utilsSpec.js +++ b/packages/sui-ssr/test/server/utilsSpec.js @@ -8,16 +8,13 @@ import {publicFolder} from '../../server/utils/index.js' import {getMockedRequest} from './fixtures/index.js' import {publicFolderWithMultiSiteConfig} from './fixtures/utils.js' -const ASYNC_CSS_ATTRS = - 'rel="stylesheet" media="only x" as="style" onload="this.media=\'all\';' +const ASYNC_CSS_ATTRS = 'rel="stylesheet" media="only x" as="style" onload="this.media=\'all\';' describe('[sui-ssr] Utils', () => { describe('Public folder', () => { describe('In a multi site project', () => { it('Should build the public folder name properly', () => { - const folderName = publicFolderWithMultiSiteConfig( - getMockedRequest('www.bikes.com') - ) + const folderName = publicFolderWithMultiSiteConfig(getMockedRequest('www.bikes.com')) expect(folderName).to.equal('public-bikes') }) }) @@ -88,9 +85,7 @@ describe('[sui-ssr] Utils', () => { }) const styles = createStylesFor({async: true}) - expect(styles).to.equal( - `` - ) + expect(styles).to.equal(``) }) it('Should create page styles', () => { @@ -127,9 +122,7 @@ describe('[sui-ssr] Utils', () => { }) const styles = createStylesFor({pageName: 'Home', async: true}) - expect(styles).to.equal( - `` - ) + expect(styles).to.equal(``) }) it('Should create an async page styles and app styles', () => { diff --git a/packages/sui-studio-create/src/index.js b/packages/sui-studio-create/src/index.js index 29265276a..7250e10f4 100755 --- a/packages/sui-studio-create/src/index.js +++ b/packages/sui-studio-create/src/index.js @@ -96,9 +96,7 @@ Promise.all([createDir(`${PROJECT_PATH}/components`)]) ) ) .then(() => { - console.log( - '[sui-studio-create] Created folder structure. Installing dependencies...' - ) + console.log('[sui-studio-create] Created folder structure. Installing dependencies...') spawn('npm', ['install', '--no-fund', '--no-audit'], { cwd: PROJECT_PATH, stdio: 'inherit' diff --git a/packages/sui-studio-utils/src/domain-builder/index.js b/packages/sui-studio-utils/src/domain-builder/index.js index b8ec647d6..e32f74e29 100644 --- a/packages/sui-studio-utils/src/domain-builder/index.js +++ b/packages/sui-studio-utils/src/domain-builder/index.js @@ -30,9 +30,7 @@ export default class DomainBuilder { } if (success === undefined && fail === undefined) { - throw new Error( - '[DomainBuilder#respondWith] Neither success nor fail are set' - ) + throw new Error('[DomainBuilder#respondWith] Neither success nor fail are set') } if (!this._useCase) { @@ -56,13 +54,10 @@ export default class DomainBuilder { const data = typeof success === 'function' ? success(params) : success - const responseParams = - data !== undefined ? {err: null, data} : {err: fail, data: null} + const responseParams = data !== undefined ? {err: null, data} : {err: fail, data: null} const createResponse = ({err, data}) => { - subscriptions.forEach(fn => - fn({error: err, params, result: [err, data]}) - ) + subscriptions.forEach(fn => fn({error: err, params, result: [err, data]})) if (inlineError) return Promise.resolve([err, data]) return err ? Promise.reject(err) : Promise.resolve(data) } diff --git a/packages/sui-studio-utils/src/test/common/domainBuilderSpec.js b/packages/sui-studio-utils/src/test/common/domainBuilderSpec.js index 904fa49b4..3d4d50995 100644 --- a/packages/sui-studio-utils/src/test/common/domainBuilderSpec.js +++ b/packages/sui-studio-utils/src/test/common/domainBuilderSpec.js @@ -7,13 +7,8 @@ describe('DomainBuilder', () => { describe('when a useCase is mocked', () => { const domainBuilder = DomainBuilder.extend({domain: {get: () => {}}}) it('should return the mocked response', async () => { - const domain = domainBuilder - .for({useCase: 'get_products'}) - .respondWith({success: 'mocked-response'}) - .build() - expect(await domain.get('get_products').execute()).to.equal( - 'mocked-response' - ) + const domain = domainBuilder.for({useCase: 'get_products'}).respondWith({success: 'mocked-response'}).build() + expect(await domain.get('get_products').execute()).to.equal('mocked-response') }) }) diff --git a/packages/sui-studio/bin/helpers/copy.js b/packages/sui-studio/bin/helpers/copy.js index 5de175ba8..75ac996a8 100644 --- a/packages/sui-studio/bin/helpers/copy.js +++ b/packages/sui-studio/bin/helpers/copy.js @@ -42,9 +42,7 @@ const resolveFilePath = (filePath, {flatten, up}) => { if (up === 0) return filePath if (!checkDepth(filePath, up)) { - throw new Error( - "The number of folders you're trying to go up are not correct. Check the path or the up config" - ) + throw new Error("The number of folders you're trying to go up are not correct. Check the path or the up config") } return path.join(...path.normalize(filePath).split(path.sep).slice(up)) diff --git a/packages/sui-studio/bin/helpers/copyGlobals.js b/packages/sui-studio/bin/helpers/copyGlobals.js index 3e6236b14..42ebd8a00 100644 --- a/packages/sui-studio/bin/helpers/copyGlobals.js +++ b/packages/sui-studio/bin/helpers/copyGlobals.js @@ -11,7 +11,5 @@ module.exports = function copyGlobals() { } fs.writeFileSync(GLOBALS_FILE_PATH, '// globals file', 'utf8') - copy([GLOBALS_FILE_PATH, DESTINATION_FOLDER]).then(() => - console.log('[sui-studio] Copied globals file correctly') - ) + copy([GLOBALS_FILE_PATH, DESTINATION_FOLDER]).then(() => console.log('[sui-studio] Copied globals file correctly')) } diff --git a/packages/sui-studio/bin/helpers/generateApiDocs.js b/packages/sui-studio/bin/helpers/generateApiDocs.js index e7028263b..6e9d250ef 100644 --- a/packages/sui-studio/bin/helpers/generateApiDocs.js +++ b/packages/sui-studio/bin/helpers/generateApiDocs.js @@ -14,19 +14,13 @@ module.exports = function generateApiDocs() { let docs = {} try { - docs = reactDocs.parse( - source, - reactDocs.resolver.findAllComponentDefinitions - ) + docs = reactDocs.parse(source, reactDocs.resolver.findAllComponentDefinitions) } catch (e) { console.warn(`[sui-studio] Couldn't generate API docs for ${file}`) } const outputFile = file.replace('index.js', 'definitions.json') - fs.writeFileSync( - path.resolve(process.cwd(), `public/${outputFile}`), - JSON.stringify(docs, null, 2) - ) + fs.writeFileSync(path.resolve(process.cwd(), `public/${outputFile}`), JSON.stringify(docs, null, 2)) }) console.timeEnd('[sui-studio] API generation took') diff --git a/packages/sui-studio/bin/migrations/demo-folders.js b/packages/sui-studio/bin/migrations/demo-folders.js index 70eb03357..15301ed4c 100644 --- a/packages/sui-studio/bin/migrations/demo-folders.js +++ b/packages/sui-studio/bin/migrations/demo-folders.js @@ -13,10 +13,7 @@ function replaceImportedPaths(file) { const replacedData = data .replace(new RegExp('../../../utils', 'g'), 'utils') - .replace( - new RegExp('../../../(../)?components/(.*)/src', 'g'), - 'components/$2/src' - ) + .replace(new RegExp('../../../(../)?components/(.*)/src', 'g'), 'components/$2/src') // Skip writing the file if there's nothing new. if (replacedData === data) return @@ -57,10 +54,7 @@ function migrateDemoFolders() { const components = glob.sync(['components/*/*/src/index.js']) components.forEach(file => { - const [category, component] = file - .replace('/index.js', '') - .replace('components/', '') - .split('/') + const [category, component] = file.replace('/index.js', '').replace('components/', '').split('/') const demoPath = `./demo/${category}/${component}` const newDemoPath = `./components/${category}/${component}/demo` diff --git a/packages/sui-studio/bin/migrations/test-folders.js b/packages/sui-studio/bin/migrations/test-folders.js index 8efbfaaaf..4a69d662f 100644 --- a/packages/sui-studio/bin/migrations/test-folders.js +++ b/packages/sui-studio/bin/migrations/test-folders.js @@ -10,10 +10,7 @@ function migrateTestFolders() { const files = glob.sync(['test/*/*/index.js']) files.forEach(file => { - const [category, component] = file - .replace('/index.js', '') - .replace('test/', '') - .split('/') + const [category, component] = file.replace('/index.js', '').replace('test/', '').split('/') const testPath = `./test/${category}/${component}` const newTestPath = `./components/${category}/${component}/test` diff --git a/packages/sui-studio/bin/sui-studio-build.js b/packages/sui-studio/bin/sui-studio-build.js index 06430990b..f57d1772a 100755 --- a/packages/sui-studio/bin/sui-studio-build.js +++ b/packages/sui-studio/bin/sui-studio-build.js @@ -13,10 +13,7 @@ const copyGlobals = require('./helpers/copyGlobals.js') program .option('-O, --only-changes', 'only build changed components or demos') - .option( - '-B, --before-build ', - 'command to be executed before the build' - ) + .option('-B, --before-build ', 'command to be executed before the build') .parse(process.argv) process.env.NODE_ENV = process.env.NODE_ENV || 'production' @@ -28,10 +25,7 @@ let needsBuild = true let beforeBuildCommand if (onlyChanges) { - const stdout = execSync( - `node ${join(__dirname, '..', 'scripts', 'prepare-only-changes.js')}`, - {encoding: 'utf8'} - ) + const stdout = execSync(`node ${join(__dirname, '..', 'scripts', 'prepare-only-changes.js')}`, {encoding: 'utf8'}) needsBuild = !stdout.includes(NO_COMPONENTS_MESSAGE) } diff --git a/packages/sui-studio/bin/sui-studio-dev.js b/packages/sui-studio/bin/sui-studio-dev.js index 7a05fbadc..c64d9e335 100755 --- a/packages/sui-studio/bin/sui-studio-dev.js +++ b/packages/sui-studio/bin/sui-studio-dev.js @@ -46,17 +46,12 @@ if (!category || !component) { const componentPath = path.join(PWD, 'components', category, component) const legacyTestPath = path.join(PWD, 'test', category, component) -const testPath = fs.existsSync(legacyTestPath) - ? legacyTestPath - : path.join(componentPath, 'test') +const testPath = fs.existsSync(legacyTestPath) ? legacyTestPath : path.join(componentPath, 'test') const studioDevConfig = { ...config, context: path.join(__dirname, '..', 'workbench', 'src'), - plugins: [ - ...config.plugins, - new webpack.DefinePlugin({__COMPONENT_ID__: JSON.stringify(componentID)}) - ], + plugins: [...config.plugins, new webpack.DefinePlugin({__COMPONENT_ID__: JSON.stringify(componentID)})], resolve: { ...config.resolve, alias: { diff --git a/packages/sui-studio/bin/sui-studio-generate.js b/packages/sui-studio/bin/sui-studio-generate.js index 5f2acd51b..186aabac7 100755 --- a/packages/sui-studio/bin/sui-studio-generate.js +++ b/packages/sui-studio/bin/sui-studio-generate.js @@ -45,9 +45,7 @@ if (!wordsOnlyRegex.test(category)) { showError('category name must contain letters or underscore only') } -const componentInPascal = toPascalCase( - `${category.replace(/s$/, '')} ${component}` -) +const componentInPascal = toPascalCase(`${category.replace(/s$/, '')} ${component}`) const COMPONENT_DIR = `/components/${category}/${component}/` const COMPONENT_PATH = `${BASE_DIR}${COMPONENT_DIR}` @@ -69,9 +67,7 @@ const COMPONENT_TEST_FILE = `${TEST_DIR}index.test.js` const {context, scope, prefix = 'sui', swc} = program.opts() const packageScope = scope ? `@${scope}/` : '' const packageCategory = category ? `${toKebabCase(category)}-` : '' -const packageName = `${packageScope}${prefix}-${packageCategory}${toKebabCase( - component -)}` +const packageName = `${packageScope}${prefix}-${packageCategory}${toKebabCase(component)}` const packageInfo = require(path.join(process.cwd(), 'package.json')) const {repository = {}, homepage} = packageInfo @@ -94,9 +90,7 @@ ${context ? "import '@s-ui/studio/src/patcher-mocha'" : ''} chai.use(chaiDOM) -describe${context ? '.context.default' : ''}('${componentInPascal}', ${ - context ? 'Component' : '()' -} => { +describe${context ? '.context.default' : ''}('${componentInPascal}', ${context ? 'Component' : '()'} => { const setup = setupEnvironment(Component) it('should render without crashing', () => { @@ -153,9 +147,7 @@ const defaultContext = `module.exports = { } ` -const buildJs = swc - ? 'sui-js-compiler' - : 'babel --presets sui ./src --out-dir ./lib' +const buildJs = swc ? 'sui-js-compiler' : 'babel --presets sui ./src --out-dir ./lib' // Check if the component already exist before continuing if (fs.existsSync(COMPONENT_PATH)) { @@ -301,26 +293,14 @@ export default () => <${componentInPascal} /> writeFile( COMPONENT_CONTEXT_FILE, - isBooleanContext - ? defaultContext - : fs.readFileSync(`${BASE_DIR}${context}`).toString() + isBooleanContext ? defaultContext : fs.readFileSync(`${BASE_DIR}${context}`).toString() ) })(), writeFile(COMPONENT_TEST_FILE, removeRepeatedNewLines(testTemplate)) ]).then(() => { console.log(colors.gray(`[${packageName}]: Installing the dependencies`)) - const install = spawn('npm', [ - 'install', - '--legacy-peer-deps', - '--no-audit', - '--no-fund', - '--production=false' - ]) - - install.stdout.on('data', data => - console.log(colors.gray(`[${packageName}]: ${data.toString()}`)) - ) - install.stderr.on('data', data => - console.log(colors.red(`[${packageName}]: ${data.toString()}`)) - ) + const install = spawn('npm', ['install', '--legacy-peer-deps', '--no-audit', '--no-fund', '--production=false']) + + install.stdout.on('data', data => console.log(colors.gray(`[${packageName}]: ${data.toString()}`))) + install.stderr.on('data', data => console.log(colors.red(`[${packageName}]: ${data.toString()}`))) }) diff --git a/packages/sui-studio/bin/sui-studio-link.js b/packages/sui-studio/bin/sui-studio-link.js index 70b21bfe3..ca5e7447a 100755 --- a/packages/sui-studio/bin/sui-studio-link.js +++ b/packages/sui-studio/bin/sui-studio-link.js @@ -7,73 +7,43 @@ const fs = require('fs-extra') const program = require('commander') const BASE_DIR = process.cwd() -console.log( - colors.cyan( - 'If you\'re linking internal components, "sui-studio link-all" might be a better option.' - ) -) +console.log(colors.cyan('If you\'re linking internal components, "sui-studio link-all" might be a better option.')) program.parse(process.argv) -const [origin, destination] = Array.prototype.map.call( - program.args, - url => `${BASE_DIR}/components/${url}` -) +const [origin, destination] = Array.prototype.map.call(program.args, url => `${BASE_DIR}/components/${url}`) const originPackageName = require(`${origin}/package.json`).name const build = () => { return new Promise((resolve, reject) => { fs.removeSync(`${destination}/node_modules/${originPackageName}`) - const build = spawn('npm', ['run', 'build'], {cwd: origin}) - .on('error', reject) - .on('close', resolve) - build.stdout.on('data', data => - console.log(colors.gray(`[${originPackageName}]: ${data.toString()}`)) - ) - build.stderr.on('data', data => - console.log(colors.red(`[${originPackageName}]: ${data.toString()}`)) - ) + const build = spawn('npm', ['run', 'build'], {cwd: origin}).on('error', reject).on('close', resolve) + build.stdout.on('data', data => console.log(colors.gray(`[${originPackageName}]: ${data.toString()}`))) + build.stderr.on('data', data => console.log(colors.red(`[${originPackageName}]: ${data.toString()}`))) }) } const createLink = () => { return new Promise((resolve, reject) => { - const link = spawn('ln', [ - '-s', - `${origin}`, - `${destination}/node_modules/${originPackageName}` - ]) + const link = spawn('ln', ['-s', `${origin}`, `${destination}/node_modules/${originPackageName}`]) .on('error', reject) .on('close', resolve) - link.stdout.on('data', data => - console.log(colors.gray(`[${originPackageName}]: ${data.toString()}`)) - ) - link.stderr.on('data', data => - console.log(colors.red(`[${originPackageName}]: ${data.toString()}`)) - ) + link.stdout.on('data', data => console.log(colors.gray(`[${originPackageName}]: ${data.toString()}`))) + link.stderr.on('data', data => console.log(colors.red(`[${originPackageName}]: ${data.toString()}`))) }) } const watch = () => { return new Promise(() => { const babel = spawn('npm', ['run', 'babel', '--', '--watch'], {cwd: origin}) - babel.stdout.on('data', data => - console.log(colors.gray(`[${originPackageName}]: ${data.toString()}`)) - ) - babel.stderr.on('data', data => - console.log(colors.red(`[${originPackageName}]: ${data.toString()}`)) - ) + babel.stdout.on('data', data => console.log(colors.gray(`[${originPackageName}]: ${data.toString()}`))) + babel.stderr.on('data', data => console.log(colors.red(`[${originPackageName}]: ${data.toString()}`))) fs.watch(origin, {recursive: true}, (event, filename) => { if (event === 'change' && filename.indexOf('.scss') !== -1) { - console.log( - colors.gray(`[${originPackageName}]: ${filename} -> lib/${filename}`) - ) - fs.copySync( - `${origin}/${filename}`, - `${origin}/${filename.replace('src', 'lib')}` - ) + console.log(colors.gray(`[${originPackageName}]: ${filename} -> lib/${filename}`)) + fs.copySync(`${origin}/${filename}`, `${origin}/${filename.replace('src', 'lib')}`) } }) }) diff --git a/packages/sui-studio/bin/sui-studio-migrate.js b/packages/sui-studio/bin/sui-studio-migrate.js index 4cbccce20..e7e7bc464 100644 --- a/packages/sui-studio/bin/sui-studio-migrate.js +++ b/packages/sui-studio/bin/sui-studio-migrate.js @@ -20,9 +20,7 @@ program const [topic] = program.args if (!topic) { - console.log( - 'An argument is required. Please, try using "test" or "demo" topic' - ) + console.log('An argument is required. Please, try using "test" or "demo" topic') process.exit(1) } diff --git a/packages/sui-studio/bin/sui-studio-test.js b/packages/sui-studio/bin/sui-studio-test.js index e583e03e8..9f0397aec 100755 --- a/packages/sui-studio/bin/sui-studio-test.js +++ b/packages/sui-studio/bin/sui-studio-test.js @@ -32,14 +32,7 @@ const run = async () => { suiTestClientPath, [ '--pattern', - path.join( - 'node_modules', - '@s-ui', - 'studio', - 'src', - 'runtime-mocha', - 'index.js' - ), + path.join('node_modules', '@s-ui', 'studio', 'src', 'runtime-mocha', 'index.js'), coverage && '--coverage', watch && '--watch', ci && '--ci', diff --git a/packages/sui-studio/bin/sui-studio.js b/packages/sui-studio/bin/sui-studio.js index 75c4309cb..97ea1363c 100755 --- a/packages/sui-studio/bin/sui-studio.js +++ b/packages/sui-studio/bin/sui-studio.js @@ -28,25 +28,14 @@ program program.command('dev ', 'Develop an isolate component').alias('d') -program - .command( - 'generate ', - 'Create a component and her demo files' - ) - .alias('g') +program.command('generate ', 'Create a component and her demo files').alias('g') -program - .command('build', 'Generate a static version ready to be deployed') - .alias('b') +program.command('build', 'Generate a static version ready to be deployed').alias('b') -program - .command('link ', 'Link components between them') - .alias('l') +program.command('link ', 'Link components between them').alias('l') program.command('test', 'Run studio tests').alias('t') -program - .command('migrate ', 'Migrate any legacy topic to the new structure') - .alias('m') +program.command('migrate ', 'Migrate any legacy topic to the new structure').alias('m') program.parse(process.argv) diff --git a/packages/sui-studio/scripts/prepare-only-changes.js b/packages/sui-studio/scripts/prepare-only-changes.js index 3e48f34ca..4cfa48a92 100644 --- a/packages/sui-studio/scripts/prepare-only-changes.js +++ b/packages/sui-studio/scripts/prepare-only-changes.js @@ -24,24 +24,15 @@ function getComponentsFromDemoImports(componentPath) { let componentsFromDemoImports = [] try { - const file = path.join( - process.cwd(), - 'components', - componentPath, - 'demo', - 'index.js' - ) + const file = path.join(process.cwd(), 'components', componentPath, 'demo', 'index.js') if (!file) return const data = fs.readFileSync(file, ENCODING) - const importRegExp = - /import (?.*) from 'components\/(?.*)\/src'/g + const importRegExp = /import (?.*) from 'components\/(?.*)\/src'/g const matchedImports = [...data.matchAll(importRegExp)] - componentsFromDemoImports = matchedImports.map( - ({groups: {componentPath} = {}}) => componentPath - ) + componentsFromDemoImports = matchedImports.map(({groups: {componentPath} = {}}) => componentPath) } catch (err) { error(err) } @@ -50,8 +41,7 @@ function getComponentsFromDemoImports(componentPath) { } function getComponentsList(commits) { - const COMMIT_MESSAGE_PATTERN = - /\(components\/(?[a-zA-Z]+)\/(?[a-zA-Z(-?)]+)\)/ + const COMMIT_MESSAGE_PATTERN = /\(components\/(?[a-zA-Z]+)\/(?[a-zA-Z(-?)]+)\)/ let list = [] commits.forEach(commit => { @@ -59,8 +49,7 @@ function getComponentsList(commits) { if (!data) return const {context, component} = data.groups const componentPath = `${context}/${component}` - const componentsFromDemoImports = - getComponentsFromDemoImports(componentPath) + const componentsFromDemoImports = getComponentsFromDemoImports(componentPath) list = [...list, componentPath, ...componentsFromDemoImports] }) @@ -82,14 +71,8 @@ async function cleanComponents(list) { }) try { - await fs.move( - `${COMPONENTS_PATH}/README.md`, - `${NEW_COMPONENTS_PATH}/README.md` - ) - await fs.move( - `${COMPONENTS_PATH}/globals.js`, - `${NEW_COMPONENTS_PATH}/globals.js` - ) + await fs.move(`${COMPONENTS_PATH}/README.md`, `${NEW_COMPONENTS_PATH}/README.md`) + await fs.move(`${COMPONENTS_PATH}/globals.js`, `${NEW_COMPONENTS_PATH}/globals.js`) await fs.rm(COMPONENTS_PATH, {recursive: true, force: true}) await fs.rename(NEW_COMPONENTS_PATH, COMPONENTS_PATH) } catch (err) { @@ -105,9 +88,7 @@ function getRepositoryUrl() { function check(requiredVarName, requiredVar) { if (!requiredVar) { - log( - `You need to set the ${requiredVarName} variable in order to fetch the pull request commits.` - ) + log(`You need to set the ${requiredVarName} variable in order to fetch the pull request commits.`) process.exit(1) } } @@ -119,9 +100,7 @@ function buildPullCommitsResource() { const gitUrl = getRepositoryUrl() check('gitUrl', gitUrl) const isPublic = gitUrl.includes(PUBLIC_GITHUB_HOST) - const apiUrlPattern = isPublic - ? PUBLIC_GITHUB_API_URL_PATTERN - : PRIVATE_GITHUB_API_URL_PATTERN + const apiUrlPattern = isPublic ? PUBLIC_GITHUB_API_URL_PATTERN : PRIVATE_GITHUB_API_URL_PATTERN const {resource, organization, name} = gitUrlParse(gitUrl) return apiUrlPattern diff --git a/packages/sui-studio/src/components/demo/CodeEditor.js b/packages/sui-studio/src/components/demo/CodeEditor.js index a5689d027..1fbc0a237 100644 --- a/packages/sui-studio/src/components/demo/CodeEditor.js +++ b/packages/sui-studio/src/components/demo/CodeEditor.js @@ -24,10 +24,7 @@ function CodeEditor({isOpen, onChange, playground}) { useEffect(function () { const onChangeDebounced = createOnChangeDebounced() - const codeMirror = window.CodeMirror.fromTextArea( - textAreaRef.current, - CODE_MIRROR_OPTIONS - ) + const codeMirror = window.CodeMirror.fromTextArea(textAreaRef.current, CODE_MIRROR_OPTIONS) codeMirror.setValue(playground) codeMirror.on('change', onChangeDebounced) diff --git a/packages/sui-studio/src/components/demo/fetch-styles.js b/packages/sui-studio/src/components/demo/fetch-styles.js index dc3a79eef..7c91fa220 100644 --- a/packages/sui-studio/src/components/demo/fetch-styles.js +++ b/packages/sui-studio/src/components/demo/fetch-styles.js @@ -21,30 +21,19 @@ export const themesFor = ({category, component}) => .map(p => p.replace(`./${category}/${component}/demo/themes/`, '')) .map(p => p.replace('.scss', '')) -export default /* stylesFor */ async ({ - category, - component, - withTheme = 'default' -}) => { +export default /* stylesFor */ async ({category, component, withTheme = 'default'}) => { const componentPath = `${category}/${component}` const isDefaultTheme = withTheme === 'default' - console.info( - `[sui-studio] Applying new styles for ${componentPath} with theme: ${withTheme}` - ) + console.info(`[sui-studio] Applying new styles for ${componentPath} with theme: ${withTheme}`) // use the correct require method to extract the expected styles - const requireLazyStyles = isDefaultTheme - ? requireComponentStyles - : requireAvailableThemes + const requireLazyStyles = isDefaultTheme ? requireComponentStyles : requireAvailableThemes // if we're not using any theme, we load the default styles from its demo or the component itself default styles. // if we've selected a theme, we load the styles for that specific theme const stylePath = requireLazyStyles.keys().find(fileName => { - if ( - !isDefaultTheme && - `./${componentPath}/demo/themes/${withTheme}.scss` === fileName - ) { + if (!isDefaultTheme && `./${componentPath}/demo/themes/${withTheme}.scss` === fileName) { return `./${componentPath}/demo/themes/${withTheme}.scss` } else if (`./${componentPath}/demo/index.scss` === fileName) { return fileName diff --git a/packages/sui-studio/src/components/demo/index.js b/packages/sui-studio/src/components/demo/index.js index 250c2e7b6..095e42d52 100644 --- a/packages/sui-studio/src/components/demo/index.js +++ b/packages/sui-studio/src/components/demo/index.js @@ -5,12 +5,7 @@ import PropTypes from 'prop-types' import SUIContext from '@s-ui/react-context' -import { - iconClose, - iconCode, - iconFullScreen, - iconFullScreenExit -} from '../icons/index.js' +import {iconClose, iconCode, iconFullScreen, iconFullScreenExit} from '../icons/index.js' import Preview from '../preview/index.js' import Style from '../style/index.js' import {fetchPlayground, importMainModules} from '../tryRequire.js' @@ -18,12 +13,7 @@ import CodeEditor from './CodeEditor.js' import ContextButtons from './ContextButtons.js' import stylesFor, {themesFor} from './fetch-styles.js' import ThemesButtons from './ThemesButtons.js' -import { - cleanDisplayName, - createContextByType, - isFunction, - removeDefaultContext -} from './utilities.js' +import {cleanDisplayName, createContextByType, isFunction, removeDefaultContext} from './utilities.js' const EVIL_HACK_TO_RERENDER_AFTER_CHANGE = ' ' const CONTAINER_CLASS = 'sui-Studio' @@ -89,13 +79,9 @@ export default class Demo extends Component { handleFullScreen = () => { this.setState({isFullScreen: !this.state.isFullScreen}, () => { const {isFullScreen} = this.state - this.containerClassList = - this.containerClassList || - document.getElementsByClassName(CONTAINER_CLASS)[0].classList + this.containerClassList = this.containerClassList || document.getElementsByClassName(CONTAINER_CLASS)[0].classList - isFullScreen - ? this.containerClassList.add(FULLSCREEN_CLASS) - : this.containerClassList.remove(FULLSCREEN_CLASS) + isFullScreen ? this.containerClassList.add(FULLSCREEN_CLASS) : this.containerClassList.remove(FULLSCREEN_CLASS) }) } @@ -141,42 +127,26 @@ export default class Demo extends Component { const ComponentToRender = Base.type ? Base.type : Base const nonDefaultExports = removeDefaultContext(exports) - const context = - Object.keys(ctxt).length && createContextByType(ctxt, ctxtType) + const context = Object.keys(ctxt).length && createContextByType(ctxt, ctxtType) const {domain} = context || {} - !ComponentToRender.displayName && - console.error(new Error('Component.displayName must be defined.')) + !ComponentToRender.displayName && console.error(new Error('Component.displayName must be defined.')) return (
- - + +
- {!DemoComponent && playground && ( <> - @@ -195,8 +165,7 @@ export default class Demo extends Component { scope={{ context, React, - [cleanDisplayName(ComponentToRender.displayName)]: - ComponentToRender, + [cleanDisplayName(ComponentToRender.displayName)]: ComponentToRender, domain, ...nonDefaultExports }} diff --git a/packages/sui-studio/src/components/demo/utilities.js b/packages/sui-studio/src/components/demo/utilities.js index 41f5d257b..2b7b66f07 100644 --- a/packages/sui-studio/src/components/demo/utilities.js +++ b/packages/sui-studio/src/components/demo/utilities.js @@ -12,8 +12,7 @@ export const createContextByType = (ctxt, type) => { return deepmerge(ctxt[DEFAULT_CONTEXT], ctxt[type]) } -export const isFunction = fnc => - !!(fnc && fnc.constructor && fnc.call && fnc.apply) +export const isFunction = fnc => !!(fnc && fnc.constructor && fnc.call && fnc.apply) export const cleanDisplayName = displayName => { const [fallback, name] = displayName.split(/\w+\((\w+)\)/) diff --git a/packages/sui-studio/src/components/documentation/Api.js b/packages/sui-studio/src/components/documentation/Api.js index 5174ee7fa..10d2dbd18 100644 --- a/packages/sui-studio/src/components/documentation/Api.js +++ b/packages/sui-studio/src/components/documentation/Api.js @@ -44,9 +44,7 @@ export default function Api({params}) {
required - - {required ? 'yes' : 'no'} - + {required ? 'yes' : 'no'}
type @@ -77,9 +75,7 @@ export default function Api({params}) { } if (docs) { - return Array.isArray(docs) - ? docs.map(renderComponentDoc) - : renderComponentDoc(docs) + return Array.isArray(docs) ? docs.map(renderComponentDoc) : renderComponentDoc(docs) } return null diff --git a/packages/sui-studio/src/components/documentation/Markdown.js b/packages/sui-studio/src/components/documentation/Markdown.js index aee7f2791..8210921c9 100644 --- a/packages/sui-studio/src/components/documentation/Markdown.js +++ b/packages/sui-studio/src/components/documentation/Markdown.js @@ -3,14 +3,7 @@ import PropTypes from 'prop-types' import snarkdown from '../../snarkdown.js' export default function Markdown({content}) { - return ( - content && ( -
- ) - ) + return content &&
} Markdown.propTypes = { diff --git a/packages/sui-studio/src/components/layout/Logo.js b/packages/sui-studio/src/components/layout/Logo.js index ed9d6417b..e30c9c34d 100644 --- a/packages/sui-studio/src/components/layout/Logo.js +++ b/packages/sui-studio/src/components/layout/Logo.js @@ -1,8 +1,3 @@ import {getStudioLogo} from '../utils' -export default () => ( - -) +export default () => diff --git a/packages/sui-studio/src/components/layout/index.js b/packages/sui-studio/src/components/layout/index.js index 809db869f..65fbd4579 100644 --- a/packages/sui-studio/src/components/layout/index.js +++ b/packages/sui-studio/src/components/layout/index.js @@ -1,4 +1,4 @@ -import React, {useEffect, useState, useRef} from 'react' +import React, {useEffect, useRef, useState} from 'react' import cx from 'classnames' import PropTypes from 'prop-types' diff --git a/packages/sui-studio/src/components/navigation/index.js b/packages/sui-studio/src/components/navigation/index.js index d50caa5b6..0adb17b39 100644 --- a/packages/sui-studio/src/components/navigation/index.js +++ b/packages/sui-studio/src/components/navigation/index.js @@ -10,10 +10,7 @@ export default function Navigation({handleClick, search}) { const filterComponentsFromSearch = ({search}) => { return componentsList.filter(({category, component}) => { const lowerCasedSearch = search.toLowerCase() - return ( - category.toLowerCase().includes(lowerCasedSearch) || - component.toLowerCase().includes(lowerCasedSearch) - ) + return category.toLowerCase().includes(lowerCasedSearch) || component.toLowerCase().includes(lowerCasedSearch) }) } @@ -53,9 +50,7 @@ export default function Navigation({handleClick, search}) { return ( ) } diff --git a/packages/sui-studio/src/components/preview/index.js b/packages/sui-studio/src/components/preview/index.js index 31eced51a..433d43872 100644 --- a/packages/sui-studio/src/components/preview/index.js +++ b/packages/sui-studio/src/components/preview/index.js @@ -57,19 +57,13 @@ export default function Preview({code, scope = {React}}) { const compiledCode = getCompiledCode({code, scope}) const Component = eval(compiledCode)(...Object.values(scope)) // eslint-disable-line - return ( - - {Component} - - ) + return {Component} } return (
-
- {renderCode()} -
+
{renderCode()}
) diff --git a/packages/sui-studio/src/components/tryRequire.js b/packages/sui-studio/src/components/tryRequire.js index b18d0e0cd..7ef5815e7 100644 --- a/packages/sui-studio/src/components/tryRequire.js +++ b/packages/sui-studio/src/components/tryRequire.js @@ -15,12 +15,9 @@ export const fetchComponentSrcRawFile = ({category, component}) => fetchStaticFile(`/components/${category}/${component}/src/index.js`) export const fetchComponentsDefinitions = ({category, component}) => - window - .fetch(`/components/${category}/${component}/src/definitions.json`) - .then(res => res.json()) + window.fetch(`/components/${category}/${component}/src/definitions.json`).then(res => res.json()) -export const fetchComponentsReadme = () => - fetchStaticFile(`/components/README.md`) +export const fetchComponentsReadme = () => fetchStaticFile(`/components/README.md`) export const fetchMarkdownFile = ({category, component, file}) => fetchStaticFile(`/components/${category}/${component}/${file}.md`) @@ -38,12 +35,7 @@ export const importContexts = ({category, component}) => ) }) -export const importReactComponent = ({ - category, - component, - subComponentName = null, - extractDefault = false -}) => { +export const importReactComponent = ({category, component, subComponentName = null, extractDefault = false}) => { if (typeof subComponentName === 'string') { return safeImport({ extractDefault, @@ -93,8 +85,4 @@ export const importGlobals = () => { } export const importMainModules = params => - Promise.all([ - importReactComponent(params), - importContexts(params), - importDemo(params) - ]) + Promise.all([importReactComponent(params), importContexts(params), importDemo(params)]) diff --git a/packages/sui-studio/src/components/utils.js b/packages/sui-studio/src/components/utils.js index 74a8c9e68..d19f8d960 100644 --- a/packages/sui-studio/src/components/utils.js +++ b/packages/sui-studio/src/components/utils.js @@ -47,9 +47,7 @@ export const getStudioLogo = () => { * @return {string} */ export const extractDisplayName = Component => - Component.displayName || - (Component.type && Component.type.displayName) || - Component.name + Component.displayName || (Component.type && Component.type.displayName) || Component.name /** * Add React Context @@ -86,11 +84,7 @@ export const addReactContextToComponent = (Component, {context}) => { * @param {() => Promise} params.importFile function to import dynamically a module * @return {Promise} */ -export const safeImport = async ({ - defaultValue = false, - extractDefault = true, - importFile -}) => { +export const safeImport = async ({defaultValue = false, extractDefault = true, importFile}) => { const file = await importFile().catch(() => defaultValue) if (typeof file === 'undefined') { return Promise.reject(new Error('Error requiring file')) diff --git a/packages/sui-studio/src/environment-mocha/setupEnvironment.js b/packages/sui-studio/src/environment-mocha/setupEnvironment.js index d7c020464..0ca2310d0 100644 --- a/packages/sui-studio/src/environment-mocha/setupEnvironment.js +++ b/packages/sui-studio/src/environment-mocha/setupEnvironment.js @@ -10,12 +10,7 @@ DefaultWrapper.propTypes = { const getWrapper = ({contexts = [], wrapper: Wrapper = DefaultWrapper}) => { const ContextsWrapper = ({children}) => - contexts.reduce( - (children, {provider: Provider, value}) => ( - {children} - ), - children - ) + contexts.reduce((children, {provider: Provider, value}) => {children}, children) const CustomWrapper = ({children}) => ( diff --git a/packages/sui-studio/src/patcher-mocha/index.js b/packages/sui-studio/src/patcher-mocha/index.js index 6b7fbe403..c0a879e21 100644 --- a/packages/sui-studio/src/patcher-mocha/index.js +++ b/packages/sui-studio/src/patcher-mocha/index.js @@ -23,20 +23,14 @@ class DescribeContext { return function (title, cb, componentKey) { const originalFn = global[FUNCTION_TO_PATCH] - const Component = - global.__STUDIO_COMPONENT__[componentKey] || global.__STUDIO_COMPONENT__ + const Component = global.__STUDIO_COMPONENT__[componentKey] || global.__STUDIO_COMPONENT__ const {displayName} = Component - const contextsForComponent = - global.__STUDIO_CONTEXTS__[componentKey] || - global.__STUDIO_CONTEXTS__ || - {} + const contextsForComponent = global.__STUDIO_CONTEXTS__[componentKey] || global.__STUDIO_CONTEXTS__ || {} if (!contextsForComponent) { - console.error( - `[${displayName}] Using context ${contextToUse} but no contexts defined in context.js file.` - ) + console.error(`[${displayName}] Using context ${contextToUse} but no contexts defined in context.js file.`) return originalFn(title, cb) } @@ -54,9 +48,7 @@ class DescribeContext { const NextComponent = addReactContextToComponent(Component, {context}) - return originalFn(`[${contextToUse}] ${title}`, () => - cb(NextComponent, {context}) - ) + return originalFn(`[${contextToUse}] ${title}`, () => cb(NextComponent, {context})) } } } diff --git a/packages/sui-studio/src/routes.js b/packages/sui-studio/src/routes.js index 3e35e0716..a725456dd 100644 --- a/packages/sui-studio/src/routes.js +++ b/packages/sui-studio/src/routes.js @@ -10,25 +10,14 @@ import {FILES} from './constants.js' export default ( - + - } - /> - ( - - )} - /> + } /> + } /> diff --git a/packages/sui-studio/src/runtime-mocha/index.js b/packages/sui-studio/src/runtime-mocha/index.js index d780f704c..3bd12a255 100644 --- a/packages/sui-studio/src/runtime-mocha/index.js +++ b/packages/sui-studio/src/runtime-mocha/index.js @@ -20,9 +20,7 @@ const categories = CATEGORIES ? CATEGORIES.split(',') : null const filterAll = key => { const [, category] = key.split('/') - return categories - ? categories.includes(category) - : micromatch.isMatch(key, globPattern, {contains: true}) + return categories ? categories.includes(category) : micromatch.isMatch(key, globPattern, {contains: true}) } // Require all the files from a context @@ -49,8 +47,7 @@ Promise.all( let categoryComponentKey = `${category}/${component}` let subComponentName = null - const subComponentRegex = - /components\.(?\w+)\.test\.(js|jsx)/ + const subComponentRegex = /components\.(?\w+)\.test\.(js|jsx)/ const matchesSubComponent = key.match(subComponentRegex) if (matchesSubComponent !== null) { @@ -59,8 +56,7 @@ Promise.all( } const getContexts = await importContexts({category, component}) - const contexts = - typeof getContexts === 'function' ? await getContexts() : getContexts + const contexts = typeof getContexts === 'function' ? await getContexts() : getContexts const componentModule = await importReactComponent({ category, @@ -69,13 +65,10 @@ Promise.all( extractDefault: true }) - const Component = - componentModule && (componentModule.type || componentModule) + const Component = componentModule && (componentModule.type || componentModule) if (!componentModule) { - console.error( - `Could not find component ${categoryComponentKey} in ${key}` - ) + console.error(`Could not find component ${categoryComponentKey} in ${key}`) console.error(`Available keys: `, selectedTestFiles.keys()) throw new Error(`Missing export default from ${categoryComponentKey}`) } diff --git a/packages/sui-studio/src/snarkdown.js b/packages/sui-studio/src/snarkdown.js index d292cb6c5..c5676f6fd 100644 --- a/packages/sui-studio/src/snarkdown.js +++ b/packages/sui-studio/src/snarkdown.js @@ -22,10 +22,7 @@ function outdent(str) { * @private */ function encodeAttr(str) { - return (str + '') - .replace(/"/g, '"') - .replace(//g, '>') + return (str + '').replace(/"/g, '"').replace(//g, '>') } /** Parse Markdown into an HTML String. */ @@ -96,16 +93,11 @@ export default function parse(md, prevLinks) { } // Images: else if (token[8]) { - chunk = `${encodeAttr(
-        token[7]
-      )}` + chunk = `${encodeAttr(token[7])}` } // Links: else if (token[10]) { - out = out.replace( - '', - `` - ) + out = out.replace('', ``) chunk = flush() + '' } else if (token[9]) { chunk = '' @@ -113,8 +105,7 @@ export default function parse(md, prevLinks) { // Headings: else if (token[12] || token[14]) { t = 'h' + (token[14] ? token[14].length : token[13][0] === '=' ? 1 : 2) - chunk = - '<' + t + '>' + parse(token[12] || token[15], links) + '' + chunk = '<' + t + '>' + parse(token[12] || token[15], links) + '' } // `code`: else if (token[16]) { diff --git a/packages/sui-studio/test/server/copySpec.js b/packages/sui-studio/test/server/copySpec.js index da09c0caf..ce5a113cc 100644 --- a/packages/sui-studio/test/server/copySpec.js +++ b/packages/sui-studio/test/server/copySpec.js @@ -32,10 +32,7 @@ describe('copyfiles', () => { const to = 'runtime' return copyfiles([from, to], {up: 1}).then(async () => { - const out = path.join( - __dirname, - 'runtime/components/atom/button/index.js' - ) + const out = path.join(__dirname, 'runtime/components/atom/button/index.js') const stat = await fs.stat(out) expect(stat.isFile()).to.be.true }) diff --git a/packages/sui-studio/test/server/integration/static-server.js b/packages/sui-studio/test/server/integration/static-server.js index ecd4d9ad9..c95b0b22f 100644 --- a/packages/sui-studio/test/server/integration/static-server.js +++ b/packages/sui-studio/test/server/integration/static-server.js @@ -14,10 +14,7 @@ const server = http.createServer((req, res) => { const ext = path.extname(req.url) - const resource = fs.readFileSync( - path.join(BASE_PATH, ext === '' ? 'index.html' : req.url), - {encoding: 'utf8'} - ) + const resource = fs.readFileSync(path.join(BASE_PATH, ext === '' ? 'index.html' : req.url), {encoding: 'utf8'}) res.statusCode = 200 res.setHeader( @@ -28,7 +25,5 @@ const server = http.createServer((req, res) => { }) server.listen(port, hostname, () => { - console.log( - `Stactically serving content from ${BASE_PATH} in http://${hostname}:${port}` - ) + console.log(`Stactically serving content from ${BASE_PATH} in http://${hostname}:${port}`) }) diff --git a/packages/sui-studio/test/server/integrationSpec.js b/packages/sui-studio/test/server/integrationSpec.js index e211ad2c8..f66f50816 100644 --- a/packages/sui-studio/test/server/integrationSpec.js +++ b/packages/sui-studio/test/server/integrationSpec.js @@ -19,16 +19,13 @@ describe.skip('[Integration] sui-studio', () => { it('Should compile and build a static version with one component', async function () { this.timeout(0) - const {stdout: stdoutStudioBuild} = await exec( - `node "${SUI_STUDIO_BINARY_DIR}/sui-studio-build" -C`, - { - cwd: SAMPLE_STUDIO_PATH, - env: { - ...process.env, - PWD: SAMPLE_STUDIO_PATH - } + const {stdout: stdoutStudioBuild} = await exec(`node "${SUI_STUDIO_BINARY_DIR}/sui-studio-build" -C`, { + cwd: SAMPLE_STUDIO_PATH, + env: { + ...process.env, + PWD: SAMPLE_STUDIO_PATH } - ) + }) expect(stdoutStudioBuild.includes('Error')).to.be.false }) @@ -37,17 +34,13 @@ describe.skip('[Integration] sui-studio', () => { this.timeout(0) let server try { - server = childProcess.spawn( - 'node', - [`${SUI_STUDIO_BINARY_DIR}/sui-studio-dev`, 'atom/button'], - { - detached: false, - env: { - ...process.env, - PWD: SAMPLE_STUDIO_PATH - } + server = childProcess.spawn('node', [`${SUI_STUDIO_BINARY_DIR}/sui-studio-dev`, 'atom/button'], { + detached: false, + env: { + ...process.env, + PWD: SAMPLE_STUDIO_PATH } - ) + }) // server.stdout.pipe(process.stdout) // server.stderr.pipe(process.stdout) @@ -82,12 +75,9 @@ describe.skip('[Integration] sui-studio', () => { const { stdout: stdoutStudioGenerate, stderr: stderrStudioGenerate // eslint-disable-line - } = await exec( - `node "${SUI_STUDIO_BINARY_DIR}/sui-studio-generate.js" -P tst -S t-est fake component`, - { - cwd: EMPTY_STUDIO_PATH - } - ) + } = await exec(`node "${SUI_STUDIO_BINARY_DIR}/sui-studio-generate.js" -P tst -S t-est fake component`, { + cwd: EMPTY_STUDIO_PATH + }) // console.log(stdoutStudioGenerate, stderrStudioGenerate) @@ -102,17 +92,7 @@ describe.skip('[Integration] sui-studio', () => { expect(stdoutStudioGenerate.includes('Error')).to.be.false expect(componentManifest.name).to.be.eql('@t-est/tst-fake-component') expect( - fs.readFileSync( - path.join( - `${EMPTY_STUDIO_PATH}`, - 'components', - 'fake', - 'component', - 'src', - 'index.js' - ), - 'utf8' - ) + fs.readFileSync(path.join(`${EMPTY_STUDIO_PATH}`, 'components', 'fake', 'component', 'src', 'index.js'), 'utf8') ).to.be.eql(`// import PropTypes from 'prop-types' export default function FakeComponent() { @@ -128,14 +108,7 @@ FakeComponent.propTypes = {} `) expect( fs.readFileSync( - path.join( - `${EMPTY_STUDIO_PATH}`, - 'components', - 'fake', - 'component', - 'src', - 'index.scss' - ), + path.join(`${EMPTY_STUDIO_PATH}`, 'components', 'fake', 'component', 'src', 'index.scss'), 'utf8' ) ).to.be.eql(`@import '~@s-ui/theme/lib/index'; @@ -146,30 +119,11 @@ FakeComponent.propTypes = {} `) expect( - fs.readFileSync( - path.join( - `${EMPTY_STUDIO_PATH}`, - 'demo', - 'fake', - 'component', - 'playground' - ), - 'utf8' - ) + fs.readFileSync(path.join(`${EMPTY_STUDIO_PATH}`, 'demo', 'fake', 'component', 'playground'), 'utf8') ).to.be.eql('return ()') - expect( - fs.readFileSync( - path.join( - `${EMPTY_STUDIO_PATH}`, - 'test', - 'fake', - 'component', - 'index.js' - ), - 'utf8' - ) - ).to.be.eql(`/* + expect(fs.readFileSync(path.join(`${EMPTY_STUDIO_PATH}`, 'test', 'fake', 'component', 'index.js'), 'utf8')).to.be + .eql(`/* * Remember: YOUR COMPONENT IS DEFINED GLOBALLY * */ diff --git a/packages/sui-studio/workbench/src/app.js b/packages/sui-studio/workbench/src/app.js index e10ce4149..e3de42a59 100644 --- a/packages/sui-studio/workbench/src/app.js +++ b/packages/sui-studio/workbench/src/app.js @@ -26,9 +26,7 @@ const params = queryStringToJSON(window.location.href) const importAll = requireContext => requireContext.keys().map(requireContext) ;(async () => { - const {default: defaultStyle} = await import( - '!css-loader!@s-ui/sass-loader!component/index.scss' - ) + const {default: defaultStyle} = await import('!css-loader!@s-ui/sass-loader!component/index.scss') let styles = [] let requireContextThemesKeys = [] @@ -43,11 +41,7 @@ const importAll = requireContext => requireContext.keys().map(requireContext) * ] * We might want to filter those to avoid importAll to import twice the same */ - const requireContextThemes = require.context( - '!css-loader!@s-ui/sass-loader!demo/themes', - false, - /\.scss$/ - ) + const requireContextThemes = require.context('!css-loader!@s-ui/sass-loader!demo/themes', false, /\.scss$/) requireContextThemesKeys = requireContextThemes.keys() styles = importAll(requireContextThemes) } catch {} diff --git a/packages/sui-studio/workbench/src/components/Raw/index.js b/packages/sui-studio/workbench/src/components/Raw/index.js index 1a23f30fc..b7e81c19d 100644 --- a/packages/sui-studio/workbench/src/components/Raw/index.js +++ b/packages/sui-studio/workbench/src/components/Raw/index.js @@ -6,11 +6,7 @@ import PropTypes from 'prop-types' import SUIContext from '@s-ui/react-context' -import { - cleanDisplayName, - createContextByType, - removeDefaultContext -} from '../../../../src/components/demo/utilities.js' +import {cleanDisplayName, createContextByType, removeDefaultContext} from '../../../../src/components/demo/utilities.js' import Preview from '../../../../src/components/preview/index.js' import Style from '../../../../src/components/style/index.js' import {fetchPlayground} from '../../../../src/components/tryRequire.js' @@ -29,8 +25,7 @@ export default function Raw({ }) { const [playground, setPlayground] = useState(null) - const context = - Object.keys(contexts).length && createContextByType(contexts, actualContext) + const context = Object.keys(contexts).length && createContextByType(contexts, actualContext) // check if is a normal component or it's wrapped with a React.memo method const ComponentToRender = Component.type ? Component.type : Component @@ -50,8 +45,7 @@ export default function Raw({ scope={{ context, React, - [cleanDisplayName(ComponentToRender.displayName)]: - ComponentToRender, + [cleanDisplayName(ComponentToRender.displayName)]: ComponentToRender, ...nonDefault }} code={playground} diff --git a/packages/sui-studio/workbench/src/components/Root/index.js b/packages/sui-studio/workbench/src/components/Root/index.js index 8568ccb45..37f324270 100644 --- a/packages/sui-studio/workbench/src/components/Root/index.js +++ b/packages/sui-studio/workbench/src/components/Root/index.js @@ -9,8 +9,7 @@ import Test from '../Suite/index.js' const importComponent = () => import('component/index.js') const importTest = () => import('test/index.test.js') -const getFromStorage = (key, defaultValue) => - window.sessionStorage[key] || defaultValue +const getFromStorage = (key, defaultValue) => window.sessionStorage[key] || defaultValue const updateOnChange = (setState, sessionKey) => nextValue => { window.sessionStorage.setItem(sessionKey, nextValue) @@ -18,15 +17,9 @@ const updateOnChange = (setState, sessionKey) => nextValue => { } export default function Root({componentID, contexts = {}, themes}) { - const [actualContext, setActualContext] = useState(() => - getFromStorage('actualContext', 'default') - ) - const [actualStyle, setActualStyle] = useState(() => - getFromStorage('actualStyle', 'default') - ) - const [showTests, setShowTests] = useState(() => - getFromStorage('showTests', 'show') - ) + const [actualContext, setActualContext] = useState(() => getFromStorage('actualContext', 'default')) + const [actualStyle, setActualStyle] = useState(() => getFromStorage('actualStyle', 'default')) + const [showTests, setShowTests] = useState(() => getFromStorage('showTests', 'show')) const iframeSrc = `/?raw=true&actualStyle=${actualStyle}&actualContext=${actualContext}` @@ -48,10 +41,7 @@ export default function Root({componentID, contexts = {}, themes}) {