From ab0fa1f5de795d662f367fcf9f1feebc72ad11ae Mon Sep 17 00:00:00 2001 From: Alexandre Bodin Date: Thu, 25 Apr 2019 12:34:55 +0200 Subject: [PATCH] Init build bin --- examples/getstarted/package.json | 1 + packages/strapi-admin/webpack.config.js | 109 ++++++------- .../strapi-generate-new/json/package.json.js | 1 + .../services/ContentManager.js | 2 +- .../config/policies/permissions.js | 9 +- .../controllers/UsersPermissions.js | 11 -- packages/strapi/bin/build.js | 151 ++++++++++-------- packages/strapi/bin/strapi.js | 18 ++- packages/strapi/lib/Strapi.js | 4 - packages/strapi/lib/core/bootstrap.js | 26 +-- packages/strapi/lib/core/index.js | 2 - packages/strapi/lib/core/plugins.js | 150 ----------------- .../strapi/lib/middlewares/public/index.js | 125 +-------------- packages/strapi/lib/utils/openBrowser.js | 28 ++-- 14 files changed, 175 insertions(+), 462 deletions(-) delete mode 100644 packages/strapi/lib/core/plugins.js diff --git a/examples/getstarted/package.json b/examples/getstarted/package.json index 1fece1de47..0f9f81f536 100644 --- a/examples/getstarted/package.json +++ b/examples/getstarted/package.json @@ -7,6 +7,7 @@ "scripts": { "setup": "cd admin && npm run setup", "start": "node server.js", + "build": "strapi build", "strapi": "node_modules/strapi/bin/strapi.js", "lint": "node_modules/.bin/eslint api/**/*.js config/**/*.js plugins/**/*.js" }, diff --git a/packages/strapi-admin/webpack.config.js b/packages/strapi-admin/webpack.config.js index 618c30d363..d0fadf4b70 100644 --- a/packages/strapi-admin/webpack.config.js +++ b/packages/strapi-admin/webpack.config.js @@ -13,62 +13,55 @@ const BundleAnalyzerPlugin = require('webpack-bundle-analyzer') .BundleAnalyzerPlugin; const alias = require('./webpack.alias.js'); -const devMode = process.env.NODE_ENV !== 'production'; -const prodMode = process.env.NODE_ENV === 'production'; - const URLs = { host: '/admin/', backend: 'http://localhost:1337', publicPath: '/admin/', mode: 'host', }; -const appDir = path.resolve(process.cwd(), '..'); -const PORT = 4000; -const webpackPlugins = devMode - ? [ - new WebpackDashboard(), - new DuplicatePckgChecker({ - verbose: true, - }), - new FriendlyErrorsWebpackPlugin({ - compilationSuccessInfo: { - messages: ['Your application is running here http://localhost:4000'], - }, - }), - new BundleAnalyzerPlugin(), - // new OpenBrowserWebpackPlugin({ - // url: `http://localhost:${PORT}/${URLs.publicPath}`, - // }), - ] - : [ - new webpack.IgnorePlugin({ - resourceRegExp: /^\.\/locale$/, - contextRegExp: /moment$/, - }), - new MiniCssExtractPlugin({ - filename: devMode ? '[name].css' : '[name].[chunkhash].css', - chunkFilename: devMode - ? '[name].chunk.css' - : '[name].[chunkhash].chunkhash.css', - }), - ]; +const webpackPlugins = ({ dev }) => + dev + ? [ + new WebpackDashboard(), + new DuplicatePckgChecker({ + verbose: true, + }), + new FriendlyErrorsWebpackPlugin(), + // new BundleAnalyzerPlugin(), + // new OpenBrowserWebpackPlugin({ + // url: `http://localhost:${PORT}/${URLs.publicPath}`, + // }), + ] + : [ + new webpack.IgnorePlugin({ + resourceRegExp: /^\.\/locale$/, + contextRegExp: /moment$/, + }), + new MiniCssExtractPlugin({ + filename: dev ? '[name].css' : '[name].[chunkhash].css', + chunkFilename: dev + ? '[name].chunk.css' + : '[name].[chunkhash].chunkhash.css', + }), + ]; // Use style loader in dev mode to optimize compilation -const scssLoader = devMode - ? [{ loader: 'style-loader', options: {} }] - : [ - { - loader: MiniCssExtractPlugin.loader, - options: { - fallback: require.resolve('style-loader'), - publicPath: URLs.publicPath, - }, - }, - ]; +const scssLoader = ({ dev }) => + dev + ? [{ loader: 'style-loader', options: {} }] + : [ + { + loader: MiniCssExtractPlugin.loader, + options: { + fallback: require.resolve('style-loader'), + publicPath: URLs.publicPath, + }, + }, + ]; -module.exports = { - mode: 'development', +module.exports = ({ entry, dest, dev }) => ({ + mode: dev ? 'development' : 'production', devServer: { historyApiFallback: { index: URLs.publicPath, @@ -77,19 +70,17 @@ module.exports = { stats: 'minimal', // hot: true, }, - stats: devMode ? 'minimal' : 'errors-only', + stats: dev ? 'minimal' : 'errors-only', devtool: 'cheap-module-source-map', context: path.resolve(__dirname), - // TODO: change this with the correct path - // It only work with the monorepo setup - entry: path.resolve(appDir, 'strapi-admin', 'admin', 'src', 'app.js'), + entry, output: { - path: path.resolve(process.cwd(), 'admin', 'build'), + path: dest, publicPath: URLs.publicPath, // Utilize long-term caching by adding content hashes (not compilation hashes) // to compiled assets for production - filename: devMode ? '[name].js' : '[name].[chunkhash].js', - chunkFilename: devMode ? '[name].chunk.js' : '[name].[chunkhash].chunk.js', + filename: dev ? '[name].js' : '[name].[chunkhash].js', + chunkFilename: dev ? '[name].chunk.js' : '[name].[chunkhash].chunk.js', }, module: { rules: [ @@ -100,8 +91,8 @@ module.exports = { loader: require.resolve('babel-loader'), options: { cacheDirectory: true, - cacheCompression: prodMode, - compact: prodMode, + cacheCompression: !dev, + compact: !dev, presets: [ require.resolve('@babel/preset-env'), require.resolve('@babel/preset-react'), @@ -110,7 +101,7 @@ module.exports = { require.resolve('@babel/plugin-proposal-class-properties'), require.resolve('@babel/plugin-syntax-dynamic-import'), require.resolve( - '@babel/plugin-proposal-async-generator-functions', + '@babel/plugin-proposal-async-generator-functions' ), [ require.resolve('@babel/plugin-transform-runtime'), @@ -148,7 +139,7 @@ module.exports = { }, { test: /\.scss$/, - use: scssLoader.concat([ + use: scssLoader({ dev }).concat([ { loader: require.resolve('css-loader'), options: { @@ -234,5 +225,5 @@ module.exports = { MODE: JSON.stringify(URLs.mode), // Allow us to define the public path for the plugins assets. PUBLIC_PATH: JSON.stringify(URLs.publicPath), }), - ].concat(webpackPlugins), -}; + ].concat(webpackPlugins({ dev })), +}); diff --git a/packages/strapi-generate-new/json/package.json.js b/packages/strapi-generate-new/json/package.json.js index 9e623346c7..3c4ff5b92a 100644 --- a/packages/strapi-generate-new/json/package.json.js +++ b/packages/strapi-generate-new/json/package.json.js @@ -41,6 +41,7 @@ module.exports = scope => { 'main': './server.js', 'scripts': { 'setup': 'cd admin && npm run setup', // Ready to deploy setup + 'build': 'strapi build', 'start': 'node server.js', 'strapi': 'strapi', // Allow to use `npm run strapi` CLI, 'lint': 'eslint api/**/*.js config/**/*.js plugins/**/*.js' diff --git a/packages/strapi-plugin-content-manager/services/ContentManager.js b/packages/strapi-plugin-content-manager/services/ContentManager.js index 8952059799..ecd1ccf5e0 100644 --- a/packages/strapi-plugin-content-manager/services/ContentManager.js +++ b/packages/strapi-plugin-content-manager/services/ContentManager.js @@ -105,7 +105,7 @@ module.exports = { id: entry.id || entry._id, }); } - + // Create an entry using `queries` system return await strapi.query(params.model, source).create({ values, diff --git a/packages/strapi-plugin-users-permissions/config/policies/permissions.js b/packages/strapi-plugin-users-permissions/config/policies/permissions.js index 65df75c45c..479ce322d9 100644 --- a/packages/strapi-plugin-users-permissions/config/policies/permissions.js +++ b/packages/strapi-plugin-users-permissions/config/policies/permissions.js @@ -16,6 +16,7 @@ module.exports = async (ctx, next) => { ctx.state.user = await strapi .query('user', 'users-permissions') .findOne({ _id, id }); + ctx.state.admin = await strapi .query('administrator', 'admin') .findOne({ _id, id }); @@ -28,7 +29,7 @@ module.exports = async (ctx, next) => { return handleErrors( ctx, 'Your account has been blocked by the administrator.', - 'unauthorized', + 'unauthorized' ); } @@ -59,7 +60,7 @@ module.exports = async (ctx, next) => { return handleErrors( ctx, 'Your account email is not confirmed.', - 'unauthorized', + 'unauthorized' ); } @@ -67,7 +68,7 @@ module.exports = async (ctx, next) => { return handleErrors( ctx, 'Your account has been blocked by the administrator.', - 'unauthorized', + 'unauthorized' ); } } @@ -90,7 +91,7 @@ module.exports = async (ctx, next) => { action: route.action, enabled: true, }, - [], + [] ); if (!permission) { diff --git a/packages/strapi-plugin-users-permissions/controllers/UsersPermissions.js b/packages/strapi-plugin-users-permissions/controllers/UsersPermissions.js index 727a695ee1..f72169626a 100644 --- a/packages/strapi-plugin-users-permissions/controllers/UsersPermissions.js +++ b/packages/strapi-plugin-users-permissions/controllers/UsersPermissions.js @@ -161,18 +161,7 @@ module.exports = { }, updateRole: async function(ctx) { - // Fetch root role. - const root = await strapi - .query('role', 'users-permissions') - .findOne({ type: 'root' }); - const roleID = ctx.params.role; - const rootID = root.id || root._id; - - // Prevent from updating the root role. - if (roleID === rootID) { - return ctx.badRequest(null, [{ messages: [{ id: 'Unauthorized' }] }]); - } if (_.isEmpty(ctx.request.body)) { return ctx.badRequest(null, [{ messages: [{ id: 'Bad request' }] }]); diff --git a/packages/strapi/bin/build.js b/packages/strapi/bin/build.js index 9908cdeb63..58e515d84b 100644 --- a/packages/strapi/bin/build.js +++ b/packages/strapi/bin/build.js @@ -1,34 +1,49 @@ const path = require('path'); +const webpack = require('webpack'); const fs = require('fs-extra'); +const getPkgPath = require('../lib/load/package-path'); -const appPath = process.cwd(); -const pkgPath = pkg => path.dirname(require.resolve(`${pkg}/package.json`)); -const cacheDir = path.resolve(appPath, '.cache'); -const pkgJSON = require(path.join(appPath, 'package.json')); +function createPluginsJs(plugins, dest) { + const content = ` + const injectReducer = require('./utils/injectReducer').default; + const injectSaga = require('./utils/injectSaga').default; + const { languages } = require('./i18n'); -fs.copySync( - path.resolve(pkgPath('strapi-admin'), 'admin'), - path.resolve(cacheDir, 'admin'), -); -fs.ensureDirSync(path.resolve(cacheDir, 'config')); -fs.copySync( - path.resolve(pkgPath('strapi-admin'), 'config', 'layout.js'), - path.resolve(cacheDir, 'config', 'layout.js'), -); + window.strapi = Object.assign(window.strapi || {}, { + node: MODE || 'host', + backendURL: BACKEND_URL, + languages, + currentLanguage: + window.localStorage.getItem('strapi-admin-language') || + window.navigator.language || + window.navigator.userLanguage || + 'en', + injectReducer, + injectSaga, + }); -const strapiDeps = Object.keys(pkgJSON.dependencies).filter( - dep => - dep.startsWith('strapi-plugin') && - fs.existsSync(path.resolve(pkgPath(dep), 'admin', 'src', 'index.js')), -); + module.exports = { + ${plugins + .map(name => { + const shortName = name.replace(/^strapi-plugin-/i, ''); + const req = `require('../../plugins/${name}/admin/src').default`; + return `'${shortName}': ${req}`; + }) + .join(',\n')} + } + `; + + fs.writeFileSync(path.resolve(dest, 'admin', 'src', 'plugins.js'), content); +} + +async function copyPlugin(name, dest) { + const pkgFilePath = getPkgPath(name); -strapiDeps.forEach(dep => { - const pkgFilePath = pkgPath(dep); const resolveDepPath = (...args) => path.resolve(pkgFilePath, ...args); - const resolveCachDir = (...args) => - path.resolve(cacheDir, 'plugins', dep, ...args); + const resolveDest = (...args) => path.resolve(dest, 'plugins', name, ...args); + const copy = (...args) => { - fs.copySync(resolveDepPath(...args), resolveCachDir(...args)); + fs.copySync(resolveDepPath(...args), resolveDest(...args)); }; // Copy the entire admin folder @@ -36,57 +51,59 @@ strapiDeps.forEach(dep => { // Copy the layout.js if it exists if (fs.existsSync(path.resolve(pkgFilePath, 'config', 'layout.js'))) { - fs.ensureDirSync(resolveCachDir('config')); + fs.ensureDirSync(resolveDest('config')); copy('config', 'layout.js'); } copy('package.json'); -}); +} -fs.writeFileSync( - path.resolve(cacheDir, 'admin', 'src', 'plugins.js'), - ` -const injectReducer = require('./utils/injectReducer').default; -const injectSaga = require('./utils/injectSaga').default; -const { languages } = require('./i18n'); +async function copyAdmin(dest) { + const adminPath = getPkgPath('strapi-admin'); -window.strapi = Object.assign(window.strapi || {}, { - node: MODE || 'host', - backendURL: BACKEND_URL, - languages, - currentLanguage: - window.localStorage.getItem('strapi-admin-language') || - window.navigator.language || - window.navigator.userLanguage || - 'en', - injectReducer, - injectSaga, -}); + await fs.ensureDir(path.resolve(dest, 'config')); + await fs.copy(path.resolve(adminPath, 'admin'), path.resolve(dest, 'admin')); + await fs.copy( + path.resolve(adminPath, 'config', 'layout.js'), + path.resolve(dest, 'config', 'layout.js') + ); +} -module.exports = { -${strapiDeps - .map( - p => - `'${p.replace( - /^strapi-plugin-/i, - '', - )}': require('../../plugins/${p}/admin/src').default`, - ) - .join(',\n')} -}\n - `, - 'utf8', -); +module.exports = async () => { + console.log('Building your app'); + const dir = process.cwd(); + const cacheDir = path.resolve(dir, '.cache'); -// const c = strapiDeps.reduce((acc, current) => { -// acc[current] = `require('../../plugins/${current}/admin/src').default`; + const pkgJSON = require(path.join(dir, 'package.json')); -// return acc; -// }, {}); -// console.log(c); + // create .cache dir + await fs.ensureDir(cacheDir); -// fs.writeFileSync( -// path.resolve(cacheDir, 'admin', 'src', 'plugins.js'), -// c, -// 'utf8', -// ); + await copyAdmin(cacheDir); + + const pluginsToCopy = Object.keys(pkgJSON.dependencies).filter( + dep => + dep.startsWith('strapi-plugin') && + fs.existsSync(path.resolve(getPkgPath(dep), 'admin', 'src', 'index.js')) + ); + + pluginsToCopy.forEach(name => copyPlugin(name, cacheDir)); + + createPluginsJs(pluginsToCopy, cacheDir); + + const config = require(path.resolve( + getPkgPath('strapi-admin'), + 'webpack.config.js' + ))({ + entry: path.resolve(cacheDir, 'admin', 'src', 'app.js'), + dest: path.resolve(dir, 'build'), + }); + + webpack(config, (err, stats) => { + // Stats Object + if (err || stats.hasErrors()) { + // Handle errors here + } + // Done processing + }); +}; diff --git a/packages/strapi/bin/strapi.js b/packages/strapi/bin/strapi.js index ec3c683f8a..5418ca2578 100755 --- a/packages/strapi/bin/strapi.js +++ b/packages/strapi/bin/strapi.js @@ -33,15 +33,16 @@ program.version(packageJSON.version, '-v, --version'); // Make `-v` option case-insensitive. process.argv = _.map(process.argv, arg => { - return (arg === '-V') ? '-v' : arg; + return arg === '-V' ? '-v' : arg; }); // `$ strapi version` (--version synonym) program .command('version') .description('output your version of Strapi') - .action(() => { console.log(packageJSON.version); }); - + .action(() => { + console.log(packageJSON.version); + }); // `$ strapi console` program @@ -72,7 +73,7 @@ program program .command('start [appPath]') .description('start your Strapi application') - .action((appPath) => { + .action(appPath => { require('./strapi-start')(appPath); }); @@ -146,6 +147,11 @@ program .description('uninstall a Strapi plugin') .action(require('./strapi-uninstall')); +program + .command('build') + .description('Builds the strapi admin app') + .action(require('./build')); + /** * Normalize help argument */ @@ -158,9 +164,7 @@ program // `$ strapi ` // Mask the '*' in `help`. -program - .command('*') - .action(program.usageMinusWildcard); +program.command('*').action(program.usageMinusWildcard); // Don't balk at unknown options. diff --git a/packages/strapi/lib/Strapi.js b/packages/strapi/lib/Strapi.js index 34d7748456..8953c91e96 100644 --- a/packages/strapi/lib/Strapi.js +++ b/packages/strapi/lib/Strapi.js @@ -16,7 +16,6 @@ const { loadMiddlewares, loadHooks, bootstrap, - plugins, admin, loadExtensions, initCoreStore, @@ -287,9 +286,6 @@ class Strapi extends EventEmitter { initializeMiddlewares.call(this), initializeHooks.call(this), ]); - - // Harmonize plugins configuration. - await plugins.call(this); } reload() { diff --git a/packages/strapi/lib/core/bootstrap.js b/packages/strapi/lib/core/bootstrap.js index a983038281..9fb7028048 100644 --- a/packages/strapi/lib/core/bootstrap.js +++ b/packages/strapi/lib/core/bootstrap.js @@ -302,15 +302,14 @@ module.exports = function(strapi) { hostname: strapi.config.host, port: strapi.config.port, }); + const adminPath = _.get( strapi.config.currentEnvironment.server, 'admin.path', 'admin' ); - strapi.config.admin.devMode = isAdminInDevMode(strapi); - strapi.config.admin.url = strapi.config.admin.devMode - ? new URL(adminPath, `http://${strapi.config.host}:4000`).toString() - : new URL(adminPath, url).toString(); + + strapi.config.admin.url = new URL(adminPath, url).toString(); // proxy settings const proxy = _.get(strapi.config.currentEnvironment, 'server.proxy', {}); @@ -391,25 +390,6 @@ const enableHookNestedDependencies = function( } }; -const isAdminInDevMode = function(strapi) { - try { - fs.accessSync( - path.resolve( - strapi.config.appPath, - 'admin', - 'admin', - 'build', - 'index.html' - ), - fs.constants.R_OK | fs.constants.W_OK - ); - - return false; - } catch (e) { - return true; - } -}; - const getURLFromSegments = function({ hostname, port, ssl = false }) { const protocol = ssl ? 'https' : 'http'; const defaultPort = ssl ? 443 : 80; diff --git a/packages/strapi/lib/core/index.js b/packages/strapi/lib/core/index.js index d30ccaed1e..f916e5fc30 100644 --- a/packages/strapi/lib/core/index.js +++ b/packages/strapi/lib/core/index.js @@ -6,7 +6,6 @@ const loadMiddlewares = require('./load-middlewares'); const loadExtensions = require('./load-extensions'); const loadHooks = require('./load-hooks'); const bootstrap = require('./bootstrap'); -const plugins = require('./plugins'); const admin = require('./admin'); const initCoreStore = require('./init-core-store'); @@ -17,7 +16,6 @@ module.exports = { loadApis, loadExtensions, bootstrap, - plugins, admin, initCoreStore, }; diff --git a/packages/strapi/lib/core/plugins.js b/packages/strapi/lib/core/plugins.js deleted file mode 100644 index a22cf4dfec..0000000000 --- a/packages/strapi/lib/core/plugins.js +++ /dev/null @@ -1,150 +0,0 @@ -'use strict'; - -// Dependencies. -const path = require('path'); -const fs = require('fs-extra'); -const _ = require('lodash'); - -module.exports = async function() { - // The regex removes possible slashes from the beginning and end of the value - const folder = _.get(strapi.config.currentEnvironment.server, 'admin.path', 'admin').replace(/^\/|\/$/g, ''); - - const configuratePlugin = (acc, current, source, name) => { - switch (source) { - case 'host': { - let host; - - try { - host = _.get(this.config.environments[current].server, 'admin.build.host').replace(/\/$/, '') || '/'; - - } catch (e) { - throw new Error("You can't use `remote` as a source without set the `host` configuration."); - } - - const folder = _.get(this.config.environments[current].server, 'admin.build.plugins.folder', null); - - if (_.isString(folder)) { - const cleanFolder = folder[0] === '/' ? folder.substring(1) : folder; - - return `/${host}/${cleanFolder}/${name}/main.js`.replace('//', '/'); - } - - return `/${host}/${name}/main.js`.replace('//', '/'); - } - - case 'custom': - if (!_.isEmpty(_.get(this.plugins[name].config, `sources.${current}`, {}))) { - return (acc[current] = this.plugins[name].config.sources[current]); - } - - throw new Error( - 'You have to define the source URL for each environment in `./plugins/**/config/sources.json`' - ); - - case 'backend': { - const backend = _.get( - this.config.environments[current], - 'server.admin.build.backend', - `http://${this.config.environments[current].server.host}:${ - this.config.environments[current].server.port - }`, - ).replace(/\/$/, ''); - - return `${backend}/${folder.replace(/\/$/, '')}/${name}/main.js`; - } - - default: - return `/${name}/main.js`; - } - }; - - const sourcePath = - this.config.environment !== 'test' - ? path.resolve(this.config.appPath, 'admin', 'admin', 'src', 'config', 'plugins.json') - : path.resolve( - this.config.appPath, - 'packages', - 'strapi-admin', - 'admin', - 'src', - 'config', - 'plugins.json', - ); - const buildPath = - this.config.environment !== 'test' - ? path.resolve(this.config.appPath, 'admin', 'admin', 'build', 'config', 'plugins.json') - : path.resolve( - this.config.appPath, - 'packages', - 'strapi-admin', - 'admin', - 'build', - 'config', - 'plugins.json', - ); - - const isAdmin = await fs.pathExists(path.resolve(this.config.appPath, 'admin', 'admin')); - if (!isAdmin) { - return; - } - - const existBuildPath = await fs.pathExists(buildPath); - if (strapi.config.currentEnvironment.server.production && existBuildPath) { - return; - } else if (strapi.config.currentEnvironment.server.production && !existBuildPath) { - console.log('The plugins.json file is missing and the front-end cannot work without it. Please, create it first at development environment.'); - } - - // arrange system directories - await Promise.all([ - fs.remove(sourcePath), - - (async () => { - if (existBuildPath) { - await fs.remove(buildPath); - } else { - await fs.ensureDir(path.resolve(buildPath, '..', '..')); - } - })(), - - // Create `./config` folder - fs.ensureDir(path.resolve(buildPath, '..')), - ]); - - // Create `plugins.json` file. - // Don't inject the plugins without an Admin - const existingPlugins = Object.keys(this.plugins).filter(plugin => { - try { - fs.accessSync(path.resolve(this.config.appPath, 'plugins', plugin, 'admin', 'src', 'containers', 'App')); - return true; - } catch(err) { - return false; - } - }); - - const existingPluginsInfo = existingPlugins.map(id => ({ - id, - source: Object.keys(this.config.environments).reduce((acc, current) => { - const source = _.get(this.config.environments[current].server, 'admin.build.plugins.source', 'default'); - - if (_.isString(source)) { - acc[current] = configuratePlugin(acc, current, source, id); - } else if (_.isOject(source)) { - acc[current] = configuratePlugin(acc, current, source[current], id); - } - - return acc; - }, {}), - })); - - await Promise.all([ - fs.writeJSON(sourcePath, existingPluginsInfo, { - spaces: 2, - encoding: 'utf8', - }), - fs.writeJSON(buildPath, existingPluginsInfo, { - spaces: 2, - encoding: 'utf8', - }), - ]); -}; diff --git a/packages/strapi/lib/middlewares/public/index.js b/packages/strapi/lib/middlewares/public/index.js index d19abe4b8a..9b143d72a1 100644 --- a/packages/strapi/lib/middlewares/public/index.js +++ b/packages/strapi/lib/middlewares/public/index.js @@ -38,7 +38,7 @@ module.exports = strapi => { { maxage: strapi.config.middleware.settings.public.maxAge, defer: true, - }, + } ), ], }); @@ -63,19 +63,18 @@ module.exports = strapi => { { maxage: strapi.config.middleware.settings.public.maxAge, defer: true, - }, + } ), ], }); const basename = _.get( strapi.config.currentEnvironment.server, - 'admin.path', + 'admin.path' ) ? strapi.config.currentEnvironment.server.admin.path : '/admin'; - console.log({ basename }); // Serve /admin index page. strapi.router.route({ method: 'GET', @@ -86,7 +85,7 @@ module.exports = strapi => { await next(); }, - strapi.koaMiddlewares.static('./.cache/admin/build', { + strapi.koaMiddlewares.static('./build', { maxage: strapi.config.middleware.settings.public.maxAge, defer: true, }), @@ -107,7 +106,7 @@ module.exports = strapi => { await next(); }, - strapi.koaMiddlewares.static('./.cache/admin/build', { + strapi.koaMiddlewares.static('./build', { maxage: strapi.config.middleware.settings.public.maxAge, defer: true, }), @@ -124,125 +123,13 @@ module.exports = strapi => { await next(); }, - strapi.koaMiddlewares.static('./.cache/admin/build', { + strapi.koaMiddlewares.static('./build', { maxage: strapi.config.middleware.settings.public.maxAge, defer: true, }), ], }); - // Allow page refresh - strapi.router.route({ - method: 'GET', - path: `${basename}/plugins/*`, - handler: [ - async (ctx, next) => { - const parse = path.parse(ctx.url); - - if (parse.ext === '') { - ctx.url = 'index.html'; - } - - await next(); - }, - strapi.koaMiddlewares.static('./.cache/admin/build', { - maxage: strapi.config.middleware.settings.public.maxAge, - defer: true, - }), - ], - }); - - // Serve plugins assets. - strapi.router.route({ - method: 'GET', - path: `${basename}/:resource/*.*`, - handler: async (ctx, next) => { - ctx.url = path.basename(ctx.url); - - if (Object.keys(strapi.plugins).indexOf(ctx.params.resource) !== -1) { - return await strapi.koaMiddlewares.static( - `./plugins/${ctx.params.resource}/admin/build`, - { - maxage: strapi.config.middleware.settings.public.maxAge, - defer: true, - }, - )(ctx, next); - } - - // Handle subfolders. - return await strapi.koaMiddlewares.static( - `./admin/admin/build/${ctx.params.resource}`, - { - maxage: strapi.config.middleware.settings.public.maxAge, - defer: true, - }, - )(ctx, next); - }, - }); - - // Plugins. - _.forEach(strapi.plugins, (value, plugin) => { - strapi.router.route({ - method: 'GET', - path: `/plugins/${plugin}/*.*`, - handler: [ - async (ctx, next) => { - ctx.url = path.basename(ctx.url); - - // Try to find assets into the build first. - return await strapi.koaMiddlewares.static( - `./plugins/${plugin}/admin/build`, - { - maxage: strapi.config.middleware.settings.public.maxAge, - defer: true, - }, - )(ctx, next); - }, - async (ctx, next) => { - // Try to find assets in the source then. - return await strapi.koaMiddlewares.static( - `./plugins/${plugin}/${strapi.config.middleware.settings.public - .path || strapi.config.paths.static}`, - { - maxage: strapi.config.middleware.settings.public.maxAge, - defer: true, - }, - )(ctx, next); - }, - ], - }); - - strapi.router.route({ - method: 'GET', - path: `${basename}/plugins/${plugin}/*.*`, - handler: [ - async (ctx, next) => { - ctx.url = path.basename(ctx.url); - - // Try to find assets into the build first. - return await strapi.koaMiddlewares.static( - `./plugins/${plugin}/admin/build`, - { - maxage: strapi.config.middleware.settings.public.maxAge, - defer: true, - }, - )(ctx, next); - }, - async (ctx, next) => { - // Try to find assets in the source then. - return await strapi.koaMiddlewares.static( - `./plugins/${plugin}/${strapi.config.middleware.settings.public - .path || strapi.config.paths.static}`, - { - maxage: strapi.config.middleware.settings.public.maxAge, - defer: true, - }, - )(ctx, next); - }, - ], - }); - }); - cb(); }, }; diff --git a/packages/strapi/lib/utils/openBrowser.js b/packages/strapi/lib/utils/openBrowser.js index d0dd4faec5..9866b79cf4 100644 --- a/packages/strapi/lib/utils/openBrowser.js +++ b/packages/strapi/lib/utils/openBrowser.js @@ -76,10 +76,13 @@ function startBrowserProcess(browser, url) { // Try our best to reuse existing tab // on OS X Google Chrome with AppleScript execSync('ps cax | grep "Google Chrome"'); - execSync(`osascript resources/openChrome.applescript "${encodeURI(url)}"`, { - cwd: __dirname, - stdio: 'ignore', - }); + execSync( + `osascript resources/openChrome.applescript "${encodeURI(url)}"`, + { + cwd: __dirname, + stdio: 'ignore', + } + ); return true; } catch (err) { strapi.log.error('Failed to open Google Chrome with AppleScript'); @@ -107,24 +110,19 @@ function startBrowserProcess(browser, url) { async function pingDashboard(url, multipleTime = false) { try { - await fetch(url, { method:'HEAD', timeout: 300, body: null }); + await fetch(url, { method: 'HEAD', timeout: 300, body: null }); // Inform the user that we're going to open the administration panel. - this.log.info("⏳ Opening the admin panel..."); + this.log.info('⏳ Opening the admin panel...'); } catch (e) { if (e.code !== 'ECONNREFUSED' && e.type !== 'request-timeout') { return console.error(e); } - + // Only display once. if (!multipleTime) { - this.log.warn(`⚠️ The admin panel is unavailable... Impossible to open it in the browser.`); - } - - // Only retry if the user is running the administration on another server. - if (this.config.admin.devMode) { - // Wait 1 second until the next ping. - await new Promise((resolve) => { setTimeout(resolve, 1000); }); - await pingDashboard.call(this, url, true); + this.log.warn( + `⚠️ The admin panel is unavailable... Impossible to open it in the browser.` + ); } } }