Browsersync is running but does not refresh the page - docker

I have MacOS + installed Docker container by Mark Shust (https://github.com/markshust/docker-magento) + installed browsersync on the host.
Magento has ".less" files in the folder: app/design/frontend. I set a folder as a current one in the cli. And run this command from the host:
browser-sync start --host "domain.test" --proxy "https://domain.test" --files "**/*.less" --https
I get this output:
[Browsersync] Proxying: https://domain.test
[Browsersync] Access URLs:
--------------------------------------
Local: https://localhost:3000
External: https://domain.test:3000
--------------------------------------
UI: http://localhost:3002
UI External: http://localhost:3002
--------------------------------------
[Browsersync] Watching files...
I can open https://domain.test and it works properly. http://localhost:3002 shows that there are no current connections. However, the output in the cli infoms: "[Browsersync] Reloading Browsers..."
if i change less, i still can find changes on the website but only after a manual reload.
The documentation mentions grunt configuration and there are some recipes as an example. I tried to use standard magento's file but it does not help. It looks like this:
module.exports = function (grunt) {
'use strict';
grunt.initConfig({
watch: {
files: 'app/design/**/*.less',
tasks: ['less']
},
browserSync: {
dev: {
bsFiles: {
src : [
'app/design/**/*.css'
]
},
options: {
watchTask: true,
server: './'
}
}
}
});
// load npm tasks
grunt.loadNpmTasks('grunt-contrib-sass');
grunt.loadNpmTasks('grunt-contrib-watch');
grunt.loadNpmTasks('grunt-browser-sync');
// define default task
grunt.registerTask('default', ['browserSync', 'watch']);
var _ = require('underscore'),
path = require('path'),
filesRouter = require('./dev/tools/grunt/tools/files-router'),
configDir = './dev/tools/grunt/configs',
tasks = grunt.file.expand('./dev/tools/grunt/tasks/*'),
themes;
filesRouter.set('themes', 'dev/tools/grunt/configs/themes');
themes = filesRouter.get('themes');
tasks = _.map(tasks, function (task) {
return task.replace('.js', '');
});
tasks.push('time-grunt');
tasks.forEach(function (task) {
require(task)(grunt);
});
require('load-grunt-config')(grunt, {
configPath: path.join(__dirname, configDir),
init: true,
jitGrunt: {
staticMappings: {
usebanner: 'grunt-banner'
}
}
});
_.each({
/**
* Assembling tasks.
* ToDo: define default tasks.
*/
default: function () {
grunt.log.subhead('I\'m default task and at the moment I\'m empty, sorry :/');
},
/**
* Production preparation task.
*/
prod: function (component) {
var tasks = [
'less',
'cssmin',
'usebanner'
].map(function (task) {
return task + ':' + component;
});
if (typeof component === 'undefined') {
grunt.log.subhead('Tip: Please make sure that u specify prod subtask. By default prod task do nothing');
} else {
grunt.task.run(tasks);
}
},
/**
* Refresh themes.
*/
refresh: function () {
var tasks = [
'clean',
'exec:all'
];
_.each(themes, function (theme, name) {
tasks.push('less:' + name);
});
grunt.task.run(tasks);
},
/**
* Documentation
*/
documentation: [
'replace:documentation',
'less:documentation',
'styledocco:documentation',
'usebanner:documentationCss',
'usebanner:documentationLess',
'usebanner:documentationHtml',
'clean:var',
'clean:pub'
],
'legacy-build': [
'mage-minify:legacy'
],
spec: function (theme) {
var runner = require('./dev/tests/js/jasmine/spec_runner');
runner.init(grunt, { theme: theme });
grunt.task.run(runner.getTasks());
}
}, function (task, name) {
grunt.registerTask(name, task);
});};
Should it work without gruntjs running? And why the page reload is not triggered?
PS: I did not place this question into https://magento.stackexchange.com/ cause i believe it's a general problem and not related to Magento.

Related

remoteEntry.js not found on Jenkins

We are deploying a remote app written in NextJS and Typescript; The host app is in React only.
Currently the host app gets a 404 not found error as the remote app runs into this error in the Build Snapshot on Jenkins
+ ls ./dist/static/chunks/remoteEntry.js
ls: cannot access './dist/static/chunks/remoteEntry.js': No such file or directory
script returned exit code 2
However, the file is generated locally and both apps are able to spin up in local environment.
Here is our next.config.js:
const NextFederationPlugin = require('#module-federation/nextjs-mf');
const { exposedModules } = require('./lib/routes');
const version = process.env.VERSION_OVERRIDE || require('./package.json').version;
const deps = require('./package.json').dependencies;
// Note: This path needs to match with what's specified in CIRRUS_FRONTEND_ENTRYPOINT for www.
const assetBasePath = process.env.CDN_PATH ? `${process.env.CDN_PATH}${version}` : process.env.ASSET_BASE_PATH;
// Note: Heavily references module federation example meant for omnidirectional federation between Next apps.
// Changes mostly around path resolution due to our current resolution pattern via cdn
// https://github.com/module-federation/module-federation-examples/blob/master/nextjs/home/next.config.js
module.exports = {
webpack(config, options) {
Object.assign(config.experiments, { topLevelAwait: true });
// Integrated mode calls `next build` which has minimization by default. For local development, this is unnecessary.
if (process.env.NEXT_PUBLIC_ENVIRONMENT === 'INTEGRATED') {
config.optimization.minimize = false;
}
if (!options.isServer) {
console.log("Not Server");
config.output.publicPath = 'auto';
config.plugins.push(
new NextFederationPlugin({
name: 'cirrus',
filename: 'static/chunks/remoteEntry.js',
exposes: {
'./FederatedRouter': './lib/FederatedRouter',
...exposedModules
},
remoteType: 'var',
remotes: {},
shared: {
'#transcriptic/amino': {
requiredVersion: deps['#transcriptic/amino'],
singleton: true
},
react: {
requiredVersion: deps.react,
singleton: true
},
'react-dom': {
requiredVersion: deps['react-dom'],
singleton: true
},
'#strateos/micro-apps-utils': {
requiredVersion: deps['#strateos/micro-apps-utils'],
singleton: true
}
},
extraOptions: {
// We need to override the default module sharing behavior of this plugin as that assumes a nextjs host
// and thus next modules will be provided by the parent application.
// However, web is currently NOT a nextjs application so this child application so that assumption is
// invalid. Note that this means we need to ensure we explicitly specify common modules such as `react`
// in the `shared` key above.
skipSharingNextInternals: true
}
})
);
} else {
console.log("Is Server");
}
return config;
},
// Note: Annoyingly, NextJS automatically automatically appends a `_next` directory for assetPrefix
// but NOT public path so we'll have to manually include it here.
publicPath: `${assetBasePath}/_next/`,
// Note: If serving assets via CDN, assetPrefix is required to help resolve static assets.
// Also, NextJS automatically appends and expects a `_next` directory to the assetPrefix path.
// See https://nextjs.org/docs/api-reference/next.config.js/cdn-support-with-asset-prefix
assetPrefix: process.env.CDN_PATH ? assetBasePath : undefined,
distDir: 'dist',
// Use index react-router as fallback for resolving any pages that are not directly specified
async rewrites() {
return {
fallback: [
{
source: '/:path*',
destination: '/'
}
]
};
}
};
Tried upgrade NextJS from 12.1.6 to 12.2.2
Tried upgrade Webpack from 5.74.0 to 5.75.0
Cleaned cache by sh 'yarn cache clean'
Tried clear env by sh 'env -i PATH=$PATH make build-snapshot'
Hash of node modules by tar -cf - node_modules | md5sum
Downgraded "#module-federation/nextjs-mf" from 5.12.9 to 5.10.5
Verified file writing permission

Workbox precache doesn't precache

I'm attempting to implement workbox to precache image and video assets on a website.
I've created a service worker file. It appears to be successfully referenced and used in my application. The service worker:
import { clientsClaim, setCacheNameDetails } from 'workbox-core';
import { precacheAndRoute, addRoute } from 'workbox-precaching';
const context = self; // eslint-disable-line no-restricted-globals
setCacheNameDetails({ precache: 'app' });
// eslint-disable-next-line no-restricted-globals, no-underscore-dangle
precacheAndRoute(self.__WB_MANIFEST);
context.addEventListener('install', (event) => {
event.waitUntil(
caches.open('dive').then((cache) => {
console.log(cache);
}),
);
});
context.addEventListener('activate', (event) => {
console.log('sw active');
});
context.addEventListener('fetch', async (event) => {
console.log(event.request.url);
});
context.addEventListener('message', ({ data }) => {
const { type, payload } = data;
if (type === 'cache') {
payload.forEach((url) => {
addRoute(url);
});
const manifest = payload.map((url) => (
{
url,
revision: null,
}
));
console.log('attempting to precache and route manifest', JSON.stringify(manifest));
precacheAndRoute(manifest);
}
});
context.skipWaiting();
clientsClaim();
The application uses workbox-window to load, reference and message the service worker. The app looks like:
import { Workbox } from 'workbox-window';
workbox = new Workbox('/sw.js');
workbox.register();
workbox.messageSW({
type: 'cache',
payload: [
{ url: 'https://media0.giphy.com/media/Ju7l5y9osyymQ/giphy.gif' }
],
});
This project is using vue with vue-cli. It has a webpack config which allows plugins to be sent added to webpack. The config looks like:
const { InjectManifest } = require('workbox-webpack-plugin');
const path = require('path');
module.exports = {
configureWebpack: {
plugins: [
new InjectManifest({
swSrc: path.join(__dirname, 'lib/services/Asset-Cache.serviceworker.js'),
swDest: 'Asset-Cache.serviceworker.js',
}),
],
},
};
I can see messages are successfully sent to the service worker and contain the correct payload. BUT, the assets never show up in Chrome dev tools cache storage. I also never see any workbox logging related to the assets sent via messageSW. I've also tested by disabling my internet, the assets don't appear to be loading into the cache. What am I doing wrong here?
I found the workbox docs to be a little unclear and have also tried to delete the message event handler from the service worker. Then, send messages to the service worker like this:
workbox.messageSW({
type: 'CACHE_URLS',
payload: { urlsToCache: [ 'https://media0.giphy.com/media/Ju7l5y9osyymQ/giphy.gif'] },
});
This also appears to have no effect on the cache.
The precache portion of precacheAndRoute() works by adding install and activate listeners to the current service worker, taking advantage of the service worker lifecycle. This will effectively be a no-op if the service worker has already finished installing and activating by the time it's called, which may be the case if you trigger it conditionally via a message handler.
We should probably warn folks about this ineffective usage of precacheAndRoute() in our Workbox development builds; I've filed an issue to track that.

how to take a screenshot by a locator and then compare with the other locator with the screenshot using appium with webdriverio

how to take a screenshot by a locator and then compare with the other locator with the screenshot(and compare those two images) using appium with webdriverio. I tried looking at a tutorial but not able to find anything that works
You can capture screenshot of an element with webdriver io as mentioned below
it('should save a screenshot of the browser view', function () {
const elem = $('#someElem');
elem.saveScreenshot('./some/path/elemScreenshot.png');
});
you can see more about in on official documentation of webdriver-io
Once you capture screenshot for both element then you can use Visual Regression service for WebdriverIO V5 called wdio-image-comparison-service.
Installation:
Install this module locally with the following command to be used as a (dev-)dependency:
npm install --save-dev wdio-image-comparison-service
Instructions on how to install WebdriverIO can be found here.
Usage:
wdio-image-comparison-service supports NodeJS 8 or higher
Configuration:
wdio-image-comparison-service is a service so it can be used as a normal service. You can set it up in your wdio.conf.js file with the following:
const { join } = require('path');
// wdio.conf.js
exports.config = {
// ...
// =====
// Setup
// =====
services: [
['image-comparison',
// The options
{
// Some options, see the docs for more
baselineFolder: join(process.cwd(), './tests/sauceLabsBaseline/'),
formatImageName: '{tag}-{logName}-{width}x{height}',
screenshotPath: join(process.cwd(), '.tmp/'),
savePerInstance: true,
autoSaveBaseline: true,
blockOutStatusBar: true,
blockOutToolBar: true,
// ... more options
}],
],
// ...
};
Writing tests to compare screenshot of 2 elements:
describe('Example', () => {
beforeEach(() => {
browser.url('https://webdriver.io');
});
it('should save some screenshots', () => {
// Save an element
browser.saveElement($('#element-id'), 'firstButtonElement', { /* some options*/ });
});
it('should compare successful with a baseline', () => {
// Check an element
expect(browser.checkElement($('#element-id'), 'firstButtonElement', { /* some options*/ })).toEqual(0);
});
});
Referenec: Please check all details about image comparison here

google cloud speech not working in electron package

When I run the application from command prompt using npm start command it works well. It returning the result from speech api.
I am using binaryServer and binaryclient to stream audio to google cloud API.
When I create package for electron application everything works but it not returning the result from speech api.
Here are my code snippe:
Package.json
{
"name": "test",
"version": "1.0.0",
"description": "test Web Server",
"main": "main.js",
"scripts": {
"start": "electron main.js"
},
"devDependencies": {
"electron": "^1.4.12"
},
"dependencies": {
"binaryjs": "^0.2.1",
"connect": "^3.3.4",
"biased-opener": "^0.2.8",
"serve-static": "^1.9.1",
"uaparser": "^0.0.2",
"#google-cloud/speech" : "^0.5.0"
}
}
Here is my main.js
app.on('ready', function () {
load_app();
});
var workerProcess = child_process.spawn('node', __dirname + '/binaryServer.js');
workerProcess.stdout.on('data', function (data) {
console.log('stdout: ' + data);
});
workerProcess.stderr.on('data', function (data) {
console.log('stderr: ' + data);
});
workerProcess.on('close', function (code) {
console.log('child process exited with code ' + code);
});
processes.push(workerProcess);
function load_app () {
// Launches the browser window
mainWindow = new BrowserWindow({ width: 1080, height: 1920 });
// Load just launched server in browser window
mainWindow.loadURL("http://localhost:" + config.port);
if (config.devMode) {
mainWindow.webContents.openDevTools();
}
else {
mainWindow.setFullScreen(true);
}
}
here is my binary server
var binaryServer = require('binaryjs').BinaryServer,
https = require('http'),
connect = require('connect'),
serveStatic = require('serve-static');
var config = require('./config');
var server = connect()
.use(serveStatic(__dirname));
var speech = require('#google-cloud/speech')({
projectId: config.speech.projectId,
keyFilename: config.speech.keyFilename
});
httpServer = https.createServer(server);
httpServer.timeout = 0;
httpServer.listen(config.port);
var binarySer = binaryServer({ server: httpServer });
console.log("server pid" + process.pid);
binarySer.on('connection', function (client) {
console.log("new connection...");
client.on('stream', function (stream, meta) {
var options = {
config: {
encoding: 'LINEAR16',
sampleRate: meta.sampleRate,
languageCode: "en-IN"
},
singleUtterance: false,
interimResults: true,
verbose: true
};
// Create a recognize stream
const recognizeStream = speech.createRecognizeStream(options)
.on('error', console.error)
.on('data', function (data) { if (stream.writable && !stream.destroyed) stream.write(data) }); // send data to client
if (recognizeStream.writable && !recognizeStream.destroyed && stream.readable && !stream.destroyed)
stream.pipe(recognizeStream); // pipe audio to cloud speech
});
client.on('close', function () {
console.log("Connection Closed");
});
});
Thanks for your help
Taking a shot in the dark here (without much familiarity with binaryServer, which realistically could be the issue). I'm also a bit unclear about where the audio stream actually comes from:
Electron packages its own version of V8. When you run npm install it will install (or compile on the fly) the native binaries targeted for the version of V8 that are installed on your machine (local version). When you spawn the child process it uses that same local version.
However, when you package your electron app it will try to spawn the process with Electron's version of V8 and there will be binary incompatibilities.
Put simply
[Your version of V8] != [Electron's version of V8]
On to potential solutions
Sonus is compatible with
Electron provided that you
Re-compile dependencies with
electron-recompile

Disable LiveReload with Yeoman

When testing in IE8, LiveReload throws errors since web sockets is not supported. Is there a way to configure yeoman to disable LiveReload?
IE8 isn't supported by Yeoman, for good reason.
However, you could do what Allan describes, or you could override the server task, by putting this in your Gruntfile:
grunt.registerTask('server', 'yeoman-server');
Try to use <!--[if !IE]><!--></body><!--<![endif]--><!--[if IE]></body><!--<![endif]--> instead of </body>.
Generator would try to replace first </body> element and add livereload snippet before it, so code would be placed in invisible for IE space.
P.S. It`s dirty hack so use this carefuly
Put this in your Gruntfile:
grunt.registerHelper('reload:inject', function () {
return function inject(req, res, next) {
return next();
}});
Yes there is one I know.
Go to your project folder and find the file Gruntfile.js
Open the file in a editor
Remove the reload: in watch:
It will look something like this:
// default watch configuration
watch: {
coffee: {
files: 'app/scripts/**/*.coffee',
tasks: 'coffee reload'
},
compass: {
files: [
'app/styles/**/*.{scss,sass}'
],
tasks: 'compass reload'
},
reload: {
files: [
'app/*.html',
'app/styles/**/*.css',
'app/scripts/**/*.js',
'app/images/**/*'
],
tasks: 'reload'
}
}
And after you have removed it something like this:
// default watch configuration
watch: {
coffee: {
files: 'app/scripts/**/*.coffee',
tasks: 'coffee reload'
},
compass: {
files: [
'app/styles/**/*.{scss,sass}'
],
tasks: 'compass reload'
}
}
I think i have seen a commandline flag, but I was unable to find it.
Yeoman Livereload consists of two parts: the middleware that inserts the livereload snippet, and the livereload target in the watch task. To disable livereload, remove both:
Livereload snippet at the top of the Gruntfile:
// Generated on ...
'use strict';
var LIVERELOAD_PORT = 35729; // <- Delete this
var lrSnippet = require('connect-livereload')({port: LIVERELOAD_PORT}); // <- Delete this
var mountFolder = function (connect, dir) {
return connect.static(require('path').resolve(dir));
};
Livereload task in Watch:
watch: {
// Delete this target
livereload: {
options: {
livereload: LIVERELOAD_PORT
},
files: [
//...
]
}
}
And the middleware that inserts the snippet:
connect: {
options: {
port: 9000,
hostname: 'localhost'
},
livereload: {
options: {
middleware: function (connect) {
return [
lrSnippet, // <- Delete this middleware
mountFolder(connect, '.tmp'),
mountFolder(connect, yeomanConfig.app)
];
}
}
For updates on fixing the livereload-connect issues in Yeoman, track this issue: https://github.com/yeoman/generator-webapp/issues/63

Resources