Register command for StatusBarItem - javascript

I am creating a Visual Studio Code extension and have read that in order to provide a functionality to the StatusBarItem onclick event I need to register a command for the status bar item. How do I do this? When I create a StatusBarItem using window.createStatusBarItem I get an object which doesn't seem to have any string as identifier but the command registering process requires a string as first argument and I am not sure how to associate it with the StatusBarItem.
I have used yeoman to bootstrap a JavaScript extension.
extension.js
const vscode = require('vscode');
const { exec } = require('child_process')
function activate(context) {
console.log('Thanks for installing me! Remember to add a script to run if you want this extension to do anything \
instersting at all :P');
// TODO: make status bar item clickable
const statusBarItem = vscode.window.createStatusBarItem(vscode.StatusBarAlignment.Right, 1000);
function runCommandAndUpdateStatusBarItem () {
// TODO: fetch command from settings
const command = 'git describe --dirty="-$USER"';
exec(`cd ${vscode.workspace.rootPath} && ${command}`, [], (error, stdout, stderr) => {
if (stdout) {
statusBarItem.text = `$(git-commit) ${stdout}`;
statusBarItem.show();
}
else {
vscode.window.showErrorMessage(stderr);
statusBarItem.hide();
}
});
}
statusBarItem.hide();
let disposable = vscode.commands.registerCommand('extension.sayHello', runCommandAndUpdateStatusBarItem);
context.subscriptions.push(statusBarItem);
context.subscriptions.push(disposable);
}
exports.activate = activate;
function deactivate() {
console.log('Oh...so, you hate me? Ok I go away now :(');
}
exports.deactivate = deactivate;
package.json
{
"name": "script-result-info",
"displayName": "Script Result Info",
"description": "Runs a script in shell and puts the result in the statusBar",
"version": "0.0.1",
"publisher": "emilioidk",
"engines": {
"vscode": "^1.23.0"
},
"categories": [
"Other"
],
"activationEvents": [
"onCommand:extension.sayHello"
],
"main": "./extension",
"contributes": {
"commands": [
{
"command": "extension.sayHello",
"title": "Hello world"
}
]
},
"scripts": {
"postinstall": "node ./node_modules/vscode/bin/install",
"test": "node ./node_modules/vscode/bin/test"
},
"devDependencies": {
"typescript": "^2.6.1",
"vscode": "^1.1.6",
"eslint": "^4.11.0",
"#types/node": "^7.0.43",
"#types/mocha": "^2.2.42"
}
}

When I create a StatusBarItem using window.createStatusBarItem I get an object which doesn't seem to have any string as identifier
It does not by default since it's optional, yes, but you can set command on it:
statusBarItem.command = 'extension.sayHello';
Check the API docs for StatusBarItem: https://code.visualstudio.com/docs/extensionAPI/vscode-api#StatusBarItem

Related

Babel.js: Uncaught TypeError: _interopRequireDefault is not a function

I use the babel.js node.js API to compile react jsx and js scripts.
I have the following node.js script for example:
// react_transform.js
const fs = require("fs");
code = fs.readFileSync("./samples/sample4.js", 'utf8');
result2 = require("#babel/core").transformSync(code, {
presets: [
"#babel/preset-env",
"#babel/preset-react",
],
plugins: [
"#babel/plugin-transform-runtime",
],
});
fs.writeFileSync(`./out/out4.js`, result2.code);
console.log("y.");
And the input file that has the jsx code is like:
// sample4.js
ReactDOM.render(
<div>
<p>
hoge.
</p>
</div>
,
document.getElementById('root')
);
$(".__upvote").click(async function (e) {
alertify.warning("You need to login.");
});
Without the "#babel/plugin-transform-runtime", line in the node.js script, when I use the script on the browser (where the output code should be located in the production), it causes an error:
VM496:9 Uncaught ReferenceError: regeneratorRuntime is not defined
So, I did research and added the line. But now I started to get a new error:
VM830:5 Uncaught TypeError: _interopRequireDefault is not a function
By the way the output js file is as follows:
// out4.js
"use strict";
var _interopRequireDefault = require("#babel/runtime/helpers/interopRequireDefault");
var _regenerator = _interopRequireDefault(require("#babel/runtime/regenerator"));
var _asyncToGenerator2 = _interopRequireDefault(require("#babel/runtime/helpers/asyncToGenerator"));
ReactDOM.render( /*#__PURE__*/React.createElement("div", null, /*#__PURE__*/React.createElement("p", null, "hoge.")), document.getElementById('root'));
$(".__upvote").click( /*#__PURE__*/function () {
var _ref = (0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee(e) {
return _regenerator["default"].wrap(function _callee$(_context) {
while (1) {
switch (_context.prev = _context.next) {
case 0:
alertify.warning("You need to login.");
case 1:
case "end":
return _context.stop();
}
}
}, _callee);
}));
return function (_x) {
return _ref.apply(this, arguments);
};
}());
So I again did research about the new error, found an SO post:
reactjs - How to fix TypeError _interopRequireDefault is not a function in Create React App - Stack Overflow
People say:
Add #babel/runtime to the dependency section. That will fix it.
After add "#babel/runtime", I fixed it
So I added that "#babel/runtime" to package.json then npm install-ed. Now the package.json is like (I ommited irrelevant lines):
{
"name": "tmp",
"version": "1.0.0",
"description": "",
"main": "lodash_dev.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"author": "",
"license": "ISC",
"dependencies": {
"#babel/runtime": "^7.17.8",
},
"devDependencies": {
"#babel/plugin-syntax-dynamic-import": "^7.8.3",
"#babel/plugin-transform-react-jsx": "^7.17.3",
"#babel/plugin-transform-runtime": "^7.17.0",
"#babel/preset-env": "^7.16.11",
"#babel/preset-react": "^7.16.7",
}
}
Then re-run the node.js script, I get the output, I tested it on the page on the browser, however, for some reason the error still persists.
How can I fix this? Thanks.
You're transforming your code with Babel, but you're not running a bundler such as esbuild or webpack.
require() is not a thing in the browser. The bundler's responsibility (among other things) is to take all of those require() calls and resolve them into real modules, and end up with one (or more) .js files that contains all of the require()d code and no require()s.

