hapijs - Cannot start server before plugins finished registration - javascript

So I have Hapi (v17.5.1) and when I have my plugins array as
[
{
plugin: good,
options: {
reporters: {
errorReporter: [
{
module: 'good-squeeze',
name: 'Squeeze',
args: [{ error: '*' }],
}, {
module: 'good-console',
},
'stderr',
],
infoReporter: [
{
module: 'good-squeeze',
name: 'Squeeze',
args: [{ log: '*', response: '*' }],
}, {
module: 'good-console',
},
'stdout',
],
},
}
]
Let's save it in a variable goodPlugin for the next example.
That is, only with the good plugin and it works fine but when I go and try to add Inert, Vision or Hapi-Swagger, it breaks giving the error Cannot start server before plugins finished registration.
An example:
const HapiSwagger = require('hapi-swagger');
const Inert = require('inert');
const Vision = require('vision');
const Pack = require('../package');
module.exports = [
Inert,
Vision,
// goodPlugin,
{
plugin: HapiSwagger,
options: {
info: {
title: Pack.description,
version: Pack.version,
},
},
}
];
Where am I going wrong? I even tried to add this only when the development mode is on, but it gave me the same error.

Do you use await when registering plugins? As suggested per documentation, the plugin registration part should look like this:
const init = async () => {
await server.register({
plugin: require('hapi-pino')
});
await server.start();
console.log(`Server running at: ${server.info.uri}`);
};
init();

Related

Multi-profile (ESM format) Cucumber configuration file not quite working

I have the following configuration file for Cucumber:
const common = {
// ...common settings here
};
module.exports = {
ci: {
...common,
format: [
"progress",
],
},
default: {
...common,
format: [
"progress-bar",
],
},
};
This works flawlessly. I can specify any of the defined profiles, etc. I'm looking migrate, if possible, the same configuration file into ESM format, but I just don't quite understand how to make the default profile work. If I do:
export default {
ci: { /* ... */ },
default: { /* ... */ },
};
...and place "type": "module" in package.json, it stops working and the configuration is not understood anymore.
Can anyone spot what's the catch there? Would be great a small explanation if this can be done :)
I was initially confused by the default keyword ;)
This is a working (ESM) configuration with multiple profiles:
const common = {
/* ... */
};
export const ci = {
...common,
format: [
"progress",
],
};
export default {
...common,
format: [
"progress-bar",
],
};

Using next.js with zones (one home app, one admin app). Receiving "destination` does not start with `/`" when attempting to start the app

I'm writing a Next.js app that has 2 apps that I essentially want to run as one app using next.js zones. I've been following along with the example here: https://github.com/vercel/next.js/tree/canary/examples/with-zones. The structure of my app has 2 separate folders, admin and home, each with their own next.config.js file:
Admin next.config.js:
module.exports = {
basePath: '/admin',
}
Home next.config.js:
const CopyPlugin = require('copy-webpack-plugin');
const withBundleAnalyzer = require('#next/bundle-analyzer')({
enabled: process.env.ANALYZE === 'true',
});
const { ADMIN_URL } = process.env
module.exports = withBundleAnalyzer({
async rewrites() {
return [
{
source: '/:path*',
destination: `/:path*`,
},
{
source: '/admin',
destination: `${ADMIN_URL}/admin`,
},
{
source: '/admin/:path*',
destination: `${ADMIN_URL}/admin/:path*`,
},
]
},
reactStrictMode: true,
pageExtensions: ['js', 'jsx', 'mdx', 'ts', 'tsx'],
images: {
domains: ['github.blog'],
deviceSizes: [320, 640, 1080, 1200],
imageSizes: [64, 128],
},
swcMinify: true,
compiler: {
styledComponents: true,
},
webpack: (config, { buildId, dev, isServer, defaultLoaders, webpack }) => {
config.module.rules.push({
test: /\.svg$/,
issuer: {
and: [/\.(js|ts)x?$/],
},
use: [{ loader: '#svgr/webpack' }, { loader: 'url-loader' }],
});
return config;
},
});
When I run the app (starting using "yarn dev" in the home folder), I receive the following message:
destination does not start with /, http://, or https:// for route {"source":"/admin","destination":"undefined/admin"}
destination does not start with /, http://, or https:// for route {"source":"/admin/:path*","destination":"undefined/admin/:path*"}
I'm relatively new to next.js, so I'm sure I'm missing something simple in the rewrite rules. I really appreciate any assistance. Thank you!

Webpack Issue with * in export statement

