Trouble Deploying Cesium JS Application to AWS Elastic Beanstalk - amazon-elastic-beanstalk

I have an application that I would like to deploy to AWS Elastic Beanstalk, but have been getting a plethora of errors. My issue is that I do not know exactly which files to bundle. I am using one of the Cesium examples with my own parameters. The .html opens fine in web browser via localhost and node.js. However when I've tried to bundle what I thought are the correct files together, I have been getting deployment errors in the logs. I want to hit the 3D Tiles Feature Styling. html in the folder structure below. I have ensured that express is in the node_modules and have tried different scenarios in compiling the files. What is the solution for this issue? I have also changed app.js to main.js per other thread suggestions.
.zip structure used to deploy
HTML:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=Edge,chrome=1"> <!-- Use Chrome Frame in IE -->
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1, minimum-scale=1, user-scalable=no">
<meta name="description" content="Interactive 3D Tiles styling.">
<meta name="cesium-sandcastle-labels" content="Showcases, 3D Tiles">
<title>Cesium Demo</title>
<script type="text/javascript" src="/Sandcastle-header.js"></script>
<script type="text/javascript" src="/require.js"></script>
<script type="text/javascript" src="/apps.js"></script> b
<script type="text/javascript">
require.config({
baseUrl : '../../../Source',
waitSeconds : 60
});
</script>
</head>
<body class="sandcastle-loading" data-sandcastle-bucket="bucket-requirejs.html">
<style>
#import url(/bucket.css);
</style>
<div id="cesiumContainer" class="fullSize"></div>
<div id="loadingOverlay"><h1>Loading...</h1></div>
<div id="toolbar"></div>
<script id="cesium_sandcastle_script">
function startup(Cesium) {
'use strict';
//Sandcastle_Begin
// A demo of interactive 3D Tiles styling
// Styling language Documentation: https://github.com/AnalyticalGraphicsInc/3d-tiles/tree/master/Styling
// Building data courtesy of NYC OpenData portal: http://www1.nyc.gov/site/doitt/initiatives/3d-building.page
Cesium.Ion.defaultAccessToken = 'mykey';
var viewer = new Cesium.Viewer('cesiumContainer');
// Set the initial camera view to look at Manhattan
var initialPosition = Cesium.Cartesian3.fromDegrees(-118.4912, 34.0195, 753);
var initialOrientation = new Cesium.HeadingPitchRoll.fromDegrees(21.27879878293835, -21.34390550872461, 0.0716951918898415);
viewer.scene.camera.setView({
destination: initialPosition,
orientation: initialOrientation,
endTransform: Cesium.Matrix4.IDENTITY
});
// Load the NYC buildings tileset.
var tileset = new Cesium.Cesium3DTileset({ url: Cesium.IonResource.fromAssetId(3099) });
viewer.scene.primitives.add(tileset);
// Color buildings based on their height.
function colorByHeight() {
tileset.style = new Cesium.Cesium3DTileStyle({
color: {
conditions: [
["${height} >= 300", "rgba(45, 0, 75, 0.5)"],
["${height} >= 200", "rgb(102, 71, 151)"],
["${height} >= 100", "rgb(170, 162, 204)"],
["${height} >= 50", "rgb(224, 226, 238)"],
["${height} >= 25", "rgb(252, 230, 200)"],
["${height} >= 10", "rgb(248, 176, 87)"],
["${height} >= 5", "rgb(198, 106, 11)"],
["true", "rgb(127, 59, 8)"]
]
}
});
}
// Color buildings by their total area.
function colorByArea() {
tileset.style = new Cesium.Cesium3DTileStyle({
color: "mix(color('yellow'), color('red'), min(${area} / 10000.0, 1.0))"
});
}
// Color buildings by their latitude coordinate.
function colorByLatitude() {
tileset.style = new Cesium.Cesium3DTileStyle({
color: {
conditions: [
["${latitude} >= 0.7125", "color('purple')"],
["${latitude} >= 0.712", "color('red')"],
["${latitude} >= 0.7115", "color('orange')"],
["${latitude} >= 0.711", "color('yellow')"],
["${latitude} >= 0.7105", "color('lime')"],
["${latitude} >= 0.710", "color('cyan')"],
["true", "color('blue')"]
]
}
});
}
// Color buildings by distance from a landmark.
function colorByDistance() {
tileset.style = new Cesium.Cesium3DTileStyle({
defines : {
distance : "distance(vec2(${longitude}, ${latitude}), vec2(-1.291777521, 0.7105706624))"
},
color : {
conditions : [
["${distance} > 0.0002", "color('gray')"],
["true", "mix(color('yellow'), color('green'), ${distance} / 0.0002)"]
]
}
});
}
// Color buildings with a '3' in their name.
function colorByNameRegex() {
tileset.style = new Cesium.Cesium3DTileStyle({
color : "(regExp('3').test(${name})) ? color('cyan', 0.9) : color('purple', 0.1)"
});
}
// Show only buildings greater than 200 meters in height.
function hideByHeight() {
tileset.style = new Cesium.Cesium3DTileStyle({
show : "${height} > 200"
});
}
Sandcastle.addToolbarMenu([{
text : 'Color By Height',
onselect : function() {
colorByHeight();
}
}, {
text : 'Color By Area',
onselect : function() {
colorByArea();
}
}, {
text : 'Color By Latitude',
onselect : function() {
colorByLatitude();
}
}, {
text : 'Color By Distance',
onselect : function() {
colorByDistance();
}
}, {
text : 'Color By Name Regex',
onselect : function() {
colorByNameRegex();
}
}, {
text : 'Hide By Height',
onselect : function() {
hideByHeight();
}
}]);
colorByHeight();
//Sandcastle_End
Sandcastle.finishedLoading();
}
if (typeof Cesium !== "undefined") {
startup(Cesium);
} else if (typeof require === "function") {
require(["Cesium"], startup);
}
</script>
</body>
</html>
.app js
/*eslint-env node*/
'use strict';
(function() {
var express = require('express');
var compression = require('compression');
var fs = require('fs');
var url = require('url');
var request = require('request');
var gzipHeader = Buffer.from('1F8B08', 'hex');
var yargs = require('yargs').options({
'port' : {
'default' : 3000,
'description' : 'Port to listen on.'
},
'public' : {
'type' : 'boolean',
'description' : 'Run a public server that listens on all interfaces.'
},
'upstream-proxy' : {
'description' : 'A standard proxy server that will be used to retrieve data. Specify a URL including port, e.g. "http://proxy:8000".'
},
'bypass-upstream-proxy-hosts' : {
'description' : 'A comma separated list of hosts that will bypass the specified upstream_proxy, e.g. "lanhost1,lanhost2"'
},
'help' : {
'alias' : 'h',
'type' : 'boolean',
'description' : 'Show this help.'
}
});
var argv = yargs.argv;
if (argv.help) {
return yargs.showHelp();
}
// eventually this mime type configuration will need to change
// https://github.com/visionmedia/send/commit/d2cb54658ce65948b0ed6e5fb5de69d022bef941
// *NOTE* Any changes you make here must be mirrored in web.config.
var mime = express.static.mime;
mime.define({
'application/json' : ['czml', 'json', 'geojson', 'topojson'],
'image/crn' : ['crn'],
'image/ktx' : ['ktx'],
'model/gltf+json' : ['gltf'],
'model/gltf-binary' : ['bgltf', 'glb'],
'application/octet-stream' : ['b3dm', 'pnts', 'i3dm', 'cmpt', 'geom', 'vctr'],
'text/plain' : ['glsl']
}, true);
var app = express();
app.use(compression());
app.use(function(req, res, next) {
res.header('Access-Control-Allow-Origin', '*');
res.header('Access-Control-Allow-Headers', 'Origin, X-Requested-With, Content-Type, Accept');
next();
});
function checkGzipAndNext(req, res, next) {
var reqUrl = url.parse(req.url, true);
var filePath = reqUrl.pathname.substring(1);
var readStream = fs.createReadStream(filePath, { start: 0, end: 2 });
readStream.on('error', function(err) {
next();
});
readStream.on('data', function(chunk) {
if (chunk.equals(gzipHeader)) {
res.header('Content-Encoding', 'gzip');
}
next();
});
}
var knownTilesetFormats = [/\.b3dm/, /\.pnts/, /\.i3dm/, /\.cmpt/, /\.glb/, /\.geom/, /\.vctr/, /tileset.*\.json$/];
app.get(knownTilesetFormats, checkGzipAndNext);
app.use(express.static(__dirname));
function getRemoteUrlFromParam(req) {
var remoteUrl = req.params[0];
if (remoteUrl) {
// add http:// to the URL if no protocol is present
if (!/^https?:\/\//.test(remoteUrl)) {
remoteUrl = 'http://' + remoteUrl;
}
remoteUrl = url.parse(remoteUrl);
// copy query string
remoteUrl.search = url.parse(req.url).search;
}
return remoteUrl;
}
var dontProxyHeaderRegex = /^(?:Host|Proxy-Connection|Connection|Keep-Alive|Transfer-Encoding|TE|Trailer|Proxy-Authorization|Proxy-Authenticate|Upgrade)$/i;
function filterHeaders(req, headers) {
var result = {};
// filter out headers that are listed in the regex above
Object.keys(headers).forEach(function(name) {
if (!dontProxyHeaderRegex.test(name)) {
result[name] = headers[name];
}
});
return result;
}
var upstreamProxy = argv['upstream-proxy'];
var bypassUpstreamProxyHosts = {};
if (argv['bypass-upstream-proxy-hosts']) {
argv['bypass-upstream-proxy-hosts'].split(',').forEach(function(host) {
bypassUpstreamProxyHosts[host.toLowerCase()] = true;
});
}
app.get('/proxy/*', function(req, res, next) {
// look for request like http://localhost:8080/proxy/http://example.com/file?query=1
var remoteUrl = getRemoteUrlFromParam(req);
if (!remoteUrl) {
// look for request like http://localhost:8080/proxy/?http%3A%2F%2Fexample.com%2Ffile%3Fquery%3D1
remoteUrl = Object.keys(req.query)[0];
if (remoteUrl) {
remoteUrl = url.parse(remoteUrl);
}
}
if (!remoteUrl) {
return res.status(400).send('No url specified.');
}
if (!remoteUrl.protocol) {
remoteUrl.protocol = 'http:';
}
var proxy;
if (upstreamProxy && !(remoteUrl.host in bypassUpstreamProxyHosts)) {
proxy = upstreamProxy;
}
// encoding : null means "body" passed to the callback will be raw bytes
request.get({
url : url.format(remoteUrl),
headers : filterHeaders(req, req.headers),
encoding : null,
proxy : proxy
}, function(error, response, body) {
var code = 500;
if (response) {
code = response.statusCode;
res.header(filterHeaders(req, response.headers));
}
res.status(code).send(body);
});
});
var server = app.listen(argv.port, argv.public ? undefined : 'localhost', function() {
if (argv.public) {
console.log('Cesium development server running publicly. Connect to http://localhost:%d/', server.address().port);
} else {
console.log('Cesium development server running locally. Connect to http://localhost:%d/', server.address().port);
}
});
server.on('error', function (e) {
if (e.code === 'EADDRINUSE') {
console.log('Error: Port %d is already in use, select a different port.', argv.port);
console.log('Example: node server.js --port %d', argv.port + 1);
} else if (e.code === 'EACCES') {
console.log('Error: This process does not have permission to listen on port %d.', argv.port);
if (argv.port < 1024) {
console.log('Try a port number higher than 1024.');
}
}
console.log(e);
process.exit(1);
});
server.on('close', function() {
console.log('Cesium development server stopped.');
});
var isFirstSig = true;
process.on('SIGINT', function() {
if (isFirstSig) {
console.log('Cesium development server shutting down.');
server.close(function() {
process.exit(0);
});
isFirstSig = false;
} else {
console.log('Cesium development server force kill.');
process.exit(1);
}
});
})();
logs:
-------------------------------------
/var/log/nodejs/nodejs.log
-------------------------------------
npm ERR! not with npm itself.
npm ERR! Tell the author that this fails on your system:
npm ERR! node server.js
npm ERR! You can get information on how to open an issue for this project with:
npm ERR! npm bugs cesium
npm ERR! Or if that isn't available, you can get their info via:
npm ERR! npm owner ls cesium
npm ERR! There is likely additional logging output above.
npm ERR! Please include the following file with any support request:
npm ERR! /var/app/current/npm-debug.log
> cesium#1.43.0 start /var/app/current
> node server.js
module.js:471
throw err;
^
Error: Cannot find module 'express'
at Function.Module._resolveFilename (module.js:469:15)
at Function.Module._load (module.js:417:25)
at Module.require (module.js:497:17)
at require (internal/module.js:20:19)
at /var/app/current/server.js:4:19
at Object.<anonymous> (/var/app/current/server.js:201:3)
at Module._compile (module.js:570:32)
at Object.Module._extensions..js (module.js:579:10)
at Module.load (module.js:487:32)
at tryModuleLoad (module.js:446:12)
npm ERR! Linux 4.9.77-31.58.amzn1.x86_64
npm ERR! argv "/opt/elasticbeanstalk/node-install/node-v6.11.5-linux-x64/bin/node" "/opt/elasticbeanstalk/node-install/node-v6.11.5-linux-x64/bin/npm" "start"
npm ERR! node v6.11.5
npm ERR! npm v3.10.10
npm ERR! code ELIFECYCLE
npm ERR! cesium#1.43.0 start: `node server.js`
npm ERR! Exit status 1
npm ERR!
npm ERR! Failed at the cesium#1.43.0 start script 'node server.js'.
npm ERR! Make sure you have the latest version of node.js and npm installed.
npm ERR! If you do, this is most likely a problem with the cesium package,
npm ERR! not with npm itself.
npm ERR! Tell the author that this fails on your system:
npm ERR! node server.js
npm ERR! You can get information on how to open an issue for this project with:
npm ERR! npm bugs cesium
npm ERR! Or if that isn't available, you can get their info via:
npm ERR! npm owner ls cesium
npm ERR! There is likely additional logging output above.
npm ERR! Please include the following file with any support request:
npm ERR! /var/app/current/npm-debug.log
> cesium#1.43.0 start /var/app/current
> node server.js
module.js:471
throw err;
^
Error: Cannot find module 'express'
at Function.Module._resolveFilename (module.js:469:15)
at Function.Module._load (module.js:417:25)
at Module.require (module.js:497:17)
at require (internal/module.js:20:19)
at /var/app/current/server.js:4:19
at Object.<anonymous> (/var/app/current/server.js:201:3)
at Module._compile (module.js:570:32)
at Object.Module._extensions..js (module.js:579:10)
at Module.load (module.js:487:32)
at tryModuleLoad (module.js:446:12)
npm ERR! Linux 4.9.77-31.58.amzn1.x86_64
npm ERR! argv "/opt/elasticbeanstalk/node-install/node-v6.11.5-linux-x64/bin/node" "/opt/elasticbeanstalk/node-install/node-v6.11.5-linux-x64/bin/npm" "start"
npm ERR! node v6.11.5
npm ERR! npm v3.10.10
npm ERR! code ELIFECYCLE
npm ERR! cesium#1.43.0 start: `node server.js`
npm ERR! Exit status 1
npm ERR!
npm ERR! Failed at the cesium#1.43.0 start script 'node server.js'.
npm ERR! Make sure you have the latest version of node.js and npm installed.
npm ERR! If you do, this is most likely a problem with the cesium package,
npm ERR! not with npm itself.
npm ERR! Tell the author that this fails on your system:
npm ERR! node server.js
npm ERR! You can get information on how to open an issue for this project with:
npm ERR! npm bugs cesium
npm ERR! Or if that isn't available, you can get their info via:
npm ERR! npm owner ls cesium
npm ERR! There is likely additional logging output above.
npm ERR! Please include the following file with any support request:
npm ERR! /var/app/current/npm-debug.log
> Elastic-Beanstalk-Sample-App#0.0.1 start /var/app/current
> node app.js
Server running at http://127.0.0.1:8081/

