Module "punycode" has been externalized for browser compatability - hash

I am trying to use the '#ensdomains/eth-ens-namehash' package to hash an input.
I am using it in combination with 'pinia'.
I call on this method in Nuxt3.
This is the code:
import { defineStore } from "pinia"
import namehash from "#ensdomains/eth-ens-namehash"
import { Buffer } from 'buffer'
export const exampleMethod = defineStore('example', {
state: () => {
return{
hash: String
}
},
actions: {
method(input) {
globalThis.Buffer = Buffer
this.hash = namehash.hash(input).toString()
}
}
}
When trying to call 'method' I get the following error:
Uncaught (in promise) Error: Module "punycode" has been externalized
for browser compatibility. Cannot access "punycode.ucs2" in client
code.

Related

xrpl-accountlib - UnhandledPromiseRejectionWarning: TypeError: AddressCodec.isValidSeed is not a function

Here, I use both isValidAddress and isValidSeed from utils. isValidSeed throws an error, but isValidAddress does not after being used in a similar fashion.
I get no other errors in the code.
if(process.argv.length < 3) {
console.log("Usage: node dist/index <r-address>")
process.exit(1)
}
import { XrplClient } from "xrpl-client"
import { derive, utils, XRPL_Account } from "xrpl-accountlib"
const client = new XrplClient("wss://s.altnet.rippletest.net:51233")
const main =async () => {
const data = await client.send({
id: 1,
command: "account_info",
account: process.argv[2]
})
console.log(data)
//checking isValidAddress usage
if(!utils.isValidAddress(data.account_data.Account)) {
console.log("Invalid r-address")
process.exit(1)
}
console.log("Valid r-address")
//checking isValidSeed usage
if(!utils.isValidSeed(process.argv[2])) {
console.log("Invalid Seed")
process.exit(1)
}
}
main()
which version of the xrpl-accountlib library do you use?
There was a fix regarding the isValidSeed method around December 2021:
Make sure to use the latest version of the xrpl-accountlib.

I am developing VS Code extension and I need to capture the call stack records and log the result

I am writing a simple VS Code extension that suppose to just log the call stack in the console at specific point while debugging a code.
I was able to write a code to retrieve the current session of debugging, the break points and things like this, but I failed to find any property or method to allow me retrieve the call stack records.
This is the code I wrote:
export function activate(context: vscode.ExtensionContext) {
console.log('Congratulations, your extension "sampleextension1" is now active!');
let disposable = vscode.commands.registerCommand('sampleextension1.hello', () => {
vscode.window.showInformationMessage('Hello World from sampleextension1!');
vscode.commands.executeCommand('editor.action.addCommentLine');
vscode.debug.onDidStartDebugSession(x => {
});
vscode.debug.onDidChangeActiveDebugSession(c => {
var b = vscode.debug.breakpoints[0];
});
});
context.subscriptions.push(disposable);
}
As you see in the code, there is an event handler for onDidChangeActiveDebugSession which enables me to capture the session of the debugging but no chance to find how to capture the stack trace.
I went through the documentation but it's not helpful though.
I was able to achieve what I want by sending a CutomRequest to the debugging session to retrieve the stack frames.
More information could be found in the DAP page here
The code is as shown below:
x.customRequest('stackTrace', { threadId: 1 }).then(reply => {
const frameId = reply.stackFrames[0].id;
}, error => {
vscode.window.showInformationMessage(`error: ${error.message}`);
});
or more efficient is to register tracker as shown below:
vscode.debug.registerDebugAdapterTrackerFactory('*', {
createDebugAdapterTracker(session: vscode.DebugSession) {
return {
onWillReceiveMessage: m => console.log(`> ${JSON.stringify(m, undefined, 2)}`),
onDidSendMessage: m => console.log(`< ${JSON.stringify(m, undefined, 2)}`)
};
}
});
The full example is shown here:
export function activate(context: vscode.ExtensionContext) {
console.log('Congratulations, your extension "sampleextension1" is now active!');
let disposable = vscode.commands.registerCommand('sampleextension1.hello', () => {
vscode.window.showInformationMessage('Hello World from sampleextension1!');
vscode.commands.executeCommand('editor.action.addCommentLine');
vscode.debug.onDidStartDebugSession(x => {
// x.customRequest("evaluate", {
// "expression": "Math.sqrt(10)"
// }).then(reply => {
// vscode.window.showInformationMessage(`result: ${reply.result}`);
// }, error => {
// vscode.window.showInformationMessage(`error: ${error.message}`);
// });
x.customRequest('stackTrace', { threadId: 1 }).then(reply => {
const frameId = reply.stackFrames[0].id;
}, error => {
vscode.window.showInformationMessage(`error: ${error.message}`);
});
});
vscode.debug.onDidChangeActiveDebugSession(c => {
var b = vscode.debug.breakpoints[0];
});
vscode.debug.registerDebugAdapterTrackerFactory('*', {
createDebugAdapterTracker(session: vscode.DebugSession) {
return {
onWillReceiveMessage: m => console.log(`> ${JSON.stringify(m, undefined, 2)}`),
onDidSendMessage: m => console.log(`< ${JSON.stringify(m, undefined, 2)}`)
};
}
});
});
Steps to run:
F5 to run the Extension Dev Environment.
Ctl+Shift+P then write your cmd, in my case it was Hello
Then F5 to start the debugging in the Dev Environment then you will be able to see the result.
Hope it helps

i18n addResourceBundle mocks shows error i18n not defined

I am using react testing library to test my code and I have used i18n.addResourceBundle to add some translations on the fly. I am trying to test its and have
jest.mock('i18n', () => ({
__esModule: true,
default: { addResourceBundle: jest.fn() }
}))
BUt when I try to do snapshot, it keeps saying i18n.addResourceBundle is not defined
You are mocking i18next improperly.
The usage of i18next looks like:
import i18next from 'i18next';
export const i18n = i18next.init({
...
// config
...
});
// somewhere else in the code
i18n.addResourceBundle();
//-^ this is an instance of i18next
That means that you need to return an object with init function which returns an instance with addResourceBundle.
jest.mock('i18n', () => ({
__esModule: true,
default: {
init(config) {
return {
// this is the instance
addResourceBundle: jest.fn(),
};
},
},
}));

QZ giving errors on angular install and websocket not found

I am trying to get my angular webapp working with a star sp 700 receipt printer and am trying to integrate qz-tray into my software for that reason. I am getting an error when trying to install #types/qz-tray which is displayed below. Also I get an error
unresolved variable websocket
on the line 23 and
unresolved variable api
on line 16.
Can someone please tell me how to fix this and if there is a better way of printing to either this or another receipt printer through angular?
import { Injectable } from '#angular/core';
import { from as fromPromise, Observable, throwError } from 'rxjs';
import { HttpErrorResponse } from '#angular/common/http';
import { catchError, map } from 'rxjs/operators';
import * as qz from 'qz-tray';
import { sha256 } from 'js-sha256';
#Injectable({
providedIn: 'root'
})
export class PrinterService {
//npm install qz-tray js-sha256 rsvp --save
constructor() {
qz.api.setSha256Type(data => sha256(data));
qz.api.setPromiseType(resolver => new Promise(resolver));
}
// Get the list of printers connected
getPrinters(): Observable<string[]> {
console.log('+++++++++PrinterService+++++');
return fromPromise(
qz.websocket.connect().then(() => qz.printers.find())
)
map((printers: string[]) => printers)
, catchError(this.errorHandler);
}
// Get the SPECIFIC connected printer
getPrinter(printerName: string): Observable<string> {
return fromPromise(
qz.websocket.connect()
.then(() => qz.printers.find(printerName))
)
map((printer: string) => printer)
, catchError(this.errorHandler);
}
// Print data to chosen printer
printData(printer: string, data: any): Observable<any> {
const config = qz.configs.create(printer);
return fromPromise(qz.print(config, data))
map((anything: any) => anything)
, catchError(this.errorHandler);
}
private errorHandler(error: HttpErrorResponse) {
if (error.error instanceof ErrorEvent) {
console.log(error.error);
console.log('An error occurred:', error.status);
return throwError(error.error);
} else {
console.log('An error occurred:', error.status);
console.log(error.error);
return throwError(error.error);
}
};
}
unresolved variable websocket
unresolved variable api
These are both signs that qz-tray.js did not load properly.
The objects qz.api and qz.websocket are both part of the qz namespace. If they're not available, then qz was never imported properly.
Here's a working example of QZ Tray running in Angular:
https://stackblitz.com/edit/angular-3h4cnv
The import line appears to be correct and matches that of the QZ Tray angular quickstart guide.
The import * as qz should be valid according to TypeScript guidelines on exporting the default export of a module however you can safely convert it to import { default as qz } from "qz-tray";
As a troubleshooting step, you can call:
console.log(qz);
If loaded properly, it should show something like this:
Another troubleshooting technique would be to remove and reinstall qz-tray using your preferred package manager npm uninstall qz-tray; npm install qz-tray, etc.