InvalidValueError: The ipfs-repo-migrations package does not have all migration to migrate from version 10 to 11 at verifyAvailableMigrations

I get this error: InvalidValueError: The ipfs-repo-migrations package does not have all migration to migrate from version 10 to 11 at verifyAvailableMigrations when I try to spin up ipfs-coord. Please does anyone have an idea on what I should do? Thanks in advance
Here's my code
const IPFS = require('ipfs')
const BCHJS = require('#psf/bch-js')
const IpfsCoord = require('ipfs-coord')
async function start() {
// Create an instance of bch-js and IPFS.
const bchjs = new BCHJS()
const ipfs = await IPFS.create()
// Pass bch-js and IPFS to ipfs-coord when instantiating it.
const ipfsCoord = new IpfsCoord({
ipfs,
bchjs,
type: 'node.js'
})
await ipfsCoord.start()
console.log('IPFS and the coordination library is ready.')
}
start()
Here's my package.json
{
"name": "ipfs-coord-chat-app",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"start": "nodemon app.js"
},
"keywords": [],
"author": "",
"license": "ISC",
"dependencies": {
"#psf/bch-js": "^4.20.26",
"ipfs": "^0.55.4",
"ipfs-coord": "^6.7.3",
"nodemon": "^2.0.15"
}
}
I came across this and found deleting the .jsipfs folder in my home directory solved it.
/home/tom/.jsipfs
Be warned though this will remove all previous data that was stored by your node so it would be wise to take a backup or find a way to roll back your dependencies and extract any crucial data.

What could possibly be causing this "write EOF" error after typing the "npx webpack" command?