Related

Gulpfile.js Throws exception for wrench default implemented method of readdirSyncRecursive while calling require function of node.js

i am new to Gulp and specially Gulp 4. here i have my gulpfile.js
/**
* Welcome to your gulpfile!
* The gulp tasks are splitted in several files in the gulp directory
* because putting all here was really too long
*/
'use strict';
var gulp = require('gulp');
var wrench = require('wrench');
/**
* This will load all js or coffee files in the gulp directory
* in order to load all gulp tasks
*/
wrench.readdirSyncRecursive('./gulp').filter(function(file) {
return (/\.(js|coffee)$/i).test(file);
}).map(function(file) {
require('./gulp/' + file);
});
/**
* Default task clean temporaries directories and launch the
* main optimization build task
*/
gulp.task('default', ['clean'], function () {
gulp.start(['build']);
});
function done() {
}
while trying to run => gulp build i am facing following Exception
AssertionError [ERR_ASSERTION]: Task function must be specified
at Gulp.set [as _setTask] (C:\Users\ahsan\Documents\dev-work\smsvoltapp\node_modules\undertaker\lib\set-task.js:10:3)
at Gulp.task (C:\Users\ahsan\Documents\dev-work\smsvoltapp\node_modules\undertaker\lib\task.js:13:8)
at Object.<anonymous> (C:\Users\ahsan\Documents\dev-work\smsvoltapp\gulp\build.js:28:6)
at Module._compile (node:internal/modules/cjs/loader:1159:14)
at Module._extensions..js (node:internal/modules/cjs/loader:1213:10)
at Module.load (node:internal/modules/cjs/loader:1037:32)
at Module._load (node:internal/modules/cjs/loader:878:12)
at Module.require (node:internal/modules/cjs/loader:1061:19)
at require (node:internal/modules/cjs/helpers:103:18)
at C:\Users\ahsan\Documents\dev-work\smsvoltapp\gulpfile.js:19:3 {
generatedMessage: false,
code: 'ERR_ASSERTION',
actual: false,
expected: true,
operator: '=='
}
It seems the node.js function require at line 19:3 is not upto the mark and valid for gulp4
Gulp version:
CLI version: 2.3.0
Local version: 4.0.2
npm -v => 8.19.2
Please help