Mocking a class in typescript with jest

I am trying to unit test (with Jest) my handler module that makes use of a summary class.
My original summary class looks like:
import DynamoDBClient from './ddbClient/DynamoDBClient'
import { DynamoDB } from 'aws-sdk'
import { iSummaryReader, iObsSummariesAttributes } from './Summary.d'
import { JSONAPIResource } from '../JSONAPIResponse'
export default class Summary {
reader: iSummaryReader
constructor(reader: iSummaryReader) {
this.reader = reader
}
getSummary = async (keyName: string, keyValue: string): Promise<JSONAPIResource<iObsSummariesAttributes>> => {
return new Promise<JSONAPIResource<iObsSummariesAttributes>>((resolve, reject) => {
const gettingItem = this.reader.getItem(keyName, keyValue)
console.log(gettingItem)
gettingItem.then((resp) => {
resolve(resp)
}).catch((err: Error) => {
reject(err.message)
})
})
}
}
In my handler module I import with import Summary from './lib/Summary'
(Note: same line is used in handler.test.ts
Inside the handler function
try {
const dynamodbObj: iSummaryReader = new DynamoDBClient(documentClient, someTable)
const summary = new Summary(dynamodbObj)
const data: JSONAPIResource<iObsSummariesAttributes> = await summary.getSummary('id', someID)
}
My results depend on my approach if try an automatic mock
jest.mock('./lib/Summary', () =>
{
return {
getSummary: jest.fn()
}
})
I get the error
TypeError: Summary_1.default is not a constructor
If I create a manual mock under lib/__mocks__/Summary.ts with jest.mock('./lib/Summary') it does work until I get the point
expect(Summary).toHaveBeenCalledTimes(1)
Where it complains about me not being able to do this on summary. I also am unable to access my method to test that they are being called this way.
Note: My hanlder is for a lambda function so I am unable to inject the class that way where I have successfully tested that I can mock an injected class.
EDIT
The tsconfig.json is:
{
"compilerOptions": {
"rootDir": "./src",
"outDir": "./build",
"declaration": false,
"target": "es2015",
"moduleResolution": "node",
"module": "commonjs",
"noImplicitReturns": true,
"noImplicitThis": true,
"strictNullChecks": true,
"alwaysStrict": true,
"lib": [
"dom",
"es2015.promise",
"es2017.object",
"es2016"
],
},
"include": [
"src/**/*.ts"
],
}
I do not know why this was failing, but I the following steps seem to work to fix it.
Change the class export from default
From
`export default class Summary {`
to
`class summary`
+ export = summary at the end
Use import = require to import it.
import Summary = require('./lib/Summary')
Those two changes allowed it to find the jest.mock.