I'm attempting to package with webpack. However, I am receiving a Module parse failed: Unexpected token error. It points to a node module, which has a export statement using an astrisk.
export * as example from "exampleModule";
How can I avoid webpack throwing the error when building?
I'm using babel 7.11.5 and have plugin-proposal-export-namespace-from in my babel config plugins.
My babel.config.js is as follows:
/* eslint global-require: off, import/no-extraneous-dependencies: off */
const developmentEnvironments = ['development', 'test'];
const developmentPlugins = [require('react-hot-loader/babel')];
const productionPlugins = [
require('babel-plugin-dev-expression'),
// babel-preset-react-optimize
require('#babel/plugin-transform-react-constant-elements'),
require('#babel/plugin-transform-react-inline-elements'),
require('babel-plugin-transform-react-remove-prop-types'),
];
module.exports = (api) => {
// See docs about api at https://babeljs.io/docs/en/config-files#apicache
const development = api.env(developmentEnvironments);
return {
presets: [
// #babel/preset-env will automatically target our browserslist targets
require('#babel/preset-env'),
require('#babel/preset-typescript'),
[require('#babel/preset-react'), { development }],
],
plugins: [
// Stage 0
require('#babel/plugin-proposal-function-bind'),
// Stage 1
require('#babel/plugin-proposal-export-default-from'),
require('#babel/plugin-proposal-logical-assignment-operators'),
[require('#babel/plugin-proposal-optional-chaining'), { loose: false }],
[
require('#babel/plugin-proposal-pipeline-operator'),
{ proposal: 'minimal' },
],
[
require('#babel/plugin-proposal-nullish-coalescing-operator'),
{ loose: false },
],
require('#babel/plugin-proposal-do-expressions'),
// Stage 2
[require('#babel/plugin-proposal-decorators'), { legacy: true }],
require('#babel/plugin-proposal-function-sent'),
require('#babel/plugin-proposal-export-namespace-from'),
require('#babel/plugin-proposal-numeric-separator'),
require('#babel/plugin-proposal-throw-expressions'),
// Stage 3
require('#babel/plugin-syntax-dynamic-import'),
require('#babel/plugin-syntax-import-meta'),
[require('#babel/plugin-proposal-class-properties'), { loose: true }],
require('#babel/plugin-proposal-json-strings'),
...(development ? developmentPlugins : productionPlugins),
],
};
};

How to enable JavaScript Protractor Firefox headless

We have e2e test with Protractor on headless mode.
We want to test the authentication first.
The behaviour is like the above:
1/ The user tap a link on the browser
2/ the server will check if this user is authenticated or not
2.1 if the user is authenticated, the home page will appear
2.2 if not, the user will be redirect to the sso login page by a
The problem here is that, the javascript won't be executed. I try to add some flags but it doesn't make any difference.
exports.config = {
allScriptsTimeout: 20000,
specs: [
'./e2e/account/**/account.spec.ts',
],
capabilities: {
'browserName': 'firefox',
'marionette': true,
'moz:firefoxOptions': {
args: [ "--headless"],
firefox_binary: '/opt/firefox/firefox',
binary_: '/opt/firefox/firefox',
},
acceptInsecureCerts: true,
javascriptEnabled: true,
},
directConnect: true,
baseUrl: 'http://demop-staging-ppd.com/',
framework: 'mocha',
// SELENIUM_PROMISE_MANAGER: false,
mochaOpts: {
reporter: 'spec',
slow: 3000,
ui: 'bdd',
timeout: 720000
},
beforeLaunch: function() {
require('ts-node').register({
project: 'tsconfig.e2e.json'
});
},
onPrepare: function() {
browser.driver.manage().window().setSize(1280, 1024);
// Disable animations
// #ts-ignore
browser.executeScript('document.body.className += " notransition";');
const chai = require('chai');
const chaiAsPromised = require('chai-as-promised');
chai.use(chaiAsPromised);
const chaiString = require('chai-string');
chai.use(chaiString);
// #ts-ignore
global.chai = chai;
},
useAllAngular2AppRoots: true
};
the spec file :
before(async () => {
await browser.waitForAngularEnabled(false);
});
it('should content display content ', async () => {
await browser.get('/');
browser.sleep(5000);
const content= await browser.getPageSource();
console.log(content)
});
I'm open to any suggestions and can provide you with any additional information.
[UPDATE]
I change my config file as a above to try enabling javascript on my browse. It works on local but when I try this on docker image dosen't
capabilities: {
'browserName': 'firefox',
'marionette': true,
'moz:firefoxOptions': {
args: ["--headless"],
firefox_binary: '/opt/firefox/firefox',
binary_: '/opt/firefox/firefox',
"prefs": {
"javascript.options.showInConsole": true,
"javascript.enabled": true
},
"log": { "level": "trace" }
},
acceptInsecureCerts: true,
acceptSslCerts: true,
},
multiCapabilities: [ { browserName: 'firefox', firefoxOptions: { args: ['--headless'] }, 'moz:firefoxOptions': { args: [ '--headless' ] } } ]
Please check with this
Use webdriver-manager to execute. With directConnect you will have permission denied error.
I checked in linux PC also. This works fine