Ethereum ERC20 trying to Deploy to Alpha Moonbase (Moonbeam Testnet) and I get "Source "#openzeppelin/contracts/token/ERC20/ERC20.sol" not found:"

My project structure looks like this:
contracts
├── CExampleToken.sol
├── compile.js
├── create-eth-wallet.js
├── deploy.js
├── package-lock.json
├── package.json
└── node_modules
This is my code:
CExampleToken.sol
pragma solidity 0.8.9;
import "#openzeppelin/contracts/token/ERC20/ERC20.sol";
import "#openzeppelin/contracts/token/ERC20/ERC20Detailed.sol";
contract CExampleToken is ERC20 {
constructor() ERC20("CExample", "CEXT") {
_mint(msg.sender, 25000000);
}
}
compile.js
const path = require('path');
const fs = require('fs');
const solc = require('solc');
const contractPath = path.resolve(__dirname, 'CExampleToken.sol');
const source = fs.readFileSync(contractPath, 'utf8');
const input = {
language: "Solidity",
sources: {
'CExampleToken.sol': {
content: source,
},
},
settings: {
outputSelection: {
'*': {
'*': ['*']
},
},
},
};
const tempFile = JSON.parse(solc.compile(JSON.stringify(input)));
console.log(tempFile);
const contractFile = tempFile.contracts['CExampleToken.sol']['CExampleToken'];
module.exports = contractFile;
deploy.js
const Web3 = require('web3');
const contractFile = require('./compile');
const bytecode = contractFile.evm.bytecode.object;
const abi = contractFile.abi;
const privKey = <my private key here>;
const address = <my address here>;
const web3 = new Web3('https://rpc.testnet.moonbeam.network');
const deploy = async () => {
const cexampletoken = new web3.eth.Contract(abi);
const cexampletokenTx = cexampletoken.deploy({
data: bytecode,
});
const createTransaction = await web3.eth.accounts.signTransaction(
{
from: address,
data: cexampletokenTx.encodeABI(),
gas: '4294967295'
},
privKey
);
const createReceipt = await web3.eth.sendSignedTransaction(
createTransaction.rawTransaction
);
console.log("Contract was sucessfully deployed at address: ", createReceipt.contractAddress);
};
deploy();
I am trying to compile and deploy by going
cd contracts
node deploy.js
But I get this error:
<myusername>#<mycomputername> contracts % node deploy.js
{
errors: [
{
component: 'general',
errorCode: '1878',
formattedMessage: 'Warning: SPDX license identifier not provided in source file. Before publishing, consider adding a comment containing "SPDX-License-Identifier: <SPDX-License>" to each source file. Use "SPDX-License-Identifier: UNLICENSED" for non-open-source code. Please see https://spdx.org for more information.\n' +
'--> CExampleToken.sol\n' +
'\n',
message: 'SPDX license identifier not provided in source file. Before publishing, consider adding a comment containing "SPDX-License-Identifier: <SPDX-License>" to each source file. Use "SPDX-License-Identifier: UNLICENSED" for non-open-source code. Please see https://spdx.org for more information.',
severity: 'warning',
sourceLocation: [Object],
type: 'Warning'
},
{
component: 'general',
errorCode: '6275',
formattedMessage: 'ParserError: Source "#openzeppelin/contracts/token/ERC20/ERC20.sol" not found: File import callback not supported\n' +
' --> CExampleToken.sol:3:1:\n' +
' |\n' +
'3 | import "#openzeppelin/contracts/token/ERC20/ERC20.sol";\n' +
' | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^\n' +
'\n',
message: 'Source "#openzeppelin/contracts/token/ERC20/ERC20.sol" not found: File import callback not supported',
severity: 'error',
sourceLocation: [Object],
type: 'ParserError'
},
{
component: 'general',
errorCode: '6275',
formattedMessage: 'ParserError: Source "#openzeppelin/contracts/token/ERC20/ERC20Detailed.sol" not found: File import callback not supported\n' +
' --> CExampleToken.sol:4:1:\n' +
' |\n' +
'4 | import "#openzeppelin/contracts/token/ERC20/ERC20Detailed.sol";\n' +
' | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^\n' +
'\n',
message: 'Source "#openzeppelin/contracts/token/ERC20/ERC20Detailed.sol" not found: File import callback not supported',
severity: 'error',
sourceLocation: [Object],
type: 'ParserError'
}
],
sources: {}
}
/Users/<myusername>/Desktop/Coding/CodingTestSpace/MoonbeamTutorial101921/contracts/compile.js:24
const contractFile = tempFile.contracts['CExampleToken.sol']['CExampleToken'];
^
TypeError: Cannot read properties of undefined (reading 'CExampleToken.sol')
at Object.<anonymous> (/Users/<myusername>/Desktop/Coding/CodingTestSpace/MoonbeamTutorial101921/contracts/compile.js:24:40)
at Module._compile (node:internal/modules/cjs/loader:1101:14)
at Object.Module._extensions..js (node:internal/modules/cjs/loader:1153:10)
at Module.load (node:internal/modules/cjs/loader:981:32)
at Function.Module._load (node:internal/modules/cjs/loader:822:12)
at Module.require (node:internal/modules/cjs/loader:1005:19)
at require (node:internal/modules/cjs/helpers:102:18)
at Object.<anonymous> (/Users/<myusername>/Desktop/Coding/CodingTestSpace/MoonbeamTutorial101921/contracts/deploy.js:2:22)
at Module._compile (node:internal/modules/cjs/loader:1101:14)
at Object.Module._extensions..js (node:internal/modules/cjs/loader:1153:10)
at Module.load (node:internal/modules/cjs/loader:981:32)
at Function.Module._load (node:internal/modules/cjs/loader:822:12)
at Function.executeUserEntryPoint [as runMain] (node:internal/modules/run_main:79:12)
at node:internal/main/run_main_module:17:47
<myusername>#<mycomputername> contracts %
Btw, I did install openzeppelin. When I made the project I did
cd contracts
npm init
npm install solc#latest
npm install #openzeppelin/contracts
What's the problem and how do I fix it?
UPDATE
Okay I fixed the problem thanks to #ahmad-gorji
This issue was that the #openzeppelin contracts were using s different compiler so I copied the functions that #openzeppelin was supposed to import directly into my CExampleToken.sol file.
I'm getting a new error now...
RuntimeError: abort(Error: Returned error: submit transaction to pool failed: Pool(InvalidTransaction(InvalidTransaction::ExhaustsResources))). Build with -s ASSERTIONS=1 for more info.
at process.abort (/home/Coding/CodingTestSpace/MoonbeamTutorial101921/contracts/node_modules/solc/soljson.js:1:13012)
at process.emit (node:events:390:28)
at emit (node:internal/process/promises:136:22)
at processPromiseRejections (node:internal/process/promises:242:25)
at processTicksAndRejections (node:internal/process/task_queues:97:32)
at runNextTicks (node:internal/process/task_queues:65:3)
at listOnTimeout (node:internal/timers:526:9)
at processTimers (node:internal/timers:500:7)
myusername#mycompname contracts %
I think this might have to do with the moonbeam testnet rpc node though :/. This is the network I'm using in the relevant code.
const web3 = new Web3('https://rpc.testnet.moonbeam.network');