Okay, I have a webpack project that I want to build/compile. My package.json is here:
{
"name": "project-name",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"build": "webpack"
},
"author": "",
"license": "ISC",
"devDependencies": {
"chokidar": "3.4.0",
"clean-webpack-plugin": "^3.0.0",
"closure-webpack-plugin": "^2.3.0",
"copy-webpack-plugin": "^5.1.1",
"google-closure-compiler": "^20200504.0.0",
"lodash": "^4.17.19",
"minimatch": "^3.0.4",
"raw-loader": "^4.0.1",
"terser-webpack-plugin": "^3.0.1",
"uglify-loader": "^3.0.0",
"webpack": "^4.43.0",
"webpack-cli": "^3.3.12",
"webpack-obfuscator": "^0.28.0",
"zip-folder": "^1.0.0"
},
"dependencies": {
"crypto-js": "^4.0.0",
"jquery": "^3.5.1",
"prettier": "^2.0.5",
"semver": "^7.3.2",
"sweetalert": "^2.1.2",
"sync-request": "^6.1.0",
"versioning": "^1.1.0",
"webpack-build-notifier": "^2.0.0",
"webpack-closure-compiler": "^2.1.6"
}
}
When running the command "npm i", the node_modules folder is being created and at the end there are warns informing me that some modules are deprecated like "minimatch#0.3.0", "gulp-util#3.0.8", "fsevents#1.2.13" etc. Also it gives me warns that say optional dependencies have been skipped. Dependencies such as "fsevents#^2.1.2" etc. Now I read somewhere else that if they're optional, then it shouldn't matter.. right?
Anyway, when typing the "npx webpack" command expecting my files to get compiled and placed in the "out" folder, I'm getting this error:
Error: write EOF
at WriteWrap.onWriteComplete [as oncomplete] (internal/stream_base_commons.js:94:16)
Now, I could not find anything like this anywhere on the internet. I've been searching for weeks now, and still haven't found any fix. The project that I'm trying to compile is open-source and is not mine. I barely know what I'm doing to be honest, I only know how to edit certain parts of code and stuff like that, nothing anyone else couldn't figure out.
This project used to always compile normally on my previous Windows 7 (64-bit) on the same PC. Now I have a different Windows 7 (32-bit) and this issue just popped up out of nowhere. I'm assuming there is something wrong with node, npm or whatever else, not the actual project. Because like I said, it used to compile with no problems. Also, I have node installed, python installed and chocolatey could not be installed because of issues with PowerShell and something about SecurityProtocol, but I don't think chocolatey is necessary, is it?
Lastly, here's the webpack.config.js file if that might help also:
var path = require("path")
var JavaScriptObfuscator = require("webpack-obfuscator")
var CopyWebpackPlugin = require("copy-webpack-plugin")
var { CleanWebpackPlugin } = require("clean-webpack-plugin")
var WebpackBuildNotifierPlugin = require("webpack-build-notifier")
var ClosureCompilerPlugin =
process.platform == "win32"
? require("webpack-closure-compiler")
: require("closure-webpack-plugin")
var zipFolder = require("zip-folder")
var CryptoJS = require("crypto-js")
var fs = require("fs")
var manifest
try {
manifest = require("./src/resp/data.json")
} catch (e) {
fs.writeFileSync("./src/resp/data.json", "{}")
manifest = {}
}
var version = (manifest.version = "2.1.7")
var time = new Date()
var string = (manifest.secret =
Buffer.from(
(
(new Date().getDate() + new Date().getMonth()) *
Math.pow(new Date().getFullYear(), 2)
).toString(32)
)
.toString("base64")
.replace(/[^a-zA-Z]/g, "") +
(new Date().getSeconds() + new Date().getMinutes()))
fs.writeFileSync("src/resp/data.json", JSON.stringify(manifest))
var dataURL = file => {
var file =
"data:image/png;base64," + fs.readFileSync(file).toString("base64")
return CryptoJS.AES.encrypt(file, string)
}
var config = {
entry: {
main: "./src/resp/index.js",
background: "./src/background.js",
content: "./src/content.js",
},
output: {
filename: "[name].js",
chunkFilename: "chunks/[chunkhash:8].something.js",
path: path.resolve("./out/"),
},
plugins: [
new ClosureCompilerPlugin(
process.platform == "win32"
? undefined
: {
platform: "native",
}
),
new CopyWebpackPlugin([
{
from: "src",
ignore: ["*.js", "*.txt", "data.json", "*.dev.*"],
transform: (content, path) => {
if (
path.match(/\.png|\.jpg|\.gif/g) &&
!path.match(/\.enc\./g)
)
return content
var parse = [
{
from: /[0-9]+\.[0-9]+\.[0-9]+/g,
to: version,
},
]
content = content.toString()
if (!path.match(/\.png|\.jpg|\.gif/g))
parse.forEach(p => {
content = content.replace(p.from, p.to)
})
if (path.match(/\.enc\.png/g))
content = dataURL(path).toString()
return Buffer.from(content)
},
transformPath: path => {
return path.replace(/\.enc\.png/g, ".enci")
},
},
]),
new CleanWebpackPlugin(),
{
apply: compiler => {
compiler.hooks.afterEmit.tap("AfterEmitPlugin", compilation => {
zipFolder("./out", "./zip/latest.zip", new Function())
zipFolder(
"./out",
"./zip/" +
`${time.getMonth()+1}-${time.getDate()}-${time.getFullYear()}.${Buffer.from(
time.getMilliseconds().toString(32)
)
.toString("base64")
.replace(/[^0-9a-zA-Z]/g, "")
.substr(0, 6)}.zip`,
new Function()
)
})
},
},
new WebpackBuildNotifierPlugin({
title: "game v" + version + " Build (" + string + ")",
suppressWarning: true,
}),
],
/*optimization: {
splitChunks: {
chunks: "all"
}
},*/
module: {
rules: [
{
test: /parse\.js|\.txt/i,
use: ["raw-loader"],
},
],
noParse: [/[\/\\]node_modules[\/\\]jquery[\/\\].+?$/],
},
stats: "errors-only",
}
module.exports = (env, argv) => {
if (argv.mode !== 'development') {
config.plugins.splice(1,0,new JavaScriptObfuscator(
{
//identifierNamesGenerator: "mangled",
//rotateUnicodeArray: true,
//deadCodeInjection: true,
//unicodeEscapeSequence: true,
//selfDefending: true,
//transformObjectKeys: true,
//disableConsoleOutput: true
},
["content.js"]
))
}
return config;
};
I'm really losing hope, there's no communication with the project author. He only updates the source every now and then, but he doesn't want to help at all so I'm pretty much on my own with this issue. Please if you have any idea what could possibly be causing the weird error when typing the "npx webpack" command, comment down below. Also, it's not just npx webpack that fails, I tried the "npm run-script build" command too and it gives the same error + err! code "LIFECYCLE".
EDIT: Apparently didn't have java sdk 8 installed, fixed the issue.