How can I replace files at compile time using webpack?

I have a project with miltiple configuration. The first config is config.dev.js file that contains some development configiration. I using it in development mode. The second config is config.js file. I using it in production mode.
In the code I using imports:
import * as config from './config.js';
I want to use the first config file in development and the second to production whithout rewriting all of the imports. How can I replace this config depending on the build mode?
This is an old question but I've recently stumbled across the same issue and webpack.NormalModuleReplacementPlugin doesn't seem to work anymore (or at least not in my case, where I used JSON files as config). Instead I found another solution using alias:
const path = require("path");
modules.export = {
...
resolve: {
...
alias: {
[path.resolve(__dirname, "src/conf/config.json")]:
path.resolve(__dirname, "src/conf/config.prod.json")
}
}
...
}
I realize this is an old post, but this is one of the first results on Google, so I thought a better answer would be good.
Webpack has a built in "Normal Module Replacement Plugin".
plugins: [
new webpack.NormalModuleReplacementPlugin(
/some\/path\/config\.development\.js/,
'./config.production.js'
)
]
For my use, I put the env file in a variable Here is an example:
let envFilePath = './environment.dev.js';
if (env === 'production') {
envFilePath = './environment.prod.js';
} else if (env === 'staging') {
envFilePath = './environment.stg.js';
}
module.exports = {
// other webpack stuff
....
plugins:[
new webpack.NormalModuleReplacementPlugin(
/src\/environment\/environment\.js/,
envFilePath
),
...
]
}
You can use webpack file-replace-loader
https://www.npmjs.com/package/file-replace-loader
Example:
//webpack.config.js
const resolve = require('path').resolve;
module.exports = {
//...
module: {
rules: [{
test: /\.config\.js$/,
loader: 'file-replace-loader',
options: {
condition: process.env.NODE_ENV === 'development',
replacement: resolve('./config.dev.js'),
async: true,
}
}]
}
}
I wanted to imitate the Angular fileReplacements syntax so I used a config.json like Angular's and if the configuration key matches the env I pass to webpack, loop through the replacements and create several Webpack module rules.
It's not the most elegant thing ever but this is what I ended up with:
// config.json
{
"title": "Some Title",
"configurations": {
"production": {
"fileReplacements": [
{
"replace": "src/environments/environment.ts",
"with": "src/environments/environment.prod.ts"
}
]
},
"lan": {
"fileReplacements": [
{
"replace": "src/environments/environment.ts",
"with": "src/environments/environment.lan.ts"
}
]
}
}
}
// webpack.config.js
const appConfig = require('./config.json');
module.exports = (env, argv) => {
// env.build is like `ng build --prod` as `webpack --env.build=production`
const configuration = appConfig.configurations[env.build];
const fileReplacements = [];
// Safety Check
if(configuration && configuration.fileReplacements) {
// Iterate through replacements
for(const replacement of configuration.fileReplacements) {
// create Webpack module rule
const replace = {
test: path.resolve(replacement.replace),
loader: 'file-replace-loader',
options: {
replacement: path.resolve(replacement.with),
async: true
}
}
fileReplacements.push(replace);
}
}
return {
mode: //...
entry: //...
module: {
rules: [
{
//...
},
// Unpack anywhere here
...fileReplacements
]
}
}
}
This way you don't have to keep messing with webpack and regex tests, just add to the array in config.json
You can also use babel-loader like this:
//webpack.config.js
const resolve = require('path').resolve;
module.exports = {
//...
module: {
strictExportPresence: true,
rules: [{
test: /\.config\.js$/,
include: paths.appSrc,
loader: require.resolve('babel-loader'),
options: {
plugins: [
[
"module-resolver",
{
resolvePath(sourcePath, currentFile, opts) {
if(process.env.NODE_ENV === 'development') {
return sourcePath.substr(0, sourcePath.lastIndexOf('/')) + '/config.dev.js';
} else {
return sourcePath;
}
}
}
]
]
}
}]
}
}
This way you can even define complex algorithms to determine which file you wanna use.
Another way is to use Webpack.DefinePlugin. Especially useful if you have a tiny code block that you want to be included conditionally.
Example follows:
// webpack.conf.js
// Code block that should be inserted or left blank
const ServiceWorkerReg = `window.addEventListener('load', () => {
navigator.serviceWorker.register('service-worker.js').then(registration => {
console.log('SW registered: ', registration);
}).catch(registrationError => {
console.log('SW registration failed: ', registrationError);
});
});`
appConfig = {
plugins: [
new webpack.DefinePlugin({
__SERVICE_WORKER_REG: isDev ? '' : ServiceWorkerReg,
}),
]
...
}
// Some module index.js
__SERVICE_WORKER_REG
... // other non conditional code

Categories