Parsing error: Unexpected token click_action

Currently I am working on push notifications using firebase-cloud-messaging . The token click_action is still supported, but still I am getting this error.
My code is
,
The error on cmd (Firebase CLI) is,
notification: {
title: "Notification from" + from_name,
body: from_message,
sound: "default"
click_action: "com.example.tysf_trial"
}
This error is encountered when deployed,
43:5 error Parsing error: Unexpected token click_action
? 1 problem (1 error, 0 warnings)
npm ERR! code ELIFECYCLE
npm ERR! errno 1
npm ERR! functions# lint: `eslint .`
npm ERR! Exit status 1
npm ERR!
npm ERR! Failed at the functions# lint script.
npm ERR! This is probably not a problem with npm. There is likely additional log
ging output above.
npm ERR! A complete log of this run can be found in:
npm ERR! C:\Users\abc\AppData\Roaming\npm-cache\_logs\2019-11-05T19_43_05_08
1Z-debug.log
events.js:187
throw er; // Unhandled 'error' event
^
Error: spawn npm --prefix "%RESOURCE_DIR%" run lint ENOENT
at notFoundError (C:\Users\abc\AppData\Roaming\npm\node_modules\←[4mfirebase
-tools←[24m\node_modules\←[4mcross-env←[24m\node_modules\←[4mcross-spawn←[24m\li
b\enoent.js:6:26)
at verifyENOENT (C:\Users\abc\AppData\Roaming\npm\node_modules\←[4mfirebase-
tools←[24m\node_modules\←[4mcross-env←[24m\node_modules\←[4mcross-spawn←[24m\lib
\enoent.js:40:16)
at ChildProcess.cp.emit (C:\Users\abc\AppData\Roaming\npm\node_modules\←[4mf
irebase-tools←[24m\node_modules\←[4mcross-env←[24m\node_modules\←[4mcross-spawn←
[24m\lib\enoent.js:27:25)
←[90m at Process.ChildProcess._handle.onexit (internal/child_process.js:272:1
2)←[39m
Emitted 'error' event on ChildProcess instance at:
at ChildProcess.cp.emit (C:\Users\abc\AppData\Roaming\npm\node_modules\←[4mf
irebase-tools←[24m\node_modules\←[4mcross-env←[24m\node_modules\←[4mcross-spawn←
[24m\lib\enoent.js:30:37)
←[90m at Process.ChildProcess._handle.onexit (internal/child_process.js:272:1
2)←[39m {
code: ←[32m'ENOENT'←[39m,
errno: ←[32m'ENOENT'←[39m,
syscall: ←[32m'spawn npm --prefix "%RESOURCE_DIR%" run lint'←[39m,
path: ←[32m'npm --prefix "%RESOURCE_DIR%" run lint'←[39m,
spawnargs: []
}
Here is the hole working code for me it working with me yesterday... ^_^
'use-strict'
const functions = require('firebase-functions');
const admin = require('firebase-admin');
admin.initializeApp();
exports.sendNotification = functions.firestore.document
("NotifyUsers/{user_id}/Notification/{notification_id}")
.onWrite((change, context) => {
const user_id = context.params.user_id;
const notification_id = context.params.notification_id;
return admin.firestore().collection("NotifyUsers")
.doc(user_id).collection("Notification").doc(notification_id)
.get().then(queryResult => {
const {from:from_user_id, message:from_message} = queryResult.data();
const from_data = admin.firestore().collection("NotifyUsers")
.doc(from_user_id).get();
const to_data = admin.firestore().collection("NotifyUsers")
.doc(user_id).get();
return Promise.all([from_data, to_data, from_message , from_user_id]);
// added from_message so it's available in the next .then
})
.then(([from_data, to_data, from_message, from_user_id]) => { // added from_message
const from_name = from_data.data().name;
const {name:to_name, token_id} = to_data.data();
console.log("From: " + from_name + " | To : " + to_name +"from:" +from_user_id);
const payload = {
"notification" : {
"title" : "Notification From : " + from_name,
"body" : from_message,
"icon" : 'default',
"click_action": 'return.to.NotificationActivity'
},
"data": {
"from_user_id" : from_user_id,
"message" : from_message
}
};
return admin.messaging().sendToDevice(token_id, payload);
})
.then(result => {
return console.log("Notification Sent");
});
});
You are missing a comma after the sound: line:
notification: {
title: "Notification from" + from_name,
body: from_message,
sound: "default", // here
click_action: "com.example.tysf_trial"
}

GulpUglifyError: unable to minify JavaScript error with Browserify

I'm bundling my script with Browserify + Babel like this:
function buildJs() {
let bopts = {
paths: [
`${SRC}/js`,
'./config'
],
debug: !isProduction
};
let opts = Object.assign({}, watchify.args, bopts);
let b = watchify(persistify(opts));
b.add(`${SRC}/js/index.js`)
.on('update', bundle)
.on('log', gutil.log)
.external(vendors)
.transform(babelify, {
presets: ["es2015", "react"],
plugins: [
"syntax-async-functions",
"transform-regenerator",
"transform-class-properties",
"transform-decorators-legacy",
"transform-object-rest-spread",
"transform-react-jsx-source",
staticFs
]
})
.transform(browserifyCss, { global: true });
function bundle() {
let stream = b.bundle()
.on('error', swallowError)
.on('end', () => {
gutil.log(`Building JS:bundle done.`);
})
.pipe(source('bundle.js'))
.pipe(streamify(uglify()));
return stream.pipe(gulp.dest(`${DIST}/js`));
}
return bundle();
}
It's just browserify -> babelify -> browserify-css -> uglify -> gulp.dest.
But If I ran this task, it fails with:
[17:00:30] Using gulpfile ~/ctc-web/gulpfile.js
[17:00:30] Starting 'build'...
[17:00:46] 1368516 bytes written (16.43 seconds)
[17:00:46] Building JS:bundle done.
events.js:160
throw er; // Unhandled 'error' event
^
GulpUglifyError: unable to minify JavaScript
at createError (/home/devbfex/ctc-web/node_modules/gulp-uglify/lib/create-error.js:6:14)
at wrapper (/home/devbfex/ctc-web/node_modules/lodash/_createHybrid.js:87:15)
at trycatch (/home/devbfex/ctc-web/node_modules/gulp-uglify/minifier.js:26:12)
at DestroyableTransform.minify [as _transform] (/home/devbfex/ctc-web/node_modules/gulp-uglify/minifier.js:79:19)
at DestroyableTransform.Transform._read (/home/devbfex/ctc-web/node_modules/readable-stream/lib/_stream_transform.js:159:10)
at DestroyableTransform.Transform._write (/home/devbfex/ctc-web/node_modules/readable-stream/lib/_stream_transform.js:147:83)
at doWrite (/home/devbfex/ctc-web/node_modules/readable-stream/lib/_stream_writable.js:338:64)
at writeOrBuffer (/home/devbfex/ctc-web/node_modules/readable-stream/lib/_stream_writable.js:327:5)
at DestroyableTransform.Writable.write (/home/devbfex/ctc-web/node_modules/readable-stream/lib/_stream_writable.js:264:11)
at Transform.ondata (_stream_readable.js:555:20)
Just skip uglify works, but I really need it.
The weird thing is that error was occured after end event. I tried using with vinyl-buffer, but same errors happen.
I couldn't find any solution, every my attemps fails with same error message.
What am I missing? Is there a something that I missed?
Try to replace let by var and see what happens.

Browserify - ParseError: 'import' and 'export' may appear only with 'sourceType: module

In my gulpfile I have
var gulp = require('gulp');
var browserSync = require('browser-sync').create();
var sass = require('gulp-sass');
var babel = require("gulp-babel");
var rename = require('gulp-rename');
var source = require('vinyl-source-stream');
var browserify = require('gulp-browserify');
var notify = require("gulp-notify");
gulp.task('js', function () {
gulp.src('js/main.js')
.pipe(babel())
.pipe(browserify())
.on('error', errorAlert)
.pipe(rename('./dist/js/bundle.js'))
//.pipe(uglify())
.pipe(gulp.dest('./'))
.pipe(notify({title: "Success", message: "Well Done!", sound: "Glass"}));
})
and in my app.js I am trying to import but get the errror
import SimpleBreakpoints from 'simple-breakpoints'
Any idea how to get rid of the error and use the import syntax?
Edit: the .babelrc
{
"presets": ["es2015"],
}
In your configuration, you pipe js/main.js to Babel, so that's the only file that will be transpiled. When Browserify requires app.js, it will seen ES6 content and will effect the error you are seeing.
You could use Babelify to solve the problem. It's a Browserify transform that will transpile the source that Browserify receives.
To install it, run this command:
npm install babelify --save-dev
And to configure it, change your task to:
gulp.task('js', function () {
gulp.src('js/main.js')
.pipe(browserify({ transform: ['babelify'] }))
.on('error', errorAlert)
.pipe(rename('./dist/js/bundle.js'))
//.pipe(uglify())
.pipe(gulp.dest('./'))
.pipe(notify({ title: "Success", message: "Well Done!", sound: "Glass" }));
})
Browserify in Gulp
For those who work with gulp and want to transpile ES6 to ES5 with browserify, you might stumble upon gulp-browserify plug-in. Warning as it is from version 0.5.1 gulp-browserify is no longer suported!!!. Consequences, of this action and transpiling with gulp-browserify will result with source code that might produce errors such as the one in question or similar to these: Uncaught ReferenceError: require is not defined or Uncaught SyntaxError: Unexpected identifier next to your import statements e.g. import * from './modules/bar.es6.js';
Solution
Althoutg gulp-browserify recomends to "checkout the recipes by gulp team for reference on using browserify with gulp". I found this advice to no avail. As it is now (2st July 2019) solution that worked for me was to replace gulp-browserify with gulp-bro#1.0.3 plug-in. This successfully, transpired ES6 to ES5 (as it is now) - It might change in future since support for JavaSript libraries decays with time of it appearance.
Assumption: To reproduce this solution you should have installed docker. Beside that you should be familiar with babel and babelify.
Source Code
This solution was successfully reproduced in docker environment, run node:11.7.0-alpine image.
Project Structure
/src <- directory
/src/app/foo.es6.js
/src/app/modules/bar.es6.js
/src/app/dist <- directory
/src/app/dist/app.es5.js
/src/gulpfile.js
/src/.babelrc
/src/package.json
/src/node_modules <- directory
Step 1: Run docker image
$ docker run --rm -it --name bro_demo node:11.7.0-alpine ash
Step 2: Create directories and source files
$ mkdir -p /src/dist
$ mkdir -p /src/app/modules/
$ touch /src/app/foo.es6.js
$ touch /src/app/modules/bar.es6.js
$ touch /src/gulpfile.js
$ touch /src/.babelrc
$ touch /src/package.json
$ cd /src/
$ apk add vim
.babelrc
{
"presets": ["#babel/preset-env"]
}
package.json
{
"name": "src",
"version": "1.0.0",
"description": "",
"main": "",
"keywords": [],
"author": "",
"license": "ISC",
"devDependencies": {
"#babel/core": "^7.4.5",
"#babel/preset-env": "^7.4.5",
"babelify": "^10.0.0",
"gulp": "^4.0.2",
"gulp-bro": "^1.0.3",
"gulp-rename": "^1.2.2"
}
}
bar.es6.js
"use strict"
class Bar {
constructor(grammar) {
console.log('Bar time!');
}
}
export default Bar;
foo.es6.js
"use strict"
import Bar from './modules/bar.es6.js';
class Foo {
constructor(grammar) {
console.log('Foo time!');
}
}
var foo = new Foo()
var bar = new Bar()
gulpfile.js
const bro = require('gulp-bro');
const gulp = require('gulp');
const rename = require('gulp-rename');
const babelify = require('babelify');
function transpileResources(callback) {
gulp.src(['./app/foo.es6.js'])
.pipe(bro({transform: [babelify.configure({ presets: ['#babel/preset-env'] })] }))
.pipe(rename('app.es5.js'))
.pipe(gulp.dest('./dist/'));
callback();
}
exports.transpile = transpileResources;
Step 3 - Transpile ES6 to ES5
$ npm install
$ npm install -g gulp#4.0.2
$ gulp transpile
[09:30:30] Using gulpfile /src/gulpfile.js
[09:30:30] Starting 'transpile'...
[09:30:30] Finished 'transpile' after 9.33 ms
$ node dist/app.es5.js
Foo time!
Bar time!
Source code after transpilation app.es5.js
(function(){function r(e,n,t){function o(i,f){if(!n[i]){if(!e[i]){var c="function"==typeof require&&require;if(!f&&c)return c(i,!0);if(u)return u(i,!0);var a=new Error("Cannot find module '"+i+"'");throw a.code="MODULE_NOT_FOUND",a}var p=n[i]={exports:{}};e[i][0].call(p.exports,function(r){var n=e[i][1][r];return o(n||r)},p,p.exports,r,e,n,t)}return n[i].exports}for(var u="function"==typeof require&&require,i=0;i<t.length;i++)o(t[i]);return o}return r})()({1:[function(require,module,exports){
"use strict";
var _barEs = _interopRequireDefault(require("./modules/bar.es6.js"));
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; }
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
var Foo = function Foo(grammar) {
_classCallCheck(this, Foo);
console.log('Foo time!');
};
var foo = new Foo();
var bar = new _barEs["default"]();
},{"./modules/bar.es6.js":2}],2:[function(require,module,exports){
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports["default"] = void 0;
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
var Bar = function Bar(grammar) {
_classCallCheck(this, Bar);
console.log('Bar time!');
};
var _default = Bar;
exports["default"] = _default;
},{}]},{},[1]);
Simply switching to webpack instead of browserify fixed the issue for me.
var webpack = require('webpack-stream')
gulp.task('default', function () {
return gulp.src('src/source.js')
.pipe(webpack({
output: {
filename: 'app.js'
}
}))
.pipe(gulp.dest('dist/app.js'))
})