How do I run babel-plugin-tester with jest?

It should be very simple this one, but I can't run it. I have installed the plugin according the their docs and written a simple example also according to their docs:
test.js:
import pluginTester from 'babel-plugin-tester'
pluginTester({
plugin: identifierReversePlugin,
snapshot: true,
tests: [
{code: '"hello";', snapshot: false},
{
code: 'var hello = "hi";',
output: 'var olleh = "hi";',
},
`
function sayHi(person) {
return 'Hello ' + person + '!'
}
console.log(sayHi('Jenny'))
`,
],
})
// normally you would import this from your plugin module
function identifierReversePlugin() {
return {
name: 'identifier reverse',
visitor: {
Identifier(idPath) {
idPath.node.name = idPath.node.name.split('').reverse().join('')
},
},
}
}
I have installed jest according to jest docs:
npm install jest --save-dev
My package.json file:
{
"name": "test",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"test": "jest"
},
"author": "",
"license": "ISC",
"dependencies": {},
"devDependencies": {
"#babel/cli": "^7.10.1",
"#babel/core": "^7.10.2",
"#babel/preset-env": "^7.10.2",
"babel-jest": "^26.0.1",
"babel-plugin-tester": "^9.2.0",
"jest": "^26.0.1"
}
}
I also have babel config as:
module.exports = {
presets: [
[
'#babel/preset-env',
{
targets: {
node: 'current',
},
},
],
],
};
I try to run npx jest test.js but it just spits out
No tests found, exiting with code 1
Run with `--passWithNoTests` to exit with code 0
I can run jest on a simple example without babel-plugin-tester, so everything seems to work, but I probably don't understand how it is intended to be used with jest. I feel so stupid.
This is stupid! I had to rename my testfile to fit *.test.js. Why don't jest trust me that the file I intend to run indeed contains tests?! This is obviously a stupid implementation of jest!!
Hours of wasted time.. thanks to stupid jest

PouchDB createIndex throws a 500 error code

I am just trying to create a basic index like this
currentDB.createIndex({
index: {
fields: ['name']
}
}).then((result) => {
}).catch((error) => {
})
But it just sends me a 500 with an 'unknown_error' error message
I can successfully run all other methods: .getIndexes, .allDocs, .query etc... only this method is failing for some reason.
As mentioned in the documentation:
500 - Internal Server Error
The request was invalid, either because the supplied JSON was invalid,
or invalid information was supplied as part of the request.
You need to provide more details to be able to re-produce your situation.
I tired the createIndex API on NodeJS to see if I run into any issue. I created the following code in a file named server.js:
process.env.NODE_TLS_REJECT_UNAUTHORIZED = "0"; // Ignore rejection, becasue CouchDB SSL certificate is self-signed
//import PouchDB from 'pouchdb'
const PouchDB = require('pouchdb')
PouchDB.plugin(require('pouchdb-find'))
const db = new PouchDB('https://admin:****#192.168.1.106:6984/reproduce')
db.createIndex({
index: {
fields: ['title']
}
}).then((result) => {
console.log(result)
}).catch((error) => {
console.log(error)
})
When I run the code, the results are fine:
$ node server.js
{ result: 'created',
id: '_design/94407075806d27d94ac764d9aa138a43c015dc1f',
name: '94407075806d27d94ac764d9aa138a43c015dc1f' }
So, at least on NodeJS, there shouldn't be any problem with createIndex. My PouchDB versions are shown below:
{
"name": "reproduce-pouchdb-tls",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"keywords": [],
"author": "",
"license": "ISC",
"dependencies": {
"pouchdb": "^6.4.3",
"pouchdb-find": "^6.4.3"
}
}

Categories

